0

I have quite a few places where I need to get an object, perform some side effects based on the state of that object, then finally return the object. For a specific class Foo, I can write a method

public Foo perform(Consumer<Foo> sideEffect) {
    sideEffect.accept(this);
    return this;
}

Simple enough, but I'd like to not have to rewrite it for every class, and I'd also like it to work for classes that aren't mine. I can't add this method to Object, and I'd rather not make a subclass of Consumer that returns the argument. Is there a better way to do this?

dnault
  • 8,340
  • 1
  • 34
  • 53
Alex Jones
  • 226
  • 3
  • 13
  • Create a static method perform which accepts your object and sideEffect? –  Sep 20 '19 at 23:57
  • I can do that, but it doesn't quite flow with the "functional" foo().bar().baz() style of the surrounding code. – Alex Jones Sep 21 '19 at 00:04
  • If all your classes can extend a common base class, this might help: https://stackoverflow.com/questions/17164375/subclassing-a-java-builder-class – dnault Sep 21 '19 at 05:28

1 Answers1

3

You can write a generic utility method which accepts a Consumer<? super T> and T type arguments and get this thing done. Notice that you have to use method level generics here. Here's how it looks.

public static <T> T perform(Consumer<? super T> sideEffect, T obj) {
    sideEffect.accept(obj);
    return obj;
}
Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63