Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
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 '11 at 16:49
up vote 15 down vote accepted

This is the perfect place for the Builder Pattern.

MyClass someInstance = (new MyClassBuilder())
share|improve this answer
+1 This is generally accepted practice. – Martijn Verburg Oct 3 '11 at 16:39
The Builder pattern is explained in more detail in Effective Java.… – World Engineer Oct 3 '11 at 17:13
Why not use an inner class: new MyClass.Builder()... ? It's hard to imagine two more tightly coupled classes. – kevin cline Oct 3 '11 at 17:14
Note, you need a separate builder class to ensure the integrity of MyClass. – user1249 Oct 3 '11 at 17:19
I've done both inner classes and outer classes, and have found no preference between either myself. – tylermac Oct 5 '11 at 14:05

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.

share|improve this answer

Your Answer


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.