This site is from a past semester! The current version will be here when the new semester starts.

Week 4 [Fri, Feb 2nd] - Topics

Detailed Table of Contents



Guidance for the item(s) below:

In the tP, you'll be thrown into a codebase of about 6K

LoC
. It would be hard to understand the design simply by reading the code. That's why the code base comes with a Developer Guide containing some design models i.e., the diagrams. That means, you should be able to interpret those models by the time you start the tP in a few weeks. 😨

Let's start getting ready for that today. First, let's go through a high-level explanation of models.

[W4.1] Design: Models

W4.1a

Design → Modelling → Introduction → What

Can explain models

A model is a representation of something else.

A class diagram is a model that represents a software design.

A model provides a simpler view of a complex entity because a model captures only a selected aspect. This omission of some aspects implies models are abstractions.

A class diagram captures the structure of the software design but not the behavior.

Multiple models of the same entity may be needed to capture it fully.

In addition to a class diagram (or even multiple class diagrams), a number of other diagrams may be needed to capture various interesting aspects of the software.


W4.1b

Design → Modelling → Introduction → How

Can explain how models are used

In software development, models are useful in several ways:

a) To analyze a complex entity related to software development.

Some examples of using models for analysis:

  1. Models of the
    problem domain
    can be built to aid the understanding of the problem to be solved.
  2. When planning a software solution, models can be created to figure out how the solution is to be built. An architecture diagram is such a model.

b) To communicate information among stakeholders. Models can be used as a visual aid in discussions and documentation.

Some examples of using models to communicate:

  1. You can use an architecture diagram to explain the high-level design of the software to developers.
  2. A business analyst can use a use case diagram to explain to the customer the functionality of the system.
  3. A class diagram can be reverse-engineered from code so as to help explain the design of a component to a new developer.

c) As a blueprint for creating software. Models can be used as instructions for building software.

Some examples of using models as blueprints:

  1. A senior developer draws a class diagram to propose a design for an OOP software and passes it to a junior programmer to implement.
  2. A software tool allows users to draw UML models using its interface and the tool automatically generates the code based on the model.
Model Driven Development extra


Exercises:

Statements about models


Explain usage of models in a class project



W4.1c

Design → Modelling → Introduction → UML models

Can identify UML models

Unified Modeling Language (UML) is a graphical notation to describe various aspects of a software system. UML is the brainchild of three software modeling specialists James Rumbaugh, Grady Booch and Ivar Jacobson (also known as the Three Amigos). Each of them had developed their own notation for modeling software systems before joining forces to create a unified modeling language (hence, the term ‘Unified’ in UML). UML is currently the most commonly used modeling notation used in the software industry.

The following diagram uses the class diagram notation to show the different types of UML diagrams.



Guidance for the item(s) below:

Now that we have a high-level understanding of the role played by models, let's start learning some UML models, starting with UML class diagrams (and object diagrams which are like a close cousin of class diagrams).

Note that we are learning to interpret these models only, not draw them (that would come later), or design them. Hence, we will be going through these topics fairly rapidly.

[W4.2] Class/Object Diagrams: Basics

Video Q+

W4.2a

Design → Modelling → Modelling Structure → OO structures

Can explain structure modeling of OO solutions

An OO solution is basically a network of objects interacting with each other. Therefore, it is useful to be able to model how the relevant objects are 'networked' together inside a software i.e. how the objects are connected together.

Given below is an illustration of some objects and how they are connected together. Note: the diagram uses an ad-hoc notation.

Note that these object structures within the same software can change over time.

Given below is how the object structure in the previous example could have looked like at a different time.

However, object structures do not change at random; they change based on a set of rules set by the designer of that software. Those rules that object structures need to follow can be illustrated as a class structure i.e. a structure that exists among the relevant classes.

Here is a class structure (drawn using an ad-hoc notation) that matches the object structures given in the previous two examples. For example, note how this class structure does not allow any connection between Genre objects and Author objects, a rule followed by the two object structures above.

UML Object Diagrams model object structures. UML Class Diagrams model class structures.

Here is an object diagram for the above example:

And here is the class diagram for it:


W4.2b

Design → Modelling → Modelling Structure → Class diagrams - basic

Can use basic-level class diagrams

Contents related to UML diagrams in the panels given below belong to a different chapter (i.e., the chapter dedicated to UML); they have been embedded here for convenience.

Classes form the basis of class diagrams.

UML Class Diagrams → Introduction → What

UML class diagrams describe the structure (but not the behavior) of an OOP solution. These are possibly the most often used diagrams in the industry and are an indispensable tool for an OO programmer.

An example class diagram:


UML Class Diagrams → Classes → What

The basic UML notations used to represent a class:

A Table class shown in UML notation:

The equivalent code


The 'Operations' compartment and/or the 'Attributes' compartment may be omitted if such details are not important for the task at hand. Similarly, some attributes/operations can be omitted if not relevant to the purpose of the diagram. 'Attributes' always appear above the 'Operations' compartment. All operations should be in one compartment rather than each operation in a separate compartment. Same goes for attributes.

The visibility of attributes and operations is used to indicate the level of access allowed for each attribute or operation. The types of visibility and their exact meanings depend on the programming language used. Here are some common visibilities and how they are indicated in a class diagram:

  • + : public
  • - : private
  • # : protected
  • ~ : package private

How visibilities map to programming language features


Table class with visibilities shown:

The equivalent code


Generic classes can be shown as given below. The notation format is shown on the left, followed by two examples.


Exercises:

Which classes are correct?


Draw Car class



UML Class Diagrams → Class-Level Members → What

In UML class diagrams, underlines denote class-level attributes and methods.

In the class diagram below, the totalStudents attribute and the getTotalStudents method are class-level.


Associations are the main connections among the classes in a class diagram.

OOP Associations → What

Objects in an OO solution need to be connected to each other to form a network so that they can interact with each other. Such connections between objects are called associations.

Suppose an OOP program for managing a learning management system creates an object structure to represent the related objects. In that object structure you can expect to have associations between a Course object that represents a specific course and Student objects that represent students taking that course.

Associations in an object structure can change over time.

To continue the previous example, the associations between a Course object and Student objects can change as students enroll in the course or drop the course over time.

Associations among objects can be generalized as associations between the corresponding classes too.

In our example, as some Course objects can have associations with some Student objects, you can view it as an association between the Course class and the Student class.

Implementing associations

You use instance level variables to implement associations.

In our example, the Course class can have a students variable to keeps track of students associated with a particular course.


UML Class Diagrams → Associations → What

You should use a solid line to show an association between two classes.

This example shows an association between the Admin class and the Student class:


UML Class Diagrams → Associations as Attributes

An association can be shown as an attribute instead of a line.

Association multiplicities and the default value can be shown as part of the attribute using the following notation. Both are optional.

name: type [multiplicity] = default value

The diagram below depicts a multi-player Square Game being played on a board comprising of 100 squares. Each of the squares may be occupied with any number of pieces, each belonging to a certain player.

A Piece may or may not be on a Square. Note how that association can be replaced by an isOn attribute of the Piece class. The isOn attribute can either be null or hold a reference to a Square object, matching the 0..1 multiplicity of the association it replaces. The default value is null.

The association that a Board has 100 Squares can be shown in either of these two ways:

Show each association as either an attribute or a line but not both. A line is preferred as it is easier to spot.

Diagram (a) given below shows the 'author' association between the Book class and the Person class as a line while (b) shows the same association as an attribute in the Book class. Both are correct and the two are equivalent. But (c) is not correct as it uses both a line and an attribute to show the same association.

(a)
(b)
(c)


The most basic class diagram is a bunch of classes with some solid lines among them to represent associations, such as this one.

An example class diagram showing associations between classes.

In addition, associations can show additional decorations such as association labels, association roles, multiplicity and navigability to add more information to a class diagram.

UML Class Diagrams → Associations → Labels

Association labels describe the meaning of the association. The arrow head indicates the direction in which the label is to be read.

In this example, the same association is described using two different labels.

  • Diagram on the left: Admin class is associated with Student class because an Admin object uses a Student object.
  • Diagram on the right: Admin class is associated with Student class because a Student object is used by an Admin object.

UML Class Diagrams → Associations → Roles

Association Role are used to indicate the role played by the classes in the association.

This association represents a marriage between a Man object and a Woman object. The respective roles played by objects of these two classes are husband and wife.

Note how the variable names match closely with the association roles.

class Man {
    Woman wife;
}

class Woman {
    Man husband;
}
class Man:
  def __init__(self):
    self.wife = None # a Woman object

class Woman:
   def __init__(self):
     self.husband = None # a Man object

The role of Student objects in this association is charges (i.e. Admin is in charge of students)

class Admin {
    List<Student> charges;
}
class Admin:
  def __init__(self):
    self.charges = [] # list of Student objects

Association roles are optional to show. They are particularly useful for differentiating among multiple associations between the same two classes.

In each the three associations between the Flight class and the Airport class given below, the Airport class plays a different role.


OOP Associations → Navigability

When two classes are linked by an association, it does not necessarily mean the two objects taking part in an instance of the association knows about (i.e., has a reference to) each other. The concept of which object in the association knows about the other object is called navigability.

Navigability can be unidirectional or bidirectional. Suppose there is an association between the classes Box and Rope, and the Box object b and the Rope object r is taking part in one instance of that association.

  • Unidirectional: If the navigability is from Box to Rope, b will have a reference to r but r will not have a reference to b. That is, one can navigate from b to r using the b's object reference of r (but not in the other direction).
    Similarly, if the navigability is in the other direction, r will have a reference to b but b will not have a reference to r.
  • Bidirectional: b will have a reference to r and r will have a reference to b i.e., the two objects will be pointing to each other for the same single instance of the association.

Note that two unidirectional associations in opposite directions do not add up to a single bidirectional association.

In the code below, there is a bidirectional association between the Person class and the Cat class i.e., if Person p is the owner of the Cat c, p it will result in p and c having references to each other.

class Person {
    Cat pet;
    //...
}

class Cat{
    Person owner;
    //...
}
class Person:

  def __init__(self):
    self.pet = None  # a Cat object


class Cat:

  def __init__(self):
    self.owner = None  # a Person object

The code below has two unidirectional associations between the Person class and the Cat class (in opposite directions) because the breeder is not necessarily the same person keeping the cat as a pet i.e., there are two separate associations here, which rules out it being a bidirectional association.

class Person {
    Cat pet;
    //...
}

class Cat{
    Person breeder;
    //...
}
class Person:

  def __init__(self):
    self.pet = None  # a Cat object


class Cat:

  def __init__(self):
    self.breeder = None  # a Person object

UML Class Diagrams → Associations → Navigability

Use arrowheads to indicate the navigability of an association.

In this example, the navigability is unidirectional, and is from the Logic class to the Minefield class. That means if a Logic object L is associated with a Minefield object M, L has a reference to M but M doesn't have a reference to L.

class Logic {
    Minefield minefield;
    // ...
}

class Minefield {
    //...
}
class Logic:
  
  def __init__(self):
    self.minefield = None
    
  # ...


class Minefield:
  # ...

Here is an example of a bidirectional navigability; i.e., if a Dog object d is associated with a Man object m, d has a reference to m and m has a reference to d.

class Dog {
    Man man;
    // ...
}

class Man {
    Dog dog;
    // ...
}
class Dog:
  
  def __init__(self):
    self.man = None
    
  # ...


class Man:
  def __init__(self):
    self.dog = None

  # ...

Navigability can be shown in class diagrams as well as object diagrams.

According to this object diagram, the given Logic object is associated with and aware of two MineField objects.


Exercises:

What does the navigability given by this diagram mean?



OOP Associations → Multiplicity

Multiplicity is the aspect of an OOP solution that dictates how many objects take part in each association.

The multiplicity of the association between Course objects and Student objects tells you how many Course objects can be associated with one Student object and vice versa.

Implementing multiplicity

A normal instance-level variable gives us a 0..1 multiplicity (also called optional associations) because a variable can hold a reference to a single object or null.

In the code below, the Logic class has a variable that can hold 0..1 i.e., zero or one Minefield objects.

class Logic {
    Minefield minefield;
    // ...
}

class Minefield {
    //...
}
class Logic:
  
  def __init__(self):
    self.minefield = None
    
  # ...


class Minefield:
  # ...

A variable can be used to implement a 1 multiplicity too (also called compulsory associations).

In the code below, the Logic class will always have a ConfigGenerator object, provided the variable is not set to null at some point.

class Logic {
    ConfigGenerator cg = new ConfigGenerator();
    ...
}

In the Logic class, ensure there is a variable that refers to a ConfigGenerator object.

To implement other multiplicities, choose a suitable data structure such as Arrays, ArrayLists, HashMaps, Sets, etc.

This code uses a two-dimensional array to implement a 1-to-many association from the Minefield to Cell.

class Minefield {
    Cell[][] cell;
    //...
}
class Minefield:

  def __init__(self):
    self.cells = {1:[], 2:[], 3:[]}

UML Class Diagrams → Associations → Multiplicity

Commonly used multiplicities:

  • 0..1 : optional, can be linked to 0 or 1 objects.
  • 1 : compulsory, must be linked to one object at all times.
  • * : can be linked to 0 or more objects.
  • n..m : the number of linked objects must be within n to m inclusive.

In the diagram below, an Admin object administers (is in charge of) any number of students but a Student object must always be under the charge of exactly one Admin object.

In the diagram below,

  • Each student must be supervised by exactly one professor. i.e. There cannot be a student who doesn't have a supervisor or has multiple supervisors.
  • A professor cannot supervise more than 5 students but can have no students to supervise.
  • An admin can handle any number of professors and any number of students, including none.
  • A professor/student can be handled by any number of admins, including none.

Exercises:

Which statement agrees with the multiplicity shown in this diagram?



Here is the same class diagram shown earlier but with some additional information included:


Exercises:

Which association notations are shown?


Explain Class Diagram


Draw Class Diagram for Box etc.



W4.2c

Design → Modelling → Modelling Structure → Object diagrams

Can use basic object diagrams

UML → Object Diagrams → Introduction

An object diagram shows an object structure at a given point of time.

An example object diagram:


Object diagrams can be used to complement class diagrams. For example, you can use object diagrams to model different object structures that can result from a design represented by a given class diagram.

UML → Object Diagrams → Objects

Notation:

Notes:

  • The class name and object name are underlined e.g. car1:Car.
  • objectName:ClassName is meant to say 'an instance of ClassName identified as objectName'.
  • Unlike classes, there is no compartment for methods.
  • Attributes compartment can be omitted if it is not relevant to the purpose of the diagram.
  • Object name can be omitted too e.g. :Car which is meant to say 'an unnamed instance of a Car object'.

Some example objects:


Exercises:

Draw Book object



UML → Object Diagrams → Associations

A solid line indicates an association between two objects.

An example object diagram showing two associations:



Exercises:

Draw an Object Diagram for Box etc.



W4.2d

Tools → UML → Object versus class diagrams

Can distinguish between class diagrams and object diagrams

Compared to the notation for class diagrams, object diagrams differ in the following ways:

  • Show objects instead of classes:
    • Instance name may be shown
    • There is a : before the class name
    • Instance and class names are underlined
  • Methods are omitted
  • Multiplicities are omitted. Reason: an association line in an object diagram represents a connection to exactly one object (i.e., the multiplicity is always 1).

Furthermore, multiple object diagrams can correspond to a single class diagram.

Both object diagrams are derived from the same class diagram shown earlier. In other words, each of these object diagrams shows ‘an instance of’ the same class diagram.

When the class diagram has an inheritance relationship, the object diagram should show either an object of the parent class or the child class, but not both.

Suppose Employee is a child class of the Person class. The class diagram will be as follows:

Now, how do you show an Employee object named jake?

  • This is not correct, as there should be only one object.

  • This is OK.

  • This is OK, as jake is a Person too. That is, we can show the parent class instead of the child class if the child class doesn't matter to the purpose of the diagram (i.e., the reader of this diagram will not need to know that jake is in fact an Employee).

Association labels/roles can be omitted unless they add value (e.g., showing them is useful if there are multiple associations between the two classes in concern -- otherwise you wouldn't know which association the object diagram is showing)

Consider this class diagram and the object diagram:

We can clearly see that both Adam and Eve lives in hall h1 (i.e., OK to omit the association label lives in) but we can't see if History is Adam's major or his minor (i.e., the diagram should have included either an association label or a role there). In contrast, we can see Eve is an English major.


Exercises:

Which class diagrams match the object diagram?




[W4.3] Class Diagrams: Intermediate-Level

Video Q+

W4.3a

Tools → UML → Notes

Can use UML notes

UML notes can augment UML diagrams with additional information. These notes can be shown connected to a particular element in the diagram or can be shown without a connection. The diagram below shows examples of both.

Example:


W4.3b : OPTIONAL

Tools → UML → Constraints


W4.3c

Design → Modelling → Modelling Structure → Class diagrams - intermediate

Can use intermediate-level class diagrams

A class diagram can also show different types of relationships between classes: inheritance, compositions, aggregations, dependencies.

Modeling inheritance

OOP → Inheritance → What

The OOP concept Inheritance allows you to define a new class based on an existing class.

For example, you can use inheritance to define an EvaluationReport class based on an existing Report class so that the EvaluationReport class does not have to duplicate data/behaviors that are already implemented in the Report class. The EvaluationReport can inherit the wordCount attribute and the print() method from the base class Report.

  • Other names for Base class: Parent class, Superclass
  • Other names for Derived class: Child class, Subclass, Extended class

A superclass is said to be more general than the subclass. Conversely, a subclass is said to be more specialized than the superclass.

Applying inheritance on a group of similar classes can result in the common parts among classes being extracted into more general classes.

Man and Woman behave the same way for certain things. However, the two classes cannot be simply replaced with a more general class Person because of the need to distinguish between Man and Woman for certain other things. A solution is to add the Person class as a superclass (to contain the code common to men and women) and let Man and Woman inherit from Person class.

Inheritance implies the derived class can be considered as a sub-type of the base class (and the base class is a super-type of the derived class), resulting in an is a relationship.

Inheritance does not necessarily mean a sub-type relationship exists. However, the two often go hand-in-hand. For simplicity, at this point let us assume inheritance implies a sub-type relationship.

To continue the previous example,

  • Woman is a Person
  • Man is a Person

Inheritance relationships through a chain of classes can result in inheritance hierarchies (aka inheritance trees).

Two inheritance hierarchies/trees are given below. Note that the triangle points to the parent class. Observe how the Parrot is a Bird as well as it is an Animal.

Multiple Inheritance is when a class inherits directly from multiple classes. Multiple inheritance among classes is allowed in some languages (e.g., Python, C++) but not in other languages (e.g., Java, C#).

The Honey class inherits from the Food class and the Medicine class because honey can be consumed as a food as well as a medicine (in some oriental medicine practices). Similarly, a Car is a Vehicle, an Asset and a Liability.


Exercises:

Which statements are correct?



UML → Class Diagrams → Inheritance → What

You can use a triangle and a solid line (not to be confused with an arrow) to indicate class inheritance.

Notation:

Examples: The Car class inherits from the Vehicle class. The Cat and Dog classes inherit from the Pet class.

It does not matter whether the triangle is filled or empty.

Here's an example that combines inheritance with generics:

class Foo<T> {
}

class Bar<T> extends Foo<T> {
}

class Goo extends Foo<String> {
}

Modeling composition

OOP → Associations → Composition

A composition is an association that represents a strong whole-part relationship.

A Board (used for playing board games) consists of Square objects.

Composition implies,

  1. when the whole is destroyed, parts are destroyed too i.e., the part cannot exist without being attached to a whole.
  2. there cannot be cyclical links.

The ‘sub-folder’ association between Folder objects is a composition type association. Consider the case of Folder object subF is a sub-folder of Folder object F. In this case,

  1. if F is deleted, subF will be deleted with it.
  2. F cannot be a sub-folder of subF (i.e., no cyclical 'sub-folder' association between the two objects).

Whether a relationship is a composition can depend on the context.

Is the relationship between Email and EmailSubject composition? That is, is the email subject part of an email to the extent that an email subject cannot exist without an email?

  • When modeling an application that sends emails, the answer is 'yes'.
  • When modeling an application that gather analytics about email traffic, the answer may be 'no' (e.g., the application might collect just the email subjects for text analysis).

A common use of composition is when parts of a big class are carved out as smaller classes for the ease of managing the internal design. In such cases, the classes extracted out still act as parts of the bigger class and the outside world has no business knowing about them.

Cascading deletion alone is not sufficient for composition. Suppose there is a design in which Person objects are attached to Task objects and the former get deleted whenever the latter is deleted. This fact alone does not mean there is a composition relationship between the two classes. For it to be composition, a Person must be an integral part of a Task in the context of that association, at the concept level (not simply at implementation level).

Identifying and keeping track of composition relationships in the design has benefits such as helping to maintain the data integrity of the system. For example, when you know that a certain relationship is a composition, you can take extra care in your implementation to ensure that when the whole object is deleted, all its parts are deleted too.

Implementing composition

Composition is implemented using a normal variable. If correctly implemented, the ‘part’ object will be deleted when the ‘whole’ object is deleted. Ideally, the ‘part’ object may not even be visible to clients of the ‘whole’ object.

Here is one way to implement the composition between Email and Subject:

class Email {
    private Subject subject;
  ...
}
class Email:

  def __init__(self):
    self.__subject = Subject()

In this code, the Email has a composition type relationship with the Subject class, in the sense that the subject is part of the email.


UML → Class Diagrams → Composition → What

UML uses a solid diamond symbol to denote composition.

Notation:

A Book is composed of Chapter objects. As a result, when the Book object is destroyed, its Chapter objects are destroyed too.


Modeling aggregation

OOP → Associations → Aggregation

Aggregation represents a container-contained relationship. It is a weaker relationship than composition.

SportsClub can act as a container for Person objects who are members of the club. Person objects can survive without a SportsClub object.

Implementing aggregation

Implementation is similar to that of composition except the containee object can exist even after the container object is deleted.

In the code below, there is an aggregation association between the Team class and the Person class in that a Team contains a Person object who is the leader of the team.

class Team {
    Person leader;
    ...
    void setLeader(Person p) {
        leader = p;
    }
}
class Team:
  
  def __init__(self):
    self.__leader = None
    
  def set_leader(self, person):
    self.__leader = person

UML → Class Diagrams → Aggregation → What

UML uses a hollow diamond to indicate an aggregation.

Notation:

Example:

Aggregation vs Composition

The distinction between composition (◆) and aggregation (◇) is rather blurred. Martin Fowler’s famous book UML Distilled advocates omitting the aggregation symbol altogether because using it adds more confusion than clarity.


Exercises:

Which one is not recommended to use?



Modeling dependencies

OOP → Associations → Dependencies

In the context of OOP associations, a dependency is a need for one class to depend on another without having a direct association in the same direction. Reason for the exclusion: If there is an association from class Foo to class Bar (i.e., navigable from Foo to Bar), that means Foo is obviously dependent on Bar and hence there is no point in mentioning dependency specifically. In other words, we are specifically focusing on non-obvious dependencies here. One cause of such dependencies is interactions between objects that do not have a long-term link between them.

A Course class can have a dependency on a Registrar class because the Course class needs to refer to the Registrar class to obtain the maximum number of students it can support (e.g., Registrar.MAX_COURSE_CAPACITY).

In the code below, Foo has a dependency on Bar but it is not an association because it is only a

transient
interaction and there is no long term relationship between a Foo object and a Bar object. i.e. the Foo object does not keep the Bar object it receives as a parameter.

class Foo {

    int calculate(Bar bar) {
        return bar.getValue();
    }
}

class Bar {
    int value;

    int getValue() {
        return value;
    }
}
class Foo:

    def calculate(self, bar):
        return bar.value;

class Bar:

    def __init__(self, value):
      self.value = value

UML → Class Diagrams → Dependencies → What

UML uses a dashed arrow to show dependencies.

Two examples of dependencies:

Dependencies vs associations:

  • An association is a relationship resulting from one object keeping a reference to another object (i.e., storing an object in an instance variable). While such a relationship forms a dependency, we need not show that as a dependency arrow in the class diagram if the association is already indicated in the diagram. That is, showing a dependency arrow does not add any value to the diagram.
    Similarly, an inheritance results in a dependency from the child class to the parent class but we don't show it as a dependency arrow either, for the same reason as above.
  • Use a dependency arrow to indicate a dependency only if that dependency is not already captured by the diagram in another way (for instance, as an association or an inheritance) e.g., class Foo accessing a constant in Bar but there is no association/inheritance from Foo to Bar.

A class diagram can also show different types of class-like entities:

Modeling enumerations

OOP → Classes → Enumerations

An Enumeration is a fixed set of values that can be considered as a data type. An enumeration is often useful when using a regular data type such as int or String would allow invalid values to be assigned to a variable.

Suppose you want a variable called priority to store the priority of something. There are only three priority levels: high, medium, and low. You can declare the variable priority as of type int and use only values 2, 1, and 0 to indicate the three priority levels. However, this opens the possibility of an invalid value such as 9 being assigned to it. But if you define an enumeration type called Priority that has three values HIGH, MEDIUM and LOW only, a variable of type Priority will never be assigned an invalid value because the compiler is able to catch such an error.

Priority: HIGH, MEDIUM, LOW


UML → Class Diagrams → Enumerations → What

Notation:

In the class diagram below, there are two enumerations in use:


Exercises:

Define WeekDay Enum



Modeling abstract classes

OOP → Inheritance → Abstract Classes

Abstract class: A class declared as an abstract class cannot be instantiated, but it can be subclassed.

You can declare a class as abstract when a class is merely a representation of commonalities among its subclasses in which case it does not make sense to instantiate objects of that class.

The Animal class that exists as a generalization of its subclasses Cat, Dog, Horse, Tiger etc. can be declared as abstract because it does not make sense to instantiate an Animal object.

Abstract method: An abstract method is a method signature without a method implementation.

The move method of the Animal class is likely to be an abstract method as it is not possible to implement a move method at the Animal class level to fit all subclasses because each animal type can move in a different way.

A class that has an abstract method becomes an abstract class because the class definition is incomplete (due to the missing method body) and it is not possible to create objects using an incomplete class definition.


UML → Class Diagrams → Abstract Classes → What

You can use italics or {abstract} (preferred) keyword to denote abstract classes/methods.

Example:


Modeling interfaces

OOP → Inheritance → Interfaces

An interface is a behavior specification i.e. a collection of

method specifications
. If a class
implements the interface
, it means the class is able to support the behaviors specified by the said interface.

There are a number of situations in software engineering when it is important for disparate groups of programmers to agree to a "contract" that spells out how their software interacts. Each group should be able to write their code without any knowledge of how the other group's code is written. Generally speaking, interfaces are such contracts. --Oracle Docs on Java

Suppose SalariedStaff is an interface that contains two methods setSalary(int) and getSalary(). AcademicStaff can declare itself as implementing the SalariedStaff interface, which means the AcademicStaff class must implement all the methods specified by the SalariedStaff interface i.e., setSalary(int) and getSalary().

A class implementing an interface results in an is-a relationship, just like in class inheritance.

In the example above, AcademicStaff is a SalariedStaff. An AcademicStaff object can be used anywhere a SalariedStaff object is expected e.g. SalariedStaff ss = new AcademicStaff().


UML → Class Diagrams → Interfaces → What

An interface is shown similar to a class with an additional keyword <<interface>>. When a class implements an interface, it is shown similar to class inheritance except a dashed line is used instead of a solid line.

The AcademicStaff and the AdminStaff classes implement the SalariedStaff interface.



Exercises:

Statements about class diagrams


Explain notations in the class diagram


Draw a Class Diagram for the code (StockItem, Inventory, Review, etc.)



W4.3d

Paradigms → OOP → Associations → Association classes

Can explain the meaning of association classes

An association class represents additional information about an association. It is a normal class but plays a special role from a design point of view.

A Man class and a Woman class are linked with a ‘married to’ association and there is a need to store the date of marriage. However, that data is related to the association rather than specifically owned by either the Man object or the Woman object. In such situations, an additional association class can be introduced, e.g. a Marriage class, to store such information.

Implementing association classes

There is no special way to implement an association class. It can be implemented as a normal class that has variables to represent the endpoint of the association it represents.

In the code below, the Transaction class is an association class that represents a transaction between a Person who is the seller and another Person who is the buyer.

class Transaction {

    //all fields are compulsory
    Person seller;
    Person buyer;
    Date date;
    String receiptNumber;

    Transaction(Person seller, Person buyer, Date date, String receiptNumber) {
        //set fields
    }
}

Exercises:

Which are suitable as an Association Class?



W4.3e

Tools → UML → Class Diagrams → Association Classes → Association classes

Can interpret association classes in class diagrams

Association classes are denoted as a connection to an association link using a dashed line as shown below.

In this example Loan is an association class because it stores information about the borrows association between the User and the Book.



Guidance for the item(s) below:

Switching to Java now, let's learn how to write Java GUIs. Fair warning: GUI programming is hard in any language, especially so in Java. Buckle down and get through it; there's no way around it.

[W4.4] Java: JavaFX

W4.4a

C++ to Java → Miscellaneous Topics → JavaFX

Can use JavaFX to build a simple GUI

JavaFX is a technology for building Java-based GUIs. Previously it was a part Java itself, but has become a third-party dependency since then. It is now being maintained by OpenJDK.

Refer to the JavaFX tutorial @SE-EDU/guides to learn how to get started with JavaFX.



Guidance for the item(s) below:

While we are on the topic of Java, also take note of this is a lesser-known Java 'syntactic sugar' feature that was introduced not long ago, in case you come across it one day or find some use for it in your coding.

[W4.5] Java: varargs

W4.5a :

C++ to Java → Miscellaneous Topics → Varargs

Can use Java varargs feature

Variable Arguments (Varargs) is a syntactic sugar type feature that allows writing a method that can take a variable number of arguments.

The search method below can be called as search(), search("book"), search("book", "paper"), etc.

public static void search(String ... keywords){
   // method body
}

Resources:



Guidance for the item(s) below:

Last week, we started learning about code quality. Let's continue on that, but learning a few other aspects of code quality.

[W4.6] Code Quality: Naming

W4.6a

Implementation → Code Quality → Naming → Introduction

Can explain the need for good names in code

Proper naming improves the readability of code. It also reduces bugs caused by ambiguities regarding the intent of a variable or a method.

There are only two hard things in Computer Science: cache invalidation and naming things. -- Phil Karlton


W4.6b

Implementation → Code Quality → Naming → Basic → Use nouns for things and verbs for actions

Can improve code quality using technique: use nouns for things and verbs for actions

Every system is built from a domain-specific language designed by the programmers to describe that system. Functions are the verbs of that language, and classes are the nouns.
-- Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship

Use nouns for classes/variables and verbs for methods/functions.

Name for a Bad Good
Class CheckLimit LimitChecker
Method result() calculate()

Distinguish clearly between single-valued and multi-valued variables.

Good

Person student;
ArrayList<Person> students;

Good

name = 'Jim'
names = ['Jim', 'Alice']

W4.6c

Implementation → Code Quality → Naming → Basic → Use standard words

Can improve code quality using technique: use standard words

Use correct spelling in names. Avoid 'texting-style' spelling. Avoid foreign language words, slang, and names that are only meaningful within specific contexts/times e.g. terms from private jokes, a TV show currently popular in your country.


W4.6d

Implementation → Code Quality → Naming → Intermediate → Use name to explain

Can improve code quality using technique: use name to explain

A name is not just for differentiation; it should explain the named entity to the reader accurately and at a sufficient level of detail.

Bad Good
processInput() (what 'process'?) removeWhiteSpaceFromInput()
flag isValidInput
temp

If a name has multiple words, they should be in a sensible order.

Bad Good
bySizeOrder() orderBySize()

Imagine going to the doctor's and saying "My eye1 is swollen"! Don’t use numbers or case to distinguish names.

Bad Bad Good
value1, value2 value, Value originalValue, finalValue

W4.6e

Implementation → Code Quality → Naming → Intermediate → Not too long, not too short

Can improve code quality using technique: not too long, not too short

While it is preferable not to have lengthy names, names that are 'too short' are even worse. If you must abbreviate or use acronyms, do it consistently. Explain their full meaning at an obvious location.


W4.6f

Implementation → Code Quality → Naming → Intermediate → Avoid misleading names

Can improve code quality using technique: avoid misleading names

Related things should be named similarly, while unrelated things should NOT.

Example: Consider these variables

  • colorBlack: hex value for color black
  • colorWhite: hex value for color white
  • colorBlue: number of times blue is used
  • hexForRed: hex value for color red

This is misleading because colorBlue is named similar to colorWhite and colorBlack but has a different purpose while hexForRed is named differently but has a very similar purpose to the first two variables. The following is better:

  • hexForBlack hexForWhite hexForRed
  • blueColorCount

Avoid misleading or ambiguous names (e.g. those with multiple meanings), similar sounding names, hard-to-pronounce ones (e.g. avoid ambiguities like "is that a lowercase L, capital I or number 1?", or "is that number 0 or letter O?"), almost similar names.

Bad Good Reason
phase0 phaseZero Is that zero or letter O?
rwrLgtDirn rowerLegitDirection Hard to pronounce
right left wrong rightDirection leftDirection wrongResponse right is for 'correct' or 'opposite of 'left'?
redBooks readBooks redColorBooks booksRead red and read (past tense) sounds the same
FiletMignon egg If the requirement is just a name of a food, egg is a much easier to type/say choice than FiletMignon


Guidance for the item(s) below:

Next up are two techniques that can be used to improve code quality. You need to learn them as you will be encountering both in your iP soon.

[W4.7] Static Analysis

W4.7a

Quality Assurance → Quality Assurance → Static Analysis → What

Video

Can explain static analysis

Static analysis: Static analysis is the analysis of code without actually executing the code.

Static analysis of code can find useful information such as unused variables, unhandled exceptions, style errors, and statistics. Most modern IDEs come with some inbuilt static analysis capabilities. For example, an IDE can highlight unused variables as you type the code into the editor.

The term static in static analysis refers to the fact that the code is analyzed without executing the code. In contrast, dynamic analysis requires the code to be executed to gather additional information about the code e.g., performance characteristics.

Higher-end static analysis tools (static analyzers) can perform more complex analysis such as locating potential bugs, memory leaks, inefficient code structures, etc.

Some example static analyzers for Java: CheckStyle, PMD, FindBugs

Linters are a subset of static analyzers that specifically aim to locate areas where the code can be made 'cleaner'.



[W4.8] Code reviews

W4.8a

Quality Assurance → Quality Assurance → Code Reviews → What

Video

Can explain code reviews

Code review is the systematic examination of code with the intention of finding where the code can be improved.

Reviews can be done in various forms. Some examples below:

  • Pull Request reviews

    • Project Management Platforms such as GitHub and BitBucket allow the new code to be proposed as Pull Requests and provide the ability for others to review the code in the PR.
  • In pair programming

    • As pair programming involves two programmers working on the same code at the same time, there is an implicit review of the code by the other member of the pair.
  • Formal inspections

    • Inspections involve a group of people systematically examining project artifacts to discover defects. Members of the inspection team play various roles during the process, such as:

      • the author - the creator of the artifact
      • the moderator - the planner and executor of the inspection meeting
      • the secretary - the recorder of the findings of the inspection
      • the inspector/reviewer - the one who inspects/reviews the artifact

Advantages of code review over testing:

  • It can detect functionality defects as well as other problems such as coding standard violations.
  • It can verify non-code artifacts and incomplete code.
  • It does not require test drivers or stubs.

Disadvantages:

  • It is a manual process and therefore, error prone.

Resources:


Guidance for the item(s) below:

Being able to work with PRs is an essential skill. To get started on that, let's learn how to review PRs properly. Besides, you'll be doing some PR reviews in the iP this week.

[W4.9] RCS: Managing Pull Requests I

W4.9a

Tools → Git and GitHub → Reviewing PRs

Video

Can review PRs on GitHub

The PR review stage is a dialog between the PR author and members of the repo that received the PR, in order to refine and eventually merge the PR.

Given below are some steps you can follow when reviewing a PR.

1. Locate the PR:

  1. Go to the GitHub page of the repo.
  2. Click on the Pull requests tab.
  3. Click on the PR you want to review.

2. Read the PR description. It might contain information relevant to reviewing the PR.

3. Click on the Files changed tab to see the diff view.

You can use the following setting to try the two different views available and pick the one you like.

4. Add review comments:

  1. Hover over the line you want to comment on and click on the icon that appears on the left margin. That should create a text box for you to enter your comment.
    • To give a comment related to multiple lines, click-and-drag the icon. The result will look like this:
  2. Enter your comment.
    • This page @SE-EDU/guides has some best practices PR reviewers can follow.
    • To suggest an in-line code change, click on this icon:

      After that, you can proceed to edit the suggestion code block generated by GitHub (as seen in the screenshot above).
      The comment will look like this to the viewers:

  3. After typing in the comment, click on the Start a review button (not the Add single comment button. This way, your comment is saved but not visible to others yet. It will be visible to others only when you have finished the entire review.

  4. Repeat the above steps to add more comments.

5. Submit the review:

  1. When there are no more comments to add, click on the Review changes button (on the top right of the diff page).
  2. Type in an overall comment about the PR, if any. e.g.,
    Overall, I found your code easy to read for the most part except a few places
    where the nesting was too deep. I noted a few minor coding standard violations
    too. Some of the classes are getting quite long. Consider splitting into
    smaller classes if that makes sense.
    
    LGTM is often used in such overall comments, to indicate Looks good to me (or Looks good to merge).
    nit (as in nit-picking) is another such term, used to indicate minor flaws e.g., LGTM. Just a few nits to fix..
  3. Choose Approve, Comment, or Request changes option as appropriate and click on the Submit review button.