Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

From the texts I have read so far, the conventions talk about organizing constructors, starting with the default, if any. I am wondering, should all classes have a default constructor anyway. This will at least help to create a simple instance of the class on the fly, without having to use a parameterized constructor, which itself may require additional imports for specific parameter type.

share|improve this question
1  
Is this specific to a language or are you asking in general? –  whaley Jun 14 '13 at 17:39
2  
This may vary by language, as some languages may specify that a default no-arg constructor should be automatically created (probably by the compiler) if none is given. –  FrustratedWithFormsDesigner Jun 14 '13 at 17:40
    
Blanket statements that include the words 'all' or 'never' are, in my mind, suspect. Some class instances won't be meaningful without initialization. –  Dan Pichelman Jun 14 '13 at 17:41
    
@whaley I mean in general, but for a reference language you can consider C++/C#/JAVA/PHP. –  Shamim Hafiz Jun 14 '13 at 17:45

6 Answers 6

up vote 8 down vote accepted

Generally speaking, you should have constructors for classes that take enough parameters to properly initialize the object being created into a valid state. If your class is able to provide sane defaults for all fields that comprise a valid state for objects of that class, then a default constructor is most likely a good idea.

Also, some libraries require the existence of a default constructor for certain operations. For instance, libraries in Java used for deserializing json/xml often require a default constructor to be invoked via reflection since those libraries will attempt to evaluate everything at runtime and can't know in advance what constructors are available to be used - so they expect a default constructor. In instances like these if a default constructor is required by tooling, but should not be called by anything you control or any users of your API, it's best to use the the common idiom of your language to mark the constructor as private (e.g. private access in typical statically typed languages).

share|improve this answer
1  
+1 even though the "some libraries require the existence of a default constructor for certain operations" is actually an anti-pattern. We all have to deal with it, but I sure wish it wasn't so. –  Ross Patterson Jun 23 '13 at 16:50
    
@ross-patterson could you provide some further reading on why that's an anti-pattern? I dislike it because it means there's a way I can instantiate an object (albeit with reflection/misc hacks) in which the invariants of the class aren't enforced. Is there anything beyond this problem that's particularly bad? –  whaley Jun 24 '13 at 14:25
1  
You hit the nail on the head. If the class can't function properly when built via new Myclass(), then Myclass() shouldn't exist. Period. Libraries (especially, as you say, serialization libraries) that demand this, are the Tool of the Devil. –  Ross Patterson Jun 24 '13 at 23:05

The reason that some classes opt to have only a complex constructor is often that they cannot work usefully without knowing core information about an instance. Being able to create a trivial instance is not benefit in this case - in fact, it is probably a disadvantage, because then all methods must be able to deal with an object that is missing crucial data! By disallowing this, you can often establish invariants for a class that save a lot of coding time and run-time effort.

A general rule about what constructors you "should" or shouldn't have has little weight against such class-specific considerations. In practice, the only valid reason for enforcing a trivial constructor I have ever seen is if you hand your objects to a framework that itself requires one. Even then I'll probably make the constructor private if I can get away with it.

share|improve this answer

There are two cases where default constructor makes little sense:

  1. Reliance of a class on its field or property.

    Imagine a series of classes which load statistical data from the database and display it in a chart. One of the classes, DataTransform, normalizes the data from the database in order to be used in a chart. This class uses a IDataProvider which feeds DataTransform with raw data.

    In order to be testable and interoperable, you have four classes implementing IDataProvider: the one for Oracle, the one for Microsoft SQL Server, the one which loads data directly from XML and finally the mock to use in unit tests.

    Having a default constructor would force you to:

    • Check in nearly every method of DataTransform that IDataProvider dataProvider field was initialized,

    • Expect anyone using the class to either call the parametrized constructor, or call the default constructor and then set the data provider through an additional property or method.

    This indicates a serious problem in the design. Throwing away the default constructor and having exclusively the constructor which takes the data provider as a parameter makes the class more intuitive to use, and its own code simpler.

  2. Immutable objects for which defaults make no sense.

    Imagine an immutable Person who has as properties FirstName, LastName and BirthDate. While first and last names can be defaulted to an empty string (or null, if the language authorizes null strings), what would be the birth date? The minimum authorized date? Why would you ever want an immutable person who has no name and was born in January 1st, year 1?

    Note that immutability alone doesn't mean that there should be no default constructor. For example, it makes sense to have a default constructor for Point, resulting in Point(x = 0, y = 0); another way is to have a static constant Point.Zero. Another example: it makes perfect sense to have a default constructor for an immutable String (either a null or an empty string).

share|improve this answer
    
Immutability is often a good argument against using a default constructor; even if a sensible default would exist (e.g. an immutable always-empty collection) it's generally better to encourage the use of a singleton than construction of needless instances. –  supercat Jan 13 at 18:09

Depends on your coding style and the patterns you implement. With Dependency Injection (DI) you'll often find yourself only having a default constructor when you actually need one - be it for XML serialization or whatever. Being biased with DI, I would tend to say no, you don't need a default constructor, since the only work that gets done in a constructor, is the injection of the class' dependencies: constructors become a static documentation of a type's dependencies.

share|improve this answer

Absolutely not. Default ctor is due if the class can be sensibly constructed without any info coming from outside. (If you limit the question to that subset, the answer turns to yes.)

Otherwise having a default ctor forces two-stage initialization with all the drawbacks it draws in. We chose it only for extremely good reasons.

share|improve this answer
    
Some languages (Like C#) sport object and collection initializers that bypass the problem you mention in your last sentence. –  Benjamin Gruenbaum Jun 14 '13 at 19:10

I don't like blanket all or nothing recommendations. On those terms alone I'd say no.

Do consider any practice case by case. No silver bullets.

Only create a default constructor if you have a need for it. YAGNI is a better coding convention.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.