Question

Using Lambdaj, I am trying to isolate, from a list, an object that satisfies 2 separate criteria. Both of the following will achieve my goal. A)

    List<SomeObject> someObjectsWithMatchingSomeObjectIds = select(foo.getSomeParentObject().getSomeObjects(), having(on(
            SomeObject.class).getId(), equalTo(123)));
    SomeObject someObject = selectFirst(someObjectsWithMatchingSomeObjectIds, having(on(SomeObject.class).getLoanTerm(),
            notNullValue()));

B)

    SomeObject someObject = selectFirst(select(foo.getSomeParentObject().getSomeObjects(), having(on(SomeObject.class)
            .getId(), equalTo(123))), having(on(SomeObject.class).getLoanTerm(), notNullValue()));

The first one seems more readable, particularly for people who are not familiar with the API. The second one seems to harness the functional programming aspect of lambdaj, which is best?

Readability wins I suppose. However, I wonder, is there a more concise way to handle two separate conditions when filtering a collection, using LambdaJ?

Was it helpful?

Solution

Removing intermediate definitions is not "more in the spirit" of much anything, and in general hurts readability. Having an intermediate definition helps having each line of the program simpler to read, and can be a great readability help when you can give the identifier a meaningful name -- not sure it's really the case in your code.

You could have a readability win, I think, by not applying two filtering operations, select and then selectFirst, but using only one operation that combines the two matching condition with an and (beware, code not tested):

SomeObject someObject = selectFirst(foo.getSomeParentObject().getSomeObjects(),
                                    and(having(on(SomeObject.class).getId(), equalTo(123)),
                                        having(on(SomeObject.class).getLoanTerm(), notNullValue()));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top