Lesson-06 Designing classes

Slides:



Advertisements
Similar presentations
JQuery MessageBoard. Lets use jQuery and AJAX in combination with a database to update and retrieve information without refreshing the page. Here we will.
Advertisements

1 CSC 221: Computer Programming I Fall 2006 interacting objects modular design: dot races constants, static fields cascading if-else, logical operators.
Comp1004: Building Better Classes II Software Design Partly based on BlueJ Book – Chapter 7.
Copyright by Scott GrissomCh 7 Designing Classes Slide 1 Well Designed Classes (Ch 7) Applications are a collection of interacting classes Our Goal It.
Debugging Introduction to Computing Science and Programming I.
Designing classes How to write classes in a way that they are easily understandable, maintainable and reusable 4.0.
Improving structure with inheritance
Objects First With Java A Practical Introduction Using BlueJ Designing object-oriented programs How to write code in a way that is easily understandable,
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
Module: Definition ● A logical collection of related program entities ● Not necessarily a physical concept, e.g., file, function, class, package ● Often.
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.
CS 106 Introduction to Computer Science I 03 / 30 / 2007 Instructor: Michael Eckmann.
Complexity (Running Time)
Design: Coupling and Cohesion How to write classes in a way that they are easily understandable, maintainable and reusable.
Make Sure You Know All This!. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 2 Objects and Classes.
STREAM STREAM A software process The Mañana Principle The Mañana Principle Don’t try to everything at once! Static Methods Static Methods Stateless Utility.
5.0 Objects First with Java A Practical Introduction using BlueJ David J. Barnes Michael Kölling.
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.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Chapter 9: Coupling & Cohesion Omar Meqdadi SE 273 Lecture 9 Department of Computer Science and Software Engineering University of Wisconsin-Platteville.
OOP (Java) 7. Good Class Design Objectives
Designing classes How to write classes in a way that they are easily understandable, maintainable and reusable 5.0.
สาขาวิชาเทคโนโลยี สารสนเทศ คณะเทคโนโลยีสารสนเทศ และการสื่อสาร.
Chapter 11 Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you.
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.
1 CSC 221: Computer Programming I Spring 2010 interaction & design  modular design: roulette game  constants, static fields  % operator, string equals.
Designing classes How to write classes in a way that they are easily understandable, maintainable and reusable 3.0.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
Lecture 2: Classes and Objects, using Scanner and String.
MIS215 Module 0 - Intro 1 MIS 215 Module 0 Intro to Data Structures.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 5: Software Design & Testing; Revision Session.
Chapter 7 Object-Oriented Design Concepts
Designing Classes 2 How to write classes in a way that they are easily understandable, maintainable and reusable.
Designing classes How to write classes in a way that they are easily understandable, maintainable and reusable 5.0.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Designing Classes. Software changes Software is not like a novel that is written once and then remains unchanged. Software is extended, corrected, maintained,
Designing Classes CS239 – Jan 26, Key points from yesterday’s lab  Enumerated types are abstract data types that define a set of values.  They.
Program Style Chapter 22 IB103 Week 12 (part 2). Modularity: the ability to reuse code Encapsulation: hide data access directly but may use methods (the.
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
M1G Introduction to Programming 2 5. Completing the program.
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.
Comp1004: Inheritance I Super and Sub-classes. Coming up Inheritance and Code Duplication – Super and sub-classes – Inheritance hierarchies Inheritance.
CreatingClasses-SlideShow-part31 Creating Classes part 3 Barb Ericson Georgia Institute of Technology Dec 2009.
M1G Introduction to Programming 2 3. Creating Classes: Room and Item.
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.
PROGRAMMING IN PYTHON LETS LEARN SOME CODE TOGETHER!
Refactoring Agile Development Project. Lecture roadmap Refactoring Some issues to address when coding.
Written by: Dr. JJ Shepherd
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.
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 6.0.
Today Encapsulation. Build a fully encapsulated Halloween class, going from Halloween1 to Halloween6 (eventually!): –The final version will have overloaded.
CS100Lecture 61 Announcements Homework P1 due on Thursday Homework P2 handed out.
Objektorienterad programmering d2, förel. 8
C++ coding standard suggestion… Separate reasoning from action, in every block. Hi, this talk is to suggest a rule (or guideline) to simplify C++ code.
Objects First with Java
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
CMPE212 – Stuff… Exercises 4, 5 and 6 are all fair game now.
Objects First with Java
slides created by Ethan Apter
slides created by Ethan Apter
Objects First with Java A Practical Introduction using BlueJ
Objektorienterad programmering d2, förel. 8
COS 260 DAY 14 Tony Gauvin.
Objects First with Java A Practical Introduction using BlueJ
slides created by Ethan Apter and Marty Stepp
Presentation transcript:

Lesson-06 Designing classes Objects First with Java Lesson-06 Designing classes The art of writing clear code How to write classes in a way that they are easily understandable, maintainable and reusable © David J. Barnes and Michael Kölling

Today’s Plan Talk about how to write clear code (Learn a bunch of buzz-words) It’s possible to write short programs that work without using these techniques but … It’s essential to use these techniques to write bigger systems, or smaller ones that you (and/or others) might want to edit again later

Today: World of Zuul Another antique game (1970’s!) Convince you that good design is important by extending someone else’s (badly written) code zuul-bad and zuul-better projects

Demo: Play Zuul Bad Create a new game object Run play method. .

Play Method (Game Class) public void play() { printWelcome(); boolean finished = false; while (! finished) Command command = parser.getCommand(); finished = processCommand(command); } System.out.println("Thanks for playing. Bye"); .

Game Constructor (Calls createRooms) Room outside, theater, pub, lab, office; // create the rooms outside = new Room("outside the main entrance"); theater = new Room("in a lecture theater"); pub = new Room("in the campus pub"); lab = new Room("in a computing lab"); office = new Room("in the computing admin office"); // initialise room exits outside.setExits(null, theater, lab, pub); theater.setExits(null, null, null, outside); // etc. currentRoom = outside; // start game outside

Room Class public String description; public Room northExit; public Room southExit; public Room eastExit; public Room westExit; public void setExits(Room north, Room east, Room south, Room west) { if(north != null) northExit = north; if(east != null) eastExit = east; // etc.

CommandWords Class // more code here Array of String Objects public class CommandWords { private static final String[] validCommands = "go", "quit", "help" }; // more code here .

Don't stress over code in parser class World of Zuul zuul-bad Don't stress over code in parser class Reads Input Produces command Main setup & play Array of Strings User Command Location in the game

The Zuul Classes Game: The starting point and main control loop. Room: A room in the game. Parser: Reads user input. Command: A user command. CommandWords: Recognized user commands.

Lots of comments But this is zuul-bad!?! So good comments alone doesn’t mean good code!

What makes good code? Two important concepts for quality of code: Loose Coupling High degree of Cohesion Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

Buzz-Word: Coupling How interconnected are different classes? If two classes depend closely on many details of each other, we say they are tightly coupled. We want: Loose coupling Less interconnectedness

Why is Tight Coupling Bad? If you change one class, you may have to change many others Finding all the things you need to change can Be difficult Take lots of time

Why is Loose Coupling Good? Loose coupling lets us: Understand one class without having to look at others; Change one class without affecting others. So loose coupling improves maintainability.

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 logical task, we say it has high cohesion. We aim for high cohesion. ‘Unit’ applies to classes, methods and modules (packages).

Buzz-Word: Cohesion Cohesion refers to the number and diversity of tasks that a single unit is responsible for. How many different “things” a class represents How many different “jobs” a method does

Cohesion If a class represents one thing, we say it has high cohesion. If a method does one task, we say it has high cohesion. High cohesion is good

Why is High Cohesion Good Makes it easier to Understand what a class or method does Fix classes and methods since all the related “stuff” is probably in the same place Use clear descriptive names Reuse code in a different project

Recap: Coupling and Cohesion Classes should just represent one thing A method should be responsible for one and only one well defined task. Methods should just do ONE thing Classes shouldn’t be interdependent

An example to test quality Add two new directions to the 'World of Zuul': “up” “down” What do you need to change to do this? How easy are the changes to apply thoroughly?

Bad code 101 Do these and Obvious tricks – use bad variable names Embarrass yourself in front of colleagues Make your code hard for you to read Make your code really hard for others to read Get a bad grade Obvious tricks – use bad variable names

Bad code 101: The obvious Use lousy variable, method, and class names Use bad indentation Don’t comment your code Declare instance variables for your whole class when you only really need them temporarily in one method

Advanced Bad Coding: Buzz-Phrase: Code Duplication Rewriting the same code in two places Example: zuul-bad Game class: printWelcome method goRoom method Why is this bad?

Code Duplication  Low Cohesion Low Cohesion Means (for a method)???? Tries to do more than one thing printWelcome: Code for welcome message Code for print current location Two things! goRoom: Code to check whether you can go in a particular direction Code to print current location

Why is Code Duplication Bad? printWelcome can’t call goRoom to print the location info, since goRoom does other stuff too goRoom can’t call printWelcome to print the location info, since printWelcome does other stuff too If we want to change the way a location is printed, we’ve got to fix it in TWO places

Key Problems with Code Duplication Makes maintenance harder Can lead to introduction of errors during maintenance.

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.

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 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.

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.

Advanced Bad Coding (cont): Public Instance Variables zuul-bad: Room class has PUBLIC variables southExit, eastExit, etc. Game class USES those variables if(currentRoom.northExit != null) AARRGGHH!!!! Insanely tight coupling We can’t update Room class without changing Game class too

AARRGGHH!!!!! Result: Insanely tight coupling Room class has PUBLIC variables Game class USES those variables Result: Insanely tight coupling We can’t update Room class without changing Game class too What if we wanted to add up & down methods (zuul-3D) AARRGGHH!!!!!

Buzz-Word: Encapsulation Hide implementation details from outsiders Good Encapsulation can: Reduce Coupling Reduce amount of work required to modify an application

Responsibility-driven design The class that USES the data should also be the class that STORES the data Question: Where should we add a new method (which class?) RDD Answer: Wherever that data is stored

Responsibility-driven design The class that USES the data should also be the class that STORES the data zuul-bad example (Game class) System.out.println("You are " + currentRoom.getDescription()); System.out.print("Exits: "); // print north, south, east, west as // appropriate Exits are STORED in the Room class So printing information about exits should happen in the Room class

Buzz-Phrase: Localizing change When a change is needed, as few classes as possible should be affected. We try to reduce coupling and use responsibility- driven design (in part) to localize change.

Localizing change Ideally: only one class needs to be changed when making a modification Realistically: if you need to change more than one class, you’d better try hard to make it as few classes as possible

Buzz Phrase: Explicit Coupling Public variables used outside a class Horrible, but at least when we make a mistake we’ll know pretty quick Our program won’t compiled

(Scarier) Buzz-Phrase: Implicit Coupling One class depends on knowledge about private information in another class

Implicit Coupling Example Look at printHelp in the Game class What assumptions does it make? Only commands are “go”, “quit”, and “help” What happens if we add a new command??? (“fly”) The new command will probably work We may not notice that printHelp no longer works It compiles It appears to run fine (doesn’t crash)

Fixing Our Example Add a “printCommands” method to the CommandWords class (Hey – Responsibility-driven design!)

As you write new classes - think 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. Hey – maybe one day zuul will be a graphical game ...

Buzzword: 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.

Review (Most) 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.

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.

Bonus Topic: Make your own Types: Enumerated Types Use enum instead of class to introduce a type name. Their simplest use is to define a set of significant names. Alternative to static int constants. When the constants’ values would be arbitrary.

A basic enumerated type public enum CommandWord { // A value for each command word, // plus one for unrecognised commands. GO, QUIT, HELP, UNKNOWN; } Each name represents an object of the enum type, e.g., CommandWord.HELP. Enum objects are not created directly. Enum definitions can also have fields, constructors and methods.