# OOAD Lab 11, 12, 13 (05/18)
###### tags: `OOAD`
---
[TOC]
---
## 11. Movie Rental Example
- **`movie-p05`**
- not well designed, poorly written
- hard to change to deal with obvious future evolution.
- A design is made to deal with focused **future change**
- Not to copy-paste
- **centralize** the part of code that is subject to change in the future
- **未來的維護需求**
- 幾乎一定會發生
- 可能會發生
- 會發生但是可能性微乎其微
- **software entropy**
- **cost(fixing+debug+testing) > cost(rework) ---> TO REBUILD**
- **`movie-p11`**
- In most cases, **a method should be on the object whose data it uses**
- **`movie-p19`**
- **`movie-p21`**
- **`movie-p24`**
- **`movie-p25`**
- **`movie-p30`**
- **Remove temp variables**
- temp variables can be a problem, which encourage long routines
- **`movie-p33`**
- It is a **bad** idea to do a **switch based on an attribute of another object**
- **`movie-p36`**
- **`movie-p37`**
- In practice, such **`switch()`** can occurs **in several places**
- Each switch must be kept **consistent**
- Often, a switch that will change from time to time satisfies the precondition of subclassing. We can **replace it by polymorphism and inheritance**
- a movie object may change its classification during life time
- **An object cannot change its class during life time**
- **---> state design pattern**
- **`movie-p51`**
- **`movie-p52`**
- **Refactoring**
- The above technique is called refactoring, a mechanism to improve architecture of as-build codes.
- **change is based on step by step** and **each step is validated by all the testing cases**.
- It is of course, **not cost-free**
- **Design Pattern**
- 過去,在實做各種各類的軟體過程中,許多人累積了寶貴的物件導向分析經驗。經過蒐集整理,這些寶貴的繼承架構,class diagram,物件互動架構等等,被蒐集成所謂的 design patterns
- When you encounter some problems in OOAD or OOP. **It is rare that your problem is new.**
- design patterns are one kind of reuse, but not code reuse. Instead, it is a kind of **pattern reuse**.
- **Discussion**
- The main purpose of OOAD is to make our code **easy to maintain, change, and evolve**
- **Good architecture != good performance**
- **Don’t overdesign**. If the change will not occurs within 100 years, make the part Ooly is a waste of time.
- **Good OOAD must eventually demonstrate at the level of code.** Extensive programming experience is required.
## 12. UML Class Diagram
- UML Class Diagram
- A class diagram describes the **classes** and the association (**static relationship**) between these classes (描述系統中物件的type(class),以及這些class 的靜態關連.)
- association
- sub-type
- **Class Diagram**:

- **Class**
- ***Abstract Class***: ***"{abstract}"***
- ***Interface***: ***"\<\<interface>>"***
- **Attribute**
- ***Derived Attribute***: ***"/..."***
- **Operation** *(in OO, methods on a class)*:
***"`{visibility} {name}({parameter-list}): {return-type}`"***
- Visibility:
- *"+"*: public
- *"~"*: package
- *"#"*: protected
- *"-"*: private
- Example: *"+ foo(int a): float"*
- **Parameterized Class** *(talk about it later)*: ***[T]** (dotted blocked text on topper right)*
- **Association** *(兩類別之間的關聯)*: ***"---"***
- ***Aggregation*** *(talk about it later)*: ***"⬦---"***
- ***Composition*** *(talk about it later)*: ***"⬥---"***
- ***Dependency*** *(talk about it later)*: ***"- - -"***
- ***Qualified Association*** *(talk about it later)*: ***"|...]---"** (blocked text)*
- **Role name**
- **Derived Association**: ***"/..."***
- ~~**Navigability**: ***"--->"***~~
- specification model ---> a responsibility
- implementation diagram ---> a pointer
- UML 2.x remove this feature
- **Constraint**: ***"{...}"***
- 用來包含特別說明
- **Multiplicity**
- ***Optional***: ***"0..1"***
- ***Mandatory***: ***"1"***
- ***Many-valued***: ***"\*"***
- **Association Class** *(talk about it later)*: ***"- - -{class}"***
- **Generalization** *(in OO, inheritance)*: ***"---▷"***
- ***Realization*** *(talk about it later)*: ***"- - -▷"***
- **Classification** *(talk about it later)*: ***"---▶"***
- **Object Diagram** *(instance diagram)*:
- A snapshot of the objects in a system at a point in time
- Example: Composite design pattern
- Class Diagram:

- Code:
```cpp=
class party {
Location location;
virtual int computeSalary();
}
class person : party {
virtual int computeSalary() override {
return /* his personal wages */;
}
}
class organization : party {
vector<party*> children;
virtual int computeSalary() override {
int total = 0;
for(party* o : children)
total += o->computeSalary();
}
}
```
- Object Diagram:

- In UML, **"<u>underlines</u>"** means:
- **Object Diagram**
- it is objects, instead of classes
- **Class/Instance Scope**
- it belongs to classes, instead of objects
- **Static/Non-static members *(attributes & operations)***
- **Classification**: **"---▶"**
- **Generalization is transitive, classification is not**
- **Classification**: *"is a kind of"*
- **Generalization**: *"is a"*
- **Multiple Classification**:

- **Discriminator**:
- *"sex {complete}"*:
- *"sex"* **ONLY accept these types** *("Male", "Female")* BUT sub-types of them
- Not multiple inheritance in OO
- You should make it clear which combinations are legal by using a discriminator
- **Dynamic Classification**:

- **Discriminator**:
- *"job \<\<dynamic>>"*:
- *"job"* **allows object to change type** within the subtyping structure
- useful for conceptual modeling
- implementation? ---> **state design pattern**
- **Aggregation/Composition**:
- UML decide to include **aggregation** and **a stronger variety of aggregation called composition**
- Basically an aggregation/composition relation is still an association. They are used to **emphasize the type of association**
- **Aggregation** *(聚集)*: ***"⬦---"***
- A kind of **Association**
- A kind of **has-a relationship**
- 可分,多個物件組合成一個大單位,但是各物件仍獨立存在
- **Composition** *(合成)*: ***"⬥---"***
- A kind of **Association**
- A kind of **part-of relationship**
- 不可分,成為一體,通常不獨立存在,通常同時建構銷毀
- **Life cycle of children are controlled by the parent**
- OR in graphics, put this child-class inside the parent-class
- Example:
```cpp=
class X {vector<Y> a;}
```
- `X` is a composition of `vector<Y>`
- `vector<Y>` is a composition of `X`
- **`X` is NOT a composition of `Y`**
- **Derived Attribute/Association**: ***"/..."***
- Derived Associations and derived attributes can be calculated from other associations and attributes
- **Abstract Class/Interface**: ***"{abstract}"** | **"\<\<interface>>"***
- Programming language that use a single construct, the class, which contains both interface and implementation.
- an **abstract class** allows you to add implementation of some of the methods
- an **interface** forces you to defer definition of all methods
- **Dependency**: ***"- - -"***
- **Association**, but **use and not store it**
- **Realization**: ***"- - -▷"***
- **Generalization** with a **abstract class** / interface ("can-do")
- **Qualified Association**: ***"|...]---"** (blocked text)*

- *"Order Line"* is **indexed** by "Product"
- use an associative array or similar data structure (**map**) to hold the order lines
- **Association Class**: ***"- - -{class}"***

- Association class allow you to **add attributes, operations, and other features to association**
- Useful in **many-to-many relationship**
- Can add a derived association to redraw this diagram:

- **Parameterized Class** *(template in C++)*: ***[T]** (dotted blocked text on topper right)*

- **Visibility**
- **Conclusion**:

- **UML Drawing Tools**:
- **Web Tools**: *Gliffy*
- **IDE**: *VS 2015*
## 13. UML Sequence Diagram
- **Interaction Diagram**:
- how groups of **objects** *(NOT classes)* collaborate in some behavior
- Two kinds:
- **sequence diagrams**
- **collaboration diagrams**
- **UML 1.0 Sequence Diagram Example**:

- **Object**
- **Deletion**: End of its life cycle
- **Message**
- **Iteration**
- **Condition**
- **Self Call**
- **Return *(Data)***
- **Creation**
- **When to Use Sequence Diagram**:
- One of the hardest things to understand in an object-oriented program is the **overall flow of control**.
- **A good design has lots of small methods in different classes and at times** it can be tricky to figure out the overall sequence of behavior
- Valuable for **concurrent process**:

- **Distributed Control** is usually better than **Centralized Control**
- Sequence diagram 並**不擅長展示有 loop 等的演算法**
- **適合展示某個複雜的互動情境**
- **Creation & Deletion**:

- **Loop & Condition *(UML 2.0)***:

- Loop 以及 alternative 框架是 **UML 2.0** 之後才有的
有些人不喜歡 loop 以及 alternative 框架,而自行採用其他的方法如下圖

- Frame options:
- **alt**: Alternative Multiple Fragments
- only the one fragment whose condition is true will execute
- **opt**: Optional
- the whole fragment executes only if its condition is true
- **par**: Parallel
- each fragment is run in parallel
- **loop**: Loop
- the fragment may execute multiple times
- the guard indicates the basis of iteration
- **region**: Critical Region
- the fragment can have only one thread executing it at once
- **neg**: Negative
- the fragment shows an invalid interaction
- **ref**: Reference
- refers to an interaction defined on another diagram.
- **sd**: Sequence Diagram
- used to surround an entire sequence diagram, if you wish
- **Collaboration Diagram**:

- The **sequence is indicated by numbering the message**
- the **spatial layout** allows you to show other things more easily
- show **how object link together**
- you can **overlay packages or other information more easily**
- How to find **methods (behaviors, operations) of object**
- Six techniques for Finding Operations:
1. By Inspection
2. Basic CRUD
3. ***---> Use Cases <---***
4. Statechart Diagram
5. CRC Cards
6. CRUD Revisited
- **Use Case**:
- 使用案例 (系統使用情境 scenario)
- A **scenario** is a sequence of steps describing **an interaction between a user and a system**.
- Use cases 是你的系統所要完成的功能
- 這些功能當然要由你所設計的 objects 互動來完成
- **Use Case Diagram**:

- **最常看到的三種 Diagram**:
- **Class Diagram**
- **Sequence Diagram**
- **Use Case Diagram**
- **How to find methods of objects**
- **會畫與看懂 Sequence Diagram 不是重點,重點是要把物件的 Methods 找出來**
- Two methods:
- **Maximize**:
- **Do as much as you can.**
- Basically you **guess** how other applications will use your class.
- If your task is to **complete an application**, coding methods in **this way will never work**.
- Eg. CRC methods
- This is sometimes called the **“C++ newbie syndrome”**
- **Minimize** *(usually better)*:
- only **implement the needed methods**
- each method is **carefully planned**
- each method is **called by what classes is pre-determined.**
- each written method is **definitely invoked**
- **suitable for a project which has deadline with precise goals**.
- OOAD requires the **behaviors to be placed under the right class** to reduce maintenance problems
- Side effect:
- sometimes **the execution flow (logics) are obscured by inheritance and polymorphism**
- that is why UML introduces **sequence diagram** to visualize the execution flow of a scenario or test case
- **Use Case Based Approach**:
- **Precondition**:
- A close to 90% **correct class diagram (without methods yet)** should be ready.
- **Algorithm**:
- For each **use case**:
1. Write down **pseudo code**
2. For each **part of pseudo code**
1. Determine **which class** should take over or related
2. **Create methods** for the class
3. **Evaluate the code maintainability**
3. Until **each part of the pseudo code is placed**
- **Exercise**:
- **Use Case B.1 Creating an UML connection line**:
1. Kevin clicks assoc line button
2. In canvas, Kevin presses mouse button at (x1, y1)
3. Canvas mousepressed(x1, y1) is called
4. If (x1, y1) is located to object o1, save o1 port p1
5. In canvas, Kevin drag the mouse to (x2, y2)
6. If (x2, y2) is located to object o2, save o2 port p2
7. If o1 and o2 are basic object, create a line from (o1, p1) to (o2, p2)
- **Sequence Diagram dRawing Tool**: https://www.websequencediagrams.com