0

I'm writing a library, for more readability I want to force user to use nested methods to call the correct functions.

For example this is my class looks like:

public class Foo{
public void methodA(){}
public void methodB(){}
public void methodC(){}
}

What I'm expecting the user:

Foo foo = new Foo();
foo.methodA.methodB();
foo.methodA.methodC();

to call method B & C through calling the methodA as a prefix

3 Answers3

2

After reading your question i think you are asking about Builder Design patten in which every methods return type is same class object and you can make call hierarchy like this.

obj.aMethod().bMethod().cMethod();

in your example just do like this:

public class Foo{
 private static final Foo instance = new Foo();
 private Foo(){}

 public static Foo getInstance(){
    return instance;
 }

 public Foo methodA(){
  //Do stuff 
  return getInstance();
 }
 public Foo methodB(){}
 public Foo methodC(){}
}

Now you can call like objfoo.getInstance().methodA().methodB();

Hope it will help you. To read more about that pattern

Intsab Haider
  • 3,491
  • 3
  • 23
  • 32
0

This is called as method chaining. You will need to set the return type of all methods as the same as the Class.

public class Foo{ 
public Foo methodA()
public Foo methodB() 
public Foo methodC() 
}

Now the client can simply call:

foo.methodA().methodB(), etc. 

You can have one "terminal method" i.e. one that does not return a value. For example

public void methodD();

This method will be called last.

foo.methodA().methodB().methodC().method();

This line in itself will be valid as return type is void.

Please look at method chaining/ builder pattern YouTube videos, it will be clear.

kush
  • 486
  • 4
  • 6
0

To force the user to use methodA to access methodB you could use an inner class. In methodB you can access the Foo-Object with Foo.this.

public class Foo{
   public Bar methodA()
   {
       // ...
       return new Bar();
   }

   public class Bar {

      private Bar() {}; // only methodA can create a Bar object

      public void methodB(){}
      public void methodC(){}

  } 
}
Turo
  • 4,724
  • 2
  • 14
  • 27