Smooth Java – Part 1.1: Initialize object with too many attributes

Tram Ho

When building complex objects, we often encounter the situation of having to create a constructor containing many parameters. For example, we need to build a Team object that includes the following properties:

  • Required (required parameter) : memberNum
  • Maybe or not (optional parameter) : designerNum, editorNum, engineerNum, mentorNum, … (there can be a lot)

Assumption: Most Team objects will not have all components such as designer, editor, …

Of course there are many patterns to build constructors for the Team class. So my job now is to analyze each one to show you how effective they are.

  1. Telescoping constructor pattern :

This way roughly will build the first constructor for all required parameters, then in turn the following constructors will add an optional parameter compared to the previous constructor.

You can see a possible problem is: wrong order of the parameters . Obviously, because the parameters here are of the same type, if the order is wrong (mistyped between editorNum and engineerNum), the compiler will not error, but it will cause the wrong operation (not as expected). This error is often difficult to figure out.

  1. JavaBeans Pattern :

This solves Telescoping’s problem by using a setter to initialize a value for each property.

When used will be:

Looks good? This reminds me of when I first learned about Java Swing, I had to set each property for the object. It is quite tiring when I want to change some property without knowing where to write it. Thereby, it is seen that it loses consistency. You may experience unexpected results when accessing an unset property. One way to get around this is to freezing the object – that is to disallow access until completion of initialization. However, it is of little use in practice since it will throws a lot of exceptions and moreover, because there is a better way outlined below.

  1. Builder Pattern : This approach helps you take advantage of both Telescoping’s consistency and JavaBeans’ legibility and ease of use.

The way is: instantiating an object (Team) through a Builder object (storing information on Team properties). Builder will be declared as a static member class in Team class

The Team initialization process includes the following steps:

  • First, call the Builder constructor to initialize the required parameters
  • Then, assign values ​​to optional parameters. Note that the value assignment methods are built for use in the same way as the setter
  • Finally, call the build function to create the object of the Team class. After the build function is called, that object becomes immutable .

It’s over. That’s all I got when reading Item 2 of the book Effective Java. My later articles will also refer to the Items in this book. Thank you everyone so much

Share the news now

Source : Viblo