I have a class called RawReader that reads the bytes of some resource, parses them, then writes files to an output directory.
It makes sense to allow different types to be passed in as the source and destination to the constructor.
- Source: String (of file or URL), URL, File or InputStream
- Destination: String (directory) or File
However if I overload the constructor that leaves me with 8 different versions. If I wanted to add a third optional argument for example chunkSize I’d have 16 constructors!
On the other hand I could just have two constructors accepting (Object, Object) and (Object, Object, int). The argument types could be detected and an IllegalArgumentExceptions thrown if they aren’t correct.
How are situations like this normally handled in Java?
You can use a builder:
Where
.build()invokes a constructor ofFoothat takes the builder and assigns whichever variables are set. Something like that:public class Foo {
}