Paw Paw - 5 months ago 8
Java Question

Is there shorthand in Java to call a bunch of class methods in a row?

Hey, all! New java programmer here, trying to learn good style. Is there a shorthand to call a bunch of class methods in a row? Like say I wanted to do:

Dog gus = new Dog();

gus.fetch();
gus.sit();
gus.lieDown();
gus.rollOver();


In VBasic, for example, I could enclose it all in a With block. Does java have anything similar?

Answer

You've got a couple of options. I think you want patterns. You could build a helper method that calls all of the methods. Your other option is to have your methods return the parent object.

public Dog fetch(){
    //Do stuff for fetch
    return this;
}
public Dog sit(){
    //Do stuff for sit
    return this;
}
public Dog lieDown(){
    //Do stuff for lieDown
    return this;
}
public Dog rollOver(){
    //Do stuff for rollOver
    return this;
}

Then you can call them like:

Dog gus = new Dog();

gus.fetch().sit().lieDown().rollOver();