Designing Classes - PowerPoint PPT Presentation

1 / 31
About This Presentation
Title:

Designing Classes

Description:

int ones, fives, tens; //BAD: not local vars. public Money withdraw( int amount ) ... return new Money( tens, fives, ones); //GOOD. Writing Better Code ... – PowerPoint PPT presentation

Number of Views:34
Avg rating:3.0/5.0
Slides: 32
Provided by: Jim478
Category:

less

Transcript and Presenter's Notes

Title: Designing Classes


1
Designing Classes
2
Identifying Classes
  • During design, you need to identify the classes.
    Classes are used to model things
  • Tangible things in the design nouns, such as
  • purse, mailbox, bank account, keypad, email
    message
  • Users
  • Student, Administrator, Bank Manager
  • Agents ("-er" or "-or" words)
  • Scanner, file reader, sentence reader, CSVreader
  • agents perform some operation (sentence reader)
  • Events and Transactions
  • Button click, ATM Withdrawal, Register for Course
  • transactions are uses for interactions between
    classes, usually contain info that doesn't
    "belong" in a thing class

3
Identifying Classes (2)
  • Interfaces and Devices
  • connection to a database -- "a connection"
  • Printer, File, URL
  • Foundation Classes
  • String, List, Queue, Rectangle, Button
  • basic "data types" with well-known properties
    Date, Money

4
Identify Responsibilities
  • Verbs in specification often are responsibilities
  • deposit
  • withdraw
  • confirm

5
Assigning Responsibilities
  • Best Design
  • A class should have only one purpose
  • (but may have several related behaviors)
  • Purse responsible for managing coins in a purse
  • More than one CLOSELY related responsibilities OK
  • Bank purpose is to manage bank accounts and
    assets
  • A class should have well defined responsibilities
  • ATM communicate with the client and execute
    transactions (but not verify them... that's the
    Bank's job)

6
Assigning Responsibilities
  • CRC card approach
  • no more than you can write on a 3x5-inch note
    card
  • Avoid Bloated Classes
  • Put unrelated responsibilities in different
    classes
  • If a class gets too large, look for ways to
    delegate some responsibility to other classes.
  • A class with no responsibility can be eliminated

7
Identifying Behavior
  • What behavior (methods) must a class provide to
    perform its responsibilities?
  • A Purse is responsible for managing coins in a
    purse.
  • Behavior a purse should have
  • insert coins
  • withdraw coins
  • get the balance
  • is it full? purse has a limited capacity

8
Behavior
  • Behavior should be related (coherent)
  • don't put unrelated responsibilities into the
    same class
  • avoid assigning too many behaviors to a class
  • A Purse is not responsible for
  • printing the balance
  • asking the user what he wants
  • computing the price of stuff

9
(No Transcript)
10
Writing Better Code
  • 1. Write code that is easy to read
  • Use comments!
  • Use descriptive variable names
  • Follow a formatting convention

public Money withdraw( int x ) int t
Math.min(x/10,ten) x - t10 int f
Math.min(x/5,five) x - f5 int o
Math.min(o,one) x - o1 if (x0) return new
Money(t,f,o) return null
11
Writing Better Code
  • 2. Localize variables
  • use attributes only for things that are an
    object's state
  • minimize sharing of information between methods

public class Purse private Money money new
Money( ) //BAD int ones, fives, tens //BAD
not local vars public Money withdraw( int amount
) ones ... // how many ones to
withdraw fives ... // how many fives to
withdraw tens ... // how many tens to
withdraw money.setOnes(ones)
money.setFives(fives) money.setTens(tens) re
turn money
12
Writing Better Code
  • 2. Localize variables
  • better use a local Money object for the
    withdraw.
  • also avoids problem of breaking encapsulation of
    attributes

public class Purse //X private Money money
new Money( ) public Money withdraw( int amount
) int ones ... int fives ... int
tens ... //X money.setOnes(ones)
money.setFives(fives) //X money.setTens(tens)
return new Money( tens, fives, ones) //GOOD
13
Writing Better Code
  • 3. Minimizing Coupling between classes
  • Classes are coupled if
  • a class uses attributes or constants from other
    class
  • a class contains objects from other class
  • a class's method has a parameter of type other
    class

Bank
ATM
Manager
ATM Keypad
ATM Display
Database
14
Writing Better Code
  • 4. Use Interfaces to specify required behavior
  • reduces coupling and promotes re-usability

"Program to an interface, not an implementation"
// a course contains a list of students class
Course private List students ... students
new ArrayList( )
List is an interface
ArrayList is a kind of list
15
Writing Better Code
  • 5. Limit the visibility of methods and attributes
  • only required behavior and constants are public
  • attributes are private, with public accessor
    methods
  • only write a mutator ("set") method if it is
    necessary
  • be suspicious of protected attributes, especially
    in the default package

16
Writing Better Code
  • 6. Code re-use
  • know the Java API. Use API methods instead of
    writing them yourself.
  • simple, single-responsibility classes with low
    coupling promote code re-use.
  • Example a "List" class is more reusable than a
    "List of Bank Accounts".

17
Additional Topics for Self-Study
  • Java I/O Hierarchy
  • what I/O classes are there? How are they used?
  • what are the interfaces? what is their behavior?
  • java.io package
  • Java Collections Framework
  • what collection classes are there? (List, Queue,
    Hash, ...)
  • why is it called a "framework"?
  • know the common interfaces Iterator, List,
    Map, Queue, Set, SortedSet
  • Graphics
  • AWT and Swing are frameworks
  • Component, Container, and JComponent form the
    basis

18
Designing a Class's Interface
19
5 Criteria for Good Interface Design
  • Convenience - has methods that make it easy for
    programming to access the desired behavior
  • Clarity - purpose of interface should be clear to
    the programmer.
  • Consistency - method names and signatures are
    consistent with each other, and consistent with
    those of other, similar classes
  • Completeness - class provides methods for all
    required behavior
  • Cohesion - a class's responsibilities (methods)
    are all related to a common concept or purpose

20
What about Coupling?
  • Coupling is important, too.
  • But, coupling is a property of a class's
    implementation, not its interface.

Low Coupling - class doesn't depend to too many
other classes. Exception coupling to stable
classes -- such as the Java foundation classes --
is OK.
21
Interface Design and Class Design
  • These criteria are related to the class's
    interface
  • Convenience
  • Clarity
  • Consistency
  • Completeness
  • Cohesion
  • This concerned with a class's implementation
  • Coupling

22
Convenience and Clarity
  • Here are two ways of doing the same thing
  • if ( collection.isEmpty( ) ) break
  • if ( collection.size() 0 ) break
  • which one makes it easier to understand the
    purpose ?
  • This is an example of clarity and convenience (
    I'm too lazy to type " 0" ).

23
Clarity
  • Get the last element from a list
  • Object e list.get( list.size() - 1 )
  • // or
  • Object e list.getLast( )
  • Get the first element from a list
  • Object f list.get( 0 )
  • // or
  • Object f list.getFirst( )

24
Completeness
  • BinaryTree
  • BinaryTree( )
  • add( E obj ) boolean
  • size( ) int
  • height( ) int
  • isEmpty( ) boolean

Is this good enough for a BinaryTree? What
methods are missing? delete( E obj
)__________ contains( E obj ) boolean ___________
__________ _____________________
Fails to meet the design criterion of
______________
25
Coupling
Account
ActivityHistory

Bank
Customer
Transaction
  • This has high coupling (bad)
  • HARD TO MAINTAIN (MODIFY)
  • HARD TO TEST

26
Cohesion
Good Design
Bad Design
Customer getAccounts()
Account getBalance() getOwner() deposit(
) withdraw() doInteterest()
Customer countAccounts( ) getBalance( k
) deposit( k, amt ) withdraw( k, amt
) doInteterest( k )
handle responsibilities directly related to
customer.
handle responsibilities directly related to bank
accounts.
handle responsibilities directly related to bank
accounts.
27
Consistency
  • Convert String to a Number
  • d Double.parseDouble( string )
  • k Integer.parseInt string )
  • l Long.parseLong ( string )
  • Convert Number to a String
  • s Double.toString( d )
  • s Long.toString( l )
  • s Integer.toString( k )

Consistent Interface
28
Convenience
  • s Long.toString( n )
  • is the same as
  • s ( new Long( n ) ).toString()
  • which one is more convenient?

29
Modeling
30
3 Levels of Modeling
  • Domain Model - model of the problem in
    terminology of the domain of application. Uses
    stakeholders' terms.
  • Design Model - software design.
  • Implementation Model - package, class, and
    behavior model for how the software will be
    implemented.

31
4 Parts of a Model
  • Different views to help understand the problem
  • Class Model - model of structure
  • State Model - the states of components and how
    they transition to other states
  • Behavioral Model - how objects react to different
    external triggers
  • Collaboration Model - how objects interact
  • Which UML diagram(s) are useful for these views?
  • Class diagram
  • State (Machine) diagram
  • Sequence and Activity diagrams
  • Communications Diagram
Write a Comment
User Comments (0)
About PowerShow.com