SlideShare a Scribd company logo
1 of 27
Download to read offline
Objects First With Java
A Practical Introduction Using BlueJ
Designing classes
How to write classes in a way that
they are easily understandable,
maintainable, and reusable
2.0
Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling;
extensions by HJB&TN for TUM-CSE, winter 2010/2011
2
Main concepts to be covered
• Responsibility-driven design
• Coupling
• Cohesion
• Refactoring
Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling;
extensions by HJB&TN for TUM-CSE, winter 2010/2011
3
Quality of a class
• What are well designed classes, what are
badly designed ones?
• What are the principles we should follow?
• Typically, a poor class design can be done
faster – which often makes it more
attractive from the short term point of view.
• However, in the long term, things look
completely different!
Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling;
extensions by HJB&TN for TUM-CSE, winter 2010/2011
4
Software changes
• Software is not like a novel that is written
once and then remains unchanged.
• Software is extended, corrected,
maintained, ported, adapted, re-
engineered, …
• The work is done by different people over
time (often decades).
• Hence: Functionality is only part of the job
– maintainability counts, too!
Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling;
extensions by HJB&TN for TUM-CSE, winter 2010/2011
5
Change or die
• There are only two options for
software:
– Either it is continuously maintained
– or it dies.
• Software that cannot be maintained
(easily) will be thrown away.
Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling;
extensions by HJB&TN for TUM-CSE, winter 2010/2011
6
Example (BlueJ): World of Zuul
Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling;
extensions by HJB&TN for TUM-CSE, winter 2010/2011
7
World of Zuul
• An early adventure game form the early 1970s –
finding your way through a complex cave system.
• Very basic structure: 5 classes
– CommandWords: all valid commands (array of strings)
– Parser: reads lines of input and interprets them as
commands; creates objects of class Command
– Command: a command entered by the user
– Room: a location (rooms have exits leading to other
rooms)
– Game: main class, starts the games and then enters a
loop to read and execute commands
• Any other ideas for the game design?
• A very nice example for stepwise software design.
Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling;
extensions by HJB&TN for TUM-CSE, winter 2010/2011
8
Code quality
Two important concepts for quality of
code:
• Coupling
• Cohesion
Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling;
extensions by HJB&TN for TUM-CSE, winter 2010/2011
9
Coupling
• Coupling refers to links or relations
between separate units of a program.
– Remember: Applications are designed as sets
of cooperating classes that communicate via
well-defined interfaces.
• If two classes depend closely on many
details of each other, we say they are
tightly coupled.
• We aim for loose coupling.
Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling;
extensions by HJB&TN for TUM-CSE, winter 2010/2011
10
Loose coupling
Loose coupling makes it possible to:
• understand one class without reading
others;
• change one class without affecting (i.e.
having to modify) others – identifying all
possible side effects may be tedious;
• thus: improve maintainability.
Encapsulation is one strategy to keep
coupling loose.
Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling;
extensions by HJB&TN for TUM-CSE, winter 2010/2011
11
Even worse: implicit coupling
Imagine the following scenario:
• There is a printHelp method in Game which,
among other things, prints a fixed text containing
all existing commands.
• Later, you add a new command to your game.
• This is an implicit coupling: the next time a player
needs help, the list won’t be complete any more.
• Remedy: Don’t use a constant text, but let the list
of commands be generated by a method in
CommandWords – this class is responsible of the
commands, anyway.
• This will be called responsibility-driven design
later!
Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling;
extensions by HJB&TN for TUM-CSE, winter 2010/2011
12
Encapsulation
• Hide information.
• Fields or methods that do not have to
be public should be kept private.
Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling;
extensions by HJB&TN for TUM-CSE, winter 2010/2011
13
Cohesion
• Cohesion refers to the number and
diversity of tasks that a single unit is
responsible for.
• If each unit is responsible for one single
task or logical entity, we say it has high
cohesion.
• Cohesion applies to classes and methods.
• We aim for high cohesion – high cohesion
increases the chances of reusability in
different contexts.
Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling;
extensions by HJB&TN for TUM-CSE, winter 2010/2011
14
High cohesion
High cohesion makes it easier to:
• understand what a class or method
does;
• identify all relevant pieces in case of a
change;
• briefly: to read the code;
• use descriptive names;
• reuse classes or methods.
Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling;
extensions by HJB&TN for TUM-CSE, winter 2010/2011
15
Cohesion of methods
• A method should be responsible for
one and only one well-defined task.
• Cohesive frequently also means short.
Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling;
extensions by HJB&TN for TUM-CSE, winter 2010/2011
16
Cohesion of classes
• Classes should represent one single, well-
defined entity.
• What’s bad with non-cohesive classes?
– Extend World of Zuul: Let each room now
contain an item with a description and a weight.
– Realization: additional fields vs. new class
Item.
– What happens if later more than one item can
be in one room??
Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling;
extensions by HJB&TN for TUM-CSE, winter 2010/2011
17
Code duplication
Code duplication
• means to have the same segment of code
more than once in one application;
• is an indicator of bad cohesion and design;
• makes maintenance much harder (change
all occurrences to avoid inconsistencies);
• can lead to the introduction of errors during
maintenance.
Finding code duplicates is one of
challenges of code re-engineering.
Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling;
extensions by HJB&TN for TUM-CSE, winter 2010/2011
18
Code duplication
An example:
• Imagine in class Game two methods
LocateYourself and GotoRoom
• Semantics?
• LocateYourself:
– Some tests, and then print the current room.
• GotoRoom:
– Realize the steps, and then print the current room.
• How should these methods not be implemented?
• Compare good and bad design, and discuss why!
Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling;
extensions by HJB&TN for TUM-CSE, winter 2010/2011
19
Responsibility-driven design
• Question: where should we add a new
method (where = in 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.
• RDD helps to locate functionality later
(“where was this or that defined?”).
Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling;
extensions by HJB&TN for TUM-CSE, winter 2010/2011
20
Localizing change
• One aim of reducing coupling and of
responsibility-driven design is to
localize change.
• When a change is needed, as few
classes as possible should be
affected (side effects).
Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling;
extensions by HJB&TN for TUM-CSE, winter 2010/2011
21
Thinking ahead
• 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.
• Example:
– In our game, so far all output is done via
System.out.println statements.
– What should be changed, if we thought about
placing response in a text field in a window??
Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling;
extensions by HJB&TN for TUM-CSE, winter 2010/2011
22
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.
Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling;
extensions by HJB&TN for TUM-CSE, winter 2010/2011
23
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
(automated tests++!!).
Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling;
extensions by HJB&TN for TUM-CSE, winter 2010/2011
24
Design questions
Common questions:
• How long should a class be?
• How long should a method be?
• Can not be answered in terms of lines
of code.
• Can now be answered in terms of
cohesion and coupling.
Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling;
extensions by HJB&TN for TUM-CSE, winter 2010/2011
25
Design guidelines
• A method is too long if it does more
than 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.
Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling;
extensions by HJB&TN for TUM-CSE, winter 2010/2011
26
Review
• 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.
Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling;
extensions by HJB&TN for TUM-CSE, winter 2010/2011
27
Review
• 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.

More Related Content

What's hot

Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)
Jim Driscoll
 
The View object orientated programming in Lotuscript
The View object orientated programming in LotuscriptThe View object orientated programming in Lotuscript
The View object orientated programming in Lotuscript
Bill Buchan
 

What's hot (20)

Polymorphism 9
Polymorphism 9Polymorphism 9
Polymorphism 9
 
Programming Terminology
Programming TerminologyProgramming Terminology
Programming Terminology
 
java review
java reviewjava review
java review
 
Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)Groovy DSLs (JavaOne Presentation)
Groovy DSLs (JavaOne Presentation)
 
Session 02 - Elements of Java Language
Session 02 - Elements of Java LanguageSession 02 - Elements of Java Language
Session 02 - Elements of Java Language
 
Oop in php lecture 2
Oop in  php lecture 2Oop in  php lecture 2
Oop in php lecture 2
 
Java - OOPS and Java Basics
Java - OOPS and Java BasicsJava - OOPS and Java Basics
Java - OOPS and Java Basics
 
Presentation on java
Presentation  on  javaPresentation  on  java
Presentation on java
 
04 sorting
04 sorting04 sorting
04 sorting
 
Session 01 - Introduction to Java
Session 01 - Introduction to JavaSession 01 - Introduction to Java
Session 01 - Introduction to Java
 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7
 
Java 102 intro to object-oriented programming in java - exercises
Java 102   intro to object-oriented programming in java - exercisesJava 102   intro to object-oriented programming in java - exercises
Java 102 intro to object-oriented programming in java - exercises
 
Projects Valhalla, Loom and GraalVM at JUG Mainz
Projects Valhalla, Loom and GraalVM at JUG MainzProjects Valhalla, Loom and GraalVM at JUG Mainz
Projects Valhalla, Loom and GraalVM at JUG Mainz
 
The View object orientated programming in Lotuscript
The View object orientated programming in LotuscriptThe View object orientated programming in Lotuscript
The View object orientated programming in Lotuscript
 
Java 103
Java 103Java 103
Java 103
 
Function-and-prototype defined classes in JavaScript
Function-and-prototype defined classes in JavaScriptFunction-and-prototype defined classes in JavaScript
Function-and-prototype defined classes in JavaScript
 
hibernate
hibernatehibernate
hibernate
 
Smalltalk on the JVM
Smalltalk on the JVMSmalltalk on the JVM
Smalltalk on the JVM
 
EKON 23 Code_review_checklist
EKON 23 Code_review_checklistEKON 23 Code_review_checklist
EKON 23 Code_review_checklist
 
A Tour Through the Groovy Ecosystem
A Tour Through the Groovy EcosystemA Tour Through the Groovy Ecosystem
A Tour Through the Groovy Ecosystem
 

Similar to Chapter06 designing class

Better Functional Design through TDD
Better Functional Design through TDDBetter Functional Design through TDD
Better Functional Design through TDD
Phil Calçado
 

Similar to Chapter06 designing class (20)

Thomas Wolf "Transfer learning in NLP"
Thomas Wolf "Transfer learning in NLP"Thomas Wolf "Transfer learning in NLP"
Thomas Wolf "Transfer learning in NLP"
 
Dtacs
DtacsDtacs
Dtacs
 
Design poo my_jug_en_ppt
Design poo my_jug_en_pptDesign poo my_jug_en_ppt
Design poo my_jug_en_ppt
 
Metamorphosis from Forms to Java: a technical lead's perspective
Metamorphosis from Forms to Java:  a technical lead's perspectiveMetamorphosis from Forms to Java:  a technical lead's perspective
Metamorphosis from Forms to Java: a technical lead's perspective
 
Is Groovy better for testing than Java?
Is Groovy better for testing than Java?Is Groovy better for testing than Java?
Is Groovy better for testing than Java?
 
Tdd and-design-draft
Tdd and-design-draftTdd and-design-draft
Tdd and-design-draft
 
A Systematic Approach to Generate Diverse Instantiations for Conceptual Schemas
A Systematic Approach to Generate Diverse Instantiations for Conceptual SchemasA Systematic Approach to Generate Diverse Instantiations for Conceptual Schemas
A Systematic Approach to Generate Diverse Instantiations for Conceptual Schemas
 
ODSC East: Effective Transfer Learning for NLP
ODSC East: Effective Transfer Learning for NLPODSC East: Effective Transfer Learning for NLP
ODSC East: Effective Transfer Learning for NLP
 
Code quality
Code quality Code quality
Code quality
 
Introduction to Behavior Driven Development
Introduction to Behavior Driven Development Introduction to Behavior Driven Development
Introduction to Behavior Driven Development
 
Programming in Java: Getting Started
Programming in Java: Getting StartedProgramming in Java: Getting Started
Programming in Java: Getting Started
 
A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)A la découverte des google/test (aka gtest)
A la découverte des google/test (aka gtest)
 
51 ways to reduce your out-of-class marking
51 ways to reduce your out-of-class marking51 ways to reduce your out-of-class marking
51 ways to reduce your out-of-class marking
 
Better Functional Design through TDD
Better Functional Design through TDDBetter Functional Design through TDD
Better Functional Design through TDD
 
iHale Milestone 1 Feedback
iHale Milestone 1 FeedbackiHale Milestone 1 Feedback
iHale Milestone 1 Feedback
 
[부스트캠프 Tech Talk] 안영진_Tackling Complexity with Easy Stuff
[부스트캠프 Tech Talk] 안영진_Tackling Complexity with Easy Stuff[부스트캠프 Tech Talk] 안영진_Tackling Complexity with Easy Stuff
[부스트캠프 Tech Talk] 안영진_Tackling Complexity with Easy Stuff
 
Improving Software Quality Using Object Oriented Design Principles
Improving Software Quality Using Object Oriented Design PrinciplesImproving Software Quality Using Object Oriented Design Principles
Improving Software Quality Using Object Oriented Design Principles
 
Ian Cooper webinar for DDD Iran: Kent beck style tdd seven years after
Ian Cooper webinar for DDD Iran: Kent beck style tdd   seven years afterIan Cooper webinar for DDD Iran: Kent beck style tdd   seven years after
Ian Cooper webinar for DDD Iran: Kent beck style tdd seven years after
 
VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)VT.NET 20160411: An Intro to Test Driven Development (TDD)
VT.NET 20160411: An Intro to Test Driven Development (TDD)
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principles
 

More from Fajar Baskoro

Membangun aplikasi mobile dengan Appsheet
Membangun aplikasi mobile dengan AppsheetMembangun aplikasi mobile dengan Appsheet
Membangun aplikasi mobile dengan Appsheet
Fajar Baskoro
 

More from Fajar Baskoro (20)

Generasi Terampil Digital Skill-2023.pptx
Generasi Terampil Digital Skill-2023.pptxGenerasi Terampil Digital Skill-2023.pptx
Generasi Terampil Digital Skill-2023.pptx
 
Cara Membuat Kursus Online Wordpress-tutorstarter
Cara Membuat Kursus Online Wordpress-tutorstarterCara Membuat Kursus Online Wordpress-tutorstarter
Cara Membuat Kursus Online Wordpress-tutorstarter
 
PPT-Kick Off Double Track 2024 melaksanakan Festival Ramadhan
PPT-Kick Off Double Track 2024 melaksanakan Festival RamadhanPPT-Kick Off Double Track 2024 melaksanakan Festival Ramadhan
PPT-Kick Off Double Track 2024 melaksanakan Festival Ramadhan
 
Buku Inovasi 2023 - 2024 konsep capaian KUS
Buku Inovasi 2023 - 2024 konsep capaian  KUSBuku Inovasi 2023 - 2024 konsep capaian  KUS
Buku Inovasi 2023 - 2024 konsep capaian KUS
 
Pemaparan Sosialisasi Program Dual Track 2024.pptx
Pemaparan Sosialisasi Program Dual Track 2024.pptxPemaparan Sosialisasi Program Dual Track 2024.pptx
Pemaparan Sosialisasi Program Dual Track 2024.pptx
 
Executive Millennial Entrepreneur Award 2023-1a-1.pdf
Executive Millennial Entrepreneur Award  2023-1a-1.pdfExecutive Millennial Entrepreneur Award  2023-1a-1.pdf
Executive Millennial Entrepreneur Award 2023-1a-1.pdf
 
1-Executive Millennial Entrepreneur Award 2023-1-cetak.pptx
1-Executive Millennial Entrepreneur Award  2023-1-cetak.pptx1-Executive Millennial Entrepreneur Award  2023-1-cetak.pptx
1-Executive Millennial Entrepreneur Award 2023-1-cetak.pptx
 
Executive Millennial Entrepreneur Award 2023-1.pptx
Executive Millennial Entrepreneur Award  2023-1.pptxExecutive Millennial Entrepreneur Award  2023-1.pptx
Executive Millennial Entrepreneur Award 2023-1.pptx
 
Pemrograman Mobile - JetPack Compose1.pptx
Pemrograman Mobile - JetPack Compose1.pptxPemrograman Mobile - JetPack Compose1.pptx
Pemrograman Mobile - JetPack Compose1.pptx
 
Evaluasi KPP Program Dual Track Provinsi Kaltim
Evaluasi KPP Program Dual Track Provinsi KaltimEvaluasi KPP Program Dual Track Provinsi Kaltim
Evaluasi KPP Program Dual Track Provinsi Kaltim
 
foto tenda digital skill program dari sekolah
foto tenda digital skill program dari sekolahfoto tenda digital skill program dari sekolah
foto tenda digital skill program dari sekolah
 
Meraih Peluang di Gig Economy yang cocok bagi remaja
Meraih Peluang di Gig Economy yang cocok bagi remajaMeraih Peluang di Gig Economy yang cocok bagi remaja
Meraih Peluang di Gig Economy yang cocok bagi remaja
 
Membangun aplikasi mobile dengan Appsheet
Membangun aplikasi mobile dengan AppsheetMembangun aplikasi mobile dengan Appsheet
Membangun aplikasi mobile dengan Appsheet
 
epl1.pdf
epl1.pdfepl1.pdf
epl1.pdf
 
user.docx
user.docxuser.docx
user.docx
 
Dtmart.pptx
Dtmart.pptxDtmart.pptx
Dtmart.pptx
 
DualTrack-2023.pptx
DualTrack-2023.pptxDualTrack-2023.pptx
DualTrack-2023.pptx
 
BADGE.pptx
BADGE.pptxBADGE.pptx
BADGE.pptx
 
womenatwork.pdf
womenatwork.pdfwomenatwork.pdf
womenatwork.pdf
 
Transition education to employment.pdf
Transition education to employment.pdfTransition education to employment.pdf
Transition education to employment.pdf
 

Recently uploaded

%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 

Recently uploaded (20)

WSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaSWSO2CON 2024 Slides - Open Source to SaaS
WSO2CON 2024 Slides - Open Source to SaaS
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
WSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - KanchanaWSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - Kanchana
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 

Chapter06 designing class

  • 1. Objects First With Java A Practical Introduction Using BlueJ Designing classes How to write classes in a way that they are easily understandable, maintainable, and reusable 2.0
  • 2. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011 2 Main concepts to be covered • Responsibility-driven design • Coupling • Cohesion • Refactoring
  • 3. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011 3 Quality of a class • What are well designed classes, what are badly designed ones? • What are the principles we should follow? • Typically, a poor class design can be done faster – which often makes it more attractive from the short term point of view. • However, in the long term, things look completely different!
  • 4. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011 4 Software changes • Software is not like a novel that is written once and then remains unchanged. • Software is extended, corrected, maintained, ported, adapted, re- engineered, … • The work is done by different people over time (often decades). • Hence: Functionality is only part of the job – maintainability counts, too!
  • 5. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011 5 Change or die • There are only two options for software: – Either it is continuously maintained – or it dies. • Software that cannot be maintained (easily) will be thrown away.
  • 6. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011 6 Example (BlueJ): World of Zuul
  • 7. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011 7 World of Zuul • An early adventure game form the early 1970s – finding your way through a complex cave system. • Very basic structure: 5 classes – CommandWords: all valid commands (array of strings) – Parser: reads lines of input and interprets them as commands; creates objects of class Command – Command: a command entered by the user – Room: a location (rooms have exits leading to other rooms) – Game: main class, starts the games and then enters a loop to read and execute commands • Any other ideas for the game design? • A very nice example for stepwise software design.
  • 8. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011 8 Code quality Two important concepts for quality of code: • Coupling • Cohesion
  • 9. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011 9 Coupling • Coupling refers to links or relations between separate units of a program. – Remember: Applications are designed as sets of cooperating classes that communicate via well-defined interfaces. • If two classes depend closely on many details of each other, we say they are tightly coupled. • We aim for loose coupling.
  • 10. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011 10 Loose coupling Loose coupling makes it possible to: • understand one class without reading others; • change one class without affecting (i.e. having to modify) others – identifying all possible side effects may be tedious; • thus: improve maintainability. Encapsulation is one strategy to keep coupling loose.
  • 11. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011 11 Even worse: implicit coupling Imagine the following scenario: • There is a printHelp method in Game which, among other things, prints a fixed text containing all existing commands. • Later, you add a new command to your game. • This is an implicit coupling: the next time a player needs help, the list won’t be complete any more. • Remedy: Don’t use a constant text, but let the list of commands be generated by a method in CommandWords – this class is responsible of the commands, anyway. • This will be called responsibility-driven design later!
  • 12. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011 12 Encapsulation • Hide information. • Fields or methods that do not have to be public should be kept private.
  • 13. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011 13 Cohesion • Cohesion refers to the number and diversity of tasks that a single unit is responsible for. • If each unit is responsible for one single task or logical entity, we say it has high cohesion. • Cohesion applies to classes and methods. • We aim for high cohesion – high cohesion increases the chances of reusability in different contexts.
  • 14. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011 14 High cohesion High cohesion makes it easier to: • understand what a class or method does; • identify all relevant pieces in case of a change; • briefly: to read the code; • use descriptive names; • reuse classes or methods.
  • 15. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011 15 Cohesion of methods • A method should be responsible for one and only one well-defined task. • Cohesive frequently also means short.
  • 16. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011 16 Cohesion of classes • Classes should represent one single, well- defined entity. • What’s bad with non-cohesive classes? – Extend World of Zuul: Let each room now contain an item with a description and a weight. – Realization: additional fields vs. new class Item. – What happens if later more than one item can be in one room??
  • 17. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011 17 Code duplication Code duplication • means to have the same segment of code more than once in one application; • is an indicator of bad cohesion and design; • makes maintenance much harder (change all occurrences to avoid inconsistencies); • can lead to the introduction of errors during maintenance. Finding code duplicates is one of challenges of code re-engineering.
  • 18. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011 18 Code duplication An example: • Imagine in class Game two methods LocateYourself and GotoRoom • Semantics? • LocateYourself: – Some tests, and then print the current room. • GotoRoom: – Realize the steps, and then print the current room. • How should these methods not be implemented? • Compare good and bad design, and discuss why!
  • 19. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011 19 Responsibility-driven design • Question: where should we add a new method (where = in 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. • RDD helps to locate functionality later (“where was this or that defined?”).
  • 20. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011 20 Localizing change • One aim of reducing coupling and of responsibility-driven design is to localize change. • When a change is needed, as few classes as possible should be affected (side effects).
  • 21. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011 21 Thinking ahead • 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. • Example: – In our game, so far all output is done via System.out.println statements. – What should be changed, if we thought about placing response in a text field in a window??
  • 22. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011 22 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.
  • 23. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011 23 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 (automated tests++!!).
  • 24. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011 24 Design questions Common questions: • How long should a class be? • How long should a method be? • Can not be answered in terms of lines of code. • Can now be answered in terms of cohesion and coupling.
  • 25. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011 25 Design guidelines • A method is too long if it does more than 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.
  • 26. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011 26 Review • 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.
  • 27. Objects First with Java - A Practical Introduction using BlueJ, David J. Barnes, Michael Kölling; extensions by HJB&TN for TUM-CSE, winter 2010/2011 27 Review • 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.