I have an interface :
public interface I {
getBar();
}
I have 2 class : A and B implementing I.
What I want to do is :
public void foo(List<I> items) {
for (I item : items){
if (item instanceof A) this.append((A) item);
if (item instanceof B) this.append((B) item);
}
}
Is there something as of java 8 that would allow me to not have that list of instanceof and call it like this ?
items.foreach(this::append);
Note :
I could do something like item.add(this) which would append itself to this but then I would call a method on an object that modifies the parameter (and only it) but this is bad practice as stated by Robert C. Martin's "Clean Code" :
Arguments are most naturally interpreted as inputs to a function.
Anything that forces you to check the function signature is equivalent to a double-take. It’s a cognitive break and should be avoided. In the days before object oriented programming it was sometimes necessary to have output arguments. However, much of the need for output arguments disappears in OO languages
append(A)andappend(B)at all? The design looks quite iffy to begin with.append(I)and then inside of it you perform different things based on type.append(I)toadd(I)and you have what's in the note.append(A)andappend(B)much different?