Ada 95 Quality and Style Guide | Chapter 9 |
9.3.2 Class-Wide Operationsguideline
Consider using a class-wide operation (i.e., an operation with parameter[s] of a class-wide type) when an operation can be written, compiled, and tested without knowing all the possible descendants of a given tagged type (Barnes 1996).
Consider using a class-wide operation when you do not want an operation to be inherited and/or overridden. example
The following example is adapted from Barnes (1996) using the geometric objects from the example of Guideline 9.2.1 and declaring the following functions as primitives in the package specification:
function Area (O : in Object) return Float; function Area (C : in Circle) return Float; function Area (S : in Shape) return Float;A function for computing the moment of a force about a fulcrum can now be created using a class-wide type as follows:
function Moment (OC : Object'Class) return Float is begin return OC.X_Coord*Area(OC); end Moment;Because Moment accepts the class-wide formal parameter of Object'Class, it can be called with an actual parameter that is any derivation of type Object. Assuming that all derivations of type object have defined a function for Area, Moment will dispatch to the appropriate function when called. For example:
C : Circle; M : Float; ... -- Moment will dispatch to the Area function for the Circle type. M := Moment(C);rationale
The use of class-wide operations avoids unnecessary duplication of code. Run-time dispatching may be used where necessary to invoke appropriate type-specific operations based on an operand's tag.
See also Guideline 8.4.3 for a discussion of class-wide pointers in an object-oriented programming framework registry.
< Previous Page | Search | Contents | Index | Next Page > |
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
TOC | TOC | TOC | TOC | TOC | TOC | TOC | TOC | TOC | TOC | TOC |
Appendix | References | Bibliography |