Solution to d363: Bloated person
See code at solutions/code/tutorialquestions/questiond363
As in the solution to c2b8, the clue is in the name. The problem is that
Person
should be composed of objects from a number of different classes,
rather than being "bloated" with a flat list of fields. You can see that the fields of Person
are divided into several data clumps -- the fields associated with the person's name,
the fields for their address, the fields for their date of birth, and their national insurance
number field. These data clumps should be extracted into their own classes, one per clump.
There are some deliberate mistakes in Person
, but I hope you agree that it would
be very easy to genuinely make these mistakes with the flat design. In the constructor, the dayOfBirth
field gets the value of the houseNumber
parameter, and the postCode
and
nationalInsuranceNumber
fields are each initialised using the parameter intended for
the other.
In the sample solution, classes Name
, Address
, Date
and NiNumber
have been created. After fixing the bugs in Person
, this class has been refactored to make
use of these classes. The Person
class is now much easier to read. The chances of making a mistake
in the constructor assignments are vastly reduced: to see this, think about what you would have to write to
swap post code with national insurance number in the solution.
The various methods of Person
have been distributed to the classes that should be responsible
for providing these services. For example, getInitials
now belongs to Name
.
The original toString
method of Person
has been distributed across the new classes:
for each class, toString
has been implemented appropriately, and Person
's toString
works by (implicitly) calling toString
on the Person
's fields.
Also notice that the sameAddress
of Person
now simply calls the equals
method of
Address
, which has been implemented appropriately (overriding the equals
method of Object
).
You may wonder why I made a class NINumber
, instead of simply using a String
. This is to guard
against accidental assignment of a String
that does not represent a national insurance number to the
national insurance number field of a Person
.