Comp1004: Building Better Classes II Software Design Partly based on BlueJ Book – Chapter 7.

Slides:



Advertisements
Similar presentations
Revealing the Secrets of Self-Documenting Code Svetlin Nakov Telerik Corporation For C# Developers.
Advertisements

Lilian Blot Announcements Teaching Evaluation Form week 9 practical session Formative Assessment week 10 during usual practical sessions group 1 Friday.
1 CSC 221: Computer Programming I Fall 2006 interacting objects modular design: dot races constants, static fields cascading if-else, logical operators.
Unit 6 Assignment 2 Chris Boardley.
Internal Documentation Conventions. Kinds of comments javadoc (“doc”) comments describe the user interface: –What the classes, interfaces, fields and.
Lesson-06 Designing classes
OOAD Using the UML - Use-Case Analysis, v 4.2 Copyright  Rational Software, all rights reserved 1/18 Use Case Analysis – continued Control Classes.
Software Engineering and Design Principles Chapter 1.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Immutable Objects and Classes.
Designing classes How to write classes in a way that they are easily understandable, maintainable and reusable 4.0.
Objects First With Java A Practical Introduction Using BlueJ Designing object-oriented programs How to write code in a way that is easily understandable,
Module: Definition ● A logical collection of related program entities ● Not necessarily a physical concept, e.g., file, function, class, package ● Often.
Design The goal is to design a modular solution, using the techniques of: Decomposition Abstraction Encapsulation In Object Oriented Programming this is.
Designing Classes How to write classes in a way that they are easily understandable, maintainable and reusable.
Well-behaved objects Improving your coding skills 1.0.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Design: Coupling and Cohesion How to write classes in a way that they are easily understandable, maintainable and reusable.
Object-Orientated Design Unit 3: Objects and Classes Jin Sa.
About the Presentations The presentations cover the objectives found in the opening of each chapter. All chapter objectives are listed in the beginning.
Computer Science 240 Principles of Software Design.
Test-Driven Development “Test first, develop later!” –OCUnit.
Lilian Blot Announcements The TPOP problem class this afternoon:  group 1 should come at 3.30pm and group 2 at 4pm. Teaching Evaluation Form  week 9.
Chapter 7 Designing Classes. Class Design When we are developing a piece of software, we want to design the software We don’t want to just sit down and.
1 Web Based Programming Section 6 James King 12 August 2003.
Chapter 9: Coupling & Cohesion Omar Meqdadi SE 273 Lecture 9 Department of Computer Science and Software Engineering University of Wisconsin-Platteville.
Designing classes How to write classes in a way that they are easily understandable, maintainable and reusable 5.0.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
CS 350 – Software Design The Object Paradigm – Chapter 1 If you were tasked to write code to access a description of shapes that were stored in a database.
University of Toronto Department of Computer Science CSC444 Lec05- 1 Lecture 5: Decomposition and Abstraction Decomposition When to decompose Identifying.
Designing classes How to write classes in a way that they are easily understandable, maintainable and reusable 3.0.
Computer Science 240 © Ken Rodham 2006 Principles of Software Design.
Chapter 7: High Quality Routines By Raj Ramsaroop.
SE: CHAPTER 7 Writing The Program
Improving the Quality of Existing Code Svetlin Nakov Telerik Corporation
Cohesion and Coupling CS 4311
Designing Classes 2 How to write classes in a way that they are easily understandable, maintainable and reusable.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
Programming Logic and Design Using Methods. 2 Objectives Review how to use a simple method with local variables and constants Create a method that requires.
Designing classes How to write classes in a way that they are easily understandable, maintainable and reusable 5.0.
Software Engineering Principles. SE Principles Principles are statements describing desirable properties of the product and process.
Chapter 12 Object Oriented Design.  Complements top-down design  Data-centered view of design  Reliable  Cost-effective.
B065: PROGRAMMING Sub Procedures I. Starter  Identify the separate tasks to be performed in the programming task below (break it down into numbered sections).
I Power Higher Computing Software Development High Level Language Constructs.
Designing Classes. Software changes Software is not like a novel that is written once and then remains unchanged. Software is extended, corrected, maintained,
Ordered Linked Lists using Abstract Data Types (ADT) in Java Presented by: Andrew Aken.
Final Review. From ArrayLists to Arrays The ArrayList : used to organize a list of objects –It is a class in the Java API –the ArrayList class uses an.
1 COS 260 DAY 14 Tony Gauvin. 2 Agenda Questions? 6 th Mini quiz graded  Oct 29 –Chapter 6 Assignment 4 will be posted later Today –First two problems.
Or how to work smarter when building solutions.  2:30 – 3:30 Mondays – focus on problem solving (with some terminology thrown in upon occasion)  All.
SEG 4110 – Advanced Software Design and Reengineering Topic T Introduction to Refactoring.
Refactoring1 Improving the structure of existing code.
Objects First With Java A Practical Introduction Using BlueJ Designing classes How to write classes in a way that they are easily understandable, maintainable.
1 COS 260 DAY 12 Tony Gauvin. 2 Agenda Questions? 5 th Mini quiz –Chapter 5 40 min Assignment 3 Due Assignment 4 will be posted later (next week) –If.
Refactoring. DCS – SWC 2 Refactoring ”A change made to the internal structure of software to make it easier to understand and cheaper to modify without.
Chapter 9: Coupling & Cohesion Omar Meqdadi SE 273 Lecture 9 Department of Computer Science and Software Engineering University of Wisconsin-Platteville.
Programming Logic and Design Fifth Edition, Comprehensive Chapter 7 Using Methods.
Designing classes How to write classes in a way that they are easily understandable, maintainable and reusable 6.0.
Objektorienterad programmering d2, förel. 8
DESIGNING CLASSES THE GAME OF LIFE
Data Abstraction: The Walls
CS240: Advanced Programming Concepts
Objects First with Java
Stack ADT & Modularity 2 implementations of the Stack abstract data type: Array Linked List Program design: modularity, abstraction and information hiding.
Objects First with Java
PROGRAMMING Sub Procedures I.
Unit 6 Assignment 2 Chris Boardley.
Programming Logic and Design Fourth Edition, Comprehensive
Objektorienterad programmering d2, förel. 8
COS 260 DAY 14 Tony Gauvin.
Software Design Principles
Chapter 9: Implementation
Presentation transcript:

Comp1004: Building Better Classes II Software Design Partly based on BlueJ Book – Chapter 7

Coming Up Duplication Coupling Cohesion Responsibility-driven design Refactoring

Software changes Software is not like a novel that is written once and then remains unchanged. Software is extended, corrected, maintained, ported, adapted… The work is done by different people over time (often decades).

Change or die There are only two options for software: – Either it is continuously maintained – or it dies. Software that cannot be maintained will be thrown away. Three important concepts for quality of code: – Duplication – Coupling – Cohesion

Duplication public void getTotal(int[] array) { int totalcost = 0; for(int n : array){ totalcost += n; } return totalcost; } public void getTotalIncVAT(int[] array) { int totalcost = 0; for(int n : array){ totalcost += n; } totalcost = totalcost * 1.2; return totalcost; }

Duplication public void getTotal(int[] array) { int totalcost = 0; for(int n : array){ totalcost += n; } return totalcost; } public void getTotalIncVAT(int[] array) { int totalcost = 0; for(int n : array){ totalcost += n; } totalcost = totalcost * 1.2; return totalcost; } Code Duplication is an indicator of bad design Makes maintenance harder and can lead to the introduction of errors What is a better solution?

Duplication public void getTotal(int[] array) { int totalcost = 0; for(int n : array){ totalcost += n; } return totalcost; } public void getTotalIncVAT(int[] array) { int totalcost = getTotal(array); totalcost = totalcost * 1.2; return totalcost; } Code Duplication is an indicator of bad design Makes maintenance harder and can lead to the introduction of errors What is a better solution? Use methods to write code once and call many times

Coupling Coupling refers to links between separate units of a program. If two classes depend closely on many details of each other, we say they are tightly coupled. We aim for loose coupling.

Loose coupling Loose coupling makes it possible to: – understand one class without reading others; – change one class without affecting others. – Thus: improves maintainability.

Real World Examples Are these tightly or loosely coupled systems? The Human BodyHousehold Plumbing

Real World Examples Are these tightly or loosely coupled systems? The Human BodyHousehold Plumbing Loosely Coupled Modular, each section is independent and linked to the whole through a simple interface. So it is easy to change one bit without breaking the rest (within reason). Tightly Coupled Each part is linked in thousands of ways to the whole. This creates excellent performance and is very efficient, but makes it difficult to maintain

Cohesion Cohesion refers to the the number and diversity of tasks that a single unit is responsible for. If each unit is responsible for one single logical task, we say it has high cohesion. Cohesion applies to classes and methods. We aim for high cohesion.

High cohesion High cohesion makes it easier to: – understand what a class or method does; – use descriptive names; – reuse classes or methods. Cohesion of Methods A method should be responsible for one and only one well defined task. Cohesion of Methods A method should be responsible for one and only one well defined task. Cohesion of Classes Classes should represent one single, well defined entity. Cohesion of Classes Classes should represent one single, well defined entity.

Responsibility-driven design Question: where should we add a new method (which class)? Each class should be responsible for manipulating its own data. The class that owns the data should be responsible for processing it. RDD leads to low coupling and high cohesion

Responsibility-driven design Question: where should we add a new method (which class)? Each class should be responsible for manipulating its own data. The class that owns the data should be responsible for processing it. RDD leads to low coupling. Encapsulation

public class DogBooking { protected String name; protected String breed; protected String ownersname; protected Calendar startDate; protected Calendar endDate; //some code omitted public void printInvoice() { System.out.println(name + “, ” + breed); int numDaysInMilliseconds = startDate.compareTo(endDate); int numDays = numDaysInMilliseconds / (1000 * 60 * 60 * 24); System.out.println(“Nights in total: ” + numDays); System.out.println(“Total cost: ” + getCost(numDays)); }

public class DogBooking { protected String name; protected String breed; protected String ownersname; protected Calendar startDate; protected Calendar endDate; //some code omitted public void printInvoice() { System.out.println(name + “, ” + breed); int numDaysInMilliseconds = startDate.compareTo(endDate); int numDays = numDaysInMilliseconds / (1000 * 60 * 60 * 24); System.out.println(“Nights in total: ” + numDays); System.out.println(“Total cost: ” + getCost(numDays)); } Cohesion of Methods A method should be responsible for one and only one well defined task. Cohesion of Methods A method should be responsible for one and only one well defined task. Is this method cohesive?

public class DogBooking { protected String name; protected String breed; protected String ownersname; protected Calendar startDate; protected Calendar endDate; //some code omitted public void printInvoice() { printDetails(); int numDays = getNumberOfDays(); System.out.println(“Nights in total: ” + numDays); System.out.println(“Total cost: ” + getCost(numDays)); } public void printDetails() { System.out.println(name + “, ” + breed); } public int getNumberOfDays() { int numDaysInMilliseconds = startDate.compareTo(endDate); return numDaysInMilliseconds / (1000 * 60 * 60 * 24); } Cohesion of Methods A method should be responsible for one and only one well defined task. Cohesion of Methods A method should be responsible for one and only one well defined task. Is this method cohesive? Arguably it does three things – so it would be better to pull the other two out into separate methods

public class DogBooking { protected String name; protected String breed; protected String ownersname; protected Calendar startDate; protected Calendar endDate; //some code omitted public void printInvoice() { printDetails(); int numDays = getNumberOfDays(); System.out.println(“Nights in total: ” + numDays); System.out.println(“Total cost: ” + getCost(numDays)); } public void printDetails() { System.out.println(name + “, ” + breed); } public int getNumberOfDays() { int numDaysInMilliseconds = startDate.compareTo(endDate); return numDaysInMilliseconds / (1000 * 60 * 60 * 24); } Cohesion of Classes Classes should represent one single, well defined entity. Cohesion of Classes Classes should represent one single, well defined entity. Is this class cohesive?

public class Dog { protected String name; protected String breed; protected String ownersname; //some code omitted public void printDetails() { System.out.println(name + “, ” + breed); } public class Booking { protected Dog dog; protected Calendar startDate; protected Calendar endDate; //some code omitted public void printInvoice() { dog.printDetails(); int numDays = getNumberOfDays(); System.out.println(“Nights in total: ” + numDays); System.out.println(“Total cost: ” + getCost(numDays)); } public int getNumberOfDays() { int numDaysInMilliseconds = startDate.compareTo(endDate); return numDaysInMilliseconds / (1000 * 60 * 60 * 24); } Cohesion of Classes Classes should represent one single, well defined entity. Cohesion of Classes Classes should represent one single, well defined entity. Is this class cohesive? Arguably it is better represented by two classes – one to hold the details of the dog, the other the details of the booking

Localizing change One aim of reducing coupling and responsibility-driven design is to localize change. When a change is needed, as few classes as possible should be affected.

Thinking ahead public void switchOffElectrics() { //switch off all four lights Lights[] lights = getLights(); lights[0].switchOff(); lights[1].switchOff(); lights[2].switchOff(); lights[3].switchOff(); //setHeatingtoMinimum HeatingControl hc = getHeatingControl(); hc.setThermoStat(18); } When designing a class, we try to think what changes are likely to be made in the future. We aim to make those changes easy What might we change here?

Thinking ahead public void switchOffElectrics() { //switch off all lights Lights[] lights = getLights(); for(Light light : lights) { light.switchOff(); } //setHeatingtoMinimum HeatingControl hc = getHeatingControl(); hc.setThermoStat(18); } When designing a class, we try to think what changes are likely to be made in the future. We aim to make those changes easy What might we change here? Use a loop to switch off the lights – now it doesn’t matter how many we have

Thinking ahead public void switchOffElectrics() { //switch off all lights Lights[] lights = getLights(); for(Light light : lights) { light.switchOff(); } //setHeatingtoMinimum HeatingControl hc = getHeatingControl(); hc.setThermoStat(getLowTemperature()); } protected int getLowTemperature() { //low is currently defined as 18 return 18; } When designing a class, we try to think what changes are likely to be made in the future. We aim to make those changes easy What might we change here? Use a loop to switch off the lights – now it doesn’t matter how many we have Hide the low temperature behind another method – in case it changes in the future

Refactoring When classes are maintained, often code is added. Classes and methods tend to become longer. Every now and then, classes and methods should be refactored to maintain cohesion and low coupling.

Refactoring and testing When refactoring code, separate the refactoring from making other changes. First do the refactoring only, without changing the functionality. Test before and after refactoring to ensure that nothing was broken.

Design questions Common questions: – How long should a class be? – How long should a method be? Can now be answered in terms of cohesion and coupling.

Design guidelines A method is too long if it does more then one logical task. A class is too complex if it represents more than one logical entity. Note: these are guidelines - they still leave much open to the designer.

Summary Programs are continuously changed. It is important to make this change possible. Quality of code requires much more than just performing correct at one time. Code must be understandable and maintainable.

Summary Good quality code – avoids duplication – displays high cohesion, low coupling. Coding style (commenting, naming, layout, etc.) is also important. There is a big difference in the amount of work required to change poorly structured and well structured code.