Why you should return “this” from your setter methods.

Fortunately most API designers know to use this technique, but it’s still pretty common to find some that do not. It’s generally good practice, that when writing a setter method for a class, that you return the object’s “this” rather than “void”. The reason is that it allows a user of your class to chain together setter methods and save some typing and screen space. For example:

SomeObject o=new SomeObject().setTextSize(5).setBackgroundColor(Color.BLUE).setSomeOtherProperty(true);

The alternative would look like:

SomeObject o=new SomeObject();

The first example is much more concise and uses up much less screen real estate for someone reading the code, and also requires less typing. Granted the second example is much easier to read. But you should leave it up to the developer to determine which style they want to use.

In order to enable such a feature, all you need to do is return “this” from your class’ setter methods. For example:

public SomeObject setTextSize(Integer textSize){

     return this;

Since almost all setter methods do not return a value, this can easily be added to a class.

An alternative in some situations, is where the developer is likely to want the old value (usually because they want to restore it when they’re done). For example:

public Integer setTextSize(Integer textSize){
     Integer temp=this.textSize;
     return temp;

If you have some methods that return the previous value of a setter, it’s generally not a good idea to mix returning “this” and previous values inside the same class. It would be difficult and cumbersome for a user to remember which functions return the object, and which functions return the previous value, and may try to chain together setters that aren’t possible. Such a situation would be particularly problematic if the object returned from your setter actually had a valid function that the user was trying to call.

There is also a small amount of overhead in returning an object that will just be ignored in many (or most) circumstances. But, in almost all circumstances, this small amount of overhead is negligible.

Leave a Reply