Is this code convertible to a lambda style?

Samir Talwar samir at noodlesandwich.com
Sat Dec 28 07:32:21 PST 2013


That `convertToPropertyOrNull` method won't be useful, and in fact isn't
possible to use like that. You would use it like this:

    return
convertToPropertyOrNull(getMetadataReader().blahblahblah().findAny());

I actually think this is harder to read because it combines the nested
function style with the method pipeline style. You're better off sticking
to the original for that part, IMO.

Howard is totally right to show you how to extract `hasChildAssociation`.
In general, complexity with lambda-ified code should follow the same rules
as complexity in regular code: when in doubt, extract it out. I'd argue
that the real problem here, though, is too much Spring; some proper OO code
following the tell-don't-ask principle will help you clean this up far more
than lambdas can, and a mix of both really does work wonders.

One more thing: you could change `d -> d.convertToProperty()` to
`PropertyDescriptor::convertToProperty`. IntelliJ will suggest this
refactoring for you if you load up the code there.

— Samir.


On Sat, Dec 28, 2013 at 2:37 PM, Marcos Antonio <
marcos_antonio_ps at hotmail.com> wrote:

> Hello, Howard. Thanks for the suggestions to improve the code.
>
> I really liked the increased abstraction by the introduction of the static
> hasChildAssociation() method. That really made the code more clear and
> readable. The tip about the findAny() method was also useful, I will change
> it, although I have my doubts if the introduction of a
> convertToPropertyOrNull() method is needed.
>
> Thank you once again.
>
> Marcos
>
> ________________________________
> > Date: Sat, 28 Dec 2013 11:56:59 +1100
> > Subject: Re: Is this code convertible to a lambda style?
> > From: howard.lovatt at gmail.com
> > To: marcos_antonio_ps at hotmail.com
> > CC: lambda-dev at openjdk.java.net
> >
> > Hi Marcos,
> >
> > I would make some small changes:
> >
> > private static boolean hasChildAssociation(PropertyDescriptor d) {
> > return
> >
> DataFactory.getInstance().getMetadataReader(d.getReaderMethod().getReturnType()).getCollectionDescriptors().stream()
> > .anyMatch(c -> c.isChildAssociation(d)));
> > }
> >
> > private static Property
> > convertToPropertyOrNull(Optional<PropertyDescriptor> d) {
> > if (d.isPresent()) {
> > return d.get().convertToProperty()
> > }
> > return null;
> > }
> >
> > return getMetadataReader().getPropertyDescriptors().stream()
> > .unordered() // Assuming that order is not important
> > .parallel() // Assuming that there are a lot of Properties
> > .filter(d -> d.getType() == PropertyType.ENTITY)
> > .filter(ThisClass::hasChildAssociation)
> > .findAny() // Potentially faster
> > .map(ThisClass::convertToPropertyOrNull);
> >
> > Cheers,
> >
> > -- Howard.
>
>


More information about the lambda-dev mailing list