- All public functions (member or global) should be have few arguments, provide conceptually simple operations - which may well be complex internally - and disclose no design details. Returning a pointer from a function requires the user to know enough about the function's design to know whether to delete the pointer when no longer needed, for example, so try not to do that. Another example is passing a function argument by non-constant reference. That makes possible the modification of that argument in the caller's scope. You have to know some design details to understand the implications of that, so favor passing arguments by constant reference or value. Like most design rules there are exceptions to these, and you often encounter them when building linked data structures and clone() functions.
- A designer may wish to partition a function into several parts, some of which may require a lot of design knowledge to use safely. These should be private to an outer function which can be safely used by clients without any such knowledge.
- Data should almost never be made public. A change of name or type of any variable will require changes to all code that uses the variable directly. Keeping data private isolates those changes to the class defining the data instead of propagating throughtout a project. This means, for example, that only the designer of the class needs to know about the change.
- The only thing that never changes in a project is the constant flow of changes. Change happens because a design is incomplete or immature, because requirements change, because of changes in code a package depends on, because of latent errors, and inadequate performance margins. One of the most important requirements for a professional developer is to write code that is robust against change. Learning to do that is one reasone you are taking this course. The first step is to favor well encapsulated classes.
- Note: A string class example
Conclusions for Encapsulate Classes and Packages:
Encapsule the classes and packages you design:
- Make all data private. Try to avoid returning pointers and passing arguments by non-constant reference.
- Make all public functions have simple and meaningful signatures; and try to ensure they can be used without understanding the design of the class. This encapsulates "need to know".
- C++ classes control access by using the keywords: public, protected, and private.
- Packages implemented using C and C++ make global functions and global data private by qualifying with the static keyword. Otherwise they are public.