Classes Vs. Built-in Types

Source: comp.object
Date: 20-Oct-98

Related Sites


------------------------------

o-< Problem: Should you use classes even for trivial data?


---------------

o-< John Burton asked:

[...] I've stored a telephone extension number as in "int" attribute of a more complex class. At what point is it worth making that a class of it's own?

My thoughts against the idea are that it adds complexity to the design increasing the chance of errors and slowing down the program.

My thoughts for the idea are that a telephone number is not really an integer, it just happens to be convenient to store it in one. [...]


---------------

o-< Gerhard Menzl replied:

Suppose that at some time in the future, phone companies start to introduce telephone numbers that contain letters because they run out of decimal numbers, or they stick to decimal digits but the numbers get longer than an int can hold. Now ask yourself whether you would rather do the job of incorporating the changes into an application that uses "int", or one that uses "class PhoneNumber". You will quickly find that the additional complexity caused by introducing another class type is nothing compared to the complexity caused by changing all those ints.

Whether a concept is better represented by a built-in type or a class has nothing whatsoever to do with size, but everything with encapsulation, decoupling, and resilience to change. A class can be without any data members at all and yet be useful. OO languages other than C++ often don't even distinguish between built-in types and classes.

Your apprehensions about slowing down the program by introducing a class are completely unfounded. Most modern compilers do a much better job at micro-optimizing than people, at least for typical applications. Some OO constructs can be faster than their hand-coded procedural versions. [...]

Of course, you can overdo it, but most of the time (and definitely in your example) when your find yourself wondering "gee, this looks like it could be a class of its own", you're on the right track.


---------------

o-< Robert C. Martin presented other reasons to use classes:

  1. Type safety.
      void f(Extension& e);
    One cannot pass anything but an Extension (or a derivative of Extension) into the function f.
  2. Reduce inadvertent errors.
    [...] there are invalid exchanges such as 000. Your class can detect these very early.
  3. Clarity of expression.
    void f(int) is not nearly as clear as void f(Extension& e);
[...]

There is a perception that lots of little classes increase complexity. (They don't, they actually decrease it by decreasing options).


------------------------------

o-< More Info:

Ward Cunningham, The CHECKS Pattern Language of Information Integrity
(See the Whole Value pattern)


------------------------------