Object-Oriented Design
Four Design Principles
Abstraction
Abstraction breaks a concept down into a simplified description that ignores unimportant details and emphasizes the essentials needed for the concept, within some context.
An abstraction should follow the rule of least astonishment. This rule suggests that essential attributes and behaviours should be captured with no surprises and no definitions that fall beyond its scope.
public class Food {
public String groceryID;
public String name;
public String manufacturer;
public Date expiryDate;
public double price;
public boolean isOnSale( Date date ) {
//
}
}
Encapsulation
- The ability to bundle attributes and behaviours into a self-contained object.
- The ability to expose certain attributes and behaviours of that object, which can be accessed from other objects, usually through an interface.
- The ability to restrict access to certain data and functions to only within the object.
Accessibility
- Public(+): can be accessed publicly
- Private(-): can only be accessed from within the class
Data Integrity
Getter methods | Setter methods | |
---|---|---|
Functionality | retrieve data | change data |
Naming | get{AttributeName} | set{AttributeName} |
Outcome | attribute will be returned | attribute will be changed |
Note | Getters often retrieve private data. | Setters often set a private attribute in a safe way. |
Decomposition
Association
The two objects are completely separate, but have a loose relationship.
public class Person {
public void checkin(Hotel hotel){
execute.checkin(hotel);
}
...
}
Aggregation
"Has-a" Relationship. Although parts can belong to wholes, they can also exist independently.
public class Airliner {
private ArrayList<CrewMember> crew;
public Airliner() {
crew = new ArrayList<CrewMember>();
}
public void add( CrewMember crewMember ) {
...
}
}
Composition
A whole cannot exist without its parts, and if the whole is destroyed, then the parts are destroyed too.
A house is made up of multiple rooms, but if you remove the house, the room no longer exists.
public class House {
private Room room;
public House(){
room = new Room();
}
}
Generalization
Inheritance
public abstract class Animal {
protected int numberOfLegs;
protected int numberOfTails;
protected String name;
public Animal( String petName, int legs, int tails ) {
this.name = petName;
this.numberOfLegs = legs;
this.numberOfTails = tails;
}
public void walk() { ... }
public void run() { ... }
public void eat() { ... }
}
public class Lion extends Animal {
public Lion( String name, int legs, int tails){
super( name, legs, tails );
}
public void roar() { ... }
}
Implementation
public abstract class Animal {
protected int numberOfLegs;
public void walk() { ... }
}
public abstract class Animal {
protected int numberOfLegs;
public Animal( int legs ) {
this.numberOfLegs = legs;
}
}