开发者

Best way to aggregate different responsibility

I have an application that reads a barcode, extracts a part and checks if it is valid. I use C#, Autofac and Nunit and I am undecided on which is the best开发者_如何学JAVA implementation:

Solution A: (Facade Pattern?)

public class Checker {
   public Checker(IBarcodeReader reader, IBarcodeParser parser) {
      ...
   }
   public bool Check() {
     string barcode = reader.Read();
     string id = parser.Parse(barcode);
     // check if id is valid

   }
}

Solution B: (Strategy Pattern?)

public class Checker {
   public Checker(IBarcodeReader reader) {
      ...
   }
   public bool Check() {
     string id = reader.Read();
     // check if id is valid

   }
}

public class BarcodeReader: IBarcodeReader {
   public BarcodeReader(IBarcodeParser parser) {
      ...
   }
   public string Read() {
     string barcode = ... // read barcode from device
     return parser.Parse(barcode);
   }
}


Aren't you overengineering a bit? At least that's how it looks from the example. I would drop the Strategy pattern idea. Are you going to ever have more then one strategy?

I like the first solution (good testability and DI), but I wouldn't call 3 line code a Facade, really.


I like solution A better because, in my opinion, it does a better job of separating concerns. The BarcodeReader reads a barcode and returns it as a string (which is what a barcode represents).


Assuming nothing else about your app, go with Solution A. It keeps things as succinct and maintainable as possible, until you show a need for the added complexity of Solution B. A third option is to not even use the constructors, but to have static functions performing the check.

Additionally, I would rename your functions. They return values, but their names don't reflect that. You want to go with something like IsValid() instead of Check() and GetBarcode() instead of Read().


I would opt for your Solution B. While it does not necessarily look like a strategy pattern I like it because it has better separation of concerns. The BarcodeReader is generic, it knows only how to read parts of a barcode and send it back. It can be used for any application reading barcodes. The Checker looks to be more business specific. Your first solution is mixing the business logic and the generic reading of barcodes together. (Note: I'm assuming that the logic for validating is business logic and not barcode specific validation. If it is barcode specific validation then it should go in the barcode reader.)

I would Model the reader after the XmlReader. It will check for wellformed xml, etc.


Solution B makes your Checker class easier to test, which is usually a sign that you're doing something right. (You have to stub one fewer method.)

If your consuming classes are only interested in the parsed barcode, that's a better approach.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜