Question

I'm facing a design related dilemma in my project & I'd really appreciate if I could get some suggestions. There's a POJO with around 20-25 fields & in some cases this object is partially instantiated as per the need. In my view this is not a good practice & should be avoided perhaps by using inheritance or composition. I'm looking for suggestions on best way to implement the object creation logic (a design pattern perhaps) so as to avoid partial instantiation. Currently, objects are being created using builder pattern.

Basically, it is a swing application. Data is taken from different fields (20-25) of a JDialog & passed to the next window to be displayed for confirmation. This data is passed on using a POJO. This POJO is currently instantiated using builder pattern. But I am looking for a way to implement this where the POJO isn't partially instantiated & used in other cases where only a few fields needs to be passed.

Thanks in advance!

Was it helpful?

Solution

If you have a class with parameters that are only used under some conditions and are not needed under the others, you definately should do some refactoring. Try Extract Class refactoring, for example, to group some parameters and methods. If you have some typecodes, that indicate the need in some parameters, think about replacing typecode with subclasses if typecode is not changing during lifetime of an object or replace typecode with state/strategy otherwise. Then just move fields and methods from original class to these newly created classes.

I recomend you to read Martin Fowler's Refactoring book. It's just awesome and very helpful.

The builder pattern is ok, but you may want to implement factory method pattern for object creation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top