Object Oriented Programming Notes

Object Oriented Analysis, Design, & Development

Styles HotKeys:

Heading 1-6:         C-A-[1,2,3,4,5,6]

code1:                 C-A-C,C

code-Output:         C-A-C,V

Bullets:                C-S-L

 

 

Chapter 1:

Software Development Methodologies

 

Waterfall

Analysis > Design > Implementation > Installation > Maintenance

 

Agile / Iterative approach

Repeating cycles, getting closer to the goal

Just enough design to move forward successfully

“Good Enough”

 

Object Oriented Languages

Separate program into modular blocks

 

Procedural Languages

ProLog – Logic programming language

Haskell – Functional programming language

 

What is an Object?

Not always physical items

Not always visible items

Can you put ‘THE’ in front of it?

 

Example:

Bank Account

  • Property:        Number
  • Property:        Balance
  • Method:        Deposit
  • Method:        Withdrawl

 

What is a Class?

The Blueprint of an Object

NOT the Object itself

 

type

name: what is it?

        Employee, BankAccount, Event, Player, Document, Album

Properties, data

Attributes: what describes it?

        Width, Height, Color, Score, FileType, Length

 

Operations, methods

Behavior: what can it do?

        Play, Open, Search, Save, Print, Create, Delete, Close

 

Example:

Name: BankAccount

Attributes: accountNumber, balance, dateOpened, accountType

Behavior: open(), close(), deposit(), withdraw()

 

Class/ Objects

 

 

Existing Classes in OO Languages

  • Most OOP have predefined classes: strings, dates
  • Java Class Library
  • .NET Framework BCL
  • C++ Standard Library
  • Ruby Standard Library
  • Python Standard Library

 

 

4 Fundamental Ideas when Creating Classes

  • Abstraction
  • Polymorphism
  • Inheritance
  • Encapsulation

 

Abstraction

  • Focus on the essentials
  • Ignore the irrelevant
  • Ignore the unimportant

Example:

 

 

Polymorphism ( “many forms”)

  • Automatically do correct behavior if class can do many things
  • With inheritance…can change base class when inheriting.
  • a + b
  • if string concatenation
  • if integer, arithmetic
  • Overriding method of base class is one form
  • Inheriting when useful, overriding when useful

Example:

Can call the withdrawl() method regardless of account type

 

Inheritance

  • Code Re-use
  • Hand down attributes from one class to another – no need to re-write code

Person > Customer(+accountNumber)

Person > Employee(+companyName)

Example:

 

Encapsulation

  • Bundle Attributes and behaviors in same class
  • Restrict access to those attributes
  • Reducing dependencies

 

Example:

 

 

Chapter 2: Object Oriented Design Process

  1. Gather Requirements
  1. What does the app need to do?
  1. Describe the app
  1. Build a simple narrative in common language
  2. Use cases and user stories
  3. Smallest number of stories to suffice
  4. Prototype of UI
  1. Identify the main objects
  1. Use stories/descriptions to create objects
  2. Should be basis for classes
  1. Describe the Interactions
  1. Work out how the objects work together
  2. Sequence diagram
  1. Create a Class Diagram
  1. Visual representation of class

 

 

Gathering Requirements

Functional Requirements:

  • What does it need to do
  • Feature
  • Capabilities

Example:

System must:

  • Allow user to search by customer’s last name.

 

Non-Functional Requirements:

  • What else?
  • Help
  • Legal
  • Performance
  • Support

 

Example:

System must

  • respond to searches within 2 seconds
  • Helpdesk available by phone 24/7

 

FURPS / FURPS+

  • Functional
  • Usability
  • Reliability
  • Performance
  • Supportability
  • +Design
  • +Implementation
  • +Interface
  • +Physical

 

Go for minimum set of requirements to satisfy needs

WHAT IS REQUIRED?

 

Status ok if:

  • Not Applicable
  • TBA

 

SOMETHING WRITTEN DOWN

 

UML is at Tool in this process

 

 

Chapter 03

Use cases

  • Title – what is the goal?
  • Actor – who desires it?
  • Scenario – how is it accomplished?

 

Title

Short phrase, active verb

  • Register new member
  • Transfer funds
  • Purchase items

Actor

Need to identify WHO is having the interaction

  • User
  • Customer
  • Member
  • Administrator

 

Scenario

Details of accomplishing this one goal

 

One paragraph:

Title: Purchase items

Actor: Customer

Scenario: Customer reviews items in basket, checks out and pays

 

As Steps:

Title: Purchase items

Actor: Customer

Scenario:

  1. Customer reviews items in basket
  2. checks out
  3. pays

 

Additional Details

Extensions: Describe steps for out-of-stock situations

Extensions: Describe steps for order never finalized

Precondition: Customer has added at least one item to shopping cart

 

Fully Dressed Use Case

Templates useful here

 

Other

Spend 1 or 2 days per iteration

Only written text, no diagrams

 

Identify Actors

Actor – anything with behavior outside who lives outside of app, but has goal to accomplish with it

Questions:

  • Other computer systems/organizations
  • External data sources, web services, other corp apps, tax reporting, backup systems
  • Distinguish between roles/security
  • Visitor, member, admin, owner
  • Job titles / Departments
  • Manager, payroll admin, Production Staff, Exec, Account
  • Focus not on ROLE, but GOAL actor wants to accomplish
  • Different roles may have SAME GOAL

 

 

 

 

Many different ROLES, but only two main GOALS

 

 

 

 

 

Identify Scenarios

 

Emphasize the goal of ONE encounter

GOOD:

  • Purchase items
  • Create new Document
  • Balance accounts

 

BAD: Too Big

  • Log in to application
  • Write Book
  • Merge Organizations

 

Multiple Scenarios

 

 

Use Case Writing Tips

  • Keep it simple
  • Use Active Voice.
  • Omit Needless words.
  • Shoot for one sentence
  • Focus on intention, leave UI out of it
  • Use Case prompts (helps ID actors)
  • Who performs sys admin tasks
  • Who managers users and security
  • What happens if the system fails
  • Is anyone looking at performance metrics or logs

 

Diagramming Use Cases

 

Knowledge Base Example

  • Box Application name and Titles ( elipses )
  • Titles ( elipse )
  • Search Articles
  • View Article manage users
  • Create Article
  • View Analytics
  • Actors ( stick figures)
  • Visitor
  • Contributor
  • Administrator
  • Draw Lines from Actors to Titles
  • <<external actor>>: Analytics System ( << >> )

 

 

 

 

User Stories

  • Simpler and Shorter than Use Case
  • Describes single small scenario from users perspective ( where & why )
  • One-two sentences on index cards ( to force them to be short )
  • Format
  • As a (type of user)
  • I want (goal)
  • So that (reason)
  • Example 1
  • As a Bank Customer
  • I want to change my PIN online
  • So that I don’t have to go into a branch
  • Example 2
  • As a User
  • I want to search by keyword
  • So that I can find and read relevant articles
  • Can brainstorm many scenarios quickly
  • Focused on intention
  • Serve as placeholders for deeper conversation on a feature
  • Both stories and cases serve different purposes
  • Whatever we write stories/cases, they are input for the next step

 

 

Chapter 4: Creating a Conceptual Model

  • ID most important objects in the app
  • Change from users/actors to wider scope
  • Example: Product, shopping cart,
  • Focus on the OO structure of the application
  • Need requirements and user goals to consider structure
  • A few hours per iteration
  • Should be incomplete first time around

 

Identifying Objects

  • Start picking out nouns
  • Create noun list
  • Consolidate list – things that belong to a more general class

 

 

  • Box all the objects
  • Conceptual Object Model
  • Just using names of objects
  • By Creating diagram easy to see responsibilities and relationships between objects

  • Indicate main relationships/associations
  • Add a short note for the association
  • Better to have specific terms
  • Symbols to aid in visualization
  • One to many: 1-----*
  •  

 

 

Identifying Responsibilities

  • Highlight Verbs
  • Easy to find responsibilities
  • Not obvious where the responsibilities belong
  •  

 

  • Object should be responsible for itself
  • Object has responsibility of an action, not what is requesting
  • Customer is creating order, but is Order’s responsibility
  •  

 

  • Order has many responsibilities while Customer has none
  • A common trap is to assign too much responsibility to an Object

  • Avoid Global Master Objects

  • Responsibilities should be well distributed

 

CRC – Another Format To Use

  • Class
  • Responsibility
  • Collaboration
  • Card ( index card )

 

 

 

  • Move related CRC Cards together
  • Don’t go electronic yet
  • Forced constraint only can have so many cards
  • Too many cards can indicate another class is needed
  • Fless out ideas next

 

Chapter 5: Creating Class Diagram

  • Now closer to coding, official names encouraged
  • Attributes ( Pascal Case ( thisVar” ) )
  • Suggested Data Type ( : String )
  • Actual syntax not important, general idea ok
  • Default value ok too ( = “new product” )
  • Operations
  • get/set encouraged over change/read
  • Parameters ()
  • Return Type :()
  • - denotes private (encapsulation)
  • + denotes get/set
  • - name
  • Make private as much as possible
  • +getName
  • +setName
  • Notes with line to item

 

Avoid Building Plain Data Structures

  • Often people focus on the data, creating data structures
  • Focus on what they DO
  • Class has no behavior – revisit responsibilities

 

Transforming Class Diagrams to Code

Class Diagram

 

Example: Java

 

Example: C#

 

Example: VB.NET

 

Example: Ruby

 

Example: Objective-C

  • Has two files that separate interface and implementation

 

 

Exploring Object Lifetime

  • How are objects created
  • What happens when they are created
  • What happens when we are finished with them

 

Instantiation

  • Create a new object
  • “new” keyword
  • Do you take part in the instantiation?

 

 

Constructor

  • Special method that is called when object is created

Constructor in UML

 

Example: Java/C#/C++

  • Created Method in the Class with the same name as the Class

 

Syntax for several languages

Java/C#/C++

  • className()

VB.NET/Python

  • new()

Ruby

  • initialize()

OC

  • init()

 

Overloaded Constructors

  • multiple constructors with same name
  • each takes different number of parameters

Overloaded Constructor in UML

 

Destructors / Finalizers

  • Called when an object is destroyed/deallocated/released
  • Use for releasing resources
  • FileIO/ Document Open

 

Static/Shared Members

  • Method shared cross all members of a class
  • Many accounts share one interest rate
  • 1000s of accounts/variables
  • Don’t create a global variable for everything
  • Class Level variable vs. Instance Level variable
  • Value can change, but there’s only one of them

 

Creating Static Variables

 

Accessing Static Variable

  • Use the name of the class to access
  • savingsAccount.interestRate =- 0.5;

 

Creating Static Methods

  • Static Methods CANNOT work with Instance Variables
  • Static Methods CAN work with Static Variables

 

Showing Static Members in UML

 

Chapter 6: Inheritance

Inheritance

  • Describes “is a” relationship
  • Example 1
  • A Car is a Vehicle
  • Bus is a Vehicle
  • Car is a Bus
  • Example 2
  • An Employee is a person
  • A customer is a person
  • Example 3: multiple inheritance
  • A Corvette is a car is a vehicle
  • Example 4: No relationship
  • Bank is not a Bank Account
  • Bank Account is not a Bank
  • A Checking Account is a Bank Account
  • A Savings Account is a Bank Account

UML

  • Open Arrow
  • Parent/Super Class
  • Child Sub Class
  • Children can ‘override’ Parent Class
  • To REPLACE or ADD Parent Class implementation
  • Don’t over-inherit or over-think

  • Sub Classes will present themselves
  • Album
  • Book
  • Movie

  • THEN create Super Class and strip out similar behaviors and put into Super Class

  • Should be obvious
  • Can be identified from top-down or down-up
  • Not all classes will have inheritance

 

Example: Java

  • Object is Super Class of everything else

 

  • Be weary of more than 2-3 levels of inheritance

 

Inheritance in Varying Languages

 

Overriding in Varying Languages – See Language Ref

 

 

Calling a Method in the Super/Parent/Base Class in Varying Languages

 

Composition

  • Class that is never instantiated
  • Abstract Class
  • Never instantiated
  • Used as blueprint only
  • Used for inheritance only
  • Concrete Class
  • Instantiated

 

 

 

User Interfaces

  • Defining Interface Contracts
  • Has no functionality and only defines structure
  • Create a new class and choose to use an interface
  • More classes that use the contract, the better
  • Easier to manage/maintain
  • Don’t need to know how the Object works, just adhere to the Interface
  • Using Interfaces
  • Interface Title as <<Interface>>
  • Dotted Line to represent Interface- - - ->
  • “Implement an Interface”
  • “Program to an interface, not an implementation”
  • Then developer can choose how to implement the methods, not restricted
  • Interfaces preferred over inheritance, cleaner model
  • Objective-C uses “Protocol”: list of method signatures
  • “Conform to a protocol”

 

 

 

UML

 

Aggregation

  • Associations
  • Lines between objects suggesting some sort of interaction
  • Inheritance with Arrow
  • Describe an obvious relationship between objects
  • Object can be built off other objects
  • “HAS A” vs. “IS A”
  • Customer has a address
  • Car has a engine
  • Bank has many bank accounts

UML

  • Unfilled diamond <>

  • A Classroom HAS MANY Students

 

Composition

  • Composition implies Ownership
  • Not just “HAS A”
  • When Object is destroyed, associated Objects are destroyed also
  • Might need to write a deconstructor to remove
  • Difference
  • Removing Classroom, Students should still persist
  • Removing Document, removes Page

UML

 

 

Chapter 7: Sequence Diagrams

 

Sequence Diagrams

  • Does not describe entire system
  • Only one interaction
  • Start with object boxes for participants in interaction
  • If using class name, use colon
  • A Customer
  • a Cart: Shopping Cart
  • :Order
  • Draw Lines for interactions
  • Method names with (parameters)
  • createNewOrder
  • AddItem(item, quantity)
  • Itemtotal
  • Surround loops with a Frame
  • Don’t get too detailed, just basic interactions
  • For short-lived interactions, use X for the line
  • Send ---------- (solid line)
  • Return - - - - - -  (dotted line)
  • Should be able to work with BA (non-developer)
  • No need to diagram EVERY part of system
  • Only for situations that are not vary clear
  • Could identify need for new Class

 

UML Diagrams

  • 14 types

 

State Chart

  • Focused on a single object
  • How it changes state over time
  • Rectangle with rounded corners

 

Activity Diagram

  • Detail steps, transitions, and decisions that occur as flow through part of the system
  • Partitions/swim lanes
  • Represent different classes/business units that handle activity

 

UML Tools

Wikipedia.org has a list of UML tools

 

 

 

Chapter 8

Design Patterns

  • Gang of Four / “GoF”

Creational Patterns

  • Abstract Factory
  • Builder
  • Factory Method
  • Prototype
  • Singleton

 

Structural Patterns

  • Adapter
  • Bridge
  • Composite
  • Decorator
  • Façade
  • Flyweight
  • Proxy

 

Behavioral Patterns

  • Chain of Responsibility
  • Command
  • Interpreter
  • Iterator
  • Mediator
  • Memento
  • Observer
  • State
  • Strategy
  • Template method
  • Visitor

 

Singleton Design Pattern

  • Want only ONE of a class
  • NOT STATIC, since that is 0
  • SPECIFICALLY ONE

Example: Java

  • Create a static variable that acts as a placeholder for a Singleton (__me)
  • Create new method
  • Lazy Singleton, create upon FIRST request
  • Call static method “getInstance()”
  • Do I exist? If no, return the object
  • If so, do not create one

  • Calling

 

Memento Design Pattern

  • Managing change in a way that doesn’t violate encapsulation
  • Used for “UNDO” type functions
  • Arose naturally in the programming world and will be encountered often

 

Originator

  • original_state

 

Caretaker

  • When and why Originator needs to save or revert its state
  • Request originator to save itself

 

Pattern

  • Originator creates memento

  • Sends memento to Caretaker for storage

  • Request can come from anywhere, not just Caretaker, though caretaker always does the storing

  • Upon “REVERT” request, the Caretaker sends memento back to the originator

  • Originator back to original state

 

 

Chapter 9: Object Oriented Design Patterns

 

  • Language will not prevent poor design
  • Apply good OO practices
  • Not design patterns, but are general rules to follow
  • Did I design this well?

 

General Software Development Principles

  • DRY: Don’t Repeat Yourself ( duplicated code )
  • Don’t block copy code over and over, create a function/method
  • One place in the system that takes care of a problem
  • YAGNI: You Ain’t Gonna Need it ( unnecessary code )
  • Solve today’s problem
  • Don’t code for tomorrow

 

Code Smells

  • Long method (200-300 lines)
  • Very short (or long) identifiers
  • Pointless Comments

//this creates i and sets it to zero

int i = 0;

  • God Objects
  • Objects that do everything
  • Feature Envy
  • Class does very little, but use methods of another class

 

SOLID

 

  • Checklist of things to consider and look out for

SOLID

  • S: Single Responsibility Principle
  • O: Open/Closed Principle
  • L: Liskov Substitution Principle
  • I: Interface Segregation Principle
  • D: Dependency Inversion Principle

S: Single Responsibility Principle

  • An object should have one reason to exist, one reason to change – one primary responsibility

O: Open/Closed Principle

  • Open for extension, but closed for modification
  • Once written and working, don’t change old code, create new code
  • Inheritance
  • Class created, then new feature arises
  • Create new method/subclass

L: Liskov Substitution Principle

  • Derived classes must be substitutable for their base classes without altering correctness of the program
  • Extension of inheritance
  • Derived classes should be able to pass subclasses around in lieu of base class
  • Never should be able to use all BUT ONE subclass

 

I: Interface Segregation Principle

  • Multiple specific interfaces are better than one general purpose interface
  • Interfaces should be as small as possible
  • If too large, split into smaller Interfaces
  • No class should be forced to support huge interfaces it doesn’t need

D: Dependency Inversion Principle

  • Depend on abstractions not on concretions
  • Don’t tie concrete objects together, but deal with abstractions to reduce dependencies

  • Disconnect two very concrete classes
  • Insert new layer, abstract class
  • Store class isn’t dependent on the two AudioFile classes
  • Now any low-level class that inherits from Reader/Writer can be used
  • MovieFile Reader/Writer
  • GameFile Reader/Writer
  • Store object doesn’t need to be altered for updates
  • Flexibility

 

 

 

 

GRASP

GRASP

  • GRASP: General Responsibility Assignment Software Patterns
  • Focus on Responsibility
  • Who creates this object
  • Who takes care of receiving information from user interface
  • Compatible with SOLID

 

9 Principles

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

 

Expert/Information Expert

  • Assign the responsibility to the class that has the information needed to fulfill it
  • Object should take care of itself
  • Example
  • Customer, Shopping Cart, Item
  • “Current Total” belongs to the Shopping Cart as it knows most about the total

Creator

  • Who is responsible for creating an object
  • How the objects are created
  • Easy to tell interactions
  • Not easy to tell how they come into being
  • Sequence diagram can help
  • Q’s
  • Does one object contain another? (Composition)
  • One object closely use another
  • Know enough to make another object?

Low Coupling / High Cohesion

  • Coupling: the level of dependencies between objects
  • If one objects connects tightly to other objects
  • Things can break easily
  • Reduce dependencies to a minimum
  • Cohesion: the level that a class contains focused, related behaviors
  • AIM is LOW COUPLING, HIGH COHESION
  • Don’t connect UI elements directly to business objects
  • Concept: Model U Controller
  • Well described idea within the app
  • Create controller class for UI and Business Object

 

Pure Fabrication

  • When the behavior does not belong anywhere else, create a new class
  • Rather than force into an existing class ( decreasing cohesion ), create new class

 

Indirection

  • Decrease coupling between objects
  • Ro reduce coupling, introduce an intermediate object

 

Polymorphism

  • Automatically correct behavior based on type
  • As opposed to: conditional logic that checks for particular types

 

Protected Variations

  • Protect the system from changes and variations
  • Identify the most likely points of change
  • Use multiple techniques: encapsulation, LSP, OCP
  • Interfaces, Substitution, Overriding Classes, Open/Closed Principle

 

Chapter 10

 

Feature Support Across Languages

 

  • Inheritance
  • Typing
  • Most are static typed
  • Dynamic languages have flexibility without the static typing
  • Call to super
  • Private Methods
  • Protecting classes
  • Abstract Classes
  • Interfaces

 

Resources

  • Initial stage of determining requirements
  • “Software Requirements” by Carl Regas
  • Use Cases
  • “Writing Effect Use Cases” by Alistair Cockbens
  • “User Stories Applied for Agile Software Development” by Mike Koehn
  • UML
  • “UML Distilled” & “Refactoring” by Martin Fallor
  • Design Patterns
  • “Gang of Four” (C++)
  • “Head First Design Patterns” (Java)