Object-Oriented Design

Similar documents
Review: Cohesion and Coupling, Mutable, Inheritance Screen Layouts. Object-Oriented Design CRC Cards - UML class diagrams

Designing Classes. Check out DesigningClasses project from SVN

More on Objects and Classes

Chapter 10 Object-Oriented Design Principles

Goal: build an object-oriented model of the realworld system (or imaginary world) Slicing the soup: OOA vs. OOD

Object-Oriented Systems Analysis and Design Using UML

Object-Oriented Programming in Java

Object Oriented Software Development CIS Today: Object Oriented Analysis

MSO Lecture 3. Wouter Swierstra. September 14, 2015

Java Object Oriented Design. CSC207 Fall 2014

A - 1. CS 494 Object-Oriented Analysis & Design. UML Class Models. Overview. Class Model Perspectives (cont d) Developing Class Models

Inheritance and Subclasses

Chapter 2: The Object-Oriented Design Process

Lecture 34 SDLC Phases and UML Diagrams

Chapter 10. Object-Oriented Analysis and Modeling Using the UML. McGraw-Hill/Irwin

Object-Oriented Design. Module UFC016QM. and Programming. Objects and Classes. O-O Design Unit 2: Faculty of Computing, Engineering

Java Programming Lecture 7

Inheritance and Interfaces

The Unified Modeling Language. Asst.Prof.Dr. Supakit Nootyaskool IT-KMITL

SE 1: Software Requirements Specification and Analysis

CSE 403: Software Engineering, Spring courses.cs.washington.edu/courses/cse403/15sp/ UML Class Diagrams. Emina Torlak

CSC/ECE 517: Object-Oriented Languages and Systems Summer 2008 Test 2 with Answers

Software and Programming I. Classes and Arrays. Roman Kontchakov / Carsten Fuhs. Birkbeck, University of London

Building custom components IAT351

Introduction to Software Engineering. 5. Modeling Objects and Classes

S T R U C T U R A L M O D E L I N G ( M O D E L I N G A S Y S T E M ' S L O G I C A L S T R U C T U R E U S I N G C L A S S E S A N D C L A S S D I A

Chapter 5: Structural Modeling

CSSE 220 Day 15. Inheritance. Check out DiscountSubclasses from SVN

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Chapter Goals. Chapter 7 Designing Classes. Discovering Classes Actors (end in -er, -or) objects do some kinds of work for you: Discovering Classes

Design Engineering. Dr. Marouane Kessentini Department of Computer Science

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Design Engineering. Overview

Basic Structural Modeling. Copyright Joey Paquet,

Object-Oriented Design

OBJECT ORİENTATİON ENCAPSULATİON

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Use the scantron sheet to enter the answer to questions (pages 1-6)

Object-Oriented Programming Paradigm

Class diagrams. Modeling with UML Chapter 2, part 2. Class Diagrams: details. Class diagram for a simple watch

MSO Analysis & UML. Hans Philippi (based on the course slides of Wouter Swierstra) August 24, Analysis & UML 1 / 56

OO design. Classes, Responsibilities, Collaborations (CRC) 13/9/1999 COSC

Object-Oriented Software Engineering Practical Software Development using UML and Java

OO System Models Static Views

C18a: Abstract Class and Method

CS-202 Introduction to Object Oriented Programming

Object- Oriented Design with UML and Java Part I: Fundamentals

2 nd Grade Math Learning Targets. Algebra:

Object Oriented Software Design

CSE 70 Final Exam Fall 2009

Unified Modeling Language

ITI Introduction to Computing II

Database Applications (15-415)

Expanding Our Horizons. CSCI 4448/5448: Object-Oriented Analysis & Design Lecture 9 09/25/2011

Abstraction. Design fundamentals in OO Systems. Fundamental Software Development Principles

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

CTIS 359 Principles of Software Engineering SOFTWARE DESIGN OO(A)D

Exam Questions. Object-Oriented Design, IV1350. Maximum exam score is 100, grade limits are as follows. Score Grade 90 A 80 B 70 C 60 D 50 E

Information Technology Audit & Cyber Security

ITI Introduction to Computing II

Unified Modeling Language (UML) Class Diagram

Inheritance and Interfaces

The Object-Oriented Paradigm

INTERNAL ASSESSMENT TEST III Answer Schema

Principles of Software Construction: Objects, Design, and Concurrency

Lecturer: Sebastian Coope Ashton Building, Room G.18 COMP 201 web-page:

Software Development Cycle. Unified Modeling Language. Unified Modeling Language. Unified Modeling Language. Unified Modeling Language.

Arrays and Basic Algorithms

3. UML Class Diagrams Page 1 of 15

CSE 403 Lecture 8. UML Class Diagrams. Thanks to Marty Stepp, Michael Ernst, and other past instructors of CSE 403

Software Engineering I (02161)

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

user.book Page 45 Friday, April 8, :05 AM Part 2 BASIC STRUCTURAL MODELING

Introducing the UML Eng. Mohammed T. Abo Alroos

MechEng SE3 Lecture 7 Domain Modelling

Software and Programming 1

Encapsulation. Inf1-OOP. Getters and Setters. Encapsulation Again. Inheritance Encapsulation and Inheritance. The Object Superclass

Lecture 9: Lists. MIT-AITI Kenya 2005

1: Introduction to Object (1)

Course "UML and Design Patterns" of module "Software Engineering and Design", version February 2011 (X)

CSCU9T4: Managing Information

Chapter 6 Introduction to Defining Classes

ADVANCED SOFTWARE DESIGN LECTURE 7 GRASP

2D1358 Object Oriented Program Construction in C++ Exercises & Labs. Course Registration / Accounts. Course Literature

Object-Oriented Design

Object-Oriented Software Engineering Practical Software Development using UML and Java. Chapter 5: Modelling with Classes

Lesson 11. W.C.Udwela Department of Mathematics & Computer Science

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

CS/IT Secure Software Construction

Chapter 5 Object-Oriented Programming

Principles of Software Construction: Objects, Design, and Concurrency

Inf1-OP. Classes with Stuff in Common. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein.

Object-Oriented Design and Modeling Using the UML

Object-Oriented and Classical Software Engineering

Chapter 8 Designing Classes. Big Java by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved.

Unit Maps: Kindergarten Math

administrivia today UML start design patterns Tuesday, September 28, 2010

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

Chapter 14 Abstract Classes and Interfaces

Introduction to UML and Class Diagrams

Transcription:

Software and Programming I Object-Oriented Design Roman Kontchakov / Carsten Fuhs Birkbeck, University of London

Outline Discovering classes and methods Relationships between classes An object-oriented process for software development Sections 12.1 12.3 http://higheredbcs.wiley.com/legacy/college/horstmann/1118063317/web_chapters/ch12.pdf slides are available at www.dcs.bbk.ac.uk/ roman/sp1 SP1 2019-10 1

Problem Solving: the Story So Far objects are first-class citizens that exchange messages: object.method(parameter values) similar objects are organised into classes organising classes for related concepts into inheritance hierarchies (e.g., Employee extends Person) polymorphism: talk to different objects in the same way, but they may process the request differently allows code reuse when they do use the same solution But how do we know which classes (and methods) to have, and how to come up with the inheritance hierarchies? SP1 2019-10 2

Discovering Classes Starting point: requirements specification in natural language Candidates for classes: nouns (from the problem domain) Examples: Person, Student, Employee, BankAccount, CashRegister,... Suitable classes may already exist in Java standard libraries / earlier programs; or maybe we can extend an existing class Class name tells us what its objects are supposed to do Don t go too far: e.g., address as class Address, or just a String? depends what we need from addresses for the task... NB: code may later need classes outside the problem domain for technical purposes, e.g., user interface, database access, basic data structures like ArrayList,... requirements give us the domain model SP1 2019-10 3

Discovering Classes: Example Program for invoices that list each item with its price and quantity, the overall total due amount, as well as the address of the customer Possible classes: Invoice LineItem Customer C. Horstmann, Java for Everyone, 2013, p. W551 SP1 2019-10 4

Discovering Methods: CRC Cards Candidates for methods: verbs in the task description Invoice example: computing the overall total amount due But which of the classes should take the method, Invoice, LineItem or Customer? Approach: use CRC Cards (index cards) Responsibilities Class Invoice Collaborators compute amount due LineItem SP1 2019-10 5

Discovering Methods: CRC Cards Responsibility method, but can be higher level (Java implementation may need several methods) Listing collaborators may reveal their own responsibilities (e.g., LineItem must tell its own total) CRC cards can be rearranged on table, handy for discussions A single CRC card should not have too many responsibilities keep design simple Later: find out how classes are related Can we move common responsibilities to a superclass? Are there independent clusters? SP1 2019-10 6

Cohesion (1) Public interface of a class should be cohesive: everything should be closely related to single concept represented by the class 1 public class CashRegister { 2 public static final double NICKEL_VALUE = 0.05; 3 public static final double DIME_VALUE = 0.1; 4 public static final double QUARTER_VALUE = 0.25; 5... 6 public void enterpayment(int dollars, int quarters, int dimes, int nickels, int pennies) {... } 7... 8 } Q: What is wrong here? SP1 2019-10 7

Cohesion (2) Two separate concepts: cash register and values of coins Rather have a dedicated Coin class with Coins responsible for knowing their own value Allows us to simplify the CashRegister... 1 public class CashRegister { 2... 3 public void enterpayment(coin[] coins) { 4... 5 } 6... 7 }... responsibilities of cash register and coins are separated SP1 2019-10 8

Good cases Relationships Between Classes Can we move some common responsibilities to a superclass? less implementation effort, cleaner design Are there (groups of) classes that are completely independent from each other? can assign different programmers to implement them, no worries about one waiting for the other SP1 2019-10 9

Dependency Dependency relationship between classes aka: knows about Example: CashRegister knows about Coin objects but Coin does not know about CashRegister Notation for dependencies in UML Class Diagrams: dashed arrow, normal arrow tip CashRegister Coin In Java: CashRegister needs Coin to compile, but not vice versa CashRegister depends on Coin, but not vice versa SP1 2019-10 10

Coupling Coupling is the degree of dependency between classes Aim for low coupling: C. Horstmann Java for Everyone 2013, p. W555 If, say, Coin changes in the future, all classes that depend on Coin may need to be changed as well Want to be able to use Coin in another program without dragging in a lot of dependencies SP1 2019-10 11

Aggregation (1) Aggregation relationship between classes aka: has-a Example: a Quiz contains (1 or more) Question objects, so class Quiz aggregates class Question UML notation: solid arrow with diamond-shaped tip at the aggregating class Quiz Question Can also keep track of multiplicities (how many do I have?) Quiz 1..* Question Later on implementation level: Question[] as attribute of Quiz (multiple Questions in a Quiz) SP1 2019-10 12

Aggregation (2) Another example: Car aggregates Tyre objects Tyre Car Aggregation is a stronger form of dependency: if you have something, you certainly know about it Quiz also depends on Scanner (to read input), but Quiz does not aggregate Scanner Generally: need aggregation ( instance variable) in your class if you need to remember an object between calls to the methods of your class SP1 2019-10 13

Inheritance Inheritance relationship between classes aka: is-a Example: an Employee is a Person, class Employee inherits from class Person UML notation: solid arrow with triangle-shaped tip at the superclass Employee Person In Java: 1 public class Employee extends Person { 2... 3 } SP1 2019-10 14

Inheritance: A Pitfall Should Tyre be a subclass of Circle? Could inherit methods for computing radius, centre point,... No! A Tyre is a car part, not a geometric object like Circle Use aggregation instead of inheritance for code reuse : 1 public class Tyre { 2 private Circle boundary; 3... 4 public double radius() { 5 // delegate method calls to aggregated object 6 return this.boundary.radius(); 7 } 8 } SP1 2019-10 15

Inheritance: Another Example Car: Every Car is a Vehicle, every Car has Tyres inherit from Vehicle and aggregate Tyre Tyre Car Vehicle In Java: 1 public class Car extends Vehicle { 2 private Tyre[] tyres; 3... 4 } SP1 2019-10 16

Attributes & Operations in UML Often want more details than just class names in nodes Attributes (= instance variables) and operations (= methods) Employee hourlywage: double void pay(double hoursworked) Person name: String birthday: Date int getage() Use (conceptually) primitive classes as attribute types Do not represent aggregated classes from the diagram as attributes (redundant information) SP1 2019-10 17

Implementing Interfaces Use the stereotype <<interface>> to mark interfaces UML proposes dedicated implements arrow from class to interface: dashed arrow with triangle-shaped tip MyClass... <<interface>> MyInterface... 1 public interface MyInterface {... } 2 public class MyClass implements MyInterface { 3... 4 } NB: in Java, a class can implement any number of interfaces SP1 2019-10 18

Extending Interfaces An interface can extend another interface. In UML Class Diagrams, it is represented with the extends arrow: <<interface>> MySubInterface... <<interface>> MyInterface... 1 public interface MyInterface {... } 2 public interface MySubInterface extends MyInterface { 3... 4 } NB: in Java, a class can (directly) extend only one class SP1 2019-10 19

Example: Modelling Vehicles Every vehicle has an owner. A bicycle is a vehicle where the tyre height in inch is important. A rickshaw is a special bicycle where the driver can transport a passenger for a fare. Here, the max. add. weight in kg matters. A car is a vehicle that has four wheels and that can tell what its power in kw is. A police car is a car that can activate special traffic rights when needed and with a specific number of blue lights. A crew transporter is a vehicle by the Technical Relief Service. Here, the number of benches is important. It can tell what its power in kw is, and it can activate special rights when needed. Vehicles designed to transport passengers can tell how many passengers are currently in the passenger area of the vehicle. Vehicles that transport their passengers only for a fare can tell about the concrete fare for a trip to a specified destination. SP1 2019-10 20

Example: Modelling Vehicles, v1 Some parts of the spec are ambiguous (and others are missing): Don t all vehicles have at least one passenger (the driver)? Even if we don t count the driver, can t all vehicles transport also a passenger, even a bicycle? While we are building the domain model, we may find shortcomings in the results of an earlier activity, the requirements analysis. Similarly, while coding, you may find that some parts of the design don t make sense as such. Revisiting (and fixing) the results of earlier activities is actually quite common in software development processes. Due to the flexibility of software, this is not as costly as in other engineering disciplines (and lets us upgrade the software later with new features). (Lab example: new undo() feature in CashRegister) SP1 2019-10 21

Example: Modelling Vehicles, v2 (1) Every vehicle has an owner. A bicycle is a vehicle where the tyre height in inch is important. A rickshaw is a special bicycle such that the driver can transport a passenger for a fare. Here the maximum additional weight in kg is a relevant property. A car is a vehicle that has four tyres and that can tell what its power in kw is. A police car is a car that can activate special traffic rights when needed and that has a specific number of blue lights. SP1 2019-10 22

Example: Modelling Vehicles, v2 (2) A crew transporter is a vehicle that transports passengers for the Technical Relief Service (no fare is charged). Here the number of benches is important. It can tell what its power in kw is, and it can activate special rights when needed. Vehicles whose primary purpose is to transport passengers in addition to the driver can be queried how many passengers are currently in the passenger area of the vehicle. Vehicles whose primary purpose is to transport passengers in addition to the driver and that moreover transport their passengers only for a fare can be queried about the concrete fare for a trip to a specified destination. Vehicles that can activate special rights provide a corresponding method to toggle whether special rights should be active. SP1 2019-10 23

Example: Modelling Vehicles, v2 Vehicle ownername: String <<interface>> HasPassengers <<interface>> int getpassengercount() HasPower double getkw() <<interface>> HasFarePassengers Bicycle tyreinches: double double computefare(string destination) Car double getkw() CrewTransporter numberofbenches: int double getkw() <<interface>> HasSpecialRights Rickshaw maxkg: int 4 void togglespecialrights() Tyre PoliceCar numberofbluelights: int SP1 2019-10 24

Example: Modelling Vehicles v2, remarks Still further variations possible: aggregate wheels in Vehicle? In the classes here we have (often) omitted concrete methods that correspond to methods from implemented interfaces. We do not mention the getters and setters for attributes in the domain model (they are artefacts of the implementation). SP1 2019-10 25

Example: Modelling Vehicles v2, implementation (1) From class diagram to Java: replace aggregation by instance variable (single object or array of objects), get Java code: 1 public interface HasPassengers { 2 int getpassengercount(); 3 } 1 public interface HasFarePassengers extends HasPassengers { 2 double computefare(string destination); 3 } 1 public class Tyre { 2 } SP1 2019-10 26

Example: Modelling Vehicles v2, implementation (2) 1 public interface HasPower { 2 double getkw(); 3 } 1 public class Vehicle { 2 private String ownername; 3 } 1 public class Car extends Vehicle implements HasPower { 2 private Tyre[] tyres; 3 4 public double getkw() { 5 return 0; // TODO Auto-generated method stub 6 } 7 } SP1 2019-10 27

Example: Modelling Vehicles v2, implementation (3) 1 public interface HasSpecialRights { 2 void togglespecialrights(); 3 } 1 public class PoliceCar extends Car implements HasSpecialRights { 2 private int numberofbluelights; 3 4 public void togglespecialrights() { 5 // TODO Auto-generated method stub 6 } 7 } SP1 2019-10 28

Example: Modelling Vehicles v2, implementation (4) 1 public class CrewTransporter extends Vehicle implements HasPassengers, HasPower, HasSpecialRights { 2 private int numberofbenches; 3 4 public int getpassengercount() { 5 return 0; // TODO Auto-generated method stub 6 } 7 public void togglespecialrights() { 8 // TODO Auto-generated method stub 9 } 10 public double getkw() { 11 return 0; // TODO Auto-generated method stub 12 } 13 } SP1 2019-10 29

Example: Modelling Vehicles v2, implementation (5) 1 public class Bicycle extends Vehicle { 2 private double tyreinches; 3 } 1 public class Rickshaw extends Bicycle implements HasFarePassengers { 2 private int maxkg; 3 4 public int getpassengercount() { 5 return 0; // TODO Auto-generated method stub 6 } 7 public double computefare(string destination) { 8 return 0; // TODO Auto-generated method stub 9 } 10 } SP1 2019-10 30

Architecture (1) So far: focus on the domain model. In larger projects you may also need a dedicated user interface (GUI, web app, command line,... ) and a persistence layer (store data not only in memory, but also on permanent storage, e.g., an SQL database) Those are not represented in the domain model; a separate design model includes such classes SP1 2019-10 31

Architecture (2) Can often use a layered architecture with 3 layers: Layer 1 User interface (JavaFX, web, command line,... ) Layer 2 Business logic (implementation of the domain-specific aspects goes here, e.g., Invoice, Customer,... ) Layer 3 Persistence layer (databases and other technical services, like logging) Lower layers cannot see subsystems on higher layers Flexibility Reusability Today s web app may become tomorrow s mobile app, but the business logic may not have to change SP1 2019-10 32

An Object-Oriented Software Development Process 1. Gather requirements specification (talk to customer, domain experts,... ) 2. Use CRC cards to find classes, responsibilities, collaborators 3. Use UML class diagram to record classes and their relationships in domain model 4. Refine domain model to design model 5. Write classes with corresponding method stubs in Java 6. Use comments to document the desired behaviour 7. Write the implementation in Java 8. Test your implementation SP1 2019-10 33

Take Home Messages Goal: from requirements (in natural language) to Java code discovering classes and methods representing relationships between classes in a UML class diagram translating the UML class diagram to Java code a software development process SP1 2019-10 34