by Conrad Weisert
August 8, 2013
© 2013 Information Disciplines, Inc.
|"Provide as good support for user-defined types as for built-in-types."||"You should always make small value objects, such as
Those two bits of advice appear to be in direct conflict with each other.
+=operator as primitive and then define the simple
+operator in terms of it.
Of course Java doesn't support overloaded operator syntax, so Bloch's warning often goes
unnoticed by Java programmers, who tend to avoid numeric objects anyway. If you follow Bloch's advice
you mustn't even simulate the compound operator with an
method. But then
Bill Wagner, writing about C#, a more flexible language
than Java, echoes Bloch's advice.
Those four OOP experts actually agree, once we clarify the essential distinction that eluded them1:
PhoneNumber example is apt. Programs don't do
arithmetic on telephone numbers. But his
doesn't fit the purpose or the spirit of numeric objects. He probably just didn't think about it
carefully. If we prohibit straightforward code like this:
Complex x, y;
x += y;
then we burden our program in two ways:
If Bloch and Wagner are more concerned about accidental (or malicious) data modification than about
either efficiency or readability, then the object-oriented languages provide other tools they can draw
upon. The user program is free to create
final objects. However, the nature of typical numeric
computation renders such concerns unlikely. Why does a
Money item need more protection against accidental
change than a
double or a
Return to Technical articles
IDI Home page
Last modified August 8, 2013