This post originated from an RSS feed registered with Java Buzz
by Marc Logemann.
Original Post: Use constructor chaining
Feed Title: Marc's Java Blog
Feed URL: http://www.logemann.org/day/index_java.xml
Feed Description: Java related topics for all major areas. So you will see J2ME, J2SE and J2EE issues here.
Recently i had the pleasure to review a lot of third party java code and one thing that i realized is that many programmers dont know how to handle components / classes with a lot of constructors. I saw redundany of property assignment and an overall poor approach in defining multi-constructor classes.
I really prefer to do constructor chaining whenever possible, this way, your classes keep the complexity low and the last constructor in you chain is a perfect place to do changes.
Just check out JTextField from Sun to see what i mean:
01
02 public class JTextField extends JTextComponent implements SwingConstants {
03
04 public JTextField() {
05 this(null, null, 0);
06 }
07
08 public JTextField(String text) {
09 this(null, text, 0);
10 }
11
12 public JTextField(int columns) {
13 this(null, null, columns);
14 }
15
16 public JTextField(String text, int columns) {
17 this(null, text, columns);
18 }
19
20 public JTextField(Document doc, String text, int columns) {
21 if (columns < 0) {
22 throw new IllegalArgumentException("columns less than zero.");
23 }
24 visibility = new DefaultBoundedRangeModel();
25 visibility.addChangeListener(new ScrollRepainter());
26 this.columns = columns;
27 if (doc == null) {
28 doc = createDefaultModel();
29 }
30 setDocument(doc);
31 if (text != null) {
32 setText(text);
33 }
34 }
35 [..]
36 }
Its really not that surprising and its in no way new to do it this way, but i just saw too much of weird things happening inside the classes of other programemrs when it comes to multiple constructors.