SlideShare uma empresa Scribd logo
1 de 54
Lecture 04 
Software Design 2
Agenda 
 Programming with Objects 
– Classes 
– Interfaces 
– Generic programming 
– Reflection 
 Software Design 
– Ducks…
Reading 
 Barbin Introduction, 1 Core Principles 
– Separation of concerns (SoC) 
– Coupling 
– Cohesion 
– Information Hiding 
 Don’t Repeat Yourself 
 Polymorphism 
 Optional: 
– http://docs.oracle.com/javase/tutorial/
Generic Programming
Generic Programming 
 Programming in an data type independent way 
– Same code is used regardless of the data type 
 Example 
– Sort can be applied to any data type 
– Generic collection 
• Java Collection Framework 
 Design Principle 
– Always use the most generic data type possible
Generic Programming 
 All classes extend Object 
– Allows generic algorithms and data structures 
static int find (Object[] a, Object key) 
{ 
int i; 
for (i=0;i<a.length;i++) 
if (a[i].equals(key)) return i; 
return -1; 
} 
Employee[] staff = new Employee[10]; 
Employee e1 = new Employee("Dilbert"); 
staff[x] = e1; 
int n = find(staff, e1);
Generic Programming 
 Generic collections 
– ArrayList is an example class that uses Object 
ArrayList al = new ArrayList(); 
al.add (new Employee ("Dilbert")); 
al.add (new Employee ("Wally")); 
al.add (new Employee ("Alice")); 
Iterator i = al.iterator(); 
Employee e; 
while (i.hasNext()) 
{ 
e = (Employee)i.next(); 
System.out.println(e.getName()); 
} 
Dilbert 
Wally 
Alice
Generic Programming 
 Generic collections 
– The Collections class is another example 
List<Employee> list = new ArrayList<Employee>(); 
list.add (new Employee ("Dilbert")); 
list.add (new Employee ("Wally")); 
list.add (new Employee ("Alice")); 
Collections.sort(list); 
for (Employee e: list) 
{ 
System.out.println(e); 
} 
Alice 
Dilbert 
Wally
Reflection
Reflection 
 Reflection allows examination and manipulation of 
objects at runtime 
– Get information about a class 
• Fields, methods, constructors, and super classes 
• Constants and method declarations belong to an interface 
– Create an instance of a class whose name is not known 
until runtime 
– Get and set the value of an object's field, even if the field 
name is unknown to your program until runtime 
– Invoke a method on an object, even if the method is not 
known until runtime
Reflection 
static void showMethods(Object o) 
{ 
Class c = o.getClass(); 
Method[] theMethods = c.getMethods(); 
for (int i = 0; i < theMethods.length; i++) { 
String methodString = theMethods[i].getName(); 
System.out.println("Name: " + methodString); 
String returnString = theMethods[i].getReturnType().getName(); 
System.out.println(" Return Type: " + returnString); 
Class[] parameterTypes = theMethods[i].getParameterTypes(); 
System.out.print(" Parameter Types:"); 
for (int k = 0; k < parameterTypes.length; k ++) 
{ 
String parameterString = parameterTypes[k].getName(); 
System.out.print(" " + parameterString); 
} 
System.out.println(); 
} 
} }
Reflection 
public class ReflectMethods 
{ 
public static void main(String[] args) 
{ 
Polygon p = new Polygon(); 
showMethods(p); 
} Name: getBoundingBox 
Bla 
Return Type: java.awt.Rectangle 
Parameter Types: 
Name: contains 
Return Type: boolean 
Parameter Types: java.awt.geom.Point2D 
... 
Name: toString 
Return Type: java.lang.String 
Parameter Types:
Reflection 
 Reflection is very useful in frameworks 
– Infrastructure code 
– “plumbing” – The “Noise” 
 Examples 
– Create Java objects from XML descriptions 
– Load classes at runtime and invoke methods 
– Tools and utilities for development
Dynamically Loading Classes 
 Classes can be dynamically loaded at runtime 
– Offers the flexibility to decide which class to run 
dynamically 
– Class names can be specified in configuration files 
 Class class 
Class instanceClass = Class.forName("RssFeedReader"); 
reader = (FeedReader)instanceClass.newInstance();
A) BD 
B) DB 
C) BDC 
D) Compilation fails 
QUIZ 
class Top { 
public Top(String s) { 
System.out.print("B"); 
} } 
public class Bottom2 extends Top { 
public Bottom2(String s) { 
System.out.print("D"); 
} 
public static void main(String [] args) { 
new Bottom2("C"); 
System.out.println(" "); 
} }
A) BD 
B) DB 
C) BDC 
D) Compilation fails 
QUIZ 
✔ 
class Top { 
public Top(String s) { 
System.out.print("B"); 
} } 
public class Bottom2 extends Top { 
public Bottom2(String s) { 
System.out.print("D"); 
} 
public static void main(String [] args) { 
new Bottom2("C"); 
System.out.println(" "); 
} }
Software Design
Object Oriented Design 
 Design and implementation of software needs to 
be of quality 
– Badly designed, well implemented = problem! 
– Well designed, badly implemented = problem! 
CODE 
HORROR!! 
CODE HORROR DUDE
Object Oriented Design 
 Good design 
Is based on OO principles 
Abstracts complex APIs such as J2EE 
Is flexible and can be changed 
Contains loosely coupled components
 Example from Head First Design Patterns
Getting Started 
 SimUDuck is highly successful duck pond 
simulation game 
 Original design
Change Request 
 But now we need the ducks to FLY
Problem! 
 But not all duck fly – We forgot Rubber Duck!
How can we fix this? 
 Just override fly and quack to do nothing
We even think ahead 
 We fix all non-flyable and non-quackable ducks 
as well 
Code smell!
QUIZ 
Which of the following are disadvantages of using inheritance to 
provide Duck behavior? 
A) Code is duplicated across subclasses 
B) Runtime behavior changes are difficult 
C) We can’t make ducks dance 
D) Hard to gain knowledge of all duck behaviors 
E) Ducks can’t fly and quack at the same time 
F) Changes can unitentionally affect other ducks 
✔ 
✔ 
✔ 
✔
The Problem 
 The problem is this 
– Derived classes (RubberDuck) are forced to inherit 
behaviour they don’t have 
– Derived classes (RubberDuck) needs to be exposed 
to the inner workings of the superclass (Duck) 
– Users of the base class (Duck) should expect same 
functionality 
– Violation of the Liskov Substitution Principle
The Liskov Substitution Principle 
Subtypes must be 
substitutable for their base 
types. Code that uses 
references to base class must 
be able to use objects of 
derived classes without 
knowing it. 
Barbara 
Liskov
The Liskov Substitution Principle 
 All code operating with reference to the base 
class should be completely transparent to the 
type of the inherited object 
 It should be possible to substitute an object of 
one type with another within the same class 
hierarchy 
 Inheriting classes should not perform any 
actions that will invalidate the assumptions made 
by the base class
LSP Example 
public class Rectangle { 
protected int _width; 
protected int _height; 
public int getWidth() { 
return _width; 
} 
public int getHeight() { 
return _height; 
} 
public void setWidth(int width) { 
_width = width; 
} 
public void setHeight(int height) { 
_height = height; 
} 
}
LSP Example 
public class Square extends Rectangle { 
public void setWidth(int width) { 
_width = width; 
_height = width; 
} 
public void setHeight(int height) { 
_height = height; 
_width = _height; 
} 
} 
Implementation convenience
LSP Example 
import junit.framework.Assert; 
import org.junit.Test; 
public class RectangleTests { 
@Test 
public void areaOfRectangle() { 
Rectangle r = new Square(); 
r.setWidth(5); 
r.setHeight(2); 
// Will Fail - r is a square and sets 
// width and height equal to each other. 
Assert.assertEquals(r.getWidth() * r.getHeight(),10); 
} 
}
Trying to fix the Problem 
 Let’s try using interfaces 
– Flyable and Quackable Code duplication!
What is the Problem? 
 We tried this 
– Inheritance changes all subcasses 
– Interfaces cause code duplication 
 The problem is we are mixing different types of 
code in one type of classes 
 Fix 
– Separate Variation Design Principle 
– Take what varies and encapsulate it so it wont affect 
the rest of the code
Separate Variations 
Identify the aspects of 
your application that 
vary and separate 
them from what stays the 
same
Separation of Concerns 
 Separate what changes from what stays the 
same 
– Move duck behavior to a separte classes 
FlyWithWings flyBehavior = new FlyWithWings(); 
DATA TYPE IS TOO SPECIFIC
Separation of Concerns 
 But the Duck classes cannot use the concrete 
behavior classes! 
– We need an interface or supertype 
FlyBehavior flyBehavior = new FlyWithWings(); 
INTERFACE - POLYMORPHISIM
The Interface Design Principle 
Program to an interface, 
not an implementation
Loose Coupling with Interfaces 
 Advantages 
– The ability to change the implementing class of any 
application object without affecting calling code 
– Total freedom in implementing interfaces 
– The ability to provide simple test implementations and 
stub implementations of application interfaces as 
necessary
Program to an interfaces 
 Program to an implementation 
Dog d = new Dog(); 
d.bark(); 
 Program to interface/subtype 
Animal animal = new Dog(); 
animal.makeSound(); 
 Program to unknown creation 
Animal animal = getAnimal(); 
animal.makeSound();
Program to an interfaces 
 Dependency Injection 
– Make the caller responsible for setting the dependency 
private Animal animal; 
public setAnimal(Animal animal) 
{ 
this.animal = animal; 
} 
... 
animal.makeSound(); 
Injection happens 
here, in the 
set-method 
LOOSE COUPLING = BEAUTIFUL!
Implementing Behavior 
 We can add new behaviors without touching the 
Duck classes
Integrating the Behavior 
 The Duck classes will now delegate its flying 
and quacking behavior 
Behavior interfaces 
Perform the 
Bahavior
Integrating the Behavior 
 Using the behavior 
public class Duck 
{ 
QuackBehavior quackBehavior; 
... 
public void performQuack() 
{ 
quackBehavior.performQuack() 
} 
} 
We don’t care what kind of object this 
is, all we care is that it knows how to 
quack!
Integrating the Behavior 
 Setting the behavior 
public class MallardDuck extends Duck 
{ 
public MallardDuck() 
{ 
quackBehavior = new Quack(); 
flyBehavior = new FlyWithWings(); 
} 
} 
This is not 
programming 
to an interface!
Setting Behavior Dynamically 
 Add two new methods to the Duck class 
 Dependency Injection 
public void setFlyBehavior(FlyBehavior flyBehavior) 
{ 
this.flyBehavior = flyBehavior 
} 
public void setQuackBehavior(QuackBehavior quackBehavior) 
{ 
this.quackBehavior = quackBehavior 
} 
DuckFactory 
{ 
public Duck getMallardDuck() 
{ 
Duck duck = new MallardDuck() 
duck.setFlyBehavior(new FlyWithWings()); 
duck.setQuackBehavior(new Quack()); 
return duck; 
} 
}
Setting Behavior Dynamically 
 The idea 
– Don´t think: Mallard is-a flying duck, think: it has-a 
flying behavior 
– Putting two classes together where one is a member 
in the other is a composition 
 Creating systems using composition give 
flexibilty 
– You can change the behavior at runtime
Composition Design Principle 
Favor composition over 
inheritance
Object Composition 
 Problems with concrete inheritance 
– Class hierarchy can get rigid 
– Difficult to change the implementation 
 Object Composition is more flexible 
– Allows the behaviour of an object to be altered at run 
time, through delegating part of its behaviour to an 
interface and allowing callers to set the 
implementation of that interface
Summary 
 OO Programming is powerful 
– If used correctly 
– Remember Encapsulation, Interfaces, Polymorphism 
 Generic programming 
– Using classes, abstract classes and interfaces can 
lead to powerful and flexible programs 
 Reflection 
– Powerful for building infrastructure
EXERCISE 
Job interview question 
You are given the assignment of creating a component that needs to 
know sales statistics of Lottery tickets. You know that there is a 
another component in the system, Sale Server, that handles the sale. 
You need real-time information. What would you suggest?
Design Patterns 
 Design pattern is a general solution to a common 
problem in software design 
– Systematic approach for problems that reoccur in software 
development 
– Not complete solution but starting point for design 
– Not code ready to use 
– Patterns have names and definitions 
– Built on common practices 
 Patterns should not be language dependant 
– However patterns apply for types of programming 
languages
Next 
 Design Patterns

Mais conteúdo relacionado

Mais procurados

20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulationIntro C# Book
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsMuhammadTalha436
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritancemanish kumar
 
06 Java Language And OOP Part VI
06 Java Language And OOP Part VI06 Java Language And OOP Part VI
06 Java Language And OOP Part VIHari Christian
 
Effective Java - Generics
Effective Java - GenericsEffective Java - Generics
Effective Java - GenericsRoshan Deniyage
 
On Parameterised Types and Java Generics
On Parameterised Types and Java GenericsOn Parameterised Types and Java Generics
On Parameterised Types and Java GenericsYann-Gaël Guéhéneuc
 
Java Generics
Java GenericsJava Generics
Java Genericsjeslie
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywordsmanish kumar
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with pythonArslan Arshad
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptmanish kumar
 
Python Advanced – Building on the foundation
Python Advanced – Building on the foundationPython Advanced – Building on the foundation
Python Advanced – Building on the foundationKevlin Henney
 
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Codemotion
 
Lecture - 5 Control Statement
Lecture - 5 Control StatementLecture - 5 Control Statement
Lecture - 5 Control Statementmanish kumar
 

Mais procurados (20)

20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
L03 Software Design
L03 Software DesignL03 Software Design
L03 Software Design
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritance
 
L04 Software Design Examples
L04 Software Design ExamplesL04 Software Design Examples
L04 Software Design Examples
 
06 Java Language And OOP Part VI
06 Java Language And OOP Part VI06 Java Language And OOP Part VI
06 Java Language And OOP Part VI
 
Effective Java - Generics
Effective Java - GenericsEffective Java - Generics
Effective Java - Generics
 
Java generics
Java genericsJava generics
Java generics
 
On Parameterised Types and Java Generics
On Parameterised Types and Java GenericsOn Parameterised Types and Java Generics
On Parameterised Types and Java Generics
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java q ref 2018
Java q ref 2018Java q ref 2018
Java q ref 2018
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
 
java tutorial 2
 java tutorial 2 java tutorial 2
java tutorial 2
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops concept
 
Python Advanced – Building on the foundation
Python Advanced – Building on the foundationPython Advanced – Building on the foundation
Python Advanced – Building on the foundation
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
 
Lecture - 5 Control Statement
Lecture - 5 Control StatementLecture - 5 Control Statement
Lecture - 5 Control Statement
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 

Semelhante a L04 Software Design 2

Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshowilias ahmed
 
Basic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentBasic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentSuresh Mohta
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Pythondn
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummaryAmal Khailtash
 
Java for android developers
Java for android developersJava for android developers
Java for android developersAly Abdelkareem
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworksMD Sayem Ahmed
 
Core Java- An advanced review of features
Core Java- An advanced review of featuresCore Java- An advanced review of features
Core Java- An advanced review of featuresvidyamittal
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.Tarunsingh198
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental PrinciplesIntro C# Book
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Javabackdoor
 
Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Alena Holligan
 

Semelhante a L04 Software Design 2 (20)

Object-oriented Basics
Object-oriented BasicsObject-oriented Basics
Object-oriented Basics
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshow
 
Basic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentBasic concept of class, method , command line-argument
Basic concept of class, method , command line-argument
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Python
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
 
Java for android developers
Java for android developersJava for android developers
Java for android developers
 
L02 Software Design
L02 Software DesignL02 Software Design
L02 Software Design
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworks
 
Java for beginners
Java for beginnersJava for beginners
Java for beginners
 
Core Java- An advanced review of features
Core Java- An advanced review of featuresCore Java- An advanced review of features
Core Java- An advanced review of features
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles20. Object-Oriented Programming Fundamental Principles
20. Object-Oriented Programming Fundamental Principles
 
Clean Code
Clean CodeClean Code
Clean Code
 
oops-1
oops-1oops-1
oops-1
 
Unit i
Unit iUnit i
Unit i
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017
 
Java sessionnotes
Java sessionnotesJava sessionnotes
Java sessionnotes
 
Core java oop
Core java oopCore java oop
Core java oop
 

Mais de Ólafur Andri Ragnarsson

New Technology Summer 2020 Course Introduction
New Technology Summer 2020 Course IntroductionNew Technology Summer 2020 Course Introduction
New Technology Summer 2020 Course IntroductionÓlafur Andri Ragnarsson
 
New Technology 2019 L13 Rise of the Machine
New Technology 2019 L13 Rise of the Machine New Technology 2019 L13 Rise of the Machine
New Technology 2019 L13 Rise of the Machine Ólafur Andri Ragnarsson
 

Mais de Ólafur Andri Ragnarsson (20)

Nýsköpun - Leiðin til framfara
Nýsköpun - Leiðin til framfaraNýsköpun - Leiðin til framfara
Nýsköpun - Leiðin til framfara
 
Nýjast tækni og framtíðin
Nýjast tækni og framtíðinNýjast tækni og framtíðin
Nýjast tækni og framtíðin
 
New Technology Summer 2020 Course Introduction
New Technology Summer 2020 Course IntroductionNew Technology Summer 2020 Course Introduction
New Technology Summer 2020 Course Introduction
 
L01 Introduction
L01 IntroductionL01 Introduction
L01 Introduction
 
L23 Robotics and Drones
L23 Robotics and Drones L23 Robotics and Drones
L23 Robotics and Drones
 
L22 Augmented and Virtual Reality
L22 Augmented and Virtual RealityL22 Augmented and Virtual Reality
L22 Augmented and Virtual Reality
 
L20 Personalised World
L20 Personalised WorldL20 Personalised World
L20 Personalised World
 
L19 Network Platforms
L19 Network PlatformsL19 Network Platforms
L19 Network Platforms
 
L18 Big Data and Analytics
L18 Big Data and AnalyticsL18 Big Data and Analytics
L18 Big Data and Analytics
 
L17 Algorithms and AI
L17 Algorithms and AIL17 Algorithms and AI
L17 Algorithms and AI
 
L16 Internet of Things
L16 Internet of ThingsL16 Internet of Things
L16 Internet of Things
 
L14 From the Internet to Blockchain
L14 From the Internet to BlockchainL14 From the Internet to Blockchain
L14 From the Internet to Blockchain
 
L14 The Mobile Revolution
L14 The Mobile RevolutionL14 The Mobile Revolution
L14 The Mobile Revolution
 
New Technology 2019 L13 Rise of the Machine
New Technology 2019 L13 Rise of the Machine New Technology 2019 L13 Rise of the Machine
New Technology 2019 L13 Rise of the Machine
 
L12 digital transformation
L12 digital transformationL12 digital transformation
L12 digital transformation
 
L10 The Innovator's Dilemma
L10 The Innovator's DilemmaL10 The Innovator's Dilemma
L10 The Innovator's Dilemma
 
L09 Disruptive Technology
L09 Disruptive TechnologyL09 Disruptive Technology
L09 Disruptive Technology
 
L09 Technological Revolutions
L09 Technological RevolutionsL09 Technological Revolutions
L09 Technological Revolutions
 
L07 Becoming Invisible
L07 Becoming InvisibleL07 Becoming Invisible
L07 Becoming Invisible
 
L06 Diffusion of Innovation
L06 Diffusion of InnovationL06 Diffusion of Innovation
L06 Diffusion of Innovation
 

Último

Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 

Último (20)

Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 

L04 Software Design 2

  • 2. Agenda  Programming with Objects – Classes – Interfaces – Generic programming – Reflection  Software Design – Ducks…
  • 3. Reading  Barbin Introduction, 1 Core Principles – Separation of concerns (SoC) – Coupling – Cohesion – Information Hiding  Don’t Repeat Yourself  Polymorphism  Optional: – http://docs.oracle.com/javase/tutorial/
  • 5. Generic Programming  Programming in an data type independent way – Same code is used regardless of the data type  Example – Sort can be applied to any data type – Generic collection • Java Collection Framework  Design Principle – Always use the most generic data type possible
  • 6. Generic Programming  All classes extend Object – Allows generic algorithms and data structures static int find (Object[] a, Object key) { int i; for (i=0;i<a.length;i++) if (a[i].equals(key)) return i; return -1; } Employee[] staff = new Employee[10]; Employee e1 = new Employee("Dilbert"); staff[x] = e1; int n = find(staff, e1);
  • 7. Generic Programming  Generic collections – ArrayList is an example class that uses Object ArrayList al = new ArrayList(); al.add (new Employee ("Dilbert")); al.add (new Employee ("Wally")); al.add (new Employee ("Alice")); Iterator i = al.iterator(); Employee e; while (i.hasNext()) { e = (Employee)i.next(); System.out.println(e.getName()); } Dilbert Wally Alice
  • 8. Generic Programming  Generic collections – The Collections class is another example List<Employee> list = new ArrayList<Employee>(); list.add (new Employee ("Dilbert")); list.add (new Employee ("Wally")); list.add (new Employee ("Alice")); Collections.sort(list); for (Employee e: list) { System.out.println(e); } Alice Dilbert Wally
  • 10. Reflection  Reflection allows examination and manipulation of objects at runtime – Get information about a class • Fields, methods, constructors, and super classes • Constants and method declarations belong to an interface – Create an instance of a class whose name is not known until runtime – Get and set the value of an object's field, even if the field name is unknown to your program until runtime – Invoke a method on an object, even if the method is not known until runtime
  • 11. Reflection static void showMethods(Object o) { Class c = o.getClass(); Method[] theMethods = c.getMethods(); for (int i = 0; i < theMethods.length; i++) { String methodString = theMethods[i].getName(); System.out.println("Name: " + methodString); String returnString = theMethods[i].getReturnType().getName(); System.out.println(" Return Type: " + returnString); Class[] parameterTypes = theMethods[i].getParameterTypes(); System.out.print(" Parameter Types:"); for (int k = 0; k < parameterTypes.length; k ++) { String parameterString = parameterTypes[k].getName(); System.out.print(" " + parameterString); } System.out.println(); } } }
  • 12. Reflection public class ReflectMethods { public static void main(String[] args) { Polygon p = new Polygon(); showMethods(p); } Name: getBoundingBox Bla Return Type: java.awt.Rectangle Parameter Types: Name: contains Return Type: boolean Parameter Types: java.awt.geom.Point2D ... Name: toString Return Type: java.lang.String Parameter Types:
  • 13. Reflection  Reflection is very useful in frameworks – Infrastructure code – “plumbing” – The “Noise”  Examples – Create Java objects from XML descriptions – Load classes at runtime and invoke methods – Tools and utilities for development
  • 14. Dynamically Loading Classes  Classes can be dynamically loaded at runtime – Offers the flexibility to decide which class to run dynamically – Class names can be specified in configuration files  Class class Class instanceClass = Class.forName("RssFeedReader"); reader = (FeedReader)instanceClass.newInstance();
  • 15. A) BD B) DB C) BDC D) Compilation fails QUIZ class Top { public Top(String s) { System.out.print("B"); } } public class Bottom2 extends Top { public Bottom2(String s) { System.out.print("D"); } public static void main(String [] args) { new Bottom2("C"); System.out.println(" "); } }
  • 16. A) BD B) DB C) BDC D) Compilation fails QUIZ ✔ class Top { public Top(String s) { System.out.print("B"); } } public class Bottom2 extends Top { public Bottom2(String s) { System.out.print("D"); } public static void main(String [] args) { new Bottom2("C"); System.out.println(" "); } }
  • 18. Object Oriented Design  Design and implementation of software needs to be of quality – Badly designed, well implemented = problem! – Well designed, badly implemented = problem! CODE HORROR!! CODE HORROR DUDE
  • 19. Object Oriented Design  Good design Is based on OO principles Abstracts complex APIs such as J2EE Is flexible and can be changed Contains loosely coupled components
  • 20.
  • 21.  Example from Head First Design Patterns
  • 22. Getting Started  SimUDuck is highly successful duck pond simulation game  Original design
  • 23. Change Request  But now we need the ducks to FLY
  • 24. Problem!  But not all duck fly – We forgot Rubber Duck!
  • 25. How can we fix this?  Just override fly and quack to do nothing
  • 26. We even think ahead  We fix all non-flyable and non-quackable ducks as well Code smell!
  • 27. QUIZ Which of the following are disadvantages of using inheritance to provide Duck behavior? A) Code is duplicated across subclasses B) Runtime behavior changes are difficult C) We can’t make ducks dance D) Hard to gain knowledge of all duck behaviors E) Ducks can’t fly and quack at the same time F) Changes can unitentionally affect other ducks ✔ ✔ ✔ ✔
  • 28. The Problem  The problem is this – Derived classes (RubberDuck) are forced to inherit behaviour they don’t have – Derived classes (RubberDuck) needs to be exposed to the inner workings of the superclass (Duck) – Users of the base class (Duck) should expect same functionality – Violation of the Liskov Substitution Principle
  • 29. The Liskov Substitution Principle Subtypes must be substitutable for their base types. Code that uses references to base class must be able to use objects of derived classes without knowing it. Barbara Liskov
  • 30. The Liskov Substitution Principle  All code operating with reference to the base class should be completely transparent to the type of the inherited object  It should be possible to substitute an object of one type with another within the same class hierarchy  Inheriting classes should not perform any actions that will invalidate the assumptions made by the base class
  • 31. LSP Example public class Rectangle { protected int _width; protected int _height; public int getWidth() { return _width; } public int getHeight() { return _height; } public void setWidth(int width) { _width = width; } public void setHeight(int height) { _height = height; } }
  • 32. LSP Example public class Square extends Rectangle { public void setWidth(int width) { _width = width; _height = width; } public void setHeight(int height) { _height = height; _width = _height; } } Implementation convenience
  • 33. LSP Example import junit.framework.Assert; import org.junit.Test; public class RectangleTests { @Test public void areaOfRectangle() { Rectangle r = new Square(); r.setWidth(5); r.setHeight(2); // Will Fail - r is a square and sets // width and height equal to each other. Assert.assertEquals(r.getWidth() * r.getHeight(),10); } }
  • 34. Trying to fix the Problem  Let’s try using interfaces – Flyable and Quackable Code duplication!
  • 35. What is the Problem?  We tried this – Inheritance changes all subcasses – Interfaces cause code duplication  The problem is we are mixing different types of code in one type of classes  Fix – Separate Variation Design Principle – Take what varies and encapsulate it so it wont affect the rest of the code
  • 36. Separate Variations Identify the aspects of your application that vary and separate them from what stays the same
  • 37. Separation of Concerns  Separate what changes from what stays the same – Move duck behavior to a separte classes FlyWithWings flyBehavior = new FlyWithWings(); DATA TYPE IS TOO SPECIFIC
  • 38. Separation of Concerns  But the Duck classes cannot use the concrete behavior classes! – We need an interface or supertype FlyBehavior flyBehavior = new FlyWithWings(); INTERFACE - POLYMORPHISIM
  • 39. The Interface Design Principle Program to an interface, not an implementation
  • 40. Loose Coupling with Interfaces  Advantages – The ability to change the implementing class of any application object without affecting calling code – Total freedom in implementing interfaces – The ability to provide simple test implementations and stub implementations of application interfaces as necessary
  • 41. Program to an interfaces  Program to an implementation Dog d = new Dog(); d.bark();  Program to interface/subtype Animal animal = new Dog(); animal.makeSound();  Program to unknown creation Animal animal = getAnimal(); animal.makeSound();
  • 42. Program to an interfaces  Dependency Injection – Make the caller responsible for setting the dependency private Animal animal; public setAnimal(Animal animal) { this.animal = animal; } ... animal.makeSound(); Injection happens here, in the set-method LOOSE COUPLING = BEAUTIFUL!
  • 43. Implementing Behavior  We can add new behaviors without touching the Duck classes
  • 44. Integrating the Behavior  The Duck classes will now delegate its flying and quacking behavior Behavior interfaces Perform the Bahavior
  • 45. Integrating the Behavior  Using the behavior public class Duck { QuackBehavior quackBehavior; ... public void performQuack() { quackBehavior.performQuack() } } We don’t care what kind of object this is, all we care is that it knows how to quack!
  • 46. Integrating the Behavior  Setting the behavior public class MallardDuck extends Duck { public MallardDuck() { quackBehavior = new Quack(); flyBehavior = new FlyWithWings(); } } This is not programming to an interface!
  • 47. Setting Behavior Dynamically  Add two new methods to the Duck class  Dependency Injection public void setFlyBehavior(FlyBehavior flyBehavior) { this.flyBehavior = flyBehavior } public void setQuackBehavior(QuackBehavior quackBehavior) { this.quackBehavior = quackBehavior } DuckFactory { public Duck getMallardDuck() { Duck duck = new MallardDuck() duck.setFlyBehavior(new FlyWithWings()); duck.setQuackBehavior(new Quack()); return duck; } }
  • 48. Setting Behavior Dynamically  The idea – Don´t think: Mallard is-a flying duck, think: it has-a flying behavior – Putting two classes together where one is a member in the other is a composition  Creating systems using composition give flexibilty – You can change the behavior at runtime
  • 49. Composition Design Principle Favor composition over inheritance
  • 50. Object Composition  Problems with concrete inheritance – Class hierarchy can get rigid – Difficult to change the implementation  Object Composition is more flexible – Allows the behaviour of an object to be altered at run time, through delegating part of its behaviour to an interface and allowing callers to set the implementation of that interface
  • 51. Summary  OO Programming is powerful – If used correctly – Remember Encapsulation, Interfaces, Polymorphism  Generic programming – Using classes, abstract classes and interfaces can lead to powerful and flexible programs  Reflection – Powerful for building infrastructure
  • 52. EXERCISE Job interview question You are given the assignment of creating a component that needs to know sales statistics of Lottery tickets. You know that there is a another component in the system, Sale Server, that handles the sale. You need real-time information. What would you suggest?
  • 53. Design Patterns  Design pattern is a general solution to a common problem in software design – Systematic approach for problems that reoccur in software development – Not complete solution but starting point for design – Not code ready to use – Patterns have names and definitions – Built on common practices  Patterns should not be language dependant – However patterns apply for types of programming languages
  • 54. Next  Design Patterns