Under Construction
A couple of months ago I talked about the builder pattern for object instantiation. Another option is the factory pattern. It certainly has its place. Factories let you isolate the logic and flow of construction from both your code and the thing being constructed. Factories can also give you a kind of dependency injection, which can make testing easier.
The ability to isolate and extend leads me to an article I ran
across a couple of weeks ago. In the article the author talks about a Score
class that
initially can be Low, Medium, or High, and takes an int as the parameter to the
constructor.
As the author notes, there are oh so many problems with that. What's the high score? What if you try an invalid
number? How do you know what number to use? So the author suggests a factory with three methods,
CreateHighScore
, CreateMediumScore
, and CreateLowScore
. That certainly
solves
the "What number should I pass?" problem, but that's about it.
The extensible option adds an enum to the factory and then uses that to create a Score
with
the right value. Better, but still, WAT? There's got to be a better way.
What I would have done is skipped the factory, and switched the Score
class from using an
int to use an enum. Then there's never any question about what value to
use.
You just use the enum with the name you want. Of course, over time more and more enums get added and pretty soon
you
end up with Low, Medium, High, MediumHigh, VeryHigh, ExtremelyHigh, Highest, and everyone's favorite,
EvenHigher.
Of course, that brings up its own set of issues. What's higher, VeryHigh or ExtremelyHigher? How do you deal
with that? By making Score
comparable (or the equivalent in your language of choice) you can
then
find the highest of a set or sort by Score
as needed.
Doing it that way brings intent to the foreground and reduces cognitive load, which, as I've said before, is always a good thing.
https://uberatg.slack.com/archives/CLVTB4W20/p1586442600018500