Should all classes have a default constructor as part of good coding convention

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.

5

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).

3

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).

1

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.

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.

1

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.

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật