SlideShare a Scribd company logo
HÖNNUN OG SMÍÐI HUGBÚNAÐAR 2015
L04 SOFTWARE DESIGN EXAMPLES
Agenda
Generic Programming
Reflection
Software Design Principles
Software Design in Action
GENERIC PROGAMMING
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();
}
} }
Bla
public class ReflectMethods
{
public static void main(String[] args)
{
Polygon p = new Polygon();
showMethods(p);
}
Name: getBoundingBox
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
Reflection
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) AB	
B) BA	
C) ABC	
D) Compilation	fails	
	
QUIZ
class A

{

public A(String s)

{

System.out.print("A");

}

}
public class B extends A

{

public B(String s) {

System.out.print("B");

}

public static void main(String [] args) {

new B("C");

}
}
A) AB	
B) BA	
C) ABC	
D) Compilation	fails	
	
QUIZ
✔
class A

{

public A(String s)

{

System.out.print("A");

}

}
public class B extends A

{

public B(String s) {

System.out.print("B");

}

public static void main(String [] args) {

new B("C");

}
}
SOFTWARE DESIGN PRINCIPLES
Software Design Principles
Software development has over the years established a
set of principles that apply to building software
Separation of Concern
Coupling
Cohesion
Information Hiding
Separation of Concern
The process of dividing the application into distanct
units without overlapping
Concern can be feature, functionality, point of interest,
data, or process
Allows for changing one area without affecting other
areas
Examples: Presentaion, Domain, Data Source
Model View Controller
HTML, CSS, JavaScript
Separation of Concern
Divide by Feature - vertical
Customer Wallet
Single
Sign-on
Single
Sign-on
Logging Security Session I18N Caching
Cross-
cutting
concerns
Coupling
Refers to the degree of dependence between objects
The objective is to assign responsibility to classes so
that coupling is low
If coupling is high, any 

change becomes difficult
Loosely coupled systems 

are easier and cheaper to 

maintain
Goal is: Low Coupling
Cohesion
Refers to the degree to which the elements of a module
belong together
measures the strength of 

relationship between pieces 

of functionality within 

a given module.
In highly cohesive systems 

functionality is strongly
related
Goal is: High Cohesion
SOFTWARE DESIGN IN ACTION
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
MallardDuck
display() { }
Duck
quack
swim
display
// other methods
RedHeadDuck
display() { }
Change Request!
But now we need the ducks to FLY
MallardDuck
display() { }
Duck
quack
swim
display
// other methods
RedHeadDuck
display() { }
Change Request!
Ok just add the fly method to Duck
MallardDuck
display() { }
Duck
quack
swim
display
fly
// other methods
RedHeadDuck
display() { }
Problem!
But not all duck fly – We forgot Rubber Duck!
MallardDuck
display() { }
Duck
quack
swim
display
fly
// other methods
RedHeadDuck
display() { }
RubberDuck
display() { }
How can we fix this?
Just override fly to do nothing
MallardDuck
display() { }
Duck
quack
swim
display
fly
// other methods
RedHeadDuck
display() { }
RubberDuck
quack() {
// squeck
}
fly() {
// do nothing
}
We even think ahead
We fix all non-flyable and non-quackable ducks as well
Duck
quack
swim
display
fly
// other methods
RedHeadDuck
display() { }
RubberDuck
quack() {
// squeck
}
fly() {
// do nothing
DecoyDuck
quack() {
// no sound
}
fly() {
// do nothing
Code	smell!
MallardDuck
display() { }
Which of the following are disadvantages of using inheritance to
provide Duck behaviour?
A) Code is duplicated across subclasses
B) Runtime behaviour changes are difficult
C) We can’t make ducks dance
D) Hard to gain knowledge of all duck behaviours
E) Ducks can’t fly and quack at the same time
F) Changes can unintentionally affect other ducks
QUIZ
Which of the following are disadvantages of using inheritance to
provide Duck behaviour?
A) Code is duplicated across subclasses
B) Runtime behaviour changes are difficult
C) We can’t make ducks dance
D) Hard to gain knowledge of all duck behaviours
E) Ducks can’t fly and quack at the same time
F) Changes can unintentionally affect other ducks
QUIZ
✔
✔
✔
✔
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
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.
Liskov Substitution Principle
Trying to fix the Problem
Let’s try using interfaces! Flyable and Quackable
MallardDuck
display() { }
fly() { }
quack() { }
Duck
swim
display
// other methods
RedHeadDuck
display() { }
fly() { }
quack() { }
RubberDuck
display() { }
quack() {
// squeck
}
DecoyDuck
Code	
duplication!
Flyable
fly
Quackable
quack
display() { }
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 Design Principle
Identify the aspects of your
application that vary and separate
them from what stays the same
fly
behaviour
fly
behaviour
Separation of Concerns
FlyWithWings flyBehavior = new FlyWithWings();
DATA	TYPE	IS	TOO	SPECIFIC	
Duck
class
▪ Separate what changes from what stays the same
– Move duck behaviour to a separate class
fly
behaviour
quack
behaviour
quack
behaviour
quack
behaviour
Duck Behaviours
fly
behaviour
fly
behaviour
Separation of Concerns
Duck
class
▪ Duck classes cannot use the concrete behaviour classes!
▪ We need an interface or supertype
fly
behaviour
quack
behaviour
quack
behaviour
quack
behaviour
Duck Behaviours
FlyBehaviour
<interface>
FlyBehavior flyBehavior = new FlyWithWings();
INTERFACE	-	POLYMORPHISIM
The Interface Design Principle (GoF)
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 Interfaces
Program to an implementation
Program to interface/subtype
Program to unknown creation
Dog d = new Dog();
d.bark();
Animal animal = new Dog();
animal.makeSound();
Animal animal = getAnimal();
animal.makeSound();
We are making
classes
responsible for
their
dependencies
Program to Interfaces
Another way is to make the caller responsible for setting the
dependency
class Zoo {
private Animal animal;
public setAnimal(Animal animal)
{
this.animal = animal;
}
...
animal.makeSound();
Injection
happens here
Dependency Injection Design Pattern
Implementing Behaviour
We can add new behaviour without touching the Duck classes
FlyWithWings
fly() { }
FlyBehaviour
<interface>
fly();
FlyNoWay
fly() { }
Quack
quack() { }
QuackBehaviour
<interface>
quack();
Squeak
quack() { }
implements implements
Integrating Behaviour
The Duck classes will now delegate its flying and 

quacking behaviour
Duck
QuackBehaviour quackBehaviour;
FlyBehaviour flyBehaviour;
swim() { }
display() { }
performQuack() { }
performFly() { }
Behaviour Interfaces
Performing the behaviour
Integrating Behaviour
The Duck classes will now delegate its flying and 

quacking behaviour
public class Duck
{
QuackBehavior quackBehavior;
...
public void performQuack()
{
quackBehavior.performQuack()
}
}
We don’t care what this object is
behind the interface, we just call it
Integrating Behaviour
But how do we set the behaviour classes?
public class MallardDuck extends Duck
{
public MallardDuck()
{
quackBehavior = new Quack();
flyBehavior = new FlyWithWings();
}
}
This is not
programming to
interfaces!
Setting the Behaviour Dynamically
Use Dependency Injection - make the caller responsible
Add two new methods to the Duck class
QuackBehavior quackBehavior;
FlyBehavior flyBehavior;	
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;
}
}
This is an
assembler class
Setting the Behaviour Dynamically
Use Dependency Injection - make the caller responsible
Creating systems using composition give flexibility
You can change the behaviour at runtime
The idea: Don´t think: Mallard is-a flying duck, think: it has-a
flying behaviour
Put two classes together using composition
One is member in the other
The Composition Design Principle (GoF)
Favour composition over inheritance
Object Composition
Problems with concrete inheritance
Class hierarchies are 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
Generic programming
Using classes, abstract classes and interfaces can lead to
powerful and flexible programs
Reflection
Powerful for building infrastructure
Design
Decouple behaviour of objects from the object them selves
Loosely coupled with interfaces and dependency injection
Program to interfaces
Favour composition over inheritance
Summary
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?
EXERCISE
Design pattern is a general solution to a common problem in
software design
Fyrirlestur mánudaginn 31.08 er video fyrirlestur vegna
ferðalaga
Next

More Related Content

What's hot

Operator precedence
Operator precedenceOperator precedence
Operator precedence
Akshaya Arunan
 
Remote invocation
Remote invocationRemote invocation
Remote invocation
ishapadhy
 
Application Layer
Application Layer Application Layer
Application Layer
Dr Shashikant Athawale
 
Functional dependency
Functional dependencyFunctional dependency
Functional dependency
Dashani Rajapaksha
 
JSP Processing
JSP ProcessingJSP Processing
JSP ProcessingSadhana28
 
LR(0) PARSER
LR(0) PARSERLR(0) PARSER
Inter Process Communication
Inter Process CommunicationInter Process Communication
Inter Process Communication
Adeel Rasheed
 
programming with python ppt
programming with python pptprogramming with python ppt
programming with python ppt
Priyanka Pradhan
 
Regular Languages
Regular LanguagesRegular Languages
Regular Languages
parmeet834
 
Inter Process Communication Presentation[1]
Inter Process Communication Presentation[1]Inter Process Communication Presentation[1]
Inter Process Communication Presentation[1]Ravindra Raju Kolahalam
 
Lecture 2 role of algorithms in computing
Lecture 2   role of algorithms in computingLecture 2   role of algorithms in computing
Lecture 2 role of algorithms in computing
jayavignesh86
 
File handling in Python
File handling in PythonFile handling in Python
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queue
Rajkiran Nadar
 
Tcp/ip model
Tcp/ip  modelTcp/ip  model
Tcp/ip model
Kumar Alok
 
Data Structure and Algorithms.pptx
Data Structure and Algorithms.pptxData Structure and Algorithms.pptx
Data Structure and Algorithms.pptx
Syed Zaid Irshad
 
Computer Networking Lab File
Computer Networking Lab FileComputer Networking Lab File
Computer Networking Lab File
Nitin Bhasin
 
Slr parser
Slr parserSlr parser
Database administrator
Database administratorDatabase administrator
Database administratorTech_MX
 
debugging (1).ppt
debugging (1).pptdebugging (1).ppt
debugging (1).ppt
jerlinS1
 

What's hot (20)

Operator precedence
Operator precedenceOperator precedence
Operator precedence
 
Daa
DaaDaa
Daa
 
Remote invocation
Remote invocationRemote invocation
Remote invocation
 
Application Layer
Application Layer Application Layer
Application Layer
 
Functional dependency
Functional dependencyFunctional dependency
Functional dependency
 
JSP Processing
JSP ProcessingJSP Processing
JSP Processing
 
LR(0) PARSER
LR(0) PARSERLR(0) PARSER
LR(0) PARSER
 
Inter Process Communication
Inter Process CommunicationInter Process Communication
Inter Process Communication
 
programming with python ppt
programming with python pptprogramming with python ppt
programming with python ppt
 
Regular Languages
Regular LanguagesRegular Languages
Regular Languages
 
Inter Process Communication Presentation[1]
Inter Process Communication Presentation[1]Inter Process Communication Presentation[1]
Inter Process Communication Presentation[1]
 
Lecture 2 role of algorithms in computing
Lecture 2   role of algorithms in computingLecture 2   role of algorithms in computing
Lecture 2 role of algorithms in computing
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queue
 
Tcp/ip model
Tcp/ip  modelTcp/ip  model
Tcp/ip model
 
Data Structure and Algorithms.pptx
Data Structure and Algorithms.pptxData Structure and Algorithms.pptx
Data Structure and Algorithms.pptx
 
Computer Networking Lab File
Computer Networking Lab FileComputer Networking Lab File
Computer Networking Lab File
 
Slr parser
Slr parserSlr parser
Slr parser
 
Database administrator
Database administratorDatabase administrator
Database administrator
 
debugging (1).ppt
debugging (1).pptdebugging (1).ppt
debugging (1).ppt
 

Similar to L04 Software Design Examples

L04 Software Design 2
L04 Software Design 2L04 Software Design 2
L04 Software Design 2
Ólafur Andri Ragnarsson
 
Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2
Savio Sebastian
 
L09 Frameworks
L09 FrameworksL09 Frameworks
L09 Frameworks
Ólafur Andri Ragnarsson
 
Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing Scenario
Tara Hardin
 
Certification preparation - Net classses and functions.pptx
Certification preparation - Net classses and functions.pptxCertification preparation - Net classses and functions.pptx
Certification preparation - Net classses and functions.pptx
Rohit Radhakrishnan
 
LINQ Inside
LINQ InsideLINQ Inside
LINQ Insidejeffz
 
Robots in Swift
Robots in SwiftRobots in Swift
Robots in Swift
Janie Clayton
 
Linq To The Enterprise
Linq To The EnterpriseLinq To The Enterprise
Linq To The EnterpriseDaniel Egan
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
Amal Khailtash
 
.Net Classes and Objects | UiPath Community
.Net Classes and Objects | UiPath Community.Net Classes and Objects | UiPath Community
.Net Classes and Objects | UiPath Community
Rohit Radhakrishnan
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
ciklum_ods
 
Thinking In Swift
Thinking In SwiftThinking In Swift
Thinking In Swift
Janie Clayton
 
SQL Saturday 28 - .NET Fundamentals
SQL Saturday 28 - .NET FundamentalsSQL Saturday 28 - .NET Fundamentals
SQL Saturday 28 - .NET Fundamentals
mikehuguet
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
pleeps
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Python
dn
 
P Training Presentation
P Training PresentationP Training Presentation
P Training PresentationGaurav Tyagi
 
Design patterns for fun and profit
Design patterns for fun and profitDesign patterns for fun and profit
Design patterns for fun and profit
Nikolas Vourlakis
 
Linq 1224887336792847 9
Linq 1224887336792847 9Linq 1224887336792847 9
Linq 1224887336792847 9google
 
Introduction to CLIPS Expert System
Introduction to CLIPS Expert SystemIntroduction to CLIPS Expert System
Introduction to CLIPS Expert System
Motaz Saad
 

Similar to L04 Software Design Examples (20)

L04 Software Design 2
L04 Software Design 2L04 Software Design 2
L04 Software Design 2
 
Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2Design Patterns - Part 1 of 2
Design Patterns - Part 1 of 2
 
L09 Frameworks
L09 FrameworksL09 Frameworks
L09 Frameworks
 
Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing Scenario
 
Certification preparation - Net classses and functions.pptx
Certification preparation - Net classses and functions.pptxCertification preparation - Net classses and functions.pptx
Certification preparation - Net classses and functions.pptx
 
LINQ Inside
LINQ InsideLINQ Inside
LINQ Inside
 
Robots in Swift
Robots in SwiftRobots in Swift
Robots in Swift
 
Linq To The Enterprise
Linq To The EnterpriseLinq To The Enterprise
Linq To The Enterprise
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
 
.Net Classes and Objects | UiPath Community
.Net Classes and Objects | UiPath Community.Net Classes and Objects | UiPath Community
.Net Classes and Objects | UiPath Community
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Clean code
Clean codeClean code
Clean code
 
Thinking In Swift
Thinking In SwiftThinking In Swift
Thinking In Swift
 
SQL Saturday 28 - .NET Fundamentals
SQL Saturday 28 - .NET FundamentalsSQL Saturday 28 - .NET Fundamentals
SQL Saturday 28 - .NET Fundamentals
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Python
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
 
Design patterns for fun and profit
Design patterns for fun and profitDesign patterns for fun and profit
Design patterns for fun and profit
 
Linq 1224887336792847 9
Linq 1224887336792847 9Linq 1224887336792847 9
Linq 1224887336792847 9
 
Introduction to CLIPS Expert System
Introduction to CLIPS Expert SystemIntroduction to CLIPS Expert System
Introduction to CLIPS Expert System
 

More from Ólafur Andri Ragnarsson

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
Ólafur Andri Ragnarsson
 
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
Ó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
 
L01 Introduction
L01 IntroductionL01 Introduction
L01 Introduction
Ólafur Andri Ragnarsson
 
L23 Robotics and Drones
L23 Robotics and Drones L23 Robotics and Drones
L23 Robotics and Drones
Ólafur Andri Ragnarsson
 
L22 Augmented and Virtual Reality
L22 Augmented and Virtual RealityL22 Augmented and Virtual Reality
L22 Augmented and Virtual Reality
Ólafur Andri Ragnarsson
 
L20 Personalised World
L20 Personalised WorldL20 Personalised World
L20 Personalised World
Ólafur Andri Ragnarsson
 
L19 Network Platforms
L19 Network PlatformsL19 Network Platforms
L19 Network Platforms
Ólafur Andri Ragnarsson
 
L18 Big Data and Analytics
L18 Big Data and AnalyticsL18 Big Data and Analytics
L18 Big Data and Analytics
Ólafur Andri Ragnarsson
 
L17 Algorithms and AI
L17 Algorithms and AIL17 Algorithms and AI
L17 Algorithms and AI
Ólafur Andri Ragnarsson
 
L16 Internet of Things
L16 Internet of ThingsL16 Internet of Things
L16 Internet of Things
Ólafur Andri Ragnarsson
 
L14 From the Internet to Blockchain
L14 From the Internet to BlockchainL14 From the Internet to Blockchain
L14 From the Internet to Blockchain
Ólafur Andri Ragnarsson
 
L14 The Mobile Revolution
L14 The Mobile RevolutionL14 The Mobile Revolution
L14 The Mobile Revolution
Ó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
 
L12 digital transformation
L12 digital transformationL12 digital transformation
L12 digital transformation
Ólafur Andri Ragnarsson
 
L10 The Innovator's Dilemma
L10 The Innovator's DilemmaL10 The Innovator's Dilemma
L10 The Innovator's Dilemma
Ólafur Andri Ragnarsson
 
L09 Disruptive Technology
L09 Disruptive TechnologyL09 Disruptive Technology
L09 Disruptive Technology
Ólafur Andri Ragnarsson
 
L09 Technological Revolutions
L09 Technological RevolutionsL09 Technological Revolutions
L09 Technological Revolutions
Ólafur Andri Ragnarsson
 
L07 Becoming Invisible
L07 Becoming InvisibleL07 Becoming Invisible
L07 Becoming Invisible
Ólafur Andri Ragnarsson
 
L06 Diffusion of Innovation
L06 Diffusion of InnovationL06 Diffusion of Innovation
L06 Diffusion of Innovation
Ólafur Andri Ragnarsson
 

More from Ó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
 

Recently uploaded

FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
名前 です男
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Vladimir Iglovikov, Ph.D.
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
Neo4j
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 

Recently uploaded (20)

FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
みなさんこんにちはこれ何文字まで入るの?40文字以下不可とか本当に意味わからないけどこれ限界文字数書いてないからマジでやばい文字数いけるんじゃないの?えこ...
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIEnchancing adoption of Open Source Libraries. A case study on Albumentations.AI
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AI
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024GraphSummit Singapore | The Art of the  Possible with Graph - Q2 2024
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 

L04 Software Design Examples

  • 1. HÖNNUN OG SMÍÐI HUGBÚNAÐAR 2015 L04 SOFTWARE DESIGN EXAMPLES
  • 2. Agenda Generic Programming Reflection Software Design Principles Software Design in Action
  • 4. 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
  • 5. 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);
  • 6. 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
  • 7. 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
  • 9. 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
  • 10. 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(); } } }
  • 11. Bla public class ReflectMethods { public static void main(String[] args) { Polygon p = new Polygon(); showMethods(p); } Name: getBoundingBox 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
  • 12. ▪ 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 Reflection
  • 13. 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();
  • 14. A) AB B) BA C) ABC D) Compilation fails QUIZ class A
 {
 public A(String s)
 {
 System.out.print("A");
 }
 } public class B extends A
 {
 public B(String s) {
 System.out.print("B");
 }
 public static void main(String [] args) {
 new B("C");
 } }
  • 15. A) AB B) BA C) ABC D) Compilation fails QUIZ ✔ class A
 {
 public A(String s)
 {
 System.out.print("A");
 }
 } public class B extends A
 {
 public B(String s) {
 System.out.print("B");
 }
 public static void main(String [] args) {
 new B("C");
 } }
  • 17. Software Design Principles Software development has over the years established a set of principles that apply to building software Separation of Concern Coupling Cohesion Information Hiding
  • 18. Separation of Concern The process of dividing the application into distanct units without overlapping Concern can be feature, functionality, point of interest, data, or process Allows for changing one area without affecting other areas Examples: Presentaion, Domain, Data Source Model View Controller HTML, CSS, JavaScript
  • 19. Separation of Concern Divide by Feature - vertical Customer Wallet Single Sign-on Single Sign-on Logging Security Session I18N Caching Cross- cutting concerns
  • 20. Coupling Refers to the degree of dependence between objects The objective is to assign responsibility to classes so that coupling is low If coupling is high, any 
 change becomes difficult Loosely coupled systems 
 are easier and cheaper to 
 maintain Goal is: Low Coupling
  • 21. Cohesion Refers to the degree to which the elements of a module belong together measures the strength of 
 relationship between pieces 
 of functionality within 
 a given module. In highly cohesive systems 
 functionality is strongly related Goal is: High Cohesion
  • 23. 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
  • 24. 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
  • 25.
  • 26. Example from Head First Design Patterns
  • 27. Getting Started SimUDuck is highly successful duck pond simulation game Original design MallardDuck display() { } Duck quack swim display // other methods RedHeadDuck display() { }
  • 28. Change Request! But now we need the ducks to FLY MallardDuck display() { } Duck quack swim display // other methods RedHeadDuck display() { }
  • 29. Change Request! Ok just add the fly method to Duck MallardDuck display() { } Duck quack swim display fly // other methods RedHeadDuck display() { }
  • 30. Problem! But not all duck fly – We forgot Rubber Duck! MallardDuck display() { } Duck quack swim display fly // other methods RedHeadDuck display() { } RubberDuck display() { }
  • 31. How can we fix this? Just override fly to do nothing MallardDuck display() { } Duck quack swim display fly // other methods RedHeadDuck display() { } RubberDuck quack() { // squeck } fly() { // do nothing }
  • 32. We even think ahead We fix all non-flyable and non-quackable ducks as well Duck quack swim display fly // other methods RedHeadDuck display() { } RubberDuck quack() { // squeck } fly() { // do nothing DecoyDuck quack() { // no sound } fly() { // do nothing Code smell! MallardDuck display() { }
  • 33. Which of the following are disadvantages of using inheritance to provide Duck behaviour? A) Code is duplicated across subclasses B) Runtime behaviour changes are difficult C) We can’t make ducks dance D) Hard to gain knowledge of all duck behaviours E) Ducks can’t fly and quack at the same time F) Changes can unintentionally affect other ducks QUIZ
  • 34. Which of the following are disadvantages of using inheritance to provide Duck behaviour? A) Code is duplicated across subclasses B) Runtime behaviour changes are difficult C) We can’t make ducks dance D) Hard to gain knowledge of all duck behaviours E) Ducks can’t fly and quack at the same time F) Changes can unintentionally affect other ducks QUIZ ✔ ✔ ✔ ✔
  • 35. 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
  • 36. 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. Liskov Substitution Principle
  • 37. Trying to fix the Problem Let’s try using interfaces! Flyable and Quackable MallardDuck display() { } fly() { } quack() { } Duck swim display // other methods RedHeadDuck display() { } fly() { } quack() { } RubberDuck display() { } quack() { // squeck } DecoyDuck Code duplication! Flyable fly Quackable quack display() { }
  • 38. 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
  • 39. Separate Variations Design Principle Identify the aspects of your application that vary and separate them from what stays the same
  • 40. fly behaviour fly behaviour Separation of Concerns FlyWithWings flyBehavior = new FlyWithWings(); DATA TYPE IS TOO SPECIFIC Duck class ▪ Separate what changes from what stays the same – Move duck behaviour to a separate class fly behaviour quack behaviour quack behaviour quack behaviour Duck Behaviours
  • 41. fly behaviour fly behaviour Separation of Concerns Duck class ▪ Duck classes cannot use the concrete behaviour classes! ▪ We need an interface or supertype fly behaviour quack behaviour quack behaviour quack behaviour Duck Behaviours FlyBehaviour <interface> FlyBehavior flyBehavior = new FlyWithWings(); INTERFACE - POLYMORPHISIM
  • 42. The Interface Design Principle (GoF) Program to an interface, not an implementation
  • 43. 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
  • 44. Program to Interfaces Program to an implementation Program to interface/subtype Program to unknown creation Dog d = new Dog(); d.bark(); Animal animal = new Dog(); animal.makeSound(); Animal animal = getAnimal(); animal.makeSound(); We are making classes responsible for their dependencies
  • 45. Program to Interfaces Another way is to make the caller responsible for setting the dependency class Zoo { private Animal animal; public setAnimal(Animal animal) { this.animal = animal; } ... animal.makeSound(); Injection happens here Dependency Injection Design Pattern
  • 46. Implementing Behaviour We can add new behaviour without touching the Duck classes FlyWithWings fly() { } FlyBehaviour <interface> fly(); FlyNoWay fly() { } Quack quack() { } QuackBehaviour <interface> quack(); Squeak quack() { } implements implements
  • 47. Integrating Behaviour The Duck classes will now delegate its flying and 
 quacking behaviour Duck QuackBehaviour quackBehaviour; FlyBehaviour flyBehaviour; swim() { } display() { } performQuack() { } performFly() { } Behaviour Interfaces Performing the behaviour
  • 48. Integrating Behaviour The Duck classes will now delegate its flying and 
 quacking behaviour public class Duck { QuackBehavior quackBehavior; ... public void performQuack() { quackBehavior.performQuack() } } We don’t care what this object is behind the interface, we just call it
  • 49. Integrating Behaviour But how do we set the behaviour classes? public class MallardDuck extends Duck { public MallardDuck() { quackBehavior = new Quack(); flyBehavior = new FlyWithWings(); } } This is not programming to interfaces!
  • 50. Setting the Behaviour Dynamically Use Dependency Injection - make the caller responsible Add two new methods to the Duck class QuackBehavior quackBehavior; FlyBehavior flyBehavior; 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; } } This is an assembler class
  • 51. Setting the Behaviour Dynamically Use Dependency Injection - make the caller responsible Creating systems using composition give flexibility You can change the behaviour at runtime The idea: Don´t think: Mallard is-a flying duck, think: it has-a flying behaviour Put two classes together using composition One is member in the other
  • 52. The Composition Design Principle (GoF) Favour composition over inheritance
  • 53. Object Composition Problems with concrete inheritance Class hierarchies are 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
  • 54. Generic programming Using classes, abstract classes and interfaces can lead to powerful and flexible programs Reflection Powerful for building infrastructure Design Decouple behaviour of objects from the object them selves Loosely coupled with interfaces and dependency injection Program to interfaces Favour composition over inheritance Summary
  • 56. Design pattern is a general solution to a common problem in software design Fyrirlestur mánudaginn 31.08 er video fyrirlestur vegna ferðalaga Next