3

From time to time, I'll have a class in Java that takes a multitude of parameters, however, sometimes when I am creating an object of this class, I don't need to use all the parameters. As of now, I usually set the parameters to null or 0 depending on the type. However, would it be easier if I just created chained methods to set certain fields in the class?

So, instead of:

MyClass someInstance = new MyClass(param0, null, null, 0, null, param5);

Have something like this:

MyClass someInstance = (new MyClass()).setParam0(param0).setParam5(param5);

Does this go against OOP or Java's usual paradigm?

1
  • Heavy usage of null indiquate a probable conception error. Maybe you could split that class into several ones or create several constructors.
    – deadalnix
    Oct 3, 2011 at 16:49

2 Answers 2

15

This is the perfect place for the Builder Pattern.

MyClass someInstance = (new MyClassBuilder())
    .setParam0(param0)
    .setParam5(param5)
    .build();
4
  • 1
    The Builder pattern is explained in more detail in Effective Java. amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683/…
    – user28988
    Oct 3, 2011 at 17:13
  • Why not use an inner class: new MyClass.Builder()... ? It's hard to imagine two more tightly coupled classes. Oct 3, 2011 at 17:14
  • 1
    Note, you need a separate builder class to ensure the integrity of MyClass.
    – user1249
    Oct 3, 2011 at 17:19
  • I've done both inner classes and outer classes, and have found no preference between either myself.
    – tylermac
    Oct 5, 2011 at 14:05
1

while it's not particularly uncommon to see the chains...

the chained methods approach (to me) suggests that you are dealing with a class that is a data blob where all/most fields/members are publicly accessible and mutable, and that there really is no separation of members and interface (e.g. little substance beyond public accessors). these classes tend not to manage their dependencies correctly, and when they do, it is often quite costly compared to initialization proper. the abstractions are also likely to be weak.

at that point, the class has really meandered from good OOD because they have typically violated multiple OOD principles/concepts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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