Designing Classes with UML
To this point, the chapter has discussed OOP in terms of both syntax and theory, but there are two other related topics worth exploring, both new additions to this edition. First up is an introduction to Unified Modeling Language (UML), a way to graphically represent your OOP designs. Entire books are written on the subject, but since this chapter covers the fundamentals of OOP, I’ll also introduce the fundamentals of UML.
A class at its core has three components:
- Its name
- Its attributes
- Its methods
UML graphically represents a class by creating a class diagram: a three-part box for each class, with the class name at the top. The next section of the box would identify the class attributes, and the third would list the methods .
How UML represents a class graphically.
For the attributes, the attribute type (e.g., string, array, etc.) is listed after the attribute’s name, as in
If the attribute had a default value, you could reflect that too:
width:number = 0
To define a method in a class diagram, you would start with the method name, placing its arguments and types within parentheses. This is normally followed by the type of value the method returns:
The sayHello() method doesn’t return anything, so its return type is void.
With this in mind, you can complete the class diagram for the HelloWorld class . In the next steps, you’ll design the diagram that reflects the Rectangle class.
A UML representation of the simple HelloWorld class.
To design a class using UML:
Using paper or software, draw a three-part box.
If you like the feeling of designing with paper and pencil, feel free, but there are also plenty of software tools that can fulfill this role, too. Search online for an application that will run on your platform, or for a site that can serve the same purposes within the browser.
Add the name of the class to the top of the box:
Use the class’s proper name (i.e., the same capitalization).
Add the attributes to the middle section:
width:number = 0 height:number = 0
Here are the two attributes for the Rectangle class. Both are numbers with default values of 0.
Add the constructor definition to the third part of the box:
_ _construct(width:number = 0, height:number = 0):void
This method is named _ _construct. It takes two arguments, both of type number, and both with default values of 0. The method does not return anything, so its return value is void.
Add the setSize() method definition:
setSize(width:number = 0, height:number = 0):void
The setSize() method happens to be defined exactly like _ _construct().
Add the getArea() method definition:
The getArea() method takes no arguments and returns a number.
Add the getPerimeter() method definition:
The getPerimeter() method also takes no arguments and returns a number.
Add the isSquare() method definition:
This method takes no arguments but returns a Boolean value.
- Save your design for later reference .
A UML representation of the simple Rectangle class.