7.4 Defining Operations


All class operations either handle messages or assist in their handling. This means that once a class's state machine is defined and important scenarios elucidated, the messages and events shown on those diagrams become class operations.

In the UML, an operation is the specification of a behavior. This is distinct from a method, which is the realization of an operation. An operation is the fundamental unit of object behavior. The overall behavior of the object is decomposed into a set of operations, some of which are within the interface of the class and some of which are internal and hidden. Naturally, all objects of the same class provide the same set of operations to their clients. An object's operations must directly support its required functionality and its responsibilities. Often behaviors are decomposed into more primitive operations to produce the overall class behavior. This is similar to the functional decomposition in structured system design.

Operations have a protocol for correct usage consisting of the following:

  • Preconditional invariants, that is, assumptions about the environment that must be satisfied before the operation is invoked

  • A signature containing an ordered formal list of parameters and their types and the return type of the operation

  • Postconditional invariants that are guaranteed to be satisfied when the operations are complete

  • Rules for thread-reliable interaction, including synchronization behavior

The responsibility for ensuring that preconditional invariants are met falls primarily in the client's realm. That is, the user of the operation is required to guarantee that the preconditional invariants are satisfied. However, the server operation should check as many of these as possible. Interfaces are hotbeds for common errors and the inclusion of preconditional invariant checking in acceptor operations makes objects much more robust and reliable.

In strongly typed languages, the compiler itself will check the number and types of parameters for synchronous operation calls. However, some language type checking is stronger than others. For example, enumerated values are freely and automatically converted to integer types in C++. A caller can pass an out-of-range integer value when an enumerated type is expected and the compiler typing system will not detect it. Ada's stronger type checking[9] flags this as an error and will not allow it unless an explicit unchecked_conversion type cast is performed. Even in Ada, however, not all range violations can be caught at compile time. In such cases, the operation itself must check for violations of its preconditional invariants.

[9] It has been said "C treats you like a consenting adult. Pascal treats you like a naughty child. Ada treats you like a criminal."

For example, consider an array class. Because C++ is backwardly compatible with C, array indices are not checked.[10] Thus, it is possible (even likely) that an array will be accessed with an out-of-range index, returning garbage or overwriting some unknown portion of memory. In C++, however, it is possible to construct a reliable array class, as shown in Code Listing 7-7.

[10] It is well documented that "the major problem with C++ is C."

Code Listing 7-7. Reliable Array
 #include <iostream.h> template<class T, int size> class ReliableArray { T arr[size]; public:     ReliableArray(void) { };     T &operator[](int j) {         if (j<0 || j >=size)             throw "Index range Error";             return arr[j];     };     const T *operator&() { return arr; };     T operator*() { return arr[0]; }; }; int main(void) {     ReliableArray<int, 10> iArray;     iArray[1] = 16;     cout << iArray[1] << endl;     iArray[19] = 0; // INDEX OUT OF RANGE!     return 0; }; 

Classes instantiated from the ReliableArray template overload the bracket ("[]") operator and prevent inappropriate access to the array. This kind of assertion of the preconditional invariant ("Don't access beyond the array boundaries") should be checked by the client,[11] but nevertheless is guaranteed by the server (array class).

[11] If known clearly a negative index into an array is probably nonsensical, but the client may not know the upper bounds of the array. If you always put range checking in the server array class, you can be assured that even if the client forgets, the array integrity will be maintained.

7.4.1 Types of Operations

Operations are the manifestations of behavior. This behavior is normally specified on state diagrams (for state-driven classes) and/or scenario diagrams. These operations may be divided up into several types. Booch[2] identifies five types of operations:

  • Constructor

  • Destructor

  • Modifier

  • Selector

  • Iterator

Constructors and destructors create and destroy objects of a class, respectively. Well-written constructors ensure the consistent creation of valid objects. This normally means that an object begins in the correct initial state, its variables are initialized to known, reasonable values, and required links to other objects are properly initialized. Object creation involves the allocation of memory, both implicitly on the stack, as well as possibly dynamically on the heap. The constructor must allocate memory for any internal objects or attributes that use heap storage. The constructor must guarantee its postconditional invariants; specifically, a client using the object once it is created must be assured that the object is properly created and in a valid state.

Sometimes the construction of an object is done in a two-step process. The constructor does the initial job of building the object infrastructure, while a subsequent call to an initialization operation completes the process. This is done when concerns for creation and initialization of the object are clearly distinct and not all information is known at creation time to fully initialize the object.

Destructors reverse the construction process. They must deallocate memory when appropriate and perform other cleanup activities. In real-time systems, this often means commanding hardware components to known, reasonable states. Valves may be closed, hard disks parked, lasers deenergized, and so forth.

Modifiers change values within the object while selectors read values or request services from an object without modifying them. Iterators provide orderly access to the components of an object. Iterators are most common with objects maintaining collections of other objects. Such objects are called collections or containers. It is important that these three types of operations hide the internal object structure and reveal instead the externally visible semantics. Consider the simple collection class in Code Listing 7-8.

Code Listing 7-8. Simple Collection Class
 class Bunch_O_Objects {     node* p;     node* current_node; public:     void insert(node n);     node* go_left(void);     node* go_right(void); }; 

The interface forces clients of this class to be aware of its internal structure (a binary tree). The current position in the tree is maintained by the current_node pointer. The implementation structure is made visible by the iterator methods go_left() and go_right(). What if the design changes to an n-way tree? A linked list? A hash table? The externally visible interface ensures that any such internal change to the class will force a change to the interface and therefore changes to all the clients of the class. Clearly, a better approach would be to provide the fundamental semantics (the concept of a next and a previous node), as in Code Listing 7-9.

Code Listing 7-9. Better Simple Collection Class
 class Bunch_O_Objects {     node* p;     node* current_node; public:     void insert(node n);     node* next(void);     node* previous(void); }; 

However, even this approach has problems. This interface works fine provided that marching through the objects in the collection will always be in a sequential manner and only a single reader is active.

The first problem can be resolved by adding some additional operations to meet the needs of the clients. Perhaps some clients must be able to restart the search or easily retrieve the last object. Perhaps having the ability to quickly locate a specific object in the list is important. Considering the client needs produces a more elaborate interface, shown in Code Listing 7-10.

Code Listing 7-10. Even Better Simple Collection Class
 class Bunch_O_Objects {     node* p;     node* current_node; public:     void insert(node n);     node* next(void);     node* previous(void);     node* first(void);     node* last(void);     node* find(node &n); }; 

This interface isn't primitive or orthogonal, but it does provide common-usage access methods to the clients.

Providing support for multiple readers is slightly more problematic. If two readers march through the list using next() at the same time, neither will get the entire list; some items will go to the first reader, while others will go to the second. The most common solution is to create separate iterator objects, one for each of the various readers. Each iterator maintains its own current_node pointer to track its position within the collection, as shown in Code Listing 7-11.

Code Listing 7-11. Simple Collection Class with Iterator
 class Bunch_O_Objects {     node* p; public:     void insert(node n);     node *next(node *p);     node *previous(node *p);     friend class BOO_Iterator; }; class BOO_Iterator {     node* current_node;     Bunch_O_Objects& BOO; public:     BOO_Iterator(Bunch_O_Objects& B) : BOO(B) {         current_node = BOO.p; };     node* next(void);     node* previous(void);     node* first(void);     node* last(void);     node* find(node &n); }; 

7.4.2 Strategies for Defining Operations

Defining a good set of operations for a class interface can be difficult. There are a number of heuristics that can help you decide on the operations:

  • Provide a set of orthogonal primitive interface operations.

  • Hide the internal class structure with interface operations that show only essential class semantics.

  • Provide a set of nonprimitive operations to

    • Enforce protocol rules

    • Capture frequently used combinations of operations

  • Operations within a class and class hierarchy should use a consistent set of parameter types where possible.

  • A common parent class should provide operations shared by sibling classes.

  • Each responsibility to be met by a class or object must be represented by some combination of the operations, attributes, and associations.

  • All messages directed toward an object must be accepted and result in a defined action.

    • Events handled by a class's state model must have corresponding acceptor operations.

    • Messages shown in scenarios must have corresponding acceptor operations.

    • Get and set operations provide access to object attributes when appropriate.

  • Actions and activities identified on statecharts must result in operations defined on the classes providing those actions.

  • Operations should check their preconditional invariants.

Just as with strategies for identifying objects, classes, and relationships, these strategies may be mixed freely to meet the specific requirements of a system.

By providing the complete elemental operations on the class, clients can combine these to provide all nonprimitive complex behaviors of which the class is capable. Consider a Set class, which provides set operations. The class in Code Listing 7-12 maintains a set of integers. In actual implementation, a template would most likely be used, but the use of the template syntax obscures the purpose of the class so it won't be used here.

Code Listing 7-12. Set Class
 class Set {     int size;     SetElement *bag;     class SetElement {     public:         int Element;         SetElement *NextPtr;         SetElement(): NextPtr(NULL); {};         SetElement(int initial): Element(initial), NextPtr(NULL) { };       }; public:     Set(): size(0), bag(NULL) { };     Set union(set a);     Set intersection(set a);     void clear(void);     void operator +(int x); // insert into set     void operator -(int x); // remove from set     int numElements(void);     bool operator ==(set a);     bool operator !=(set a);     bool inSet(int x); // test for membership     bool inSet(Set a); // test for subsethood }; 

This simple class provides a set type and all the common set operations. Elements can be inserted or removed. Sets can be compared for equality, inequality, and whether they are subsets of other sets. Set unions and intersections can be computed.

Often a series of operations must be performed in a specific order to get the correct result. Such a required sequence is part of the protocol for the correct use of that object. Whenever possible, the operations should be structured to reduce the amount of information the clients of an object must have in order to use the object properly. These protocol-enforcing operations are clearly not primitive, but they help ensure the correct use of an object.

A sensor that must first be zeroed before being used is a simple example. The sensor class can simply provide the primitive operations doZero() and get(), or it can provide an acquire() operation that combines them, as shown in Code Listing 7-13.

Code Listing 7-13. Sensor Class
 class Sensor {     void doZero();     int get(); public:     int acquire(void) {         doZero();         return get();     }; }; 

The acquire() operation enforces the protocol of zeroing the sensor before reading the value. Not only does this enforce the preconditions of the get() operation, but it also simplifies the use of the class. Since the doZero() and get() operations are always invoked in succession, combining them into a single operation creates a common-use nonprimitive.

Polymorphic operations are operations of the same name that perform different actions. Depending on the implementation language, polymorphism may be static, dynamic, or both. Static polymorphism is resolved at compile time and requires that the compiler have enough context to unambiguously determine which operation is intended. Dynamic polymorphism occurs when the binding of the executable code to the operator invocation is done as the program executes. Both static and dynamic polymorphism are resolved on the basis of the type and number of parameters passed to the operation.[12] Ada 83 operator overloading is purely static. C++ polymorphism may be either static or dynamic. Smalltalk polymorphism is always dynamic.

[12] C++ class operations have an invisible this pointer in their parameter lists. Thus, even an operation with otherwise identical parameter list can be polymorphic if a subclass redefines the operation, since the this pointer is a pointer to a different type.



Real Time UML. Advances in The UML for Real-Time Systems
Real Time UML: Advances in the UML for Real-Time Systems (3rd Edition)
ISBN: 0321160762
EAN: 2147483647
Year: 2003
Pages: 127

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net