SlideShare ist ein Scribd-Unternehmen logo
1 von 73
Downloaden Sie, um offline zu lesen
HÖNNUN OG SMÍÐI HUGBÚNAÐAR 2015
L03 SOFTWARE DESIGN
Agenda
Architecture Recap
Programming with Objects
Classes
Interfaces
ARCHITECTURE RECAP
Conwey’s Law
Organisations which design systems ... are constrained to
produce designs which are copies of the communication
structures of these organisations
From a 1967 paper “How do Committees Invent?”
by Mel Conway
Monolithic Architecture
Traditional Web Application Architecture
All code is built into a single application
that is deployed
Simple to develop, test, deploy, scale
Clear layering: Presentation, Domain,
Data Source
Tomcat
ApacheBrowser
WAR
Web Components
Customer
Wallet
Data Source
DB
WAR file = Web
ARchive
Tomcat = web server
for Java Servlets (web
components)
Monolithic Architecture
▪ Drawbacks
– User interface challenge – old style UI architecture
– Real-time applications (like node.js) don’t fit in easy
– Obstacle to frequent deployment – fear of change
– Overloads your IDE and container – slow build, development
– Obstacle to scaling development teams
– Locks down the technology stack – long term commitment
Technical Debt
Concept in programming that reflects the extra development
work that arises when code that is easy to implement in the
short run is used instead of applying the best overall solution
Small decisions that accumulate over time -
“I’ll fix this later”
Hard to see until any small change is
extremely expensive (CoC = Cost of
Change), and then Conway’s Second Law
applies
If the debt is not repaid, then it will keep on
accumulating interest, making it hard to
implement changes later on
Why does it Happen?
Or maybe… University Teachers that teach about concrete inheritance
Object Oriented progamming is good but can be misused
Architecture - noun
The decomposition of a
product into a collection of
components/modules and
interactions
Structure
Architecture - verb
Understanding what you
need to build, create a
vision and making the right
decisions
vision
A component is a software building block that is
independently replaceable
independently upgradable
Component
Architecture - types
Application Architecture: Application is the focus
System Architecture: Focus on multiple applications across a
number of tiers and technologies
Software Architecture: The combination of application and
system architecture and includes the technical practices to build
the software
Service Oriented Architecture
SOA actually means that components of an application
act as interoperable services, and can be used
independently and recombined into other applications.
Engineering Software as a Service by David Patterson and Armando Fox
Microservices
In recent years a new term has emerged, Microservices:
The microservice architectural style is an approach to
developing a single application as a suite of small services, each
running in its own process and communicating with lightweight
mechanisms, often an HTTP resource API.
From the Lewis & Fowler article
Layering
• Software systems can get complicated
• Abstractions are needed
• Layering provides abstraction by separating computer systems in layers
• Higher layers use services from

lower layers
• Each layer has dedicated tasks

and hides complexity from upper

layers
PROGAMMING WITH OBJECTS
What is the secret of programming?
Object Oriented Programming
Object Oriented programming can be powerful
One of the best ways for general purpose computing
But, the power of object oriented languages needs to
be used properly!
Programmers tend to forget the power of OO
Object Oriented Programming
Object Oriented Programming
Programming languages with objects
Objects hold data and methods
Object variables (reference) point to objects
Object are instances of classes, created with new
Classes describe the objects
Classes extend other classes – inheritance
Instance variables are encapsulated
Methods manipulate instance variable
EXERCISE
Explain these concepts and why they are important in
programming
Encapsulation
Interfaces
Polymorphism
Object-oriented programming is not about class
inheritance and creating advanced class diagrams
Remember
Encapsulation – Hiding data
Interfaces – Hiding implementation
Polymorphism – Flexible and Generic Programming
Object Oriented Programming
Powerful programming - beautiful programming
Right use of polymorphism
Separation of concerns
Separating what varies from what stays the same
Object Oriented Programming
Powerful programming - beatiful programming
Right use of polymorphism
Separation of concerns
Separating what varies from what stays the same
Object Oriented Programming
This is the secret of powerful programming
Powerful programming - beatiful programming
Right use of polymorphism
Separation of concerns
Right use of Polymorphism
Object Oriented Programming
Beautiful programming
Separate Variations Design Principle
Identify the aspects of your
application that vary and separate
them from what stays the same
Every piece of knowledge must have
a single, unambiguous, authoritative
representation within a system
Don’t Repeat Yourself – DRY
Object-oriented programming is not about class inheritance and
creating advanced class diagrams
Remember
Encapsulation – Hiding data
Interfaces – Hiding implementation
Polymorphism – Flexible and Generic Programming
Object Oriented Programming
Remember technical dept discussion…
University teachers talking about concreate inheritance?
Object Oriented Programming
Object Oriented Programming
Concrete inheritance did not make it to the list of powerful features of
object oriented programming
In fact, its the most dangerous thing you can do in programs and
needs to be used as such
Directly causes technical debt
It’s extremely easy to violate Liskov’s Principle, make code brittle and
rise the CoC
Object Oriented Programming
Client
SomeClass
MySomeClass
inherits
Changes the behaviour
Client breaks down
uses
Changes to this class can break MySomeClass
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
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;
}
}
Liskov Substitution Principle
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
Liskov Substitution Principle
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);
}
}
Liskov Substitution Principle
Object Oriented Design
Design of classes and interfaces
• Class diagram shows relationships
• Sequence diagrams show flows
Design Patterns
• Reoccurring solutions in design
• “Best practices” – known solutions for common problems
CLASSES
Objects
Date day1;
Date day2 = new Date();
System.out.println (new Date ());
String s = new Date().toString ();
day1 null
day2
Date
Date now = new Date();
if (day2.before(now))
{
System.out.println (day2.toString());
}
before
tostring
...
Object created
Object used
Objects
Date d = new Date();
Operator new creates memory
String is an exception
Reference variables always point
to some memory or null
day1 null
day2
Date
before
tostring
...
Can	
  be	
  any	
  supertype	
  or	
  
interface	
  of	
  the	
  concrete	
  class
Must	
  be	
  a	
  concrete	
  class
Classes
Object
+getId() : String
-id : int
-name : String
-username : String
-password : String
-email : String
User
Object obj = new User ();
User u = (User)obj;
supertype
subtype
Classes extend other classes
• Concrete Inheritance
• Subtype extends supertype
Class contains
• Instance variables
• Methods
Reference variables of type Object points 

to any class
Any supertype can reference subtype
Class methods
▪ Methods can be overridden
– Class extends a class and overrides a method
▪ Methods can be overloaded
– Same method with different parameters
▪ Methods can be
– public – any class can call the method
– private – only available within the class
– protected – only available within the class and extended classes
Class	
  A	
  inherits	
  class	
  B.	
  A	
  overwrites	
  method	
  f.	
  Variable	
  b	
  is	
  created	
  like	
  
this:	
  
	
   B	
  b	
  =	
  new	
  A();	
  
What	
  happens	
  when	
  this	
  line	
  is	
  run:	
  
	
   b.f();	
  
A) The	
  method	
  in	
  A	
  is	
  run	
  
B) The	
  method	
  in	
  B	
  is	
  run	
  
C) First	
  the	
  method	
  in	
  B	
  is	
  run,	
  then	
  the	
  method	
  in	
  A	
  
D) The	
  new	
  statement	
  is	
  illegal	
  and	
  does	
  not	
  compile	
  	
  
QUIZ
Classes
▪ References
– Point to concrete objects
– Must be same type or supertype of concrete object
– Can be interface or abstract class
Object obj = new Date ();
Date d = (Date)obj;
Dateobj
Reference of type Object
Memory space holding object Date
Concrete object of type Date
Left side = type or supertype
or interface og abstract class
right side = concrete class
with memory space
Constructors
▪ Classes have constructor
– Instantiation methods
– Same name as the class
▪ References
– this – refers to the class
– super – extended class
public Employee (String name,
double salary)
{
this (name);
this.salary = salary;
}
public Manager (String name)
{
super (name, 0.0);
...
}
class Point
{
private int x, y;
public Point ()
{
x = 0; y = 0;
}
public Point (int x, int y)
{
this.x = x; this.y = y;
}
public void move (intdx, intdy)
{
x+=dx;y+=dy;
}
public String toString ()
{
return "(" + x + "," + y + ")";
}
}
Example
Class variables
Default constuctor
Overloaded constuctor
this used to refer to the
class variables
Override toString method

of Object
Example
public class Test
{
public static void main (String[] args)
{
System.out.println ("Test");
Test test = new Test();
}
public Test ()
{
Point p0; // null reference
Point p1 = new Point ();
Point p2 = new Point (1,2);
Object obj = p2;
p0 = (Point)obj;
p0.move (1, 1);
System.out.println("p0=" + p0);
}
}
C:java>javac Test.java
C:java>java Test
Test
p0=(2,3)
p0 p1
x=0
y=0
p2
x=1
y=2
obj
x=2
y=3
Java	
  uses	
  this	
  method	
  to	
  pass	
  objects	
  reference	
  to	
  methods	
  
A) Call	
  by	
  reference	
  
B) Call	
  by	
  value	
  
C) Call	
  by	
  method	
  reference	
  
D) Call	
  by	
  value	
  reference	
  
QUIZ
Call By Value
▪ Methods use call by value
– Object references are passed by value
– The reference cannot change, but the object can
x:
y:
42
0
Point
void changeReferance(Point p)
{
while (p.x>0) p.x--;
}
p
Point p = new Point (42,0);
changeReferance(p);
System.out.println(p.x);
Reference	
  p	
  to	
  Point
Local	
  copy	
  of	
  a	
  reference	
  
p	
  to	
  Point	
  
p	
  is	
  same	
  as	
  this.p
p
Inheritance
▪ Classes extend other classes
– Subclasses extend superclasses
▪ Reference variables of super types can reference objects of subtypes
Empolyee e;
e = new Employee(. . .)
e = new Manager(. . .)
class Manager extends Employee
{ ... }
Polymorphism
Employee
Manager
extends
public class Employee
{
private String name;
private double salary;
private Date hireDate;
public Employee()
{
}
public Employee(String name, double salary, Date hireDate)
{
this.name = name;
this.salary = salary;
this.hireDate = hireDate;
}
public Employee(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public void setName(String name)
{
this.name = name;
}
public String toString()
{
return "Employee: " + getName();
}
}
class Manager extends Employee
{
String title;
double bonus;
public Manager (String name, String title)
{
super (name);
this.title = title;
}
public String getTitle ()
{
return title;
}
public String toString ()
{
return "Manager: " + getName() + 

", " + getTitle ();
}
}
New variables
New method
Overridden 

method
What	
  does	
  this	
  program	
  print?
public class Test2
{
public static void main (String[] args)
{
System.out.println ("Test2");
Test2 test2 = new Test2();
}
public Test2 ()
{
Employee e0 = new Employee ("Dilbert");
Employee e1 = new Manager ("Pointy Haired", "Boss");
System.out.println("e0: " + e0);
System.out.println("e1: " + e1);
}
} C:java>java Test2
Test2
e0: Employee: Dilbert
e1: Manager: Pointy Haired, Boss
EXERCISE
Dynamic binding
▪ Decision on which method to run is taken at
runtime
– The virtual machine uses a method table for each class
Manager m = new Manager();
m.setName(“P.H. Carl”); // Employee.setName
m.setTitle (“Boss”); // Manager.setTitle
Employee e1 = new Manager("Pointy Haired", “Boss");
e1.getTitle();
what method is run?
What	
  does	
  this	
  program	
  print?
public class Test1
{
public static void main(String[] args)
{
System.out.println("Test1");
new Test1();
}
public Test1()
{
Employee e0 = new Employee ("Dilbert");
Employee e1 = new Manager ("Pointy", "Boss");
System.out.println(e1.getTitle();
}
}
Trick	
  question!	
  
Does	
  not	
  compile	
  since	
  getTitle	
  is	
  not	
  in	
  Employee
EXERCISE
class Manager extends Employee
{
private double bonus;
public void setBonus(double bonus)
{
this.bonus = bonus;
}
public double getSalary()
{
return this.bonus + super.getSalery();
}
Manager m = new Manager("Fay", "Boss");
m.setBonus(200);
Violates the Liskov substitution principle
WHAT IS POSSIBLE WRONG WITH THIS?
	
  	
  	
   // meantime, somewhere else
Employee e = (Employee)something.getEmployees();
m.setSalary(100);
System.out.println(e.getSalary()); // should print 100
ATH
Think About This!
▪ Why use Concrete Inheritance?
– Powerful implementation approach
– Layered Supertype Pattern
– Enables polymorphism if supertypes are used
– New classes can be added without recompile
▪ But remember
– Object oriented programming is not just about concrete inheritance
– It has to be natural!
– Class hierarchies are rigid
– Not always good to force others to extend
Abstract Classes
▪ Abstract classes put the responsibility of implementation on subclasses
– Classes extending an abstract class must implement the abstract methods
– Can contain both concrete and abstract methods
– Normal classes are concrete classes
▪ Abstract classes cannot be instantiated
▪ Reference variables of abstract types are allowed
– Object must be a concrete class
Abstract Example
abstract class Person
{
private String name;
public Person(String name)
{
this.name = name;
}
// get and set methods ...
public abstract String getDescription ();
}
class Employee extends Person
{
public String getDescription()
{
return "Employee called " + super.getName();
}
} // Person p1 = new Person (); Does not work!
Person p2;
Person p3 = new Employee ("Dilbert");
System.out.println (p3.getDescription());
Key	
  Concept:	
  Polymorphism
Abstract method
Must implement
INTERFACES
Interfaces
▪ Interface is a class without implementation
– Declaration of how to implement class
– All methods and variables are static final
▪ Classes implement interfaces
– implements keyword
– Must implement all the methods – or be abstract
Interfaces
public interface Comparable
{
public int compareTo(Object other);
}
class Employee extends Person implements Comparable
{
public int compareTo(Object o)
{ ...
Example
public interface Comparable
{
public int compareTo(Object other);
}
class Employee extends Person implements Comparable
{
public int compareTo(Object o)
{
Employee e = (Employee)o;
return this.getName().compareTo (e.getName());
} ...
Employee[] ale = new Employee[3];
ale[0] = new Employee ("Dilbert");
ale[1] = new Employee ("Wally");
ale[2] = new Employee ("Alice");
Arrays.sort(ale);
for (int j=0; j <ale.length; j++)
System.out.println(ale[j].getName()); Alice
Dilbert
Wally
How is this possible?
Think About This!
▪ Class A calls class B -> A depends on B
▪ Class java.util.Arrays calls the Employee.compareTo method
▪ Does Arrays depend on Employee?
Polymorphism
Separated interface
<interface>
Comparable
Arrays Employee
implements
calls
Many Faces
▪ Arrays looks at the class as Comparable, while we regard it as Employee
Class Employee
implements Comparable
{
...
compare
Class Arrays
...
sort(Object[]
{
Comparable c ...
Test...
Arrays.sort(persons
Arrays does NOT call Employee.compareTo, 

it calls Comaparable.compareTo 

which happens to be Employee Polymorphism = many faces
Objects
class	
  Employee	
  extends	
  Person
abstract	
  class	
  Person	
  implements	
  Comparable
class	
  Manager	
  extends	
  Employee
Object o = new Manager()
Person p = new Manager()
Comparable c = new Manager()
Employee e = new Manager()
Manager m = new Manager() Memory	
  for	
  Manager
reference
Must	
  be	
  
concrete	
  class
Can	
  be	
  any	
  

supertype
Using Interfaces
▪ Interfaces cannot be instantiated
– Variables of interface types can reference objects that implement the
interface
▪ Interface can extend interfaces
public interface Powered extends Movable
{
double milesPerGallon();
double SPEED_LIMIT = 95;
}
Comarable c = new Comparable (); // NO!!!
Comarable c = new Employee (); // OK!
Why interfaces?
▪ Why not use abstract classes?
– Only one class can be extended
– Class hierarchies are rigid and not always suitable
▪ Interfaces can improve software design
– Provide abstraction – hide the implementation
– Classes that use interfaces are not dependant on a particular
implementation
class Employee extends Person implements Comparable
{
...
Example Pattern
▪ Table Data Gateway or Data Access Object provide an interface to
database table
– Decision on what database access methods to use can be configured
▪ Example
public interface TeamDAO extends RuDAO
{
public void addTeam (Team team);
public Collection getTeams ();
}
Client
Code
Interface Implementation
Example: Drawing system
public interface Drawable
{
public void draw ();
}
public class Rectangle extends Shape
{
private int h, w;
public Rectangle (int x, int y, int h, int w)
{
this.x=x; this.y=y; this.h=h; this.w=w;
}
public void draw ()
{
System.out.println ("Rectange (x="+x+",y="+y+",h="+h+",w="+w+")");
}
}
public abstract class Shape implements Drawable
{
protected int x,y;
}
public class Circle extends Shape
{
private int r;
public Circle(int x, int y, int r)
{
this.x = x; this.y = y; this.r = r;
}
public void draw()
{
System.out.println ("Circle (x="+x+",y="+y+",r="+r+")");
}
}
Example: Drawing system
▪ Drawing all objects
– All draw objects implement Drawable
public DrawTest()
{
List<Drawable> l = new ArrayList<Drawable>();
l.add(new Rectangle(1, 1, 1, 1));
l.add(new Circle(2, 1, 1));
l.add(new Rectangle(8, 4, 1, 1));
for (Drawable d: l)
{
d.draw();
}
}
Rectange (x=1,y=1,h=1,w=1)
Circle (x=2,y=1,r=1)
Rectange (x=8,y=4,h=1,w=1)
Think About This!
▪ All drawing objects in this Layer extend Shape
▪ Shape is abstract and implements Drawable
▪ Client code does not know about the classes that implement Drawable
Shape is Layer Supertype
Shape is Template Method
Generic Programming
X	
  extends	
  Y.	
  Which	
  is	
  true?	
  	
  
	
  	
  
A)	
  Correct	
  if	
  and	
  only	
  if	
  X	
  is	
  a	
  class	
  and	
  Y	
  is	
  an	
  interface	
  
B)	
  Correct	
  if	
  and	
  only	
  if	
  X	
  is	
  an	
  interface	
  and	
  Y	
  is	
  a	
  class	
  
C)	
  Correct	
  if	
  X	
  and	
  Y	
  are	
  either	
  both	
  classes	
  or	
  both	
  interfaces	
  
D)	
  Correct	
  for	
  all	
  combinations	
  of	
  X	
  and	
  Y	
  being	
  classes	
  and/or	
  interfaces.	
  
	
  
QUIZ

Weitere ähnliche Inhalte

Was ist angesagt?

Fundamentals Of Software Architecture
Fundamentals Of Software ArchitectureFundamentals Of Software Architecture
Fundamentals Of Software ArchitectureMarkus Voelter
 
Importance Of Being Driven
Importance Of Being DrivenImportance Of Being Driven
Importance Of Being DrivenAntonio Terreno
 
What a Good Software Architect Does
What a Good Software Architect DoesWhat a Good Software Architect Does
What a Good Software Architect DoesEberhard Wolff
 
Software architecture patterns
Software architecture patternsSoftware architecture patterns
Software architecture patternsRiccardo Cardin
 
L06 Architecting Activities
L06 Architecting ActivitiesL06 Architecting Activities
L06 Architecting ActivitiesHenry Muccini
 
Simon Brown: Software Architecture as Code at I T.A.K.E. Unconference 2015
Simon Brown: Software Architecture as Code at I T.A.K.E. Unconference 2015Simon Brown: Software Architecture as Code at I T.A.K.E. Unconference 2015
Simon Brown: Software Architecture as Code at I T.A.K.E. Unconference 2015Mozaic Works
 
Basics of Software Architecture for .NET Developers
Basics of Software Architecture for .NET DevelopersBasics of Software Architecture for .NET Developers
Basics of Software Architecture for .NET DevelopersDan Douglas
 
Software Architecture: Design Decisions
Software Architecture: Design DecisionsSoftware Architecture: Design Decisions
Software Architecture: Design DecisionsHenry Muccini
 
Software Architecture vs design
Software Architecture vs design Software Architecture vs design
Software Architecture vs design Arslan Anwar
 
The Art of Visualising Software - Simon Brown
The Art of Visualising Software - Simon BrownThe Art of Visualising Software - Simon Brown
The Art of Visualising Software - Simon BrownValtech UK
 
Modern Software Architectures: Building Solutions for Web, Cloud, and Mobile
Modern Software Architectures: Building Solutions for Web, Cloud, and MobileModern Software Architectures: Building Solutions for Web, Cloud, and Mobile
Modern Software Architectures: Building Solutions for Web, Cloud, and MobileDan Mohl
 
Agile Software Architecture
Agile Software ArchitectureAgile Software Architecture
Agile Software ArchitectureChris F Carroll
 
Refactoring for Software Architecture Smells
Refactoring for Software Architecture SmellsRefactoring for Software Architecture Smells
Refactoring for Software Architecture SmellsGanesh Samarthyam
 
The Role of the Software Architect
The Role of the Software ArchitectThe Role of the Software Architect
The Role of the Software ArchitectHayim Makabee
 
software-architecture-patterns
software-architecture-patternssoftware-architecture-patterns
software-architecture-patternsPallav Kumar
 
bryn.hrld.PIP-CV 10.5.5.d-scaled
bryn.hrld.PIP-CV 10.5.5.d-scaledbryn.hrld.PIP-CV 10.5.5.d-scaled
bryn.hrld.PIP-CV 10.5.5.d-scaledBryan D. Harold
 
Love your architecture - Alexander von Zitzewitz
Love your architecture - Alexander von ZitzewitzLove your architecture - Alexander von Zitzewitz
Love your architecture - Alexander von ZitzewitzJAXLondon_Conference
 

Was ist angesagt? (20)

Fundamentals Of Software Architecture
Fundamentals Of Software ArchitectureFundamentals Of Software Architecture
Fundamentals Of Software Architecture
 
Importance Of Being Driven
Importance Of Being DrivenImportance Of Being Driven
Importance Of Being Driven
 
What a Good Software Architect Does
What a Good Software Architect DoesWhat a Good Software Architect Does
What a Good Software Architect Does
 
Dsm presentation (english)
Dsm presentation (english)Dsm presentation (english)
Dsm presentation (english)
 
Software architecture patterns
Software architecture patternsSoftware architecture patterns
Software architecture patterns
 
L06 Architecting Activities
L06 Architecting ActivitiesL06 Architecting Activities
L06 Architecting Activities
 
Simon Brown: Software Architecture as Code at I T.A.K.E. Unconference 2015
Simon Brown: Software Architecture as Code at I T.A.K.E. Unconference 2015Simon Brown: Software Architecture as Code at I T.A.K.E. Unconference 2015
Simon Brown: Software Architecture as Code at I T.A.K.E. Unconference 2015
 
Basics of Software Architecture for .NET Developers
Basics of Software Architecture for .NET DevelopersBasics of Software Architecture for .NET Developers
Basics of Software Architecture for .NET Developers
 
Software Architecture: Design Decisions
Software Architecture: Design DecisionsSoftware Architecture: Design Decisions
Software Architecture: Design Decisions
 
Software Architecture vs design
Software Architecture vs design Software Architecture vs design
Software Architecture vs design
 
Trends in Technology
Trends in TechnologyTrends in Technology
Trends in Technology
 
The Art of Visualising Software - Simon Brown
The Art of Visualising Software - Simon BrownThe Art of Visualising Software - Simon Brown
The Art of Visualising Software - Simon Brown
 
Software Engineering 101
Software Engineering 101Software Engineering 101
Software Engineering 101
 
Modern Software Architectures: Building Solutions for Web, Cloud, and Mobile
Modern Software Architectures: Building Solutions for Web, Cloud, and MobileModern Software Architectures: Building Solutions for Web, Cloud, and Mobile
Modern Software Architectures: Building Solutions for Web, Cloud, and Mobile
 
Agile Software Architecture
Agile Software ArchitectureAgile Software Architecture
Agile Software Architecture
 
Refactoring for Software Architecture Smells
Refactoring for Software Architecture SmellsRefactoring for Software Architecture Smells
Refactoring for Software Architecture Smells
 
The Role of the Software Architect
The Role of the Software ArchitectThe Role of the Software Architect
The Role of the Software Architect
 
software-architecture-patterns
software-architecture-patternssoftware-architecture-patterns
software-architecture-patterns
 
bryn.hrld.PIP-CV 10.5.5.d-scaled
bryn.hrld.PIP-CV 10.5.5.d-scaledbryn.hrld.PIP-CV 10.5.5.d-scaled
bryn.hrld.PIP-CV 10.5.5.d-scaled
 
Love your architecture - Alexander von Zitzewitz
Love your architecture - Alexander von ZitzewitzLove your architecture - Alexander von Zitzewitz
Love your architecture - Alexander von Zitzewitz
 

Ähnlich wie L03 Software Design

1669609053088_oops_final.pptx
1669609053088_oops_final.pptx1669609053088_oops_final.pptx
1669609053088_oops_final.pptxPandeeswariKannan
 
OOP-Advanced_Programming.pptx
OOP-Advanced_Programming.pptxOOP-Advanced_Programming.pptx
OOP-Advanced_Programming.pptxMohamed Essam
 
Object Oriented Programming In .Net
Object Oriented Programming In .NetObject Oriented Programming In .Net
Object Oriented Programming In .NetGreg Sohl
 
Patterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxPatterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxdanhaley45372
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxanguraju1
 
Framework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users GroupFramework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users Groupbrada
 
Building modular software with OSGi - Ulf Fildebrandt
Building modular software with OSGi - Ulf FildebrandtBuilding modular software with OSGi - Ulf Fildebrandt
Building modular software with OSGi - Ulf Fildebrandtmfrancis
 
OOP-Advanced Programming with c++
OOP-Advanced Programming with c++OOP-Advanced Programming with c++
OOP-Advanced Programming with c++Mohamed Essam
 
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Steven Smith
 
OOP lesson1 and Variables.pdf
OOP lesson1 and Variables.pdfOOP lesson1 and Variables.pdf
OOP lesson1 and Variables.pdfHouseMusica
 
Summer Training Project On C++
Summer Training Project On  C++Summer Training Project On  C++
Summer Training Project On C++KAUSHAL KUMAR JHA
 
Linq To The Enterprise
Linq To The EnterpriseLinq To The Enterprise
Linq To The EnterpriseDaniel Egan
 
2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#Daniel Fisher
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ Ganesh Samarthyam
 
DOC-20210303-WA0017..pptx,coding stuff in c
DOC-20210303-WA0017..pptx,coding stuff in cDOC-20210303-WA0017..pptx,coding stuff in c
DOC-20210303-WA0017..pptx,coding stuff in cfloraaluoch3
 

Ähnlich wie L03 Software Design (20)

1669609053088_oops_final.pptx
1669609053088_oops_final.pptx1669609053088_oops_final.pptx
1669609053088_oops_final.pptx
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
OOP-Advanced_Programming.pptx
OOP-Advanced_Programming.pptxOOP-Advanced_Programming.pptx
OOP-Advanced_Programming.pptx
 
Design for Testability
Design for TestabilityDesign for Testability
Design for Testability
 
Object Oriented Programming In .Net
Object Oriented Programming In .NetObject Oriented Programming In .Net
Object Oriented Programming In .Net
 
Patterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxPatterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docx
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Framework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users GroupFramework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users Group
 
Building modular software with OSGi - Ulf Fildebrandt
Building modular software with OSGi - Ulf FildebrandtBuilding modular software with OSGi - Ulf Fildebrandt
Building modular software with OSGi - Ulf Fildebrandt
 
OOP-Advanced Programming with c++
OOP-Advanced Programming with c++OOP-Advanced Programming with c++
OOP-Advanced Programming with c++
 
Day1
Day1Day1
Day1
 
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
 
OOP lesson1 and Variables.pdf
OOP lesson1 and Variables.pdfOOP lesson1 and Variables.pdf
OOP lesson1 and Variables.pdf
 
Summer Training Project On C++
Summer Training Project On  C++Summer Training Project On  C++
Summer Training Project On C++
 
Linq To The Enterprise
Linq To The EnterpriseLinq To The Enterprise
Linq To The Enterprise
 
2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#2009 Dotnet Information Day: More effective c#
2009 Dotnet Information Day: More effective c#
 
OO Design and Design Patterns in C++
OO Design and Design Patterns in C++ OO Design and Design Patterns in C++
OO Design and Design Patterns in C++
 
DOC-20210303-WA0017..pptx,coding stuff in c
DOC-20210303-WA0017..pptx,coding stuff in cDOC-20210303-WA0017..pptx,coding stuff in c
DOC-20210303-WA0017..pptx,coding stuff in c
 
Introduction to Design Patterns
Introduction to Design PatternsIntroduction to Design Patterns
Introduction to Design Patterns
 

Mehr von Ó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
 

Mehr von Ó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
 

Kürzlich hochgeladen

How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogueitservices996
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptxVinzoCenzo
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024VictoriaMetrics
 
Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Anthony Dahanne
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITmanoharjgpsolutions
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...Bert Jan Schrijver
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencessuser9e7c64
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 

Kürzlich hochgeladen (20)

How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogue
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptx
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024
 
Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh IT
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conference
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 

L03 Software Design

  • 1. HÖNNUN OG SMÍÐI HUGBÚNAÐAR 2015 L03 SOFTWARE DESIGN
  • 2. Agenda Architecture Recap Programming with Objects Classes Interfaces
  • 4. Conwey’s Law Organisations which design systems ... are constrained to produce designs which are copies of the communication structures of these organisations From a 1967 paper “How do Committees Invent?” by Mel Conway
  • 5. Monolithic Architecture Traditional Web Application Architecture All code is built into a single application that is deployed Simple to develop, test, deploy, scale Clear layering: Presentation, Domain, Data Source Tomcat ApacheBrowser WAR Web Components Customer Wallet Data Source DB WAR file = Web ARchive Tomcat = web server for Java Servlets (web components)
  • 6. Monolithic Architecture ▪ Drawbacks – User interface challenge – old style UI architecture – Real-time applications (like node.js) don’t fit in easy – Obstacle to frequent deployment – fear of change – Overloads your IDE and container – slow build, development – Obstacle to scaling development teams – Locks down the technology stack – long term commitment
  • 7. Technical Debt Concept in programming that reflects the extra development work that arises when code that is easy to implement in the short run is used instead of applying the best overall solution Small decisions that accumulate over time - “I’ll fix this later” Hard to see until any small change is extremely expensive (CoC = Cost of Change), and then Conway’s Second Law applies If the debt is not repaid, then it will keep on accumulating interest, making it hard to implement changes later on
  • 8. Why does it Happen? Or maybe… University Teachers that teach about concrete inheritance Object Oriented progamming is good but can be misused
  • 9. Architecture - noun The decomposition of a product into a collection of components/modules and interactions Structure
  • 10. Architecture - verb Understanding what you need to build, create a vision and making the right decisions vision
  • 11. A component is a software building block that is independently replaceable independently upgradable Component
  • 12. Architecture - types Application Architecture: Application is the focus System Architecture: Focus on multiple applications across a number of tiers and technologies Software Architecture: The combination of application and system architecture and includes the technical practices to build the software
  • 13. Service Oriented Architecture SOA actually means that components of an application act as interoperable services, and can be used independently and recombined into other applications. Engineering Software as a Service by David Patterson and Armando Fox
  • 14. Microservices In recent years a new term has emerged, Microservices: The microservice architectural style is an approach to developing a single application as a suite of small services, each running in its own process and communicating with lightweight mechanisms, often an HTTP resource API. From the Lewis & Fowler article
  • 15. Layering • Software systems can get complicated • Abstractions are needed • Layering provides abstraction by separating computer systems in layers • Higher layers use services from
 lower layers • Each layer has dedicated tasks
 and hides complexity from upper
 layers
  • 17. What is the secret of programming?
  • 18. Object Oriented Programming Object Oriented programming can be powerful One of the best ways for general purpose computing But, the power of object oriented languages needs to be used properly! Programmers tend to forget the power of OO
  • 20. Object Oriented Programming Programming languages with objects Objects hold data and methods Object variables (reference) point to objects Object are instances of classes, created with new Classes describe the objects Classes extend other classes – inheritance Instance variables are encapsulated Methods manipulate instance variable
  • 21. EXERCISE Explain these concepts and why they are important in programming Encapsulation Interfaces Polymorphism
  • 22. Object-oriented programming is not about class inheritance and creating advanced class diagrams Remember Encapsulation – Hiding data Interfaces – Hiding implementation Polymorphism – Flexible and Generic Programming Object Oriented Programming
  • 23. Powerful programming - beautiful programming Right use of polymorphism Separation of concerns Separating what varies from what stays the same Object Oriented Programming
  • 24. Powerful programming - beatiful programming Right use of polymorphism Separation of concerns Separating what varies from what stays the same Object Oriented Programming This is the secret of powerful programming
  • 25. Powerful programming - beatiful programming Right use of polymorphism Separation of concerns Right use of Polymorphism Object Oriented Programming Beautiful programming
  • 26. Separate Variations Design Principle Identify the aspects of your application that vary and separate them from what stays the same
  • 27. Every piece of knowledge must have a single, unambiguous, authoritative representation within a system Don’t Repeat Yourself – DRY
  • 28. Object-oriented programming is not about class inheritance and creating advanced class diagrams Remember Encapsulation – Hiding data Interfaces – Hiding implementation Polymorphism – Flexible and Generic Programming Object Oriented Programming
  • 29. Remember technical dept discussion… University teachers talking about concreate inheritance? Object Oriented Programming
  • 30. Object Oriented Programming Concrete inheritance did not make it to the list of powerful features of object oriented programming In fact, its the most dangerous thing you can do in programs and needs to be used as such Directly causes technical debt It’s extremely easy to violate Liskov’s Principle, make code brittle and rise the CoC
  • 31. Object Oriented Programming Client SomeClass MySomeClass inherits Changes the behaviour Client breaks down uses Changes to this class can break MySomeClass
  • 32. 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
  • 33. 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; } } Liskov Substitution Principle
  • 34. 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 Liskov Substitution Principle
  • 35. 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); } } Liskov Substitution Principle
  • 36. Object Oriented Design Design of classes and interfaces • Class diagram shows relationships • Sequence diagrams show flows Design Patterns • Reoccurring solutions in design • “Best practices” – known solutions for common problems
  • 38. Objects Date day1; Date day2 = new Date(); System.out.println (new Date ()); String s = new Date().toString (); day1 null day2 Date Date now = new Date(); if (day2.before(now)) { System.out.println (day2.toString()); } before tostring ... Object created Object used
  • 39. Objects Date d = new Date(); Operator new creates memory String is an exception Reference variables always point to some memory or null day1 null day2 Date before tostring ... Can  be  any  supertype  or   interface  of  the  concrete  class Must  be  a  concrete  class
  • 40. Classes Object +getId() : String -id : int -name : String -username : String -password : String -email : String User Object obj = new User (); User u = (User)obj; supertype subtype Classes extend other classes • Concrete Inheritance • Subtype extends supertype Class contains • Instance variables • Methods Reference variables of type Object points 
 to any class Any supertype can reference subtype
  • 41. Class methods ▪ Methods can be overridden – Class extends a class and overrides a method ▪ Methods can be overloaded – Same method with different parameters ▪ Methods can be – public – any class can call the method – private – only available within the class – protected – only available within the class and extended classes
  • 42. Class  A  inherits  class  B.  A  overwrites  method  f.  Variable  b  is  created  like   this:     B  b  =  new  A();   What  happens  when  this  line  is  run:     b.f();   A) The  method  in  A  is  run   B) The  method  in  B  is  run   C) First  the  method  in  B  is  run,  then  the  method  in  A   D) The  new  statement  is  illegal  and  does  not  compile     QUIZ
  • 43. Classes ▪ References – Point to concrete objects – Must be same type or supertype of concrete object – Can be interface or abstract class Object obj = new Date (); Date d = (Date)obj; Dateobj Reference of type Object Memory space holding object Date Concrete object of type Date Left side = type or supertype or interface og abstract class right side = concrete class with memory space
  • 44. Constructors ▪ Classes have constructor – Instantiation methods – Same name as the class ▪ References – this – refers to the class – super – extended class public Employee (String name, double salary) { this (name); this.salary = salary; } public Manager (String name) { super (name, 0.0); ... }
  • 45. class Point { private int x, y; public Point () { x = 0; y = 0; } public Point (int x, int y) { this.x = x; this.y = y; } public void move (intdx, intdy) { x+=dx;y+=dy; } public String toString () { return "(" + x + "," + y + ")"; } } Example Class variables Default constuctor Overloaded constuctor this used to refer to the class variables Override toString method
 of Object
  • 46. Example public class Test { public static void main (String[] args) { System.out.println ("Test"); Test test = new Test(); } public Test () { Point p0; // null reference Point p1 = new Point (); Point p2 = new Point (1,2); Object obj = p2; p0 = (Point)obj; p0.move (1, 1); System.out.println("p0=" + p0); } } C:java>javac Test.java C:java>java Test Test p0=(2,3) p0 p1 x=0 y=0 p2 x=1 y=2 obj x=2 y=3
  • 47. Java  uses  this  method  to  pass  objects  reference  to  methods   A) Call  by  reference   B) Call  by  value   C) Call  by  method  reference   D) Call  by  value  reference   QUIZ
  • 48. Call By Value ▪ Methods use call by value – Object references are passed by value – The reference cannot change, but the object can x: y: 42 0 Point void changeReferance(Point p) { while (p.x>0) p.x--; } p Point p = new Point (42,0); changeReferance(p); System.out.println(p.x); Reference  p  to  Point Local  copy  of  a  reference   p  to  Point   p  is  same  as  this.p p
  • 49. Inheritance ▪ Classes extend other classes – Subclasses extend superclasses ▪ Reference variables of super types can reference objects of subtypes Empolyee e; e = new Employee(. . .) e = new Manager(. . .) class Manager extends Employee { ... } Polymorphism Employee Manager extends
  • 50. public class Employee { private String name; private double salary; private Date hireDate; public Employee() { } public Employee(String name, double salary, Date hireDate) { this.name = name; this.salary = salary; this.hireDate = hireDate; } public Employee(String name) { this.name = name; }
  • 51. public String getName() { return name; } public double getSalary() { return salary; } public void setName(String name) { this.name = name; } public String toString() { return "Employee: " + getName(); } }
  • 52. class Manager extends Employee { String title; double bonus; public Manager (String name, String title) { super (name); this.title = title; } public String getTitle () { return title; } public String toString () { return "Manager: " + getName() + 
 ", " + getTitle (); } } New variables New method Overridden 
 method
  • 53. What  does  this  program  print? public class Test2 { public static void main (String[] args) { System.out.println ("Test2"); Test2 test2 = new Test2(); } public Test2 () { Employee e0 = new Employee ("Dilbert"); Employee e1 = new Manager ("Pointy Haired", "Boss"); System.out.println("e0: " + e0); System.out.println("e1: " + e1); } } C:java>java Test2 Test2 e0: Employee: Dilbert e1: Manager: Pointy Haired, Boss EXERCISE
  • 54. Dynamic binding ▪ Decision on which method to run is taken at runtime – The virtual machine uses a method table for each class Manager m = new Manager(); m.setName(“P.H. Carl”); // Employee.setName m.setTitle (“Boss”); // Manager.setTitle Employee e1 = new Manager("Pointy Haired", “Boss"); e1.getTitle(); what method is run?
  • 55. What  does  this  program  print? public class Test1 { public static void main(String[] args) { System.out.println("Test1"); new Test1(); } public Test1() { Employee e0 = new Employee ("Dilbert"); Employee e1 = new Manager ("Pointy", "Boss"); System.out.println(e1.getTitle(); } } Trick  question!   Does  not  compile  since  getTitle  is  not  in  Employee EXERCISE
  • 56. class Manager extends Employee { private double bonus; public void setBonus(double bonus) { this.bonus = bonus; } public double getSalary() { return this.bonus + super.getSalery(); } Manager m = new Manager("Fay", "Boss"); m.setBonus(200); Violates the Liskov substitution principle WHAT IS POSSIBLE WRONG WITH THIS?       // meantime, somewhere else Employee e = (Employee)something.getEmployees(); m.setSalary(100); System.out.println(e.getSalary()); // should print 100 ATH
  • 57. Think About This! ▪ Why use Concrete Inheritance? – Powerful implementation approach – Layered Supertype Pattern – Enables polymorphism if supertypes are used – New classes can be added without recompile ▪ But remember – Object oriented programming is not just about concrete inheritance – It has to be natural! – Class hierarchies are rigid – Not always good to force others to extend
  • 58. Abstract Classes ▪ Abstract classes put the responsibility of implementation on subclasses – Classes extending an abstract class must implement the abstract methods – Can contain both concrete and abstract methods – Normal classes are concrete classes ▪ Abstract classes cannot be instantiated ▪ Reference variables of abstract types are allowed – Object must be a concrete class
  • 59. Abstract Example abstract class Person { private String name; public Person(String name) { this.name = name; } // get and set methods ... public abstract String getDescription (); } class Employee extends Person { public String getDescription() { return "Employee called " + super.getName(); } } // Person p1 = new Person (); Does not work! Person p2; Person p3 = new Employee ("Dilbert"); System.out.println (p3.getDescription()); Key  Concept:  Polymorphism Abstract method Must implement
  • 61. Interfaces ▪ Interface is a class without implementation – Declaration of how to implement class – All methods and variables are static final ▪ Classes implement interfaces – implements keyword – Must implement all the methods – or be abstract
  • 62. Interfaces public interface Comparable { public int compareTo(Object other); } class Employee extends Person implements Comparable { public int compareTo(Object o) { ...
  • 63. Example public interface Comparable { public int compareTo(Object other); } class Employee extends Person implements Comparable { public int compareTo(Object o) { Employee e = (Employee)o; return this.getName().compareTo (e.getName()); } ... Employee[] ale = new Employee[3]; ale[0] = new Employee ("Dilbert"); ale[1] = new Employee ("Wally"); ale[2] = new Employee ("Alice"); Arrays.sort(ale); for (int j=0; j <ale.length; j++) System.out.println(ale[j].getName()); Alice Dilbert Wally How is this possible?
  • 64. Think About This! ▪ Class A calls class B -> A depends on B ▪ Class java.util.Arrays calls the Employee.compareTo method ▪ Does Arrays depend on Employee? Polymorphism Separated interface <interface> Comparable Arrays Employee implements calls
  • 65. Many Faces ▪ Arrays looks at the class as Comparable, while we regard it as Employee Class Employee implements Comparable { ... compare Class Arrays ... sort(Object[] { Comparable c ... Test... Arrays.sort(persons Arrays does NOT call Employee.compareTo, 
 it calls Comaparable.compareTo 
 which happens to be Employee Polymorphism = many faces
  • 66. Objects class  Employee  extends  Person abstract  class  Person  implements  Comparable class  Manager  extends  Employee Object o = new Manager() Person p = new Manager() Comparable c = new Manager() Employee e = new Manager() Manager m = new Manager() Memory  for  Manager reference Must  be   concrete  class Can  be  any  
 supertype
  • 67. Using Interfaces ▪ Interfaces cannot be instantiated – Variables of interface types can reference objects that implement the interface ▪ Interface can extend interfaces public interface Powered extends Movable { double milesPerGallon(); double SPEED_LIMIT = 95; } Comarable c = new Comparable (); // NO!!! Comarable c = new Employee (); // OK!
  • 68. Why interfaces? ▪ Why not use abstract classes? – Only one class can be extended – Class hierarchies are rigid and not always suitable ▪ Interfaces can improve software design – Provide abstraction – hide the implementation – Classes that use interfaces are not dependant on a particular implementation class Employee extends Person implements Comparable { ...
  • 69. Example Pattern ▪ Table Data Gateway or Data Access Object provide an interface to database table – Decision on what database access methods to use can be configured ▪ Example public interface TeamDAO extends RuDAO { public void addTeam (Team team); public Collection getTeams (); } Client Code Interface Implementation
  • 70. Example: Drawing system public interface Drawable { public void draw (); } public class Rectangle extends Shape { private int h, w; public Rectangle (int x, int y, int h, int w) { this.x=x; this.y=y; this.h=h; this.w=w; } public void draw () { System.out.println ("Rectange (x="+x+",y="+y+",h="+h+",w="+w+")"); } } public abstract class Shape implements Drawable { protected int x,y; } public class Circle extends Shape { private int r; public Circle(int x, int y, int r) { this.x = x; this.y = y; this.r = r; } public void draw() { System.out.println ("Circle (x="+x+",y="+y+",r="+r+")"); } }
  • 71. Example: Drawing system ▪ Drawing all objects – All draw objects implement Drawable public DrawTest() { List<Drawable> l = new ArrayList<Drawable>(); l.add(new Rectangle(1, 1, 1, 1)); l.add(new Circle(2, 1, 1)); l.add(new Rectangle(8, 4, 1, 1)); for (Drawable d: l) { d.draw(); } } Rectange (x=1,y=1,h=1,w=1) Circle (x=2,y=1,r=1) Rectange (x=8,y=4,h=1,w=1)
  • 72. Think About This! ▪ All drawing objects in this Layer extend Shape ▪ Shape is abstract and implements Drawable ▪ Client code does not know about the classes that implement Drawable Shape is Layer Supertype Shape is Template Method Generic Programming
  • 73. X  extends  Y.  Which  is  true?         A)  Correct  if  and  only  if  X  is  a  class  and  Y  is  an  interface   B)  Correct  if  and  only  if  X  is  an  interface  and  Y  is  a  class   C)  Correct  if  X  and  Y  are  either  both  classes  or  both  interfaces   D)  Correct  for  all  combinations  of  X  and  Y  being  classes  and/or  interfaces.     QUIZ