Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

After doing a rough sketch of a high level object model, I am doing iterative TDD, and letting the other objects emerge as a refactoring of the code (as it increases in complexity). (That whole approach may be a discussion/argument for another day.)

In any case, I am at the point where I am looking to refactor code blocks currently in an if-else blocks into separate objects. This is because there is another another value combination which creates new set of logical sub-branches.

To be more specific, this is a trading system feature, where buy orders have different behavior than sell orders. Responses to the orders have a numeric indicator field which describes some event that occurred (e.g. fill, cancel). The combination of this numeric indicator field plus whether it is a buy or sell, require different processing buy the code.

Creating a family of objects to separate the code for the unique handling each of the combinations of the 2 fields seems like a good choice at this point. The way I would normally do this, is to create some Factory object which when called with the 2 relevant parameters (indicator, buysell), would return the correct subclass of the object. Some times I do this pattern with a map, which allows to look up a live instance (or constructor to use via reflection), and sometimes I just hard code the cases in the Factory class.

So - for some reason this feels like not good design (e.g. one object which knows all the subclasses of an interface or parent object), and a bit clumsy.

Is there a better pattern for solving this kind of problem? And if this factory method approach makes sense, can anyone suggest a nicer design?

share|improve this question

4 Answers 4

up vote 2 down vote accepted

Your approach sounds good to me. Philosophically, while your factory does know about every subclass, it doesn't know that it knows. In other words, in the future subclasses might be generated elsewhere, in places your factory knows (and cares) nothing about. At the other end, the users of these subclasses neither know nor care where they came from. Might be from the factory, might be from somewhere else.

Your bad feeling on this is that you are replacing a simple mechanism with a fancy one, and you don't (yet) really need the power you are getting. You may indeed be wasting your time. But if your system grows, you might have several factories, and many other objects might create these subclasses, including the subclasses themselves. So long as your factory does not need to know about all the subclasses, and so long as your "consumers" don't need to know which factory, if any, they came from, your design is sound. Everything is properly encapsulated and polymorphic.

One other thing: in Java more so than in other languages, a subclass often works better than putting a switch in the base class. In Java I'll subclass anything if I need a slightly different behavior. In C#, I'll go to a lot of trouble to make one class highly flexible with extra fields and extra constructor parameters. A new Java class can be created in a small block of code with no references to it elsewhere--a local or anonymous class. In C# the new class has to be placed well away from the only spot to reference it as anything but its base class--and it may be several levels of base--or interface.

share|improve this answer
    
I've been giving a lot of thought to this hand coded factory approach, and dependency injection approach. For now, I stayed with the hand coded factory, in the spirit of not over-engineering this feature. I think DI is something to explore for the future, and for my actual usage I would need to do more advanced DI, which I don't know how to do yet. –  Sam Goldberg Mar 22 '12 at 21:31
    
At one or more places in your program, you have to choose between two or more "Strategy" (thanks Gary Buyn) subclasses (or implementations). If you have to use the same logic in more than one place, factory class or otherwise, it's time to come up with a class to make the choice and use DI. DI's no big deal in Java, particularly when it's just one independent decision-maker rather than several interactive ones. (Think of a "car" class to which you inject an "engine". No problem until you can also inject a "transmission". Then it gets interesting.) (C#'s trickier. I'm not completely sure why.) –  RalphChapin Mar 23 '12 at 13:17
> feels like not good design ... one object which knows 
> all the subclasses of an interface or parent object

I agree with your feeling - this violates the open closed principle: every time you implement a new handler you have to change the factory.

One possible solution is to inverse the dependencies:

Each instance registeres at the factory with its specefic parameters. now ever class knows the factory.

share|improve this answer
1  
INVERSE ALL THE DEPENDENCIES! –  DeadMG Mar 13 '12 at 21:42
    
I'll add that you want to look up Inversion of Control / Dependency Injection - start with Martin Fowler's seminal article and go from there :-) –  Martijn Verburg Mar 14 '12 at 10:00
    
@MartijnVerburg: I read the Martin Fowler article in detail. I've given thought about the recommendation to try to use an IOC pattern for this. I'm not clear on the mechanics of this for Java. All the subclasses have to register with the factory one way or another. If it can be done at Class Load time, then each class could register itself using a static code block. However, something needs to force the subclasses to load to invoke that static code block. If handled via some Xml configuration, that seems equivalent to coding it in the factory. –  Sam Goldberg Mar 14 '12 at 13:17
    
Hi Sam - Take a look a Picocontainer or Guice or even Spring for assistance in implementing the DI pattern. All three offer XML or annotation based configuration –  Martijn Verburg Mar 15 '12 at 12:15

A central factory sounds like a good idea to me, as it avoids having the logic of which object to choose spread over the code. The remaining issue I understand needs to solved is how to avoid this factory class knowing about all the derived classes. The way I would usually solve this is by having the factory class be a registry of types, by which I mean it knows how to give out the right type based on querying a map of objects that are fed to it by other code.

You could add to your abstapract base class for a trade some functions allowing the factory to ask for which (indicator, buy sell) combination it handles. Then when each type is registered with the factory, it calls these and adds the combination as the key to the map and the registered instance as a prototype object. Then for each request it looks the parameters up in the map and clones the prototype object.

The registration could either be done in some setup code, which would then know about all the objects, or by several blocks of code each of which knew about a few of the sub types.

share|improve this answer

Sounds fine to me.

BTW, those objects you are creating in your factories are called strategies. Determining the concrete implementation of your strategy sounds like a good use case for a factory to me. I never like that kind of if/else code so hiding it away in a factory makes it nicer for all the client code that wants to use the strategies.

Like you say, you're using TDD/iterative design so if a deficiency in the design is determined at any point, improve it then.

share|improve this answer
    
"you're using TDD/iterative design so if a deficiency in the design is determined at any point, improve it then" - agreed. I always feel this tension between what I should design in advance versus what emerges from testing. –  Sam Goldberg Mar 13 '12 at 22:56

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.