Upload
others
View
3
Download
0
Embed Size (px)
Citation preview
Made with OpenOffice.org1
Comp 152
Designing Classes
Made with OpenOffice.org2
Admin
Hows the lab coming?Hows the lab coming?
class design
● its easy to “design” a bad class● by coding what comes first to your head and then
incrementally making changes● change here and there to tweak and make work by
trial and error– guaranteed code hard to update
● avoid this problem by thinking about classes and how they work together in the first place
Made with OpenOffice.org4
Programming as modeling
When we programWhen we program● are modeling real world “things” in program
– objects– concepts– theories
● model requires abstraction– abstract away unimportant details
● depends on what modeler thought was important
● model is only as good as theory behind it.
● modeling in code: rule of thumb– objects are nouns– methods are verbs
Made with OpenOffice.org5
A class represents a single concept from the A class represents a single concept from the problem domainproblem domain
Name for a class should be a noun that describes Name for a class should be a noun that describes conceptconcept
● Concepts from mathematics: – Point– Rectangle– Ellipse
● Concepts from real life – BankAccount– CashRegister
Made with OpenOffice.org6
Questions for you
What is the rule of thumb for finding classes?What is the rule of thumb for finding classes?
Your job is to write a program that plays chess. Your job is to write a program that plays chess. Might ChessBoard be an appropriate class? How Might ChessBoard be an appropriate class? How about NextMove?about NextMove?
Use UML
● We'll use UML to model how classes work together● and classes themselves
● Use UML design tool to setup UML diagram
Single class UML
● On board single class diagram● three sections● syntax.
Modeling relationships between objects
● Several well known common relationships between objects of different classes.● have well defined implementations ● stereotypical interactions help produce
understandable programs
Composition and Aggregation.
● Relationship where one object is made up of another object● A not complete without B● Elephant is composed of a trunk
● Composition stronger than Aggregation● Aggregation
– Part can survive the whole● Robot has-a sensor
● Composition– If the whole is destroyed so are the parts
● Building has-a room.
Implementation: Composition
● AKA Has-a● Customer has-a Account
– Customer class includes an instance variable of type Account
– Customer Initializes that instance variable in its constructor with a brand new object.
● Account constructor called.
Implementation: Aggregation
● AKA Has-a (slightly weaker version)● Customer has-a Account
– Customer class includes an instance variable of type Account
– Customer Initializes that instance variable in its constructor with an account object passed in as a parameter to the constructor.
● No Account constructor called.
Association
● Relationship where neither is part of the other, but one object is associated with another object of a particular type throughout the object's lifetime● lecture is associated with an instructor.
Association
● Relationship where neither is part of the other, but one object is associated with another object of a particular type throughout the object's lifetime● lecture is associated with an instructor.
Implementation: Association
● AKA Knows-a● Customer Knows-a BankBranch
– Customer Class has an instance variable of type BankBranch
– Customer initializes that instance variable in the constructor with a value passed in as a parameter to the constructor.
Dependency
● One object requires some functionality from another object of another class● but not a lasting relationship
Implementation: Dependency
● AKA uses-a● Customer uses-a ATM● add an ATM local variable in one of Customer's
methods.
Made with OpenOffice.org18
Cohesion
CohesionCohesion● A class should represent a single concept● public interface of class is cohesive
– if all of its features are related to the concept that the class represents
● This class lacks cohesion:– public class CashRegister{
– public void enterPayment(int dollars, int quarters, int dimes,
– int nickels, int pennies)
– . . .
– public static final double NICKEL_VALUE = 0.05;
– public static final double DIME_VALUE = 0.1;
– public static final double QUARTER_VALUE = 0.25;
– . . .}
Made with OpenOffice.org19
Cohesion
How would we change the cash register class How would we change the cash register class from last slide to maintain good cohesion?from last slide to maintain good cohesion?
Made with OpenOffice.org20
Coupling
avoid couplingavoid coupling● A class depends on another if it uses objects
of that class● CashRegister depends on Coin to determine
the value of the payment● Coin does not depend on CashRegister● High Coupling = many class dependencies
– Minimize coupling to minimize the impact of interface changes
● To visualize relationships draw class diagrams ● use UML:
– lots of spaghetti relationships means bad code.
Made with OpenOffice.org21
coupling visually
Made with OpenOffice.org22
Accessors, Mutators
recallrecall● Accessor:
– retrieves value of instance variable – does not change the state of the implicit
parameter – double balance = account.getBalance();
● Mutator: – modifies the object on which it is invoked– changes private instance variable – account.deposit(1000);
● I
Made with OpenOffice.org23
Immutable Classes
nownow● immutable class: has no mutator methods ● (e.g., String class) ● String name = "John Q. Public";● String uppercased =
name.toUpperCase(); // name is not changed
● It is safe to give out references to objects of immutable classes; no code can modify the object at an unexpected time
Made with OpenOffice.org24
Wake up sleepyheads
Why should coupling be minimized between Why should coupling be minimized between classes?classes?
Is the substring method of the String class an Is the substring method of the String class an accessor or a mutator?accessor or a mutator?
Is the Rectangle class immutable?Is the Rectangle class immutable?
Made with OpenOffice.org25
Side Effects
Side effect of a method: Side effect of a method: ● any externally observable data modification● other defs used, see next
public void transfer(double amount, BankAccount other)public void transfer(double amount, BankAccount other)
{{
balance = balance - amount;balance = balance - amount;
other.balance = other.balance + amount; // Modifies explicit parameterother.balance = other.balance + amount; // Modifies explicit parameter
}}
Updating explicit parameter can be surprising to Updating explicit parameter can be surprising to programmers; it is best to avoid it if possibleprogrammers; it is best to avoid it if possible
Made with OpenOffice.org26
Side Effects II
Any change to the system (not data) is also a side Any change to the system (not data) is also a side effecteffect
● printing● popping up a window● etc● decouple side effects from data storing
classes when possible.
Made with OpenOffice.org27
One more set of Questions
QuestionsQuestions● If a refers to a bank account, then the call
a.deposit(100) modifies the bank account object. Is that a side effect?
●
Made with OpenOffice.org28
Call by Value and Call by Reference
Call by value: Call by value: ● Method parameters are copied into the
parameter variables when a method starts
Call by reference: Call by reference: ● Methods can modify parameters
Java has call by valueJava has call by value● A method can change state of object
reference parameters, but cannot replace an object reference with another
Made with OpenOffice.org29
implication: parameter modification
bad codebad code● compiles but doesn't do much
– void transfer(double amount, double otherBalance)
– {– balance = balance - amount;– otherBalance = otherBalance + amount;– }
● imagine calling it thusly:– double savingsBalance = 1000;– harrysChecking.transfer(500,
savingsBalance);– System.out.println(savingsBalance);
Made with OpenOffice.org30
but with object references
code that will workcode that will work● public class BankAccount
● {
● public void transfer(double amount, BankAccount otherAccount)
● {
● balance = balance - amount;
● double newBalance = otherAccount.balance + amount;
● otherAccount = new BankAccount(newBalance); // Won't work
● }
● }
draw picture on the boarddraw picture on the board
Made with OpenOffice.org31
Preconditions
preconditionspreconditions● Requirement that the caller of a method must
meet● Publish preconditions so the caller won't call
methods with bad parameters– javadoc comments
● Typical use: – To restrict the parameters of a method– To require that a method is only called when the
object is in an appropriate state● If precondition is violated, method is not
responsible for computing the correct result. It is free to do anything.
Made with OpenOffice.org32
Preconditions II
Method can do an assertion check Method can do an assertion check ● assert amount >= 0;● balance = balance + amount;
To enable assertion checking: To enable assertion checking: ● java -enableassertions MyProg ● You can turn assertions off after you have tested
your program, so that it runs at maximum speed
Many beginning programmers silently return to the caller Many beginning programmers silently return to the caller ● if (amount < 0) return; // Not recommended; hard to
debug● balance = balance + amount;
Made with OpenOffice.org33
Assertion Syntax
Syntax:Syntax:● assert condition;
Example:Example:● assert amount >= 0;
Purpose:Purpose:● To assert that a condition is fulfilled. If
assertion checking is enabled and the condition is false, an assertion error is thrown.
Use only in debugging, not in production code.Use only in debugging, not in production code.
Made with OpenOffice.org34
Static Methods
Every method must be in a classEvery method must be in a class● A static method is not invoked on an object
Why write a method that does not operate on an Why write a method that does not operate on an object?object?
Common reason: Common reason: ● encapsulate some computation that
involves only numbers. Numbers aren't objects, you can't invoke methods on them. E.g., x.sqrt() can never be legal in Java
● Math Class full of static methods.
Made with OpenOffice.org35
Static Methods II
ExampleExample● public class Financial{● public static double percentOf(double p, double
a) {● return (p / 100) * a;● }● // More financial methods can be added here.● }
Call with class name instead of object:Call with class name instead of object:● double tax = Financial.percentOf(taxRate,
total);● main is static–there aren't any objects yet
Made with OpenOffice.org36
Static Methods II
ExampleExample● public class Financial{● public static double percentOf(double p, double
a) {● return (p / 100) * a;● }● // More financial methods can be added here.● }
Call with class name instead of object:Call with class name instead of object:● double tax = Financial.percentOf(taxRate,
total);● main is static–there aren't any objects yet
Made with OpenOffice.org37
A question here a question there
Suppose Java had no static methods. Then all Suppose Java had no static methods. Then all methods of the Math class would be instance methods of the Math class would be instance methods. How would you compute the square methods. How would you compute the square root of x?root of x?
Harry turns in his homework assignment, a Harry turns in his homework assignment, a program that plays tic-tac-toe. His solution program that plays tic-tac-toe. His solution consists of a single class with many static consists of a single class with many static methods. Why is this not an object-oriented methods. Why is this not an object-oriented solution?solution?
Made with OpenOffice.org38
Static Fields/Variables.
A static field/variableA static field/variable● belongs to the class, not to any object of
the class. Also called class field/variable.
public class BankAccountpublic class BankAccount
{ . . .{ . . .
private double balance;private double balance;
private int accountNumber;private int accountNumber;
private static int lastAssignedNumber = 1000;}private static int lastAssignedNumber = 1000;}
If lastAssignedNumber was not static, each If lastAssignedNumber was not static, each instance of BankAccount would have its own instance of BankAccount would have its own value of lastAssignedNumbervalue of lastAssignedNumber
Made with OpenOffice.org39
Static class variables II
what does that buy us?what does that buy us?● public BankAccount()● {● // Generates next account number to be
assigned● lastAssignedNumber++; // Updates the static
field● // Assigns field to account number of this bank
account● accountNumber = lastAssignedNumber; // Sets
the instance field● }
Minimize the use of static fields. Minimize the use of static fields.
Static final fields (constants) are ok.Static final fields (constants) are ok.
Made with OpenOffice.org40
Static fields III
Three ways to initialize: Three ways to initialize: ● Do nothing. Field is with 0 (for numbers), false (for
boolean values), or null (for objects)● Use an explicit initializer, such as
– public class BankAccount– {– . . .– private static int lastAssignedNumber = 1000; //
Executed once,– // when class is loaded– }
Use a static initialization blockUse a static initialization block● this is rare - I don't recommend
Made with OpenOffice.org41
An “opportunity to excel”
Name two static fields of the System class.Name two static fields of the System class.
Harry tells you that he has found a great way to Harry tells you that he has found a great way to avoid those pesky objects: Put all code into a avoid those pesky objects: Put all code into a single class and declare all methods and fields single class and declare all methods and fields static. Then main can call the other static static. Then main can call the other static methods, and all of them can access the static methods, and all of them can access the static fields. Will Harry's plan work? Is it a good idea?fields. Will Harry's plan work? Is it a good idea?
Made with OpenOffice.org42
Assignment
Now UmbrelloNow Umbrello
Made with OpenOffice.org43
Scope Review
Scope of variable: Scope of variable: ● Region of program in which the variable
can be accessed
Local VariableLocal Variable● Scope of a local variable extends from its
declaration to end of the block that encloses it
Sometimes the same variable name is used in two Sometimes the same variable name is used in two methods: methods:
● next slide for example
Made with OpenOffice.org44
Local Scope Example
eg:eg:● public class RectangleTester{● public static double area(Rectangle rect){● double r = rect.getWidth() * rect.getHeight();● return r;● }● public static void main(String[] args){● Rectangle r = new Rectangle(5, 10, 20, 30);● double a = area(r);● System.out.println(r);● }● }● These variables completely independent from
each other; scopes are disjoint (in math-speak)
Made with OpenOffice.org45
Scope: Local vars II
as you all knowas you all know● Scope of a local variable cannot contain the
definition of another variable with the same name ● Rectangle r = new Rectangle(5, 10, 20, 30);
● if (x >= 0){
● double r = Math.sqrt(x);
● // Error–can't declare another variable called r here
● . . .
● }
compiler will smack your hand with a ruler for thiscompiler will smack your hand with a ruler for this
Made with OpenOffice.org46
Scope: Local vars II
but this is fine, scopes disjointbut this is fine, scopes disjoint● if (x >= 0)● {● double r = Math.sqrt(x);● . . .● } // Scope of r ends here● else● {● Rectangle r = new Rectangle(5, 10, 20, 30);● // OK–it is legal to declare another r here● . . .● }
Made with OpenOffice.org47
Class member scopeScope of class membersScope of class members
● instance variables– available to all non-static methods in class– public: available to anyone who has an object of the
class.– outside of class
● Must qualify public members outside scope ● Math.sqrt()● harrysChecking.getBalance()
– Inside a method, no need to qualify fields or methods that belong to the same class
● java assumes refers to the this parameter ● public class BankAccount{● public void transfer(double amount, BankAccount other){● withdraw(amount); // i.e., this.withdraw(amount);● other.deposit(amount);● } . . .}
Made with OpenOffice.org48
Overlapping Scopeshadowshadow
● jargon term in variable scope● A local variable (or parameter) can shadow a field
with the same name● Local/parameter scope wins over class scope● example:
– public class Coin{
– . . .
– public double getExchangeValue(double exchangeRate){
– double value; // Local variable
– . . .
– return value;
– }
– private String name;
– private double value; // Field with the same name
– }
Made with OpenOffice.org49
Packages
What are packages used for in java?What are packages used for in java?
Made with OpenOffice.org50
Packages
What are packages used for in java?What are packages used for in java?● organizing groups of related classes● to make a package
– create folder for package– at top of each java file in folder– package foldername– can h ave multiple packages embedded in each
other● separate with .● folder/package cs2● inside package project2● make file part of this package with
– package cs2.project2● all comfortable with importing packages?● import classes vs import whole package?
Made with OpenOffice.org51
Reading Assignment
– hopefully we will get back some of these.