0% found this document useful (0 votes)
2 views

Module_9

The document outlines the Object-Oriented Design Process, detailing the phases of Analysis, Design, and Implementation, along with key principles such as SOLID. It emphasizes the importance of class relationships, coupling, cohesion, and various design principles to ensure effective software development. Additionally, it introduces UML diagrams and symbols to represent these concepts visually.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Module_9

The document outlines the Object-Oriented Design Process, detailing the phases of Analysis, Design, and Implementation, along with key principles such as SOLID. It emphasizes the importance of class relationships, coupling, cohesion, and various design principles to ensure effective software development. Additionally, it introduces UML diagrams and symbols to represent these concepts visually.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Object Oriented Programming

BITS Pilani Dr. Tanmaya Mahapatra and Asish Bera


Computer Science & Information Systems
Pilani Campus
BITS Pilani
Pilani Campus

Object-Oriented Model Design and Analysis


(Module- 9)
Object-Oriented Design Process

Phases: Analysis, Design, and Implementation


• The result of the analysis phase is a detailed textual description, commonly
called a functional specification, that has the following characteristics:
- It completely defines the tasks to be performed.
- It is free from internal contradictions.
- It is readable both by experts in the problem domain and by software developers.
- It is reviewable by diverse interested parties.
- It can be tested against reality.
• Describing the behavior of a system is a set of use cases.
• Analysis phase concerns itself with the description of what needs to be done,
not how it should be done.
• An advantage of that approach is that the object model of the analysis phase
can be carried forward to the design phase.
BITS Pilani, Pilani Campus
Design Phase

The program designer must structure the programming tasks into a set of interrelated
classes. Each class must be specified precisely, listing both its responsibilities and its
relationship to other classes in the system.
The exact choice of data structures, for example, hash tables or binary search trees for
a collection, is not of concern in the design phase but is deferred until
implementation.
Major goals of the design phase:
Identify the classes, the responsibilities of these classes, the relationships among
these classes, etc.

The result of the design process consists of:


A textual description of the classes and their most important responsibilities.
Diagrams of the relationships among the classes, important usage scenarios, State
diagrams of objects and others.

BITS Pilani, Pilani Campus


Implementation Phase

The classes and methods are coded, tested, and deployed.


Traditional programming methods rely on completion and unit testing of procedural
units, followed by an integration phase.

Object-oriented development encourages the gradual growth of a program by


successively attaching more working classes and class clusters and repeated
testing.

Object-oriented design is particularly suited for prototyping. Building a “rapid


prototype” that displays some functionality of the final product.

BITS Pilani, Pilani Campus


Object and Class Concepts

An object is characterized by its state, behavior, and identity.


The collection of all information held by an object is the object’s state. An
object’s state may change over time, but only when an operation has been
carried out on the object that causes the state change.
The behavior of an object is defined by the methods that an object supports.
Each object has its own identity. It is possible for two or more objects to
support the same operations and to have the same state, yet to be different
from each other.

BITS Pilani, Pilani Campus


Relationships Between Classes
• Dependency (“uses”): A class depends on another class if it manipulates objects of
the other class in any way.
-An important design goal is to minimize the number of dependency relationship, i.e.,
minimize the coupling between classes. A low degree of coupling tends to make it
much easier to implement changes in the future.
-Minimize the dependencies between classes. When classes depend on each other,
changes in one, enforces changes in others.

• Aggregation (“has-a”): Aggregation takes place if objects of one class contain


objects of another class over a period of time. Aggregation is a special case of
dependency. It is useful to keep track of these multiplicities for aggregation
relationship.

• Inheritance (“is-a”) A class inherits from another if it incorporates the behavior of the
other class. (Details are provided in earlier modules)

BITS Pilani, Pilani Campus


Pattern Coupling

Loosely Coupled: Patterns are loosely tied together with few connections,
making it easier to separate the patterns. They should promote quicker,
simpler for future changes.

Tightly Coupled: Patterns are tightly tied together with many links and
dependencies. Minor changes to one of the patterns will be difficult without
affecting the other(s).

BITS Pilani, Pilani Campus


Differences

Loose Coupling Tight Coupling


Objects are independent of One object is dependent on the
each other other to complete a task.

Testability is not as great as


Better testability
the loose coupling
Asynchronous
Synchronous communication
communication
Less coordination. Swapping Provides better coordination. You
code between two classes is can easily swap code between two
not easy. objects.
Less information flow More information flow

Highly changeable Does not have change capability

BITS Pilani, Pilani Campus


Cohesion

Cohesion: measures the degree to which the elements of a module are


functionally related. It is the internal relationship for keeping the modular
component together. A good software design should have a high cohesion.

Differences between coupling and cohesion


Cohesion is a concept of intra-module, whereas coupling is the concept of inter-
module. When there is an increase in cohesion, it is good for a software,
whereas an increasing coupling should be avoided.
Cohesion depicts the functional strength of a software, but coupling depicts the
independence among the modules.
Cohesion should be high and coupling should be loose for the best software. In
coupling, the modules are connected whereas in cohesion the module focuses
on a single element. (Paper)

BITS Pilani, Pilani Campus


Differences between coupling and
cohesion

BITS Pilani, Pilani Campus


Object-oriented Design (OOD) Principles

SOLID Property. The SOLID acronym stands for:


• Single Responsibility Principle (SRP)

• Open-Closed Principle (OCP)

• Liskov Substitution Principle (LSP)

• Interface Segregation Principle (ISP)

• Dependency Inversion Principle (DIP)


SRP: It states that each class should have one responsibility, one single
purpose. This means that a class will do only one job, which leads us to
conclude it should have only one reason to change.

BITS Pilani, Pilani Campus


Single Responsibility Principle Example
class Product { String Name;
double price; double taxRate;
Product(String Name, double price, double taxRate) {
this.Name = Name; public class Main {
this.price = price; public static void main(String args[])
this.taxRate = taxRate; { Product table = new Product("table",
} 10000, 0.15);
double getPrice() { TaxCalculator t= new TaxCalculator();
return this.price; System.out.println("Tax amount: "+
} t.calculateTax(table) );
double getTaxRate() { }
return this.taxRate; } }
}
class TaxCalculator {
double calculateTax(Product p) {
return p.getPrice() * p.getTaxRate();
}
}
BITS Pilani, Pilani Campus
Single Responsibility Principle
public class Resume {
The code violates the Single Responsibility String technology;
Principle, as the Resume class has two Integer yearsOfExperience;
responsibilities.
public String getTechnology() {
1. First, it sets the properties (technology and return technology; }
yearsofExperience) related to the Resume. public void setTechnology(String technology) {
this.technology = technology;
2. Second, it searches for the resume in the
} public Integer getYearsOfExperience() {
repository. The setter methods change the
return yearsOfExperience; }
Resume object, which might cause problems
when we want to search the same resume in
public void setYearsOfExperience(Integer yearsOfExperience)
the repository.
{ this.yearsOfExperience = yearsOfExperience; }
public void searchResume() {
//logic to search resume goes here
}}
BITS Pilani, Pilani Campus
Following Single Responsibility Principle
public class Resume {
String technology;
Integer yearsOfExperience;
public String getTechnology() {
return technology; }

public void setTechnology(String technology) {


this.technology = technology;
public class RepositoryView {
} Resume resume;
public Integer getYearsOfExperience() { public RepositoryView(Resume resume) {
return yearsOfExperience; } this.resume = resume;
public void setYearsOfExperience(Integer yearsOfExperience) { }
public void searchResume() {
this.yearsOfExperience = yearsOfExperience;
//logic to search resume goes here
}} }
}
BITS Pilani, Pilani Campus
Open-Closed Principle

The Open-Closed Principle (OCP) states that software entities (classes,


modules, functions, and others) should be open for extension, but
closed for modification. This means that the behavior of a software entity
can be extended without modifying its source code.

“Open to extension” means that you should design your classes so that
new functionality can be added as new requirements are generated.
“Closed for modification” means that once you developed a class you
should never modify it, except to correct bugs.

BITS Pilani, Pilani Campus


Example: OCP
public class Rectangle {
public class AreaCalculator{
public double length;
public double width; public double calculateRectangleArea
} (Rectangle rectangle){
public class AreaCalculator { return rectangle.length * rectangle.width;
}
public double calculateRectangleArea
(Rectangle rectangle) { public Double calculateCircleArea(Circle circle){
return rectangle.length * rectangle.width; return (3.14) * circle.radius * circle.radius;
} }
} }

public class Circle {


public double radius;
}
BITS Pilani, Pilani Campus
(Solution) Contd…
interface Shape {
double calculateArea();
}
public class Main {
class Rectangle implements Shape { public static void main(String args[])
double length;
double width; {
Circle c = new Circle(10.0);
public double calculateArea() {
return length * width; } AreaCalculator ac =new AreaCalculator();
} System.out.println("Area: "+
class Circle implements Shape { ac.calculateShapeArea(c) );
double radius; }
Circle( double rad) }
{this.radius=rad;}
public double calculateArea() {
return (3.14) * radius * radius;
}
}

class AreaCalculator {
public double calculateShapeArea(Shape shape) {
return shape.calculateArea();
}
}

BITS Pilani, Pilani Campus


Liskov Substitution Principle

The Liskov Substitution Principle (LSP) states that any instance of a derived
class should be substitutable for an instance of its base class without
affecting the correctness of the program.

Liskov Substitution Principle states:


Let q(x) be a property provable about objects of x of type T. Then q(y) should be
provable for objects y of type S where S is a subtype of T.
This means that every subclass or derived class should be substitutable for
their base or parent class.
Building off the example AreaCalculator class, consider a new
VolumeCalculator class that extends the AreaCalculator class.
“Derived types must be completely substitutable for their base types”

BITS Pilani, Pilani Campus


Contd …
What are the common signs of a violation of LSP?
Common signs of a violation include derived classes overriding methods in
ways that are inconsistent with the base class, throwing unexpected
exceptions, or requiring additional conditions not specified in the base class.
How does LSP relate to the Open-Closed Principle (OCP) in SOLID?
LSP ensures that derived classes can extend base classes without altering their
behavior, enabling adherence to OCP, which states that software entities
should be open for extension but closed for modification.
Does LSP apply only to classes, or can it also be extended to interfaces
and abstract classes?
LSP can be applied to classes, interfaces, and abstract classes. It’s about
ensuring that derived types adhere to the contract specified by the base type,
regardless of the base type.

BITS Pilani, Pilani Campus


Example
public class Rectangle { public abstract class Shape {
protected int width; protected int height; public abstract int getArea();
public void setWidth(int width) { }
this.width = width; public class Rectangle extends Shape {
}
protected int width; protected int height;
public void setHeight(int height) {
this.height = height;
public Rectangle(int width, int height) {
}
this.width = width; this.height = height;
public int getArea() {
}
return width * height; }
}
public int getArea() { return width * height;
public class Square extends Rectangle { }
public void setWidth(int width) { }
this.width = width; public class Square extends Shape {
this.height = width; private int side;
} public Square(int side) { this.side = side; }
public void setHeight(int height) { public int getArea() { return side * side; }
this.height = height; }
this.width = height; }
}
BITS Pilani, Pilani Campus
Dependency Inversion Principle

The Dependency Inversion Principle (DIP) states that high-level modules


should not depend on low-level modules, but both should depend on
abstractions. Abstractions should not depend on details – details should
depend on abstractions.
This principle aims to reduce coupling between modules, increase modularity,
and make the code easier to maintain, test, and extend.

Interface segregation principle: A client should never be


forced to implement an interface that it doesn’t use, or clients shouldn’t be
forced to depend on methods they do not use.
“Don’t depend on things you don’t need”.

BITS Pilani, Pilani Campus


Example
Code that violates ISP Code that follows ISP
interface OfficeEquipment { interface Printer {
void print(); void print();
void scan(); }
interface Scanner {
} void scan();
public class LaserPrinter implements Printer {
}
public void print() {
// Implementation to print a document
}
}
public class FlatbedScanner implements Scanner {
public void scan() {
• Interface Pollution?
// Implementation to scan a document • Dependency Injection ?
}
}
BITS Pilani, Pilani Campus
Dependency Inversion Principle (DIP)

• The Dependency Inversion Principle (DIP)


states that high-level modules should not
depend upon low-level modules. Should
depend on abstractions.
• Secondly, abstractions should not depend
upon details; details should depend upon
abstractions.
• Instead of high-level modules depending on
low-level modules, both will depend on
abstractions.
• Every dependency in the design should target
an interface or an abstract class. No
dependency should target a concrete class.

BITS Pilani, Pilani Campus


Example

public interface CalculatorOperation {


public double calculate(double numbA, double numB);
}
public class AddOperation implements CalculatorOperation {
public double calculate(double numbA, double numB) {
return numbA + numB; }
}
public class SubtractOperation implements CalculatorOperation {
public double calculate(double numbA, double numB) {
return numbA - numB; }
}
public class MultiplyOperation implements CalculatorOperation {
public double calculate(double numbA, double numB) {
public class Calculator {
return numbA * numB; }
} * Performs a two numbers operation.* @return result.
public class DivideOperation implements CalculatorOperation { public double calculate(double numA, double numB,
public double calculate(double numbA, double numB) { CalculatorOperation operation){
return numbA / numB; } return operation.calculate(numB, numB); }
} }

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

UML Diagrams
(Module- 9b)
Recap: Object Oriented Design Symbols

BITS Pilani, Pilani Campus


Object Oriented Design Diagrams

BITS Pilani, Pilani Campus


Symbols

Dependency: A dependency is a semantic relationship


between two or more classes where a change in one
class cause changes in another class.
It forms a weaker relationship.

Generalization: It is a relationship between a parent class


(superclass) and a child class (subclass).
The child class is inherited from the parent class.

BITS Pilani, Pilani Campus


Symbols

Association: It describes a static or physical connection


between two or more objects. It depicts how many
objects are there in the relationship.
For example, a department is associated with the college.

Multiplicity: It defines a specific range of allowable


instances of attributes. In case if a range is not
specified, one is considered as a default multiplicity.
For example, multiple patients are admitted to one
hospital.

BITS Pilani, Pilani Campus


Symbols

Aggregation: An aggregation is a subset of association, which


represents has a relationship. It is more specific then
association. It defines a part-whole or part-of relationship. In
this kind of relationship, the child class can exist
independently of its parent class.
The company encompasses a number of employees, and even if one
employee resigns, the company still exists.

Composition: The composition is a subset of aggregation.


It portrays the dependency between the parent and its child,
which means if one part is deleted, then the other part also
gets discarded. It represents a whole-part relationship.
A contact book consists of multiple contacts, and if you delete the contact book, all the
contacts will be lost.

BITS Pilani, Pilani Campus


Class diagram: sales order system

analyses and designs a static view of an application.

describes the major responsibilities of a system.

BITS Pilani, Pilani Campus


Example
import java.io.*;
class Animal {
String name;
String colour;
public void run()
{
System.out.println("animal is running"); }
}
class dog extends Animal {
dog(String name, String colour)
{
super.name=name;
super.colour=colour;
}
public void bark()
{ System.out.println(" dog is barking"); }
public void run()
{ System.out.println("dog is running"); }
}
class cat extends Animal {
public void meww()
{ System.out.println("cat is running"); }
}
public class Example {
public static void main(String[] args)
{ dog d1 = new dog("Abc", "red");
d1.bark();
d1.run();
cat c1 = new cat();
c1.meww();
c1.run();
}
}

BITS Pilani, Pilani Campus


Example

BITS Pilani, Pilani Campus


Recap: Class Diagram
public class Person {
private String name;
private int age;

public Person(String initialName) {


this.name = initialName;
this.age = 0;
}
public void printPerson() {
System.out.println(this.name + "age " + this.age + "years");
}
}
public String getName() {
return this.name;
}

BITS Pilani, Pilani Campus


Connection between classes
public class Book {
public class Book { private String name;
private String name; private String publisher;
private String publisher; private ArrayList<Person> authors;
private Person author; // constructor
// constructors and methods public ArrayList<Person> getAuthors() {
} return this.authors;n }
public void addAuthor(Person author) {
this.authors.add(author);
}
}

BITS Pilani, Pilani Campus


Association

Delegation is a technique for


allowing one class to get help
from another class without
using inheritance.

BITS Pilani, Pilani Campus


Exercise

BITS Pilani, Pilani Campus


Inheritance

public class Triangle implements Shape {


// Private member variables
private int base, height;

public Triangle(int base, int height) {


this.base = base;
this.height = height;
}
public String toString() {
return "Triangle[base=" + base + ",height=" + height + "]";
}

public double getArea() {


return 0.5 * base * height;
} public interface Shape {
} double getArea();
}
BITS Pilani, Pilani Campus
Contd …

public class Rectangle implements Shape {


private int length, width;
/** Constructs a Rectangle instance with the given length and width */
public Rectangle(int length, int width) {
this.length = length;
this.width = width;
}
/** Returns a self-descriptive string */
public String toString() {
return "Rectangle[length=" + length + ",width=" + width + "]";
}
/** Returns the area of this rectangle */
public double getArea() {
return length * width;
}
}
BITS Pilani, Pilani Campus
Class Diagram for Producer-Consumer

shared object: mediator

Synchronized/ guarded

BITS Pilani, Pilani Campus


Contd …
// Producer.java
import java.io.*;
class Producer extends Thread {
static PrintWriter out = new PrintWriter(System.out, true);
Mediator med;
Producer(Mediator med) { // Consumer.java
this.med = med; import java.io.*;
} class Consumer extends Thread {
public void run() { static PrintWriter out = new PrintWriter(System.out, true);
for (int i = 0; i < 10; i++) { Mediator med;
med.put(i); Consumer(Mediator med) {
out.println("Producer put: " +i); this.med = med; }
try { public void run() {
sleep((int)(100.0*Math.random())); for (int i = 0; i < 10; i++) {
} catch (InterruptedException ignore) { } out.println("Consumer got: " + med.get());
}}} try { sleep((int)(1000.0*Math.random()));
} catch (InterruptedException ignore) { }
}}}

BITS Pilani, Pilani Campus


Contd…
class Mediator {
int val; boolean available;
synchronized int get() {
while (!available)
try {wait(); class ThrTest {
} catch (InterruptedException ignore) { } public static void main(String[ ] args) {
notify();
Mediator med = new Mediator();
available = false;
return val; Producer prod = new Producer(med);
} Consumer con = new Consumer(med);
synchronized void put(int i) { con.start();
while (available) prod.start();
try {wait(); }
} catch (InterruptedException ignore) { } }
notify();
val = i;
available = true;
} }

BITS Pilani, Pilani Campus


Sequence diagram

class cell {
private int value;
public void swap(cell other){
synchronized(this){
synchronized(other){
Example:
int newValue = other.value; Normal Run
other.value = value;
value = newValue;} }
}...
}
Deadlock

BITS Pilani, Pilani Campus


Case Study: Washing Machine
Composed of 7 concrete classes
(WashingMachine, Timer, WashOption,
Engine, DoorSensor, WasterSensor, and
TempSensor), abstract class Sensor, and the
interface Machine.
The classes Engine and WashingMachine
implement the interface Machine, while the
concrete classes DoorSensor, TempSensor,
and WaterSensor extend Sensor.
WashingMachine is the main class, which
has the method main, beside of other
methods representing the washing machine
operations.
WashingMachine is associated with:
Class diagram: Structural
Engine, WaterSensor, WashOption, and view of Washing Machine
Timer classes.
BITS Pilani, Pilani Campus
Contd …

Two lifelines represent the objects


washMachine and washOption, which
interact in this scenario.
Firstly, the machine must identify the desired
operation. The object washMachine invokes
the method getWashSelection from
washOption.
This method returns an integer, whose value
is verified by the operator alt to determine
the operation mode Sequence diagram of Main Method
“1” for standardWash,
“2” for twiceRinse, and
“3” for spin, selecting the method to be
invoked in such case.

BITS Pilani, Pilani Campus


Contd …
Behavioral view for the methods Spin and Period

BITS Pilani, Pilani Campus


Contd …
Java Code for Sensor, Machine, and WaterSensor

BITS Pilani, Pilani Campus


Contd …

Code for WashingMachine

BITS Pilani, Pilani Campus


Exercise: Railway reservation
use case diagram
A use case diagram can summarize the details of your system's
users (also known as actors) and their interactions with the system.

ML use case diagrams are ideal for:


•Representing the goals of system-user interactions
•Defining and organizing functional requirements in a system
•Specifying the context and requirements of a system
•Modeling the basic flow of events in a use case

Use case diagram components


Common components include:
Actors: The users that interact with a system. An actor can be a person, an
organization, or an outside system that interacts with your application or
system. They must be external objects that produce or consume data.
System: A specific sequence of actions and interactions between actors
and the system. A system may also be referred to as a scenario.
Goals: The end result of most use cases. A successful diagram should
describe the activities and variants used to reach the goal.

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Thank
you
Q&A

You might also like