Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When implement Predicate instead of boolean

I was reading a not related thread , when I read a comment: Any time I find myself needing a multi-line lambda, I move the lines to a private method and pass the method reference instead of the lambda.

I was asking: which is the correct way to implement this behaviour? With a boolean method as posted in comment, or with predicate?


Example: let's say I wanna check if a Table is usable, where usable means isClean, isEmpty, hasChair.

class Table{
    public boolean hasChair(){...}
    public boolean isClean(){...}
    public boolean isEmpty(){...}
}

I can implement my filtering test for my list List<Table> tablesList = Arrays.asList(table1,table2,table3,table4); in 2 ways: the first with boolean:

public boolean isUsable(){
    return hasChair() && isClean() && isEmpty();
}

And use it with tablesList.stream().filter(Table::isUsable)

The second way is with predicate:

public Predicate<Table> isUsable(){
    return table -> table.isEmpty() && table.isClean() && table.hasChair();
}

Usable with tablesList.stream().filter(isUsable())


Which is the correct implementation? Why choose one instead of other? Is there any big difference?

like image 270
Leviand Avatar asked Jan 02 '23 17:01

Leviand


1 Answers

I think you meant for the second example

public static Predicate<Table> isUsable(){
    return table -> table.isEmpty() && table.isClean() && table.hasChair();
}

Which might already suggest this form is likely to confuse the reader. Without static you could write table.isUsable() or Table::isUsable but it wouldn't do what you think.

Which is the correct implementation?

I would prefer the Table::isUsable as it can also be used as table.isUsable for an instance.

Why choose one instead of other?

I feel the first example is more natural and less confusing.

The second form is more useful for manipulating Predicates e.g. Predicate.or(Predicate)

Is there any big difference?

In this case, using a Stream is likely to be slower, but more importantly, more likely to confuse.

One advantage of the method returning a Predicate is it could be added to any class e.g. you can't alter Table for some reason.

like image 152
Peter Lawrey Avatar answered Jan 15 '23 05:01

Peter Lawrey