Creation of classes in Factory design pattern - java

In the factory design pattern, we write logic for deciding which class to be loaded in the factory class. Suppose I have a choice of 100 classes, so for all 100 do I need to write conditions in factory class? Or there is some other way?

In this case I'd create an annotation which describes the condition each class must meet to be created. Then I'd use reflection to discover all possible products and store a specific subfactory in a HashMap with the condition used as key.

Its not very helpful, but I would say it totally depends on your use-case. There could be some generic logic on which a particular class could be picked up.
On a side note: I would advice you to rethink on the design if such situation occurs and not fix a problem which could be avoided to begin with. Use of reflection could help if your logic is around class name but again it could be an overkill for the problem.

Related

Choice of design pattern - serial execution

I have a simple design problem - I am looking for the best pattern to implement a simple functionality. Let's say, I am going to create an xml message in java. This message consists of many fields in different logic groups.
So, the first idea - create a class to set all fields. I can do it one method (which will be really long...) or split the method into multiple smaller (for each of the logical groups). However, I don't think it is a good approach, because the class will be really long and difficult to mantain.
The second idea is to create a functional interface and some implementations for different groups, for instance GroupXxxSetter, GroupYyySetter, etc. I can create and keep all instances in a list or a set and call the method defined inside the interface for each object stored inside the collection. It seems to be very similar to the 'Chain of responsibility' pattern. However, the idea of this pattern is different, so I am not sure if it is a good idea to use this pattern in my case.
Should I use the 'chain of responsibility' pattern here? Or, maybe there is something better?
Thanks in advance.
Should I use the 'chain of responsibility' pattern here?
Clearly, no. You don't have the notion of candidate responsible to respond to a request. All elements will do a processing.
Or, maybe there is something better?
You have multiple possibilities.
Your context is not totally set. So it is hard to propose one rather than another.
I may propose you a implementation with the Builder pattern (Java Effective reference and not GOF).
For each logic group, you could have a specific class.
You would also have a composite class that is composed of logic group instances.
Instead of providing a public constructor or setters that prevent immutability and that can make rules validation cumbersome, you could use the Builder pattern for each one logic group class and in the composite class, you could use the same kind of Builder pattern where you will build the final message from the previously created logic group instances.
You could so create the instances in this way :
OneLogicGroup oneLogicGroup = OneLogicGroup.builder().fieldXXX(...).fieldYYY(...).build();
AnotherLogicGroup anotherLogicGroup = AnotherLogicGroup .builder().fieldXXX(...).fieldYYY(...).build();
MyMessage myMessage = MyMessage.builder().oneLogicGroup(oneLogicGroup).anotherLogicGroup(anotherLogicGroup).build().
I can create and keep all instances in a list or a set and call the
method defined inside the interface for each object stored inside the
collection.
It seems referring to a structural concern.
It is not directly related to the creation of the object. It is much related to how to share the created objects.
The flyweight pattern addresses this need and may be used conjointly with the presented builder Pattern.

Using strategy pattern with simple factory

I've been learning about design patterns and I think I'm a little bit stuck with an exercise where I do not posses any answer-pages to.
I already used the strategy pattern to create this:
http://i.imgur.com/5Lia4JD.png (minus the setBehavior functions in duck)
I need to improve this design with simple factory because at the moment, the 2 types of behaviors are instantiated via following code (shown via example):
public MallardDuck()
{
setQuackBehavior(new Quack());
setFlyBehavior(new FlyWithWings());
}
This is not correct because we need to program to an interface and not to an implementation.
What I thought to do is making 2 separate factories that each handle a specific behavior but when I made the design I started doubting my solution. Is it normal to do this sort of thing with simple factory?
Could anyone push me in the correct direction? :]
If you're programming Ducks, then it's a toy example anyway. Go ahead and do the two separate simple factories. The general rule is a simple factory per interface. You could put all the simple factories in one class to make it less complex.
The disadvantage of concrete classes instantiating other concrete classes is of course the risky coupling to implementations. If the implementation details change (yes, the new is trivial but the whole ducks example is trivial), your classes that know that information are also liable to change.
You're right that it's not programming to an interface. Classes that know less about implementation details are more insulated from changes in those details, which is the whole point of using interfaces.
If you want to avoid the strong coupling between concrete strategies and their host you may rely on a factory that knows how to instantiate a Duck with the proper strategies for a given type rater than having a concrete class per type.
The above design may be slightly more testable, but I do not think you should be too concerned about the coupling between concrete ducks and the concrete strategies they use.
This is not correct because we need to program to an interface and not to an implementation.
And you program to an interface since setQuackBehavior() takes as input an interface and that your quack class represents the quack behavior field as an interface and not an implementation.
At a time, in a code, using a implementation class is normal.
Using a factory with methods returning based interface instances is useful in many cases but in your case, I don't see the interest. Why your quack subclasses should not know which concrete behavior used ?
If it has no reason, so it seems ok :
setQuackBehavior(new Quack());
Using factory with not added value gives a complex code without reasons.

Should domain model mappers be static?

In many of the projects I have worked on we often have a lot of classes that map content from one domain model to another. For example from a WSDL generated model to a project specific one.
for example
public class FooBarContentMapper {
public static Foo fromWsToDomain(FooType fooType) {
...
}
}
this can also be a non-static method and the service layer can have a mapper object field instead of calling the static method:
public class FooBarContentMapper {
public Foo fromWsToDomain(FooType fooType) {
...
}
}
I find both ways used a lot, but:
is one of the solutions more efficient in any way?
are any of the solutions considered best practice?
"Is one of the solutions more efficient in any way?"
Define "efficient".
If, by "efficient", you're referring to CPU time and memory requirements, then the "instance" approach can never be more efficient than the "static" approach; at best, it can be as efficient as the static approach, and the difference depends on the frequency of object instantiation, read: how many times are you going to instantiate the "instance" approach.
"Are any of the solutions considered best practice?"
No. The "best practice" here is to match your design to your requirements.
If the mapping operation requires maintaining state, such as dependencies on other services/mappers/whatnot, then going with the "instance" approach makes more sense. One thing you don't want to get into is a world where your application's design consists of singletons that depend on each other. Use the "instance" approach, preferably using an auto-wiring facility such as the Spring Framework or CDI.
If the mapping operation requires no state, and you have an extremely high confidence in that it will never require state in the future, then use the "static" approach - unless you already have an auto-wiring facility at hand, in which case, you might as well choose the "instance" approach with auto-wiring and guarantee that, if the mapping operation requires state in the future, you won't have to alter your design much.
There are other things to consider:
Is your code testable. Mappers are used as collaborators so unit testing the object using the mapper should focus on behavior (i.e is the mapper being used when expected) ?
Is the static class used in more than one place and subject to race condition because the transform method takes a mutable object(remember, stateless static classes are still subject to race condition when taking a mutable object that is referenced by two different threads at same time)?
Does the static object actually share its life-cycle with the object using it?
If the answer is yes to any of these, you should consider switching to instance.

Good software design practise

I have a big class, which is used on the user interface of an application. It serves around 20 modules. For only one Module for the time being I need a different formation of number on a Label. The applying of formation is programatically only a line of source code. The separation of the cases can be done either by the use of a boolean flag variable, or by applying inheritance:
By boolean flag variable:
class MyClass{
private boolean isYear;
...
public setValue(){
...
if(!isYear)
doFormat();
...
}
}
The variable isYear is set of course externally, when a module serves for year valus is needed.
By applying inheritance I have to create a new class which derives from MyClass, i.e. MyYearClass and merely override the method setValue(). I think in the OO-programming the second approach is recommended, but I have heard also the opinion that in this case it makes the code complicated, more nebulous, less neat and it seems generally an overkill when only one line of code is to be changed. What approach do you consider recommendable?
As always, it depends. It can be one line now but maybe a lot more later. I agree that overengineering your code is bad but if you feel that the current design will change (and it usually does) you can use a simple design pattern here and there. For your problem (described shortly) I believe you can create a simple Factory and have that factory return for you one of the subclasses of MyClass you need when you need it.
Good design practices will favour the second method (inheritance) as it is easier to manage in the long run. When you start adding specific code to a common class, you are opening a can of worms. Maybe not you, but a developer working after you will add another feature, and another feature to the same class and then support becomes a nightmare.
What worries me more is your "I have a big class" quote. Good design principles will tell you to break it apart.
If your class has more than, say, 1000 lines, it's a good candidate for refactoring into specific functionalities.
The second approach is really better generally. But in your case you have a small class with simple logic. If you know that you are going to change this class a lot and it will become bigger and more complicated, then split it now. Otherwise you might leave it as it is, and postpone the refactoring for a future moment if you feel the class becomes too complicated. Instead, focus on other part of your application.
I think the second approach is the best practice. It might seem a bit superfluous but it is always best to keep your programming as modular as possible. Just imagine if someone else was using your code or you were using it later on and couldn't exactly remember how the MyClass worked but all you wanted to do was use the functionality of MyYearClass.

Too many "pattern suffixes" - design smell?

I just found myself creating a class called "InstructionBuilderFactoryMapFactory". That's 4 "pattern suffixes" on one class. It immediately reminded me of this:
http://www.jroller.com/landers/entry/the_design_pattern_facade_pattern
Is this a design smell? Should I impose a limit on this number?
I know some programmers have similar rules for other things (e.g. no more than N levels of pointer indirection in C.)
All the classes seem necessary to me. I have a (fixed) map from strings to factories - something I do all the time. The list is getting long and I want to move it out of the constructor of the class that uses the builders (that are created by the factories that are obtained from the map...) And as usual I'm avoiding Singletons.
A good tip is: Your class public API (and that includes it's name) should reveal intention, not implementation. I (as a client) don't care whether you implemented the builder pattern or the factory pattern.
Not only the class name looks bad, it also tells nothing about what it does. It's name is based on its implementation and internal structure.
I rarely use a pattern name in a class, with the exception of (sometimes) Factories.
Edit:
Found an interesting article about naming on Coding Horror, please check it out!
I see it as a design smell - it will make me think if all those levels of abstraction are pulling enough weight.
I can't see why you wanted to name a class 'InstructionBuilderFactoryMapFactory'? Are there other kinds of factories - something that doesn't create an InstructionBuilderFactoryMap? Or are there any other kinds of InstructionBuildersFactories that it needs to be mapped?
These are the questions that you should be thinking about when you start creating classes like these. It is possible to just aggregate all those different factory factories to just a single one and then provide separate methods for creating factories. It is also possible to just put those factory-factory in a different package and give them a more succinct name. Think of alternative ways of doing this.
Lots of patterns in a class name is most definitely a smell, but a smell isn't a definite indicator. It's a signal to "stop for a minute and rethink the design". A lot of times when you sit back and think a clearer solution becomes apparent. Sometimes due to the constraints at hand (technical/time/man power/etc) means that the smell should be ignored for now.
As for the specific example, I don't think suggestions from the peanut gallery are a good idea without more context.
I've been thinking the same thing. In my case, the abundance of factories is caused by "build for testability". For example, I have a constructor like this:
ParserBuilderFactoryImpl(ParserFactory psF) {
...
}
Here I have a parser - the ultimate class that I need.
The parser is built by calling methods on a builder.
The builders (new one for each parser that needs to be built) are obtained from builder factory.
Now, what the h..l is ParserFactory? Ah, I am glad you asked! In order to test the parser builder implementation, I need to call its method and then see what sort of parser got created. The only way to do it w/o breaking the incapsulation of the particular parser class that the builder is creating is to put an interception point right before the parser is created, to see what goes into its constructor. Hence ParserFactory. It's just a way for me to observe in a unit test what gets passed to the constructor of a parser.
I am not quite sure how to solve this, but I have a feeling that we'd be better off passing around classes rather than factories, and Java would do better if it could have proper class methods rather than static members.

Categories