Having methods with different names for roughly the same task makes sense, for example
open(String filename);
createThenOpen(String filename); // First create the file with default contents, then process the file.
This naming approach does not work for constructors. Imagine the constructor takes a filename as above. I have various options to handle the two cases:
MyClass(String filename, boolean createNew)
. Not very nice because a call like MyClass("hello.txt", true)
is cryptic.RandomAccessFile(File file, String mode)
where mode
is "r"
, "rw"
and so on. This feels very clunky for my purposes.enum
-flag similar to Files
's copy(Path source, Path target, CopyOption... options)
. Feels pretty clunky too.Currently I seem to actually favour number (6) above and simply have two methods with different names to be called immediately after a no-parameter constructor. Have I overlooked any options, or is there a "given" approach for these scenarios?
Edit: as pointed out by others below there is a 7th, perhaps most obvious option, of course:
Make your constructor with a long list of parameters protected
, introduce a lot of public static
named createFooWithBar()
methods with precise parameter lists that call your constructor.