Why chaining constructors is bag.

xiaoxiao2021-03-06  41

Why Chaining Constructionors Is Bad

I Personally Find That Code Snippet Demonstrating Constructor Chaining Is Hard To Read.

This Code Makes It Very Hard to Identify Which of The Many Constructionors Is The "Real" ONE: The Constructor That Does The Real Job and That I SHOULD CALL I Add A New Overloaded Construction.

This is why i use the folload two rules when i write overloaded Constructionors:

Have all your constructors converge toward one unique private method that you will name consistently throughout your code base (eg init) and that will contain the entirety of all the parameters that your constructors may receive. Do not add any logic to the constructors, all . t.........

Here is an example, from workt:

Public class person {

Private string m_firstname = null;

PRIVATE STRING M_LASTNAME = NULL;

PRIVATE long m_ssn = 0;

Public Person (String lastname) {

m_firstname = NULL;

m_lastname = lastname;

m_ssn = getssn ();

}

Public Person (String firstname) {

m_firstname = firstname;

m_lastname = lastname;

}

... to better:

Public Person (String lastname) {

THIS (NULL, Lastname);

m_ssn = getssn ();

}

Public Person (String firstname) {

m_firstname = firstname;

m_lastname = lastname;

}

... to best:

Public Person (String lastname) {

INIT (NULL, LASTNAME);

}

Public Person (String firstname) {

INIT (FirstName, Lastname);

}

Private void init (String firstname) {

m_firstname = NULL;

m_lastname = lastname;

IF (NULL == m_firstname) {

m_ssn = getssn ();

}

}

Here is why the latter form is preferable: It does not duplicate any code It makes the initialization rules clear:.. "If no firstName was given, then ssn gets initialized" The signature of init gives a good indication of the various parameters this Class Needs to Be Initialized, While a Multitude of Overloaded Constructors Obscures this fact.

TRACKBACK URL for this entry:

http://beust.com/weblog/mt-tb.cgi/205

Listed Below Are Links to Weblogs That Reference

'Why Chaining Constructionors Is Bad' from

Otaku, Cedric's Weblog.

转载请注明原文地址:https://www.9cbs.com/read-56295.html

New Post(0)