Skip to content
Advertisement

Chaining static methods

This might not have a solution, or I might have not been able to find one, but here it is:

!! Note: the code below is incorrect, I know. I just want to show what exactly I would like to accomplish.

I would like to do something on the lines:

public class ActionBarHandler{

    public static ActionBarHandler withAddOption(){
            //do something ...
        return ActionBarHandler;
    }
    public static ActionBarHandler withEditOption(){
           //do something ...
           return ActionBarHandler;
    }
}

… in order to do the below somewhere in another class (i.e. have it in a single line):

//..
ActionBarHandler.withAddOption().withEditOption().with........;
//..

… instead of doing this:

//..
ActionBarHandler.withAddOption();
ActionBarHandler.withEditOption();
ActionBarHandler.with........;
//..   

Can this be done in any way? With static methods, without having an instance of the class.

Advertisement

Answer

Yes, declare the method as

public static ActionBarHandler withAddOption(){

and simply return null.

But I don’t recommend this. Use objects with method chaining. From a conceptual standpoint, it doesn’t make sense to invoke a static method on an instance, even less on a null reference. For that reason alone, you should consider refactoring your design to chain instance method invocations, ie. use objects.

Advertisement