André Spironello
André Spironello

Reputation: 146

How to create chained methods in Java

I have a class responsible for controlling the objects created during runtime - it builds them from inputs at swing frames - just as a DAO. It has this method that removes already created objects:

public void removeFrom(Class<?> clazz, int index) {
    for (Map.Entry<String, Object> entry : modelsMap.entrySet()) {
        if (entry.getKey().equals(clazz.getSimpleName())) {
            ((ArrayList<Object>) entry.getValue()).remove(index);
        }
    }
}

Instead of calling this method and passing the referent class and index, I'd like the method call to be like this: dao.removeFrom(MyObject.class).at(myIndex); Guess it's looks like chained methods as the Stream API uses. Glad if anyone can help me!

Upvotes: 0

Views: 609

Answers (3)

davidxxx
davidxxx

Reputation: 131466

You could introduce a DaoRemover class that you can instantiate by a factory method and which the instance methods return the current instance.

For example :

public class DaoRemover {
    private Map<String, Object> modelsMap; // your actual data
    private final List<ArrayList<Object>> list; // list of list after filtering on the class


    public static DaoRemover of(Class<?> clazz) {
        return new DaoRemover(clazz);
    }

    private DaoRemover(Class<?> clazz) {
        list = modelsMap.entrySet()
                        .stream()
                        .filter(e -> e.getKey()
                                      .equals(clazz.getSimpleName()))
                        .map(e -> (ArrayList<Object>) e.getValue())
                        .collect(toList());
    }

    public DaoRemover at(int index) {
        list.forEach(l -> l.remove(index));
        return this;
    }

}

You could do now :

DaoRemover.of(MyObject.class)
          .at(myIndex); 

or

DaoRemover.of(MyObject.class)
          .at(myIndex) 
          .at(myOtherIndex); 

Upvotes: 0

Ivan
Ivan

Reputation: 8758

In this case your removeFrom() method should return wrapper around ((ArrayList<Object>) entry.getValue()). And that wrapper has to have method at(int index) which removes element for given index.

And you also need to think about corner case when your modelsMap doesn't have entry for a given clazz.

Upvotes: 2

janardhan sharma
janardhan sharma

Reputation: 335

Please check on the Builder design pattern. Try creating builder design pattern for a simple object which has few attributes and getters and setters.

Once you are able to do that, method chaining will look very clear. :)

Upvotes: 0

Related Questions