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

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

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

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

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.
{"cc_re__cc_re__cc_by_sa_3_0": ["        <li><a href=\"http://area51.stackexchange.com\" title=\"proposing new sites in the Stack Exchange network\">Area 51</a></li>\r\n                        <li><a href=\"http://careers.stackoverflow.com\">Stack Overflow Careers</a></li>\r\n                    \r\n                </ol>\r\n            </td>\r\n    </tr>\r\n</table>\r\n                </div>\r\n            </div>\r\n\r\n            <div id=\"copyright\">\r\n                site design / logo &#169; 2014 stack exchange inc; user contributions licensed under <a href=\"http://creativecommons.org/licenses/by-sa/3.0/\" rel=\"license\">cc by-sa 3.0</a> \r\n                with <a href=\"http://blog.stackoverflow.com/2009/06/attribution-required/\" rel=\"license\">attribution required</a>\r\n            </div>\r\n            <div id=\"svnrev\">\r\n                rev 2014.7.30.1735\r\n            </div>\r\n            \r\n        </div>\r\n    </div>\r\n    <noscript>\r\n        <div id=\"noscript-warning\">Programmers Stack Exchange works best with JavaScript enabled<img src=\"http://pixel.quantserve.com/pixel/p-c1rF4kxgLUzNc.gif\" alt=\"\" class=\"dno\"></div"], "copyright__copyright__copyright": ["asons.\n\nshare|improve this answer\n\nI don't like blanket all or nothing recommendations. On those terms alone I'd say no.\n\nDo consider any practice case by case. No silver bullets.\n\nOnly create a default constructor if you have a need for it. YAGNI is a better coding convention.\n\nshare|improve this answer\n\nYour Answer\n\n\u00a0\ndiscard\n\nBy posting your answer, you agree to the privacy policy and terms of service.\n\nNot the answer you're looking for? Browse other questions tagged or ask your own question."]}