Expert Spring MVC and Web Flow

(Dana P.) #1
For lack of a proper Moneytype, we use BigDecimalfor all monetary values. Why not simply
use doubletype? The short answer is that double’s value isn’t exact, and there’s no absolute
control over rounding. With BigDecimalyou get precise control over rounding, exact decimal
values, and immutability. If you find this class inconvenient to use, consider using intor long
to represent pennies (or your smallest unit of money). For applications where rounding impre-
cisely can cause problems, such as interest calculations, use BigDecimal. For our purposes, using
longto represent the number of pennies would have sufficed, but then we wouldn’t have been
able to bring you the next plug for Effective Java.

■Tip For more information on why you should avoid floatand doublewhen exact answers matter,
consult Item 31 from Effective Java.

Notice how we have also made defensive copies of all java.util.Dateobjects passed into
the object. For objects that are not immutable, like Date, it’s a best practice to make your own
copies of the arguments before storing in the class or using with some business logic. By using
this technique, you are protecting your class, as the client could change the internal value of
the argument after passing in the object, potentially creating odd or inconsistent states. We
did not make copies of the Airportinstances, because they are immutable, as you’ll see
shortly.
The use case also mentions that special deals are good only for a limited time, which
sounds like business logic to our ears. To encapsulate this logic, we’ve added beginOnand
endOnproperties along with isValidOn()and isValidNow()methods. Even inside isValidOn()
we make a defensive copy of the Date argument to ensure its consistency during the validity
calculation.

Design Decisions
Although we’d much like to believe the opposite, it’s not entirely possible to design layers in
total isolation. For example, the choice of persistence framework can govern the design deci-
sions we make when building the domain model. A little foresight can alleviate many
frustrations later.
Case in point is Listing 4-2’s SpecialDealclass. We chose to make the class immutable—
for safety reasons, and because it models more correctly an immutable concept (a special deal
can’t change, but it can be deleted and a new one can take its place). However, will the persist-
ence framework of choice be able to populate the fields on load or use classes without a
default constructor?

■Tip If using Hibernate, set the access type to “field” in order to use reflection to set the fields instead of
property access, which uses setters. Also, you can tell Hibernate that the class is immutable by setting muta-
ble to false,in which case Hibernate will perform small optimizations.

44 CHAPTER 4 ■JUMP INTO SPRING MVC

Free download pdf