Second, a systemcan be expanded by supplying relatively small modules that contain the new func-tions.29.1 Class and Object Decomposition The first discipline of object-oriented analysis
Trang 1the abstract class ConicSection, which is also a subclass of GeometricalFigure.Observe that the interface, which is the Draw() method, is defined in the abstractclasses (GeometricalFigure and ConicSection) and implemented in the concreteclasses We have used the C++ convention of equating the function to zero to indi-cate that the methods in the abstract classes are pure virtual functions and that noimplementation is provided Also note that virtual functions in the abstract andconcrete classes are in italics.
Figure 28.6 Classification of a Graphics Toolkit
Since the concrete classes can be instantiated, we can create objects of Line,Rectangle, Circle, Ellipse, and Parabola There can clearly be no object of the ab-stract classes ConicSection or GeometricalFigure since there can be no possibleinstantiation of these concepts For these reasons abstract classes have no attrib-utes We can now proceed to draw on the video display using objects For exam-ple:
x_coordinate y_coordinate focus line_thickness
Draw() = 0
Draw() = 0
Trang 2Object: Attributes
Line_A x_start = 10
y_start = 5 x_end = 40 y_end = 20 thickness = 0.005 Rectangle_A x_top_left = 5
y_top_left = 20 x_bottom_right = 25 y_bottom_right = 30 line_thickness = 0.010 Rectangle_B x_top_left = 30
y_top_left = 5 x_bottom_right = 45 y_bottom_right = 10 line_thickness = 0.030 Circle_A x_coordinate = 40
y_coordinate = 30 radius = 5
Rect-Figure 28.7 Objects Displayed Using the Graphics Toolkit
Trang 3In Figure 28.5 we notice that there is a type of conic curve, the hyperbola, that
is not defined in the toolkit The class structure in the object-oriented paradigmallows to later implement this subclass without introducing modifications to theexisting code The mechanics of how a library can be dynamically extended arediscussed later in the book
28.6 When to Use Object Orientation
The fact that this book’s title includes C++ as a programming language does notmean that we assume that every programming project will benefit from an ob-ject-oriented approach One advantage of hybrid languages, such as C++, is thatthey make object-orientation optional Furthermore, in a hybrid language environ-ment we have the possibility of adopting some features of an object-oriented systemwhile not others For instance, we can design a program that uses classes and ob-jects without inheritance, or one that uses inheritance but not run-time polymor-phism Or we may use some forms of inheritance and not others In other words, thesystems designer is free to decide how much object-orientation, if any, is suitablefor a particular project This is often a crucial and significant decision which maydetermine a project’s success or failure
28.6.1 Operational Guidelines
Object-oriented methods have permeated programming activities to such depththat sometimes we forget that its fundamental objective is to provide a model of theproblem domain In Figure 28.1 we showed programming as a bridge from areal-world problem-set to a machine-coded solution-set In this representation ofprogramming we see that the object-oriented paradigm emphasizes modeling theproblem domain while structured programming models the solution domain.Modeling the solution domain facilitates the coding phase (which it approximates).Modeling the problem domain facilitates analysis In one case we concentrate onthe tail-end of the process and in the other one we concentrate on its start
By emphasizing the problem domain in the analysis phase we are able toachieve two undisputable benefits: first, we are able to analyze more complicatedproblems; second, the analyst can communicate better with the domain expertssince many technical elements are removed from the model However, these bene-fits are considerably dimished if the object-oriented model that results from theanalysis has to be translated into the code of a non-object-oriented programminglanguage In spite of the claims made by some hard-core defenders of object-ori-entation, this approach is of doubtful advantage when it does not permeate the en-tire development process Therefore, it is usually undesirable to performobject-oriented analysis and design of a project to be coded in a non-object-ori-ented language Mixing models and development tools is usually a bad idea.Although in recent years the programming community appears to be favoringobject-oriented methods, it is sometimes difficult to clearly ascertain the advan-tages of object-orientation over conventional structured programming for a par-ticular project In order to make a valid judgment we would have to followthrough a host of major software projects developed using both methods, mea-
Trang 4sure and keep track of the development effort, and critically evaluate the results.Even then, many subjective considerations would muddle our conclusions In anycase, we must not forget that the advantages of object orientation come at a highprice in programming complications Few will argue that object-oriented languagesare more difficult to master and use, and that object-oriented analysis and designtechniques are elaborate and complicated.
The decision whether to use or not to use an object-oriented approach should begiven careful consideration by the analyst The following elements favor the use ofobject-oriented methods:
1 Projects in which modeling the problem domain is a major issue
2 Projects in which communication with domain experts can be expected to be a cult and critical part of the development activity
diffi-3 Volatile projects in which changes can be anticipated or in which frequent updates will
be required
4 Projects with many elements with potential for reuse
5 Toolkits and frameworks are often good candidates for the object-oriented approach
On the other hand there are elements that often advise against object-orientation:
1 If the data structures and processing operations resulting from object-orientation arenot compatible with existing data bases In other words, it may be a bad idea to de-velop an object-oriented database management system if the new system forces the re-design or restructuring of the existing databases
2 If the project, or a substantial part thereof, must be developed in a non-object-orientedprogramming language Thus, object-oriented methods may be of doubtful use in de-veloping a short, low-level device driver for a hardware accessory
3 If the problem domain model is already well defined in non-object-oriented terms
4 If the problem-domain is better expressed using a conventional, non-object-orientedmodel Projects in which software elements are the subjects to be modeled sometimesfall into this category
In general, major business and industrial applications are suitable for object entation, while small, technical, or support utilities are not
Trang 6ori-Object-Oriented Analysis
Chapter Summary
Object-oriented programming is mostly a software design methodology In this ter we discuss the elements of object-oriented analysis which is the first and most im-portant step in the design of an object-oriented application The topics includemodelling the problem domain, decomposition into classes and objects, testing objectvalidity, systems and sub-systems, attributes, services, instance and message connec-tions
chap-29.0 Elements of Object-Oriented Analysis
It has been observed by several authors that both major software engineering digms (structured programming and object orientation) started with programminglanguages, were later extended to software design, and finally to analysis This impliesthat the advent of a system analysis methodology marks the maturity of a particularparadigm Regarding object-oriented systems we have seen that full-featured pro-gramming languages were already available in the late seventies and early eighties.System design discussions started at about that time, while the object-oriented analy-sis methodologies are a product of the late eighties and early nineties
para-Observe that the object-oriented approach to analysis does not attempt to replaceevery technique and tool of conventional system analysis The feasibility study, riskanalysis, and cost-benefit analysis can be performed independently of whether theproject is modeled using structured programming or an object-oriented approach.Object-oriented analysis provides a practical methodology for project modeling dur-ing the analysis phase Its purpose is to complement, not to replace
We mentioned in Section 3.6 that the analyst should critically evaluate if a projectwill gain from using an object-oriented approach Also that the greatest benefits ofthe object-oriented paradigm result when the methodology permeates the entire de-velopment process In most cases, our decision to use object-oriented analysis im-
789
Trang 7plies that we will also follow object orientation in the design phase and that theprogram will be coded in an object-oriented programming language Paradigmmixing is theoretically possible, and sometimes recommended by hard-core de-fenders of object orientation However, regarding the smaller project, the compli-cations brought about by simultaneously using more than one model far outweighthe uncertain advantages In particular regarding the smaller development pro-ject, it is our opinion that the decision to proceed with object-oriented analysisshould presuppose that object orientation will also be used during the design andcoding phases of development.
In this chapter we follow Coad and Yourdon, although not very strictly Theseauthors are a principal force in the field of object-oriented analysis In addition,their approach is elegant and simple The Coad and Yourdon notation was de-scribed in Section 28.4
29.0.1 Modeling the Problem-Domain
One of object orientation’s principal characteristics, as well as its main tion, is that it provides a reasonable way of modeling the problem-domain Other ad-vantages often mentioned are that it makes modeling complex systems possible,facilitates building systems that are more flexible and adaptable, and promotes re-usability
justifica-Object-oriented analysis is most useful in problem-set modeling One of thepredicaments of software development is that the programmer must become anexpert in the domain field Thus, someone contracted to develop an air-trafficcontrol system has to learn about radar, about air-to-ground communications,about emergency response systems, about flight scheduling, and about a multi-tude of other technical and business topics related to the activity at hand Howmuch knowledge must the analyst acquire, and to what technical level must thisknowledge extend, is difficult to determine beforehand Many projects have failedbecause the developers did not grasp important details of the problem set Theurge to “get on with the coding” often works against us during this stage
Because the analyst needs to quickly understand the problem-domain, any toolthat facilitates this stage of the process is indeed valuable Once the analyst hasgrasped the necessary knowledge, then this information has to be transmitted toother members of the development team Here again, any tool that assists in com-municating the knowledge is greatly appreciated Finally, the model of the pro-posed solution-set must be presented to the clients or users for their validation,and to obtain feedback A model that facilitates this communication between cli-ents and developers is an additional asset
29.0.2 Defining System Responsibilities
In addition to providing a model of the problem-domain, object-oriented analysismust define the system’s responsibilities For example, the analysis of an air-trafficcontrol system includes determining what functions and operations are within thesystem’s burden Does the air-traffic control system have the obligation of inform-ing commercial airlines of delays in arrivals or departures of aircraft? How does the
Trang 8traffic control system interface with the emergency response system at the port? At what point does the tracking of an aircraft become the responsibility of a par-ticular air-traffic control system and when does this responsibility cease? A system’sresponsibilities refer to what a system should do Answering this question is one of thefundamental tasks of object-oriented analysis Questions related to how a system op-erates are left for the design and coding phases.
air-29.0.3 Managing Complexity
Analysis is necessary because natural systems are often so elaborate and complicatedthat they are difficult to understand or manage Object-oriented analysis provides atoolset for managing complexity This toolset is based on abstraction, encapsulation,inheritance, and message passing
Abstraction
Abstraction consists of eliminating what is superfluous or trivial and concentrating onwhat is fundamental Any definition is an exercise in abstraction We can state that afountain pen is a hand-held writing instrument that uses liquid ink, an ink dischargemechanism, and a fine tracing point This description attempts to gather the funda-mental attributes of a fountain pen that distinguish it from a typewriter, a ball-pointpen, and a pencil However, it ignores the less important features such as the pen’scolor, the color of the ink, the instrument’s exact dimensions, and its design or style
In the context of object-oriented analysis, abstraction refers to the class nism which simultaneously provides procedural and data abstraction In otherwords, the object-oriented notion of a class is an abstraction that represents bothprocessing and data elements of the problem set
mecha-Encapsulation
Encapsulation is one of the fundamental notions of object orientation In the ject-oriented approach encapsulation is related to the notion of data and functions (at-tributes and methods) being packaged together by means of the class construct.Those methods visible outside the class are its interface The principal purpose of en-capsulation is hiding the implementation details while stressing the interface
ob-Inheritance
In the object-oriented paradigm inheritance refers to the possibility of one class cessing the public and protected members of its parent class Class inheritance pro-motes the highest level of abstraction, reduces code size, and simplifies programming.The result is a class hierarchy that goes from the most general to the most specific.Typically, a derived class incorporates all the features of its parent classes and addssome unique ones of its own
ac-Message Passing
Object-oriented systems access processing functions by means of a mechanism calledmessage passing One of the disadvantages of hard-coded program structures such asjump tables, cascaded if statements, or case constructs, is that they must be updatedwith every program modification or change The message passing mechanism, on the
Trang 9other hand, automatically directs execution to the appropriate member function.This functionality brings about two major advantages: first, we avoid introducingnew defects into code that have already been tested and debugged Second, a systemcan be expanded by supplying relatively small modules that contain the new func-tions.
29.1 Class and Object Decomposition
The first discipline of object-oriented analysis is learning to think in terms of classesand objects At this stage we must free our minds of concerns regarding algorithms,programming structures, or any other implementation issues Our task during analy-sis is to model the problem-domain and to define the system’s responsibilities Both
of these purposes are accomplished by means of class and object decomposition
In this sense an object can be considered an abstraction of a discrete element inthe problem domain The object-oriented encapsulation is a matter of defining at-tributes and methods An object is characterized by the possibility of its identity be-ing preserved by the system Therefore each object must have a uniqueness thatallows its identification
Every object belongs to a class of objects A class is a description of a set ofunique attributes and methods associated with an object type An object is an in-stance of a class An abstract class is a description of an interface which lacks im-plementation Its fundamental purpose is to define an inheritance path It is notpossible to instantiate objects from an abstract class
Do we start modeling by thinking of objects or of classes? It is a matter of tics, but, strictly speaking, an object is a run-time construct while a class is an ab-straction that groups common attributes and methods for an object type Therefore
seman-it appears that we should think of object types or classes, rather than of possibleinstantiations On the other hand, the mental concept of a class of objects requiresthat we visualize a typical object For example, suppose we are attempting to model
a system which uses a viewport window to display a text message In order to fine the text message window type we must first imagine what the object wouldlook like Figure 29.1 shows what may be our initial visualization of a text windowobject
de-From the object’s visualization we can deduce the attributes and methods of theobject itself and the class that represents it For example, the screen location andthe object size are defined by the start and end coordinates The object also has aborder thickness and a color Its text attributes are the window’s title and its text Acontrol button on the top left corner of the object allows the user to erase the textmessage window There are three methods associated with this object: one to dis-play the window, one to report its current status, and one to erase it Using class di-agrams we can now represent the object type TextWindow to any desired degree ofdetail The left-hand diagram in Figure 29.2 merely states that there is an objectclass named TextWindow, while its attributes and methods are yet undefined Thediagram on the right shows the specific attributes and methods
Trang 10Figure 29.1 Visualization of a Text Window Object
Figure 29.2 Class Diagrams for a TextWindow Object
During classification it is common practice to make the class name a singularnoun or an adjective followed by a noun It is also a good idea to use the client’sstandard vocabulary when naming classes Suppose we are modeling a home alarm
window button
start point coordinates
end point coordinates
thickness color
TextWindowTextWindow
start_xstart_yend_xend_ycolorthicknesswindow_titletext_messagestatus
DrawWindow()ReturnStatus()EraseWindow()
Trang 11system with a rather elaborate video display and command control For historicalreasons the client calls the video display and command control a “push-buttonpanel.” During analysis we may be tempted to rename this element so that its des-ignation describes its actual functionality more exactly Clearly the term “com-mand console” would be more forceful and descriptive than “push-button panel.”However, this new name would serve only to confuse clients, who would have tomentally translate “command console” for “push-button panel” every time theyencounter the new term.
During the analysis phase the class name could be entered using any able style of spacing and capitalization However, if our class names are not com-patible with the syntax to be used in the design and coding phases, then thesenames would have to be modified at a later date Since any modification could be
reason-a source of errors, it is better to nreason-ame clreason-asses, reason-attributes, reason-and methods using reason-astyle that is consistent with the later phases of the development environment Inthe context of this book decisions regarding style are facilitated by the fact that
we have committed to C++ as a programming language Therefore, to improvereadability, and in conformance with one popular C++ programming style, wecapitalize the first letter of every word in class names and methods Methods arefollowed by parenthesis to indicate processing Attributes, which later becomevariables, are typed in lowercase, and the underscore symbol is used as a separa-tor Note that any other style is equally satisfactory as long as it can be consis-tently maintained throughout the development process
While methods are depicted by verbs and verb phrases, attributes are sented by nouns or noun phrases, as in Figure 29.2 C++ allows us to use rathersimple naming schemes for attributes and methods since these names have classscope, where the same names can be reused in other classes In this sense theDrawWindow method of the TextWindow class is not in conflict with other meth-ods called DrawWindow that could be later defined for other classes By the sametoken, the thickness attribute can also be reused in reference to other types ofgraphic objects
repre-Simplified class diagrams in which attributes and methods are not explicitlylisted can be useful in showing class relations and inheritance Consider a systemwith two types of window objects, one representing windows that contain nothingbut text, a second one for windows that include a bitmap The first type could bedesignated as a TextWindow and the second one as a GraphicWindow The classstructure would be depicted in the class diagram in Figure 29.3
N o t e t h a t i n F i g u r e 2 9 3 Te x t Wi n d o w i s a s u b c l a s s o f Wi n d o w, a s i sGraphicWindow Also that Window is an abstract class, which implies that itsmethods are not implemented Also that at run time we could instantiate objects
of type TextWindow or of type GraphicWindow, however, Window objects couldnot exist since the abstract nature of the base class precludes this possibility Amore detailed diagram of the classes is shown in Figure 29.4
Trang 12Figure 29.3 Sample Inheritance Diagram for Window_Type Classes
Figure 29.4 Refined Diagram for Window-Type Classes
In Figure 29.4 a GraphicWindow class is a subclass of Window which adds tionality to the base class The new functionality is in the form of three new attrib-utes which locate the bitmap on the viewport and a new method to draw the bitmap.The basic coordinates and characteristics of the window itself are defined in thebase class, since these attributes apply to any window object
start_x start_y end_x end_y color thickness window_title text_message status
bitmap_x bitmap_y
DrawWindow()=0 ReturnStatus()=0 EraseWindow()=0
DrawWindow()
ReturnStatus()
EraseWindow()
DrawWindow() ReturnStatus() EraseWindow()
DrawBitmap()
Trang 1329.1.1 Searching for Objects
The search for objects should not begin until the analyst has gained some familiaritywith the problem domain itself An analyst that is unfamiliar with an air-traffic con-trol system should not be searching for air-traffic control objects Instead, the firststep should be an attempt to understand the system’s fundamental characteristics
It is futile to attempt to identify objects and classes in a technology that is iar
unfamil-The following are the main sources of information about the problem domain:
1 Published materials and the Internet
2 First hand observation
3 Consultation with domain experts
4 Client documents
The search for published material usually leads to libraries, bookstores, andthe Internet First-hand observation consists of familiarizing ourselves with a sys-tem by participating in its operation For example, to analyze an air-traffic controlsystem we may begin by sitting in the air-traffic control tower for several dayswhile observing the operation of the air-traffic controllers Domain experts are of-ten the source of valuable and unique information Many systems are totally orpartially unpublished, part of trade or government secret, or are considered confi-dential In these cases published materials may be of little use Our only option is
to locate individuals with knowledge and expertise and to have them describe orexplain the system to us Client documentation can also be a valuable source ofinformation Expert analysts make it a standard practice to request a detailed doc-ument from the client This document should identify the system and its purpose
to the greatest possible detail
29.1.2 Neat and Dirty Classes
In some contexts classification is a clear and neat process, but not in others Whenconceptual objects correspond to real-world objects the classification process is of-ten simple and straightforward For example, when the task is to define a mini CADprogram, classification could turn out to be relatively uncomplicated In this casethe screen objects give rise to classes, such as drawings composed of lines, curves,geometrical figures, and text
On the other hand, classification may be somewhat less clear when the task is
to design an editor or word processing program In this case we may start ing of program operations as objects But is it reasonable to consider operationssuch as inserting, replacing, and deleting text as physical objects? What about theuser’s text file? However, since the text file is stored as an array of characters wemay be tempted to think of it as an attribute One possible classification is shown
think-in Figure 29.5
Trang 14Figure 29.5 Possible Class Diagram for a Simple Text Editor
Other projects may be even more difficult to classify For example, assume thetask is designing and coding a virus-detection utility In this case are the viruses theobjects? Would this mean that if no viruses are found the program executes withoutinstantiation? Or is the search itself an object? In this case whatever kind of classifi-cation is developed will probably be unsatisfactory, and the classes themselves will
be untidy and unreal What happens is that this is probably one of those cases, tioned in Section 3.6, that is best handled outside of object orientation
men-29.2 Finding Classes and Objects
The skills of an object-oriented analyst include the individual’s ability to locate jects and to derive valid and useful classifications In this respect there is no substitutefor experience with various types of problem domains However, there are some cir-cumstances, patterns, and constructs that the analyst can use to locate possible ob-jects One proposed methodology consists of searching through the elements of classassociations, mechanisms and devices, related systems, preserved data, roles played,sites, and organizational units
ob-29.2.1 Looking at Class Associations
In Section 27.4 we described a notation for representing two types of class tions: the Gen-Spec and the Whole-Part structure This first type refers to a generaliza-tion-specialization relation that corresponds to one class being in a “kind-of” associa-tion with a parent or base class The second type refers to an association where a class
associa-is “a-part-of” a parent or base class The notation for class associations associa-is often taken
to imply an inheritance configuration whereby the public elements of the base classbecome accessible to the derived class Although this assumption is valid during anal-ysis, we should mention that Whole-Part associations are often implemented withoutusing class inheritance
Associations (also called structures) can be used to identify objects in the lem domain and to uncover levels of complexity in the class structures The methodconsists of looking at object associations within the problem domain For example,
prob-in Figure 29.3 we found that two types of wprob-indows, called GraphicWprob-indow and
UserFile text_file
Insert() Delete() Replace() Save() Load()
Trang 15TextWindow, were subclasses of a general Window type A detailed class diagramwas later derived from these associations.
Gen-Spec Structures
The name of a specialization is usually derived from its generalization In this ner TextWindow and GraphicWindow are specializations of the Window type (seeFigure 29.4) In a Gen-Spec structure the bottommost classes are concrete classes,from which objects can be instantiated The higher-level classes can be concrete orabstract Often class structures are flexible and can be expressed in different ways.For example, we could redo the class diagram in Figure 29.4 so that a concrete classWindow serves as a generalization with a possible specialization in the form of aGraphicWindow This scheme is shown in Figure 29.6
man-Figure 29.6 Alternative Structure for Window-Type Classes
Note that Figure 29.6 depicts a class structure in which the methodsDrawWindow(), ReturnStatus(), and EraseWindow() are actually implemented inthe base class Therefore they need not be re-implemented in the derived class,except if these methods need update or modification
Once we have identified a generalization-specialization structure, performtests to ascertain whether the structure is both valid and necessary
Window
GraphicWindow
start_xstart_yend_xend_ycolorthicknesswindow_titletext_messagestatus
bitmap_xbitmap_y
DrawWindow()ReturnStatus()EraseWindow()
DrawBitmap()
Trang 161 Does the subclass respond to the “is-a-kind-of” relation regarding the parent class?
2 Does the subclass add attributes or methods to the parent class?
3 Is the structure actually within the problem domain as it pertains to proposed system?
In other words: is this structure really necessary to represent the problem at hand?
4 Is the structure within the system’s responsibilities? Often a structure that actually ists in the problem domain turns out to be unnecessary in the model since the pro-posed system does not perform any function related to it For example, we mayrecognize that a graphic window (see Figures 29.3 and 29.6) could contain vectordrawings as well as bitmaps However, if the system to be developed deals only inbitmap graphics, then the introduction of vector graphics would be an unnecessarycomplication since it falls outside of the system’s responsibilities
ex-5 Are there lines of inheritance between the subclass and the parent class? A tion-specialization structure in which no methods are inherited from the parent classshould be questioned since it is inheritance that makes the structure useful
generaliza-6 Would it be simpler to use an attribute that qualifies a type than a Gen-Spec structure?For example, a system that deals with vehicles has to distinguish between autos, mo-torcycles, and trucks This could possibly be accomplished by a Gen-Spec structure inwhich Vehicle is a base class and AutoVehicle, MotorcyleVehicle, and TruckVehicle aresubclasses Alternatively, the system could be modeled using a Vehicle class with a ve-hicle_type attribute Both alternatives are shown in Figure 29.7
Figure 29.7 Two Modeling Alternatives
TruckVehicle Vehicle
MODEL USES A GEN-SPEC STRUCUTRE
MODEL USES AN ATTRIBUTE
AutoVehicle
Vehicle MotorcycleVehicle
vehicle_type (auto) (motorcycle) (truck)
Trang 17The general rule used in determining which model is to be preferred is that ageneralization-specialization structure should not be used for extracting a com-mon attribute.
Multiple Inheritance in Gen-Spec Structures
The common case in a Gen-Spec structure is that a class inherits from a single tor However, Coad and Yourdon distinguish between an Gen-Spec structure used as
ances-a hierances-archy ances-and one used ances-as ances-a lances-attice The hierances-archy is the most common form of thestructure and corresponds to the examples used previously in this chapter In thissense the top-most model in Figure 29.7 represents a hierarchy of the Vehicle class.The notion of a hierarchy corresponds to single inheritance in object-oriented lan-guages A lattice, on the other hand, corresponds with multiple inheritance, whichoccurs when a class inherits attributes or methods from more than one ancestor.For example, in the Vehicle class structure of Figure 29.7 we could define twoadditional subclasses The class PickupVehicle could have some of the properties
of an AutoVehicle (carries passengers) and some of the properties of aTruckVehicle (transports cargo) Or an ATVVehicle may inherit some propertiesfrom the AutoVehicle class and others from MotorcycleVehicle Figure 29.8 showsthe resulting lattice-type diagram
Figure 29.8 Gen-Spec Structure Lattice
Whole-Part Structures
The triangle markings in Figure 28.4 represent a Whole-Part structure which sponds to the concept of an “is-a-part-of” class relation Sometimes the Whole-Partnotation is supplemented with digits or codes to represent the number of elements
corre-TruckVehicle Vehicle
AutoVehicle
ATVVehicle
PickupVehicle MotorcycleVehicle
Trang 18that take part in the relation For example, it may help the model if we clarify that a hicle can have four wheels but only one engine, or that a wheel can belong to only onevehicle, but a person can own more than one vehicle A comma separates the low fromthe high numerical limits The letter “m” is often used as a shorthand for “many.” Fig-ure 29.9 shows a Whole-Part structure regarding some components of an AutoVehicleclass.
ve-Figure 29.9 Whole-Part Structure
Note that the digits in Figure 29.9 add information to the model For example, wecan tell that an auto vehicle has one engine, four wheels, and zero or one automatictransmission Also that engine, wheel, and automatic transmission can exist inde-pendently of the automobile, but that cylinders do not exist outside of the engine.Finally that an engine can have either four, six, or eight cylinders
There are certain common constructs and relationships that can be investigatedwhen searching for Whole-Part associations In the example of Figure 29.9 the con-struct can be described as an assembly-components relationship Another commoncase can be described as a container-contents relationship For example, the driver
of an automobile is not one of its components, but may be considered to be in a tainer-contents relationship A third common construct is the collection-member re-lationship For example, the collection coins has the members quarter, dime, nickel,and penny Or the collection hospital has the members patient, nurse, doctor, andadministrator
con-The following tests can be performed to ascertain whether a Whole-Part structure
is valid and necessary:
Trang 191 Does the subclass correspond to the “is-a-part-of” relation regarding the parentclass?
2 Does the subclass add attributes or methods to the parent class?
3 Is the structure actually within the problem domain as it pertains to the proposedsystem? Is this structure really necessary to represent the problem at hand?
4 Is the structure within the system’s responsibilities?
5 Would it be simpler to use an attribute that qualifies a type rather than a Whole-Partstructure?
Compound Structures
It often happens that a structure contains both Gen-Spec and Whole-Part class tionships For example, the structures in Figures 29.8 and 29.9 would give rise to thecompound structure shown in Figure 29.10
rela-Figure 29.10 Compound Structure
29.2.2 Looking at Mechanisms and Devices
Another element of the search for classes and objects is the location of mechanismsand devices within the problem domain For example, in modeling a burglar alarmsystem we may notice that it includes devices such as sensors to be placed in possi-ble entry points, audible warnings that sound when a security breach is detected,switches for enabling and disabling the system, and input/output hardware such as
a keypad for entering passwords and displays for echoing input and reporting tem status In this case the devices and mechanisms that are within the system’s re-sponsibilities are all candidates for classification In the case of the burglar alarm
Trang 20system we should examine the possibility of having a class named Sensor, a classnamed AudibleAlarm, a class named OnOffSwitch, and so on.
29.2.3 Related Systems
At the fringes of a system’s responsibilities we can sometimes detect other systemswith which it interacts The interaction could be hard-wired (if both systems are me-chanically connected), through a communications link, or can result from hu-man-computer interaction Any associated or related system should be considered as
a possible candidate for classification if it is within the base system’s responsibilitiesand if it forms part of the problem domain For example, if the burglar alarm systemmentioned in Section 29.2.2 is connected to a local police alert system, then perhapssome elements of the police alert system should be included in the model
29.2.4 Preserved Data
Another possible source of class and objects are the data or events that must be served or remembered by the system Events preserved for historical purposes, modi-fications to databases, and legal documents, are all included in this category Forexample, a computer system that uses a telescope to scan the sky for unknown celes-tial objects must somehow record and remember the position of a new comet in a pos-sible collision path with Earth The file used to store the time, date, celestialcoordinates, and photographic image of the newly detected object is a possible candi-date for classification A more mundane example would be the transaction data stored
pre-by an automated teller machine
29.2.5 Roles Played
Individuals play roles within organizations and these roles are another possiblesource of classes that should be examined For example, a Health Maintenance Orga-nization (HMO) has individuals playing the roles of physicians, nurses, patients, ad-ministrators, and staff It is likely that a model of this HMO will consider these roles asclasses Figure 29.11 shows one possible (rather loose) interpretation of the interac-tion of the class Physician within a fictitious HMO
Figure 29.11 Class Depicting Human Interaction
Physician name
specialty authorized_to_perform ExaminesPatient() PrescribesMedication() PerformsSurgery() TransfersPatient() ReportsToHMO()
Trang 2129.2.6 Operational Sites
Operational sites or physical locations within the system’s responsibilities are often
a source of classes For example, a hypothetical satellite image processing systemincludes a site in New Mexico where the image data is downloaded from the satel-lites, a second site in South Dakota receives this raw data and reformats it into spe-cific image files, which are then transmitted to a third site in California whichdistributes the image files to the system clients In this case the New Mexico, SouthDakota, and California sites perform different functions and could therefore be con-sidered as candidates for classification
Another example: the quality control department of a food product turer consists of an office and a laboratory The food product samples are col-lected in eight manufacturing plants throughout the state In modeling this system
manufac-we may have to decide if the classification is based on ten sites, one of which isthe lab, the other one the office, and eight sites are manufacturing plants, or if themodel can be rationalized to three classes by combining all eight manufacturingplants sites into a single class In this last option an attribute could be used to des-ignate each one of the individual plants This case is shown in Figure 29.12
Figure 29.12 Example of Site-Based Classification
29.2.7 Organizational Units
Organizations are divided into units that perform different tasks and assume tinct responsibilities within the system At modeling time these organizational unitsare also strong candidates for classification For example, a manufacturing divisionincludes departments called engineering, production, quality control, and shipping.These organizational units should be considered as possible classes
dis-29.3 Testing Object Validity
Once we have developed a basic classification scheme for the problem at hand it is agood idea to challenge its validity and soundness There are certain requirementsusually associated with objects which can serve to test their legitimacy and signifi-cance In challenging proposed classes and objects the following questions are per-tinent:
1 Is there information that the system needs to remember regarding this object?
2 Does this object provide some method or processing operation?
3 Is there more than one attribute associated with this object?
ManufacturingPlantsite_name
Trang 224 Will more than one object be instantiated from the class?
5 Do the attributes always apply to the object?
6 Do the methods always apply to the object?
7 Are the objects related to the problem domain or to a particular implementation?
8 Are the results a simple calculation or derivation?
In the following sections we proceed to examine each of these questions rately
29.3.2 Object Behavior
A class with no methods is suspect of a classification error Even an abstract classhas methods, although these methods are not implemented If we accept that, in prin-ciple, attributes should not be accessible from outside the class, then the fact that anobject is affiliated with one or more attributes implies that there are one or moremethods to access these attributes A careful investigation is necessary if an objecthas attributes but no methods Some authors consider that classes with methods but
no attributes are a result of functional-style thinking and should be reconsidered
29.3.3 Multiple Attributes
While a class with no attributes is suspect of incorrect classification, one with a gle attribute may indicate a poorly conceived classification In this case the analystcould use an attribute (typically in the parent class) instead of a full-fledged object
sin-29.3.4 Multiple Objects
The fundamental notion of classification implies that a class is a type which usuallyconsists of more than one individual In this sense we can correctly conceive theclass FootballPlayer or the class Quarterback Multiple objects of either class can beinstantiated However, the class JohnSmith, of which only one object can beinstantiated, should set off an alarm indicating the need for further investigation Onthe other hand, often we must create a class with only one possible object For exam-ple, a satellite image processing system may have a class ReceivingStation with a sin-gle object However, in this case we may decide to validate the class considering thatanother receiving station could be built The decision about the validity and suitabil-ity of a class with a single object must be made considering the problem domain
Trang 2329.3.5 Always-Applicable Attributes
The general rule is that the attributes in a class apply to all objects instantiated fromthe class For example, suppose that the class AutoVehicle includes the attributesmanufacturer, model_number, and size-of-bed All objects generated from the classinclude the first two attributes, however, the size-of-bed attribute does not apply tothose vehicles that are not trucks The fact that an attribute is not applicable to allobjects instantiated from the class suggests that there is a possible class structureyet undiscovered In this example perhaps we could use the Gen-Spec structure inFigure 29.7
29.3.6 Always-Applicable Methods
The fact that there are methods in a class that do not apply to all possibleinstantiations indicates that there is room for improvement in the classification.Perhaps there is a class structure that has not yet been considered This is unrelated
to how simple or elaborate a particular method is, but it is linked to the fact thatmethods are expected to be applicable to all possible objects For example, con-sider a class named HospitalEmployee that includes doctors, nurses, and adminis-trators This class has a method named PerformMajorSurgery that is applicable only
to doctors, but not to nurses or administrators The fact that a method does not ply to all objects that can be instantiated from the class strongly suggests a missingclass structure
ap-29.3.7 Objects Relate to the Problem Domain
Many beginning analysts find it difficult to isolate themselves from implementationconcerns during the analysis phases Due to inattention, matters that pertain to im-plementation often permeate the model Suppose a system that deals with licensing
of automobile drivers Because the system must digitally store each driver’s sonal data we may be tempted to create a class called DriverDiskFile But, in reality,the concept of a disk file pertains to the solution set From the problem set’s view-point the class that stores driver data could be better named DriverInfo How this in-formation is stored or preserved in the computer hardware is outside the scope ofthe model at the analysis stage
per-An important conclusion is that the choice of processing operations, of ware devices, of file formats, and of other computer-related factors should not bemade during the analysis phase The specific methods, systems, or devices used inimplementing the solution are inconsequential at this stage Therefore, a classthat represents a solution-related element should be carefully investigated Ex-ceptionally, we may find that project specifications require the use of a particularalgorithm or method of computing For example, the client of a graphics packagerequests in the specification documents that lines be drawn using Bresenham’s al-gorithm In this case the algorithm becomes a domain-based requirement and itsinclusion in the model is valid and appropriate On the other hand, if no mention
hard-of a specific algorithm is made in the specification, then it would be premature todecide what method is to be used for drawing lines at the analysis phase A goodgeneral rule is that all implementation matters are best postponed until design orimplementation, except if the problem domain specifically mandates it
Trang 2429.3.8 Derived or Calculated Results
Finally, we should investigate those objects that represent a mere calculation or thatare derived by manipulating stored data For example, suppose a payroll system whichmust issue a printed report of all salaries and wages disbursed during the period Inthis case we may be tempted to create a class, perhaps called WeeklyPayrollReport, torepresent this document However, since this document is directly derived fromstored data it could be an improper classification An alternative and more satisfac-tory solution is to make the generation of a payroll report a method in the class thatstores the pertinent information, rather than an object by itself
29.4 Subsystems
The complexity of a model sometimes gets out of hand According to Coad andYourdon a system containing 35 classes is of average size, while one with about 110classes is considered large It is also common for the problem domain to include sev-eral subdomains, each one with up to 100 classes With this level of complexity the fun-damental features of the problem domain may become difficult to grasp, andtherefore, to explain to clients and users A convenient mechanism for reducing modelcomplexity is its division into subsystems, sometimes called subjects in object-ori-ented analysis literature
Subsystems do not reduce complexity by simplifying the model but rather by gressively focusing on its different components For example, suppose a model thatdepicts a full-featured graphics library, shown in Figure 29.13
pro-Figure 29.13 Classes and Structures of a Graphics Toolkit
Trang 25In such cases the resulting model can be elaborate and complicated However,
by noticing that the graphics operations refer to drawing geometrical figures, todisplaying text, and to interacting with a mouse, we are able to decompose it intothree independent subsystems Each of these subsystems can then be treated as alogical entity, even though they may share functions or interact with each other
In Figure 29.14 we have repositioned some of the classes and added rectangles toenclose the subsystems Each rectangle is labeled with the subsystem’s name.Some authors use numbers to designate subsystems In either case the result is amore manageable model
Figure 29.14 Graphics Toolkit Subsystems
29.4.1 Subsystems as Modules
In Section 26.2.3 we discussed the concept of a program module as a logical unit ofdivision based on structural or functional considerations The concept of a programmodule should not be equated with that of a procedure, a subroutine, or a disk file,although occasionally they may coincide This viewpoint determines that
Graphic Graphic subsystem
Text
Text subsystem Mouse subsystem
MouseDevice
OpenCurve StraightLine ClosedFigure
String
MouseCursor Character LeftButton RightButton
Trang 26modularization should not be considered as an implementation issue, but as one lated to system analysis and design.
re-In this sense the notion of a subsystem is quite compatible with that of a module.Therefore subsystems identified during the analysis stage can become modules dur-ing the design stage But for this to happen the subsystem must meet the same re-quirements demanded of modules
Subsystem Cohesion
Regarding modules, cohesion or binding refers to the relationship between its internalelements; the same applies to subsystems A subsystem in which the contained classesare strongly related has high cohesion Sometimes we include a class into a subsystemsimply because there is no better place for it Inclusion of an unrelated class reducessubsystem cohesion However, this does not mean that all classes in a subsystem must
be intimately linked, but rather that they must be strongly related in the problem main For example, in Figure 29.14 the Mouse subsystem contains the classMouseCursor which is not part of any class structure However, because this class isclosely related to the problem domain of mouse functions it fits well in the subsystem.Using conventional terminology we can say that a subsystem in which the classesare related loosely can show only coincidental cohesion, while one in which theclasses are related logically show logical cohesion Cohesion levels are difficult toquantify, but the functional strength of a subsystem depends on it having high cohe-sion
do-Subsystem Coupling
The concept of coupling is a measure of the degree of interconnection between systems In this sense two closely coupled subsystems have a high degree of interac-tion and interdependence, while loosely coupled subsystems stand independently ofeach other Subsystems with high coupling are difficult to understand, analyze, and re-use separately, therefore high coupling is generally considered an undesirable prop-erty On the other hand all subsystems are usually coupled in some way since theymust interact in producing a common functionality It is difficult to imagine a system
sub-in which all its component subsystems are totally uncoupled
In general, good subsystem structure should have a high cohesion and a low pling The classes must be closely related within the subsystem and there should be
cou-a minimum interdependency between subsystems
29.5 Attributes
An attribute is a data element within a class, and each different object instantiatedfrom a class is associated with a unique set of values for its attributes For example, inFigure 29.11 each object instantiated from the class Physician has a unique name, spe-cialty, and authorized_to_perform attribute values This unique set of values is some-times referred to as the object’s state
One of the fundamental rules of object orientation is that attributes should not bedirectly accessible from outside the class The only way to obtain or change the
Trang 27value of an attribute is by using a method that performs this function However,many programming languages do not impose this rule; for example, in C++ it ispossible to declare an attribute to be of public access type and thus make it visi-ble to other classes and to client code Nevertheless, making attributes visibleoutside the class violates the principles of encapsulation and data abstraction,which, in turn, defeats one of the fundamental purposes of the object-orientedparadigm.
While classes and structures are relatively stable over the lifetime of a system,attributes are likely to change In refining or expanding the functionality of a class
we often have to introduce new attributes and methods For example, the cian class in Figure 29.11 may be refined by introducing attributes to reflect theindividual’s social security number and home address In this case encapsulationrequires that new methods be developed to access the new attributes
Physi-29.5.1 Attribute Identification
During the initial stage of analysis we often draw diagrams of classes and structuresexcluding attributes and methods, whose definition is postponed until we becomemore familiar with the basic elements of the model However, the analysis phase isnot complete until we have identified attributes and methods for every class.The fundamental notion of an attribute relates to what the containing class isresponsible for knowing For example, an analyst defining an Employee class may
be tempted to include sex as an attribute However, if the system does not use theemployee’s sex in any of the processing operations performed by the class, and ifthis attribute is not required in defining an object’s state, then it is outside of thesystem’s responsibilities and should not be included If the attribute later be-comes necessary it can be added at that time Attempting to predict, at analysistime, the attributes or methods that may become necessary in the future is usually
a bad idea The result is often a system overloaded with useless elements whichserve only to complicate it and add to its cost It is much more practical to makegeneralized allowances that will accommodate growth or modification, ratherthan attempt to guess all the requirements that could become necessary
In identifying attributes we may ask the following questions:
1 How is the object described?
2 What properties are associated with the object in the problem domain?
3 What properties associated with the object are necessary for implementing the tem’s responsibilities?
sys-4 What properties of the object need to be remembered over time?
5 What states can the object be in?
Not all of these questions are pertinent for all objects and, in some cases, morethan one question can have the same answer At the same time some objects areconceptually very simple, while others are complex For example, the LeftButtonobject of a mouse device (see Figure 29.14) is a rather simple one It appears that
Trang 28questions number 3, 4, and 5 are pertinent in this case Specifically: the system’s sponsibilities may require that it be known if the left mouse button has been pressed(button down) or released (button up) The properties to be remembered over timeare the button’s current status, which are also the object’s possible states There-fore, it appears that one attribute that encodes the state of the left mouse button ascurrently being down or up may be sufficient in this case.
re-On the other hand, an Employee class that keeps track of the individuals in theemployment of an organization may require attributes such as name, address, so-cial_sec_number, date_of_employment, hourly_wage/salary, hours_worked, tax-able_income, and many others Several ethical and legal issues may be considered
at this time For example, if it is illegal to base any employment decision on the ployee’s age, should the individual’s date-of-birth be stored as an attribute? If a com-pany has no other reason for knowing an employee’s age, could the fact that thisinformation is stored with other employee data be used against the company in anage discrimination dispute? The following argument could be made in this case: whywould a firm incur in the expense of storing data that it does not intend to use?The decision to include or exclude an attribute is usually made jointly by clientand analyst The safest advice is not to include attributes that are outside of the sys-tem’s current responsibilities Crystal-ball-based system analysis can be counterpro-ductive
em-29.5.2 Attributes and Structures
Occasionally we may be uncertain regarding which class of a Gen-Spec structureshould contain a particular attribute For example, when assigning attributes to theclasses depicted in the Text subsystem (shown in Figure 29.14) we may decide thateach text string or character will have a particular letter style and point size Shouldthese attributes appear in the classes String and Character, or on the parent classText? The general rule in this case is to position the attribute at the highest point in theclass structure applicable to all specializations Therefore the attributes should ap-pear in the class Text, as shown in Figure 29.15
Figure 29.15 Attribute Positioning in a Gen-Spec Structure
Text
String
letter_style point_size
Character
Trang 2929.6 Methods or Services
A system is functional and useful by virtue of the processing operations that it forms: a system must do something A perfect structure of classes and attributes,with no methods, is worthless The specific behavior that an object must exhibit iscalled a service Service is synonymous with processing operations and coincideswith a class’ methods
per-29.6.1 Identifying Methods
The analyst can follow several routines in order to identify the methods associatedwith each class In this respect the following questions could be useful:
1 What are the object states?
2 What are the required services?
Object States
When an object is created it is associated with a set of attribute values that define itsstate These attributes can change from the time the object is created until it is re-leased Every change in attribute values defines a new object state We can deter-mine an object’s state by examining the range of values that can be assigned to eachattribute in the light of the system’s responsibilities From this analysis we can con-struct a simple diagram showing the various states which are defined for the object
as well as the transitions between states For example, regarding the MouseCursorobject in Figure 29.14 we may define that the system’s responsibilities includeknowing if the cursor is on or off; if on, its current screen position The class cannow be refined by drawing the state transition diagram Later on we can use thestate transition diagram to deduce the class’ methods The preliminary steps areshown in Figure 29.16
Figure 29.16 Attributes and Object State Diagram
Required Services
From the object states and the object attributes it is possible to deduce the requiredservices or methods Here again, the services to be considered should be thosewithin the system’s responsibilities Several categories of algorithmically-simple
MouseCursor
Defining Attribute of MouseCursor Class State Transition Diagram
State = OFF
State = ON (screen_location)
status
(ON - OFF)
screen_location
Trang 30services should always be investigated These are usually called Create, Connect, cess, and Release:
Ac-1 Create This service is used to create and optionally initialize an object When no ticular initialization is required the Create service is often implicit However, if an ob-ject’s creation requires the initialization of attributes it should be distinctly defined.This approach is consistent with the operation of constructor functions in C++
par-2 Connect This type of service is used to establish or break a connection between jects It corresponds to the notion of an instance connection described in Section 29.7
ob-3 Access This type of service assigns values to attributes or returns attribute values Itsexistence results from the principles of encapsulation and data abstraction, which re-quire that attributes not be accessed from outside the class
4 Release or Destroy This service destroys the object It corresponds to destructors inC++
Much of the required behavior of an object can be performed by the Create, nect, Access, or Destroy services In many systems these algorithmically-simplemethods account for 80 to 95 percent of the required functionality However, algor-ithmically-complex methods are also often required They usually correspond to thetypes Calculate and Monitor
Con-• Calculate This type of service uses the attribute values in the object to perform a lation
calcu-• Monitor This type of service is usually associated with an external device or system Itsfunctions relate to input, output, data acquisition, and control
The methodology to follow in defining the required services consists in first amining the object for the four algorithmically-simple service types (Create, Con-nect, Access, and Destroy) and then for the two algorithmically-complex types(Calculate and Monitor) All object methods fall into one of these categories For ex-ample, examining the MouseCursor class in Figure 29.17, we can identify two algor-ithmically-simple services An access-type service is used to determine whether thecursor is in the ON or OFF state A Connect-type service is used to establish a linkbetween the MouseCursor object and the service that monitors the cursor move-ment on the screen Figure 29.17 shows the corresponding class diagram
ex-Figure 29.17 Defining Services for the MouseCursor Object
MouseCursor
CursorOn()MonitorCursor()CursorOff()
status(ON - OFF)screen_location
Trang 3129.7 Instance Connections
While structures depict associations between classes, instance connections, as thename suggests, show associations between objects Since objects cannot beinstantiated from abstract classes, there can be no instance connection to or from
an abstract class In the analysis phase an instance connection reflects a mappingbetween objects in the problem domain Note that while instance connections de-note association they do not imply inheritance since instance connections are aweaker type of association than a Whole-Part or Gen-Spec structure Like all otherelements of system analysis, all instance connections should be within the system’sresponsibilities
29.7.1 Instance Connection Notation
Instance connections are shown in class diagrams as solid lines between objects.Optionally, instance connection lines can be labeled to show the nature of the asso-ciation Coad and Yourdon consider that these labels are usually unnecessary Thenotation includes numbers that indicate the upper and lower bounds of the objectassociation Figure 29.18 shows an example of instance connection notation
Figure 29.18 Example of Instance Connection Notation
In Figure 29.18 we note that each driver can have zero or one license, and thateach license must correspond to a single driver In the first case the numericalconstraint is separated by a comma to indicate a range When there is no explicitupper bound the letter m can be used to replace the word “many”
29.8 Message Connections
While an instance connection represents a mapping between objects in the problemdomain, a message connection refers to messages being sent between objects Inthis context the term “sender” and “receiver” are often used The purpose of themessage is to obtain a processing operation which must be defined in both thesender’s and the receiver’s specifications Trivial and literal messages are not in-cluded in this convention Message connections occur when an object instantiates
an object of another class, or when an object uses methods defined in another class
29.8.1 Message Connection Notation
Coad and Yourdon notation uses gray lines to indicate message connections Inhand-drawn diagrams we could substitute them by dashed lines To illustrate a mes-sage connection suppose a graphics package with a class StraightLine and a class
LicenseDocumentDriverPerson
0, 1
1
Trang 32Polygon Each StraightLine object has a start point, an end point, and a thickness tribute A Polygon is drawn by instantiating several objects of the class StraightLine.Figure 29.19 shows the objects and the corresponding message connection notation.
at-Figure 29.19 Example of Message Connection Notation
Note that the arrow in Figure 29.19 points from the sender to the receiver of amessage This implies that the sender takes some specified action to which the re-ceiver replies by returning a result to the sender or by performing a predefined func-tion Although typically the message connection takes place between objects, it isalso possible to make the receiver a class, in which case it responds by instantiating
a new object An alternate notation uses a multipointed arrow in the case wheremore than one object is a receiver Note that human interactions with a system (usu-ally in the form of commands or requests) can often be depicted by means of mes-sage connection symbols
29.9 Final Documentation
Once the analysis has concluded we must put together the corresponding documents.The most important one is normally the class diagram However, in substantial proj-ects it is often necessary to reduce complexity by layering the class diagram, as fol-lows:
1 A layer indicating the various subsystems
2 A layer for each subsystem indicating inheritance in the form Gen-Spec andWhole-Part structures
3 A layer showing attributes and services for each class
4 A layer depicting instance and message connection for each object
In addition to the class and object diagrams, other documents are usually ated with the analysis phase, namely:
associ-1 A description of class and object specifications
2 State transition diagrams
3 Documents describing system constraints and critical threads of execution
StraightLinestart_x
start_yend_xend_ythickness
Trang 34817
Trang 36C++ Math Unit Programming
Summary
This appendix is about programming the Intel math unit which is part of all Pentiumand later CPUs The contents of this chapter relates to techniques for programmingthe Intel math unit using low-level code (Assembly Language) from C++
AA.0 Programming the Math Unit
High-level languages, such C++, provide no facilities for programming the Intel mathunit Usually, a programmer’s only choice consists of selecting a particular library that
is documented to use the math unit, and to hope for the best In regards to the mathunit programmer control is limited to selecting rounding modes and levels of preci-sion within C++ input and output functions Numerical calculations take place inside
a black box; all you see are input and results The difficulty is that math unit ming requires Assembly Language Fortunately, some C++ development systems forthe PC, such as Microsoft’s Visual C++, make it relatively easy to use Assembly Lan-guage code from C++ programs
program-The Intel processor architecture supports a segmented, 16-bit memory model,and a flat, 32-bit model Throughout the book we adopt the later one Using the32-bit, flat memory model ensures that the resulting code is compatible with Win-dows applications At the same time, Visual C++ console applications can also bedeveloped in flat memory model The one objection to this approach is that 32-bitcode is not compatible with MS DOS programs There are two possible routes fordeveloping the low-level component of a C++ application:
1 Develop the low-level code with assembler-based environment, such as Microsoft’sMASM After the source is assembled, the resulting object files are included in the Vi-sual C++ project and referenced at link time
2 Develop low-level routines using inline assembly
Although both methods work well, here are a few points to keep in mind:
819
Trang 371 Inline code is usually easier to develop and debug The program is created and tested
in a single environment, which often leads to faster development times
2 On the other hand, inline code cannot use assembler directives to define data jects The program must use C++ variables for all data, but not all math unit datatypes can be created in C++
ob-3 Developing math unit code in MASM results in separate low-level object files Thesefiles can be later converted into a static library or into dynamic-link library (DLL)which can be shared by several applications
The approach we have followed in this book is as follows:
1 We use pure assembly language modules, developed with MASM version 6.14, forthe core math unit routines The routines use a flat, 32-bit, memory model that iscompatible with both Windows programs and Visual C++ console-based applica-tions These routines are contained in the modules named UN32_?.ASM that arepart of MATH32.LIB
2 Each directly accessible assembly language procedure is furnished with a C++ face function The C++ interface often contains inline assembly code The interfacefunctions are located in header files for the corresponding modules of MATH32.LIB.For example, UN32_4 defines the following public procedures:
inter-PUBLIC _ASCII_TO_EXP ; ASCII string to exponential form
PUBLIC _MATH_UNIT_OUTPUT ; ST(0) register to ASCII decimal
PUBLIC _MATH_UNIT_INPUT ; ASCII exponential string to ST(0)
PUBLIC _GET_TAG ; Get math unit register tag code
These four low-level procedures were developed in MASM and the resulting ject file (UN32_4) is one of the modules of MATH32.LIB
ob-The C++ interface functions to these four procedures are located in the headerfile Un32_4.h They are prototyped as follows:
int MathunitInput(char[]);
void AsciiToExp(char[], char[]);
int MathunitOutput(char[]);
int GetTag(int, char[]);
The header file also declares the external references to the corresponding cedures in MATH32.LIB The C++ application developer uses the interface func-tions to access the core procedures
pro-AA.1 MASM Sources in C++ Programs
Suppose an assembly language module named TESTX.ASM that contains a dure named _ID_CPU The module uses the following MASM directives:
proce-PUBLIC _ID_CPU ; The PUBLIC declaration makes the procedure
; accessible from outside the module 486 ; Use math unit instruction set
.MODEL FLAT ; Generate 32-bit code for a flat memory
; architecture
Trang 38.CODE ; Module code follows
To assemble the module you will use the command:
MASM TESTX /Zi;
Note that the /Zi switch ensures Codeview compatibility for easy debugging ing successful assembly MASM produces the file TESTX.OBJ After assembly youcopy both files, TESTX.ASM and TESTX.OBJ, to the Visual C++ project directory.Now, from Visual C++, you use the Add to Project button to add both files
Dur-At this point both the source and object files for the low-level module are able to the Visual C++ environment In order to gain access to the low-level proce-dure named _ID_CPU (located in the TESTX.OBJ module) you must declare it as anexternal reference, as follows:
avail-extern “C” void ID_CPU();
Notice the C++ adds a leading underscore symbol to all external references matically For this reason the assembly language function (_ID_CPU) must containthe leading _ By the same token, the C++ extern statement does not use a leading _
auto-in referencauto-ing the procedure
The C++ program is compiled and linked normally, whether it be a Windows or aConsole application
AA.1.1 Sample Code
The following example is from the C++ project Test Un32_1 that is developed where in the book The project contains three source files:
else-1 The C++ main source, which is the program’s entry point This file is namedUn32_1.cpp
2 A C++ header file, named Un32_1.h, which contains the interface routines to thelow-level function
3 The Assembly Language source file containing the low-level code for the processingroutines
The C++ source file, Test Un32_1.cpp, is coded as follows:
//**************************************************************
// Test and exercise for the interface functions to the
// routines in the Un32_1 module of the MATH32 library
//**************************************************************
// Reference: SOFTWARE SOLUTIONS FOR SCIENTISTS AND ENGINEERS
// By Sanchez and Canton
// Workspace : \Test Un32_1
// Entry point: Test Un32_1.cpp
// Other files: Un32_1.asm
// Development: Visual C++ 6.0 Console Application
// Dates: December 23/2000
Trang 39// Description:
// Driver module for exercising procedures in the
// Un32_1 module of MATH32.LIB
cout << “Testing IntToAsc10()\n”;
cout << “Enter value: ”;
cout << “Testing IntToAsc16()\n”;
cout << “Enter value: ”;
cout << “Testing AscToInt\n”;
cout << “Enter ASCII string (10 digits or less): ”;
cin >> asc10;
res1 = AscToInt(asc10);
cout << “Result = ” < res1;
cout << “\n\n”;
Trang 40// Reference: SOFTWARE SOLUYTIONS FOR SCIENTISTS AND ENGINEERS
// by Sanchez and Canton
// Workspace : \Test Un32_1
// Entry point: Test Un32_1
// Other files: Un32_1.asm
// C++ interface functions for some of the procedures
// in the Un32_1 module of the MATH32 library
// Note:
// Interface to the other procedures in the Un32_1
// module of MATH32.LIB is not provided since the
// book includes equivalent functions in C++ If
// other interfaces are required, the reader can use
// the listed ones as a pattern.
//************************************************************
// Listing of all procedures in the Un32_1 module of MATH32.LIB
extern “C” BIN_TO_ASC10(); // 16-bit binary into 5-digit ASCII decimal extern “C” BIN_TO_ASC16(); // 16-bit binary into 4-digit ASCII hex
extern “C” ASCII_TO_EDX(); // 4-digit ASCII decimal to binary in EDX
extern “C” BINF_TO_DECF(); // 8-bit binary to 8-digit decimal fraction extern “C” DECODE_SINGLE();// Isolate elements of single precision
extern “C” BIN_TO_BCD(); // 16-bit binary to 5 BCD digits
extern “C” BCD_TO_ASCII(); // 5 unpacked BCD to 5 ASCII digits
extern “C” BCD_INTO_REG(); // 5-digit BCD into a binary in DX
extern “C” BCD12_TO_ASCSTR();// BCD12 number in ASCII string
extern “C” ASCII_TO_BCD12(); // ASCII decimal string into BCD12 format extern “C” ASCII_TO_EDX(); // ASCII to binary in EDX register
//**************************************************************
//**************************************************************
void IntToAsc10(int, char[]);
void IntToAsc16(int, char[]);
int AscToInt(char[]);
//**************************************************************
// C++ interface functions to some procedures in
// the Un32_1.asm module of MATH32.LIB