Here's why:
class DOSClient {
OrderParser orderParser;
string orderCode;
DOSClient(OrderParser orderParser, string ordercode) {
this.orderParser = orderParser;
this.ordercode = ordercode;
}
void DisplayOrderCode() {
Console.Write( "Prefix: " + orderParser.GetStringPart(ordercode) );
...
}
}
class GUIClient {
OrderParser orderParser;
string orderCode;
GUI gui;
GUIClient(OrderParser orderParser, string ordercode, GUI gui) {
this.orderParser = orderParser;
this.ordercode = ordercode;
this.gui = gui;
}
void DisplayOrderCode() {
gui.Prefix( orderParser.GetStringPart(ordercode) );
...
}
}
class OrderParserUS : IOrderParser {
public string GetStringPart(string input) {
//Some input validation which is removed for clarity
if(input.Length > 5)
return input.Substring(0,1);
if(input.Substring(0,1) == "B")
return input.Substring(0,3);
return string.empty;
}
}
class OrderParserEU : IOrderParser {
public string GetStringPart(string input) {
//Some input validation which is removed for clarity
if(input.Length > 6)
return input.Substring(0,1);
if(input.Substring(0,1) == "#")
return input.Substring(0,3);
return string.empty;
}
}
If you had gone with a static method, there would be no way to change the behavior of GetStringPart
without either destroying the old behavior or polluting it with conditional logic. It's true that statics are evil globals in disguise but the fact that they disable polymorphism is my chief complaint about them. Static methods aren't first class in OOP languages. By giving the method an object to live in, even one with no state, we make the method portable. Its behavior can be passed around like the value of a variable.
Here I've imagined a system that needs to behave slightly differently when deployed in Europe than when deployed in the US. Rather than force either system to contain code only needed by the other, we can instead change the behavior by controlling which order-parsing-object is injected in the clients. This allows us to contain the spread of the region detail. It also makes it easy to add OrderParserCanada
without having to touch existing parsers.
If that means nothing to you, then there really isn't a good argument for this.
BTW, GetStringPart
is a terrible name.