Is it better to have constructors with or without parameters and why?
public NewClass( String a, String b, int c) throws IOException
{
//something
}
OR
public NewClass()
{
//something
}
Software Engineering Stack Exchange is a question and answer site for professionals, academics, and students working within the systems development life cycle. It only takes a minute to sign up.
Sign up to join this communityIs it better to have constructors with or without parameters and why?
public NewClass( String a, String b, int c) throws IOException
{
//something
}
OR
public NewClass()
{
//something
}
A constructor should establish the initial invariant of your object, that is, put it in a valid and usable state.
If your object is not really usable as an instance of the type it is after construction, it's a sign that you've got a bit of a smear between initialization of the object and use of the object.
If it's impossible to provide all the information needed up-front to construct your object properly, you may want to consider some sort of builder to gather state incrementally before instantiating the object.
In general, zombie-type objects which have initialization after construction and invalidation before disposal tend to be error-prone, particularly if there is no language support for it, leaving you to enforce the concepts in documentation and assertions.
I prefer constructors with parameters and there are two main reasons:
I don't think there is anything wrong with getter setters, but I typically only use them in a 'builder' or 'bean' class.
You should favor parameterless constructors.
There's two main reasons for this, the first being that constructors have no good way to report errors. Sure, you can toss exceptions but that's a fairly high impact response to simple bad data - it forces the users of your object to treat it with undue care since any creation can throw.
The second is that it can sometimes (in some languages especially) cause disconnects (or duplicated code) between the validation for constructor setting and property setting to enforce your invariance. Since the class invariants are the same, the validation should be the same. By allowing two effective ways to set values, it complicates the class' validation.
To be clear, I'm not saying to never have parameterized constructors. And I'm definitely not saying to have some Initialization method. What I'm saying is that objects should have a clear, well-defined initial state with sane defaults.
Sometimes objects can't have sane defaults and instead need their initial state passed to them. It happens. But in general, you should look to avoid it.