Java | Programming Fundations: Object-Oriented Design

§Programming Fundations: Object-Oriented Design

§Q & Term

  1. Objects are always physical or visible items. [False]
  2. Responsibilities should be stored in one master object. [False]
  3. Single Responsibility Principle and Open/Closed Principle are two of the principles of object-oriented design that are grouped under the acronym SOLID.
  4. Instantiation
  5. Data hiding/encapsulation
  6. FURPS: function, usability, reliability, performance, supportability
  7. Controlling visibility: Keeping an attribute private but creating a public operation to return the value of the attribute
  8. An interface contains [method signature] that have no functionality.
  9. Design patterns are split into the creational, structural, and behavioral groups.

§Core Concepts

  • class: name, attribution, behavior
  • Abstraction
  • Encapsulation: rescrict access -> information hiding or data hiding
  • Inheritance
  • Polymorphism: do the correct behavior for each one.

§Object-Oriented Analysis and Design

  • Process

    1. Gather your requirements: Must-do

      Functional Requirements: Feature/Capabilities

      Non-Funciontal Requirements: Help, Legalm Performance, Support, Security

      -> FURPS(Function, Usability, Reliability, Performance, Supportability)

      +Design requirements, Implementation r, Interface r, Physical r

    2. describe the application

    3. identify the most important objects

    4. describe the interaction between those objects

    5. create a class diagram

  • UML(Unified modeling Language)

§Utilizing Use Cases

  • Title(What is the goal) + Actor(Who esires it) + Scenario(How is it accomplished) + Extensions/Precondition/…

  • Use case diagram

  • User Story: As a (type of user), I want (goal), so that (reason)

  • User Stories Use Cases
    short - one index card long - a document
    one goal, no details multiple goals and details
    informal casual to (very formal)
    “placeholder for conversation” “record of conversation”

§Domain Modeling(Modeling the APP)

  1. Identifying objects: Noun List in User Case Scenario -> select as Conceptual Object Model
  2. Identifing class relationships: link & symbol
  3. Identifing class responsibilities: Verb List(what has happend/whose job) -> rename & split
  4. Using CRC(Class, ) cards
    • Class name
    • Responsibility of the class
    • Collaboratior: the other classes it interacts with

§Creating Classes

  • Class Diagram: Visibility: -private +public

    Class name eg. Product Spaceship
    Attributes - name: String = “New Product”
    - isActive: Boolean
    - launchDate: Date
    - itemNumber: Integer
    + name: String
    - shieldStringth: Integer
    Operations + getName(): String
    + setActive(Bollean)
    + getProductDetails(): String
    + displayProduct()
    - formatProductDetails(): String
    + fire(): String
    + reduceShields(Integer)
  • Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Spaceship{

// instance variables
public String name;
private int ShieldStringth;

//method
public String fire(){
return "Boom!";
}

public void reduceShields(int amount){
ShieldStringth -= amount;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@interface Spaceship: NSObject{
@public
NSString *name;
@private
int shieldStringth;
}
//method declarations
- (NSString *) fire;
- (void) reduceShields:(int) amount;
@end

@implementation Spaceship
- (NSString *) fire{
return @"Boom!";
}
- (void) reduceShields:(int) amount{
shieldStringth -= amout;
}
@end
  • Class lifetime

    • Instantiation

      1
      2
      3
      4
      5
      6
      Java	Customer fred = new Costomer();
      C# Customer fred = new Costomer();
      VB.NET Dim fred As New Customer
      Ruby fred = Customer.new
      C++ Customer *fred = new Costomer();
      Obective-C Customer *fred = [[Customer alloc] init];
    • Constructoe example

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      public class Spaceshio{
      ...
      // constructor method
      public Spaceship(){
      name = "Unnamed ship";
      shieldStringth = 100;
      }
      //overloaded constructor
      public Spaceship(String n){
      name = n;
      shieldStrength = 200;
      }
      ...
      }
    • Destructors/Finalizers

      1. called when an object is being deleted/deallocated/released
      2. Use for releasing resources

      A destructor is called when disposing of an object that is no longer necessary.

  • Using static/shared members

    • Static variables

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      public class SacingsAccount{
      // instance variables
      public String accountMnumber;
      private Money balance;
      //static variables
      /*
      //public (accessible) static variable
      public static float interestRate;
      // changed to private
      */

      private static float interestRate
      //public static methods
      /*static methods can only access static variable, static data.*/
      public static setInterestRate(float r){
      interestRate = r;
      }
      public static getInterestRate(){
      return interestRate;
      }
      ...
      }
      //access normal instance-level variables
      the name of the object.accountNumber
      //access a public static/shared variable
      the name of the class.interetRate

§Inheritance and Compostion

  • Using inheritance: “IS A”

    1
    2
    3
    4
    5
    6
    7
    Java	public class Album extends Product{...}
    C# public class Album : Product{...}
    VB.NET Public Class Album
    Inherits Product ...
    Ruby class Album < Product ...
    C++ class Album : public Product{...}
    Objective-C @interface Album : Product {...}
    • Overriding

      1
      2
      3
      4
      5
      6
      Jave	super.doSomething();
      C# base.doSomething();
      VB.NET Mybase.doSomething();
      Ruby super do_something
      Objective-C [super someMethod];
      C++ NamedBaseClass::doSomething();
  • Using abstract Class

    1
    2
    Java	abstract class BankAccount{...}
    VB.NET Public MustInherit Class BankAccount ...
  • Using Interfaces

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    // not allowed to put functionality inside an interface
    interface Printable{
    //method sigature
    void print();
    void printToPDF(String filename);
    }
    // if implements the interface -> have to provide those 2 methods and implementation for them
    class MyClass implements Printable{
    //method bodies
    public void print(){
    //provide implementation
    }
    public void printToPDF(String filename){
    //provide implementation
    }
    }
    • Benefits: Could have many different classes choose to implement the same interface.

      eg. In Java I’d use instance of other languages do it different ways, but the concept is the same, we can just ask, does the object that I have support that particular interface, if it does, I know I can use it.

      1
      2
      3
      4
      5
      6
      while (genericObject in listOfObjects){
      if (genericObject instanceOf Printable){
      // if it implements the interface, we can use it
      genericObject.print();
      }
      }
      <>
      Printable
      print()
      printToPDF()
  • Using aggregation and composition

    • Aggregation: “HAS A” relationship of Inheritation

    • Composition: a more specific form of Aggregation, implies ownership

    • eg.

      1. Classroom[1] ——aggregation —— Student[*]

        If deleted the Classroom Object, perhaps the class got canceled -> Student objects won’t destroyed, they may be used in different classrooms or just be able to live on their own

      2. Document[1] —— composition(implies ownership) —— Page[1…*]

        But if I were to delete the Document object all the associated Page objectsshould be deleted too

§Advanced Concepts

  • Structural/Static diagrams: Class D

    -> But they are not so great at representing the lifetime of an object or actually how objects interact with one other

    -> Behavior/Dynamic diagrams: Sequence D(eg. Pleanse see 04:20’s pic)

  • UML Diagrams:

    Class Diagram, Use Case D, Object D, Sequence D, State Machine D, Activity D, Deploment D, Package D, Component D, Profile D, Communication D, Timing D, Composite Structure D, Interaction Overview D

  • UML Tools: Please see 01:32’s pic or Wikipedia page

§Object-Oriented Design Patterns

  • “Gang of Four” / “GoF” book:

    Creational Patterns, Structural P, Behavioral P

  • eg. the Singleton Pattern

    • ensure a class only has one instance

    • one way of accessing it

    • 1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      public class MySingleton{
      // placeholder for current singleton object
      private static MySingleton _me = null;
      // private constructor - now no other object can instantiate
      private MySingleton(){}
      // this is how you ack for the singleton
      public static MySingleton getInstance(){
      // do I exist?
      if (_me == null){
      // if not, instantiate and store
      _me = new MySignleton);
      }
      return _me;
      }
      // additional functionality
      public someMethod(){//...}
      }

      // ask for the singleton
      MySingleton single = MySingleton.getInstance();
      //use it
      single.someMethod();

      //or even just call it directly
      MySingleton.getInstance.someMethod();
  • eg. the Memento Pattern

    • Handles “undo” in an object

    • Does not violate encapsulation

    • Originator: original state, Caretaker, Moemento

      C requestes O saveState => O creates a M: O: os, M, and it bundles the information up in the M and returns it to the C => C:M, O:os

      call to the O to change state => O:changed state

      calls can from C or others => O: changed again

      revert to a particular state: C:M hands back M to O => O:changed again, M, C and ask it to restore to itself => O: os

§Object-Oriented Design Priciples

  • General Softwre Development Pricibles

    1. DRY: Don’t Repeat Yourself

    2. YAGNI: You Ain’t Gonna Need it

    3. Example Code Smells

      Long methods, Very short(or long) identifiers, Pointless comments

      God object: one master object that tries to do everything in the program, or at least one object that seems to be doing very different responsibilities that have nothing to do with each other -> need to be revisited and broken apart

      Feature envy: If a class seems to do very little except use all the methods of one other class -> need to rethink the roles of one or the other

  • SOLID Priciples

    • S: Single Responsibility Principle: object should have one reason to exist, one reason to change - one primary responsibility

    • O: Open/Closed Principle: open for extension, but closed to modification

      eg. Inheritance: if get a new business requirement -> support it by adding a new class, privide some new code if it need a new business behavior, don’t change the original superclass

    • L: Liskov Substitution Principle: derived classes must be substitutable for their base classes

      if we’ve created a whole bunch of derived classes or child classes, no one can be treated specially

    • I: Interface Segregation Principle: Multiple spefic interfaces are better than one general purpose interface

      those lists of methods should be as small as possible.

      If they start to get bigger, they should be split up into smaller interfaces.Because classes can choose to implement multiple smaller interfaces, no classshould be forced to support huge lists of methods that it doesn’t need.

    • D: Dependency Inversion Principle: depend on abstractions, not on concretions

      eg. Store — AudioFileReader & AudioFileWriter

      Add a layer of abstraction -> make it more flexibility

      Store — Reader — MovieFileReader, AudioFileReader, …

      ​ — Writer — MovieFileWriter, AudioFileWriter, …

  • GRASP(General Responsibility Assignment Software Patterns) Principles

    • Creator, Controller, Pure Fabrication, Information Expert, High Cohesion, Indirection, Low Coupling, Polymorphism, Protected Variations

    • Expert/Information Expert: Assign the reponsibility to the class that has the information needed to fulgfill it

    • Creator: Who is responsible for creating an object?

    • Low Coupling/High Cohesion

      • Coupling: the level of dependencies between objects

        -> do reduce the amount of requirement connections between objects

- Cohesion: the level that a class contains focused, related behaviors

  a measure of how focused the internal behavior of a class is. Are all its behaviors related to that single responsibility?

  eg. God object has low cohesion 
  • Controller: Don’t connect UI elements directly to business objects(problem: high coupling, low cohesion)

    eg. Business Object <-> Controller Object: eg. Model View Controller <-> User Interface Object

  • Pure Fabrication: When the behavior does not belong anywhere else, create a new class

    if force that behavior into an existing class where it doesn’t belong -> decreasing Cohesion -> so we fabricate a new class

  • Indirection: to reduce coupling, introduce an intermediate object

    If you have multiple objects that need to talk to each other -> HIGH COUPLING -> so put an Ondirection Object to simplify the amount of connections -> decrease coupling between objects

  • Polymorphism: automatically correct behavior based on type

    As opposed to: conditional logic that checks for particular type -> we want to reduce checks

  • Protected Variations: protect the system from changes and viriations

    How to design a system so that changes and variations have the minimum impact on what already exists

    • Identify the most likely points of change
    • Use multiple techniques: encapsulation, LSP, OCP…

§Conclusion

  • Objective-Oriented Languages

    Language Inheritance Typing Call to super Private Methods Abstract Classes Interfaces
    Java Single static super Yes Yes Yes
    C# Single static base Yes Yes Yes
    VB.NET Single static Mybase Yes Yes Yes
    Objective-C Single static/dynamic sper No No Protocols
    C++ Multiple static name of class:: Yes Yes Abstract Class
    Ruby Mix-ins dynamic super Yes n/a n/a
    JavaScript Prototype dynamic n/a Yes n/a n/a
  • Additional resources

    Software Requirements by Karl Wiegers

    Alistair Cockburn’s Writing Effective Use Cases

    Mike Cohn’s User Stories Applied/User Stories Applied for Agile Software Development

    UML Distilled & Refactoring by Martin Fowler

    Head First Design Patterns