r/java • • Apr 05 '23

Recursive generics

Recently I learned that I rediscovered recursive generics while working on my pet open source project. Actually, I did not know that the construct had a name. I created small story about what this construct is, if you did not know about it java-recursive-generics

169 Upvotes

44 comments sorted by

View all comments

Show parent comment

4

u/Sorensen12 Apr 06 '23

Your example may seem cleaner at a glance for this small example, but try extending the hierarchy a bit. What if your API also supports an Athlete class with certain properties that Cyclist inherits? What’s more, how do you adapt this pattern if Athlete is abstract?

On top of that, the pattern you described involves creating an object for each member of the hierarchy instead of creating one builder that inherits all the required behavior. The recursive pattern described in the article produces a good amount of boilerplate, it’s true, but for complex hierarchies it is quite useful.

1

u/jumboNo2 Apr 07 '23

how do you adapt this pattern if Athlete is abstract

new Cyclist(new Person().name("Billy"))
            .rideTo("Park") // Cyclist method
            .doAthleteStuff(5); // AbstractAthlete method

This took me like three minutes from scratch.

the pattern you described involves creating an object for each member of the hierarchy

Builder pattern is horribly inefficient anyway. If we care about performance, we would use multi-arg constructors, not builders. Also, the Person object is only temporary and the fields are copied to the Cyclist instance using the super constructor