Why chaining constructors is bad.

Why chaining constructors is bad

I personally find that this code snippet demonstrating constructor chaining is hard to read.

This code makes it very hard to identify which of the many constructors is the "real" one:  the constructor that does the real job and that I should call if I add a new overloaded constructor.

This is why I use the following two rules when I write overloaded constructors:

  • Have all your constructors converge toward one unique private method that you will name consistently throughout your code base (e.g. init) and that will contain the entirety of all the parameters that your constructors may receive.
  • Don't add any logic to the constructors, all they should do is invoke init with the right parameters and null for default ones.

Here is an example, from worst:

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, String lastName) {
    m_firstName = firstName;
    m_lastName = lastName;
  }
... to better:
  public Person(String lastName) {
    this(null, lastName);
    m_ssn = getSsn();
  }

  public Person(String firstName, String lastName) {
    m_firstName = firstName;
    m_lastName = lastName;
  }
... to best:
  public Person(String lastName) {
    init(null, lastName);
  }

  public Person(String firstName, String lastName) {
    init(firstName, lastName);
  }

  private void init(String firstName, String lastName) {
    m_firstName = null;
    m_lastName = lastName;
    if (null == m_firstName) {
      m_ssn = getSsn();
    }
  }

Here is why the latter form is preferable:

  • It doesn't 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 constructors is bad' from Otaku, Cedric's weblog.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值