Factories and constructors with default arguments

My legacy Java code has an abstract class we’ll call Foo, which has a bunch of subclasses. The code also has a FooFactory object with a createXXX() method for each subclass of Foo.

Now I’ve created a new subclass written in Kotlin. This subclass’ constructor has a bunch of parameters, but the user won’t need to specify all of them all the time. “Hey, let’s use default arguments!” I think, and set defaults for most of the parameters. Yay Kotlin!

But then I need to update the factory. And the factory’s metaphor of having one createXXX() method for each subclass breaks down here. The createXXX() method has to have all of the parameters that the subclass’ constructor takes. I could convert the factory to Kotlin and once again use default arguments so the user of the factory doesn’t need to specify each one, but the factory will just pass all the arguments to the constructor. Which means, what did I use default arguments in the constructor for?

What’s the best way to handle this? The factory method uses default arguments but the constructor doesn’t? Multiple create methods in the factory to handle different cases? Switch to a builder?

1 Like

Can we see a example. This though seems like a perfect use for default arguments and top-level functions. I’m not sure I’ve needed to use a factory method for kotlin I would always use top level functions with default parameters.

tl;dr: the only code you probably need to rewrite in kotlin (with default arguments) are the factory methods.

As you said : ‘user won’t need to specify all of them’ the only users of your abstract class constructor are… subclasses… the only users of your final classes constructors are… factory methods… So they probably are called in only 1 place : no need default parameters.
if you add default parameters in factory method, then all others are useless… except if you api also expose class hierarchy.