Home > Articles > Software Development & Management > UML

  • Print
  • + Share This
This chapter is from the book

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 checking9 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.

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.

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).

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.

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.

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.

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.

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.

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.

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.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020