#13. Organize your code in classes

The minimal unit of code is a statement. The minimal unit of code which can be tested and reused is a function. Functions are rarely practical all by themselves; they are usually organized in modules which offer a set of operations which make as a whole.

The class is the main semantical unit in object oriented programming. A class is an abstract data type with an associated implementation. As Bertrand Meyer puts it in Object Oriented Software Construction, 2nd Edition:
Classes should be the only modules.
These concepts will not be obvious in the integrated development environment you use to create your code. Usually, these IDEs let you create projects, and inside them, they let you add units or files.

You know, of course, the C++ syntax; you know there are two keywords, class and struct, that let you define a type with its associated data members (fields) and operations (functions). You are probably aware of the difference between class and struct: the default visibility of its members.

For now, let's focus in class. You know you can apply your object oriented software development skills and design classes such as Person, Customer, Order, etc.

Put each class in a separate file. In this way you'll maximize the chance of reusability. You don't want to duplicate code and you don't want to write code to represent an Order twice accidentally. The best way to do so is to put each class in a single file, or, in the C++ tradicion, couple of files: header (.h) and implementation (.cpp).

Don't write "generic" or "utility" code outside of any class. Instead, you can write utility classes, with most or all members static. You'll be writing utility functions and at the same time you will retain the separation of concerns and code organization gained by using classes as the main units of your design.

Try this strategy and modify according to your experience. This is a better approach than just giving away the "classes as only modules" guideline right away.

The C++ tradition of giving structs a role as mere field aggregates is rather useful. If a struct has only a limited use within one single class, make it nested to it. If instead it may be used by more than one class, put it in its own file. If as your design evolves it becomes more complicate, for example with complex input validation or comparison semantics, change it to a class.


[Meyer 1997]
Bertrand Meyer: Object-Oriented Software Construction, 2nd Edition, Prentice Hall, 1997.

The concept of class is central to this book. It is discussed in depth in Unit 7: "The static structure: Classes" (Page 165 and following).


Popular posts from this blog

#2. Make all type conversions explicit

#10. Choosing the right loop structure