Principles of Programming CM10227 Lecture D.11: Java: Error - - PowerPoint PPT Presentation

principles of programming cm10227
SMART_READER_LITE
LIVE PREVIEW

Principles of Programming CM10227 Lecture D.11: Java: Error - - PowerPoint PPT Presentation

Error Handling Input-Output Writing Better Code Principles of Programming CM10227 Lecture D.11: Java: Error Handling & Writing Better Code Dr. Marina De Vos University of Bath Ext: 5053 Academic Year 2012-2013 Lecture D.10. (MDV)


slide-1
SLIDE 1

Error Handling Input-Output Writing Better Code

Principles of Programming CM10227

Lecture D.11: Java: Error Handling & Writing Better Code

  • Dr. Marina De Vos

University of Bath Ext: 5053

Academic Year 2012-2013

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 1 / 77

slide-2
SLIDE 2

Error Handling Input-Output Writing Better Code

Resources

Objects First with Java. David J. Barnes and Michael K¨

  • lling. Third edition

How to Think Like a Computer Scientist: Java. http://www.greenteapress.com/thinkapjava/ Big Java. Gay Horstman. Thinking in Java. Bruce Eckel’s www.mindview.net/Books/TIJ4 Sun Java Tutorials Series http://java.sun.com/ docs/books/tutorial/index.html

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 2 / 77

slide-3
SLIDE 3

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Outline

1

Error Handling Errors Defensive programming Exception Handling Assertions

2

Input-Output

3

Writing Better Code

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 3 / 77

slide-4
SLIDE 4

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Main concepts to be covered

Defensive programming.

Anticipating that things could go wrong.

Exception handling and throwing. Error reporting. Simple file processing.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 4 / 77

slide-5
SLIDE 5

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Some causes of error situations

Incorrect implementation.

Does not meet the specification.

Inappropriate object request.

E.g., invalid index.

Inconsistent or inappropriate object state.

E.g. arising through class extension.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 5 / 77

slide-6
SLIDE 6

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Not always programmer error

Errors often arise from the environment:

Incorrect URL entered. Network interruption.

File processing is particular error-prone:

Missing files. Lack of appropriate permissions.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 6 / 77

slide-7
SLIDE 7

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Defensive programming

Client-server interaction.

Should a server assume that clients are well-behaved? Or should it assume that clients are potentially hostile?

Significant differences in implementation required.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 7 / 77

slide-8
SLIDE 8

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Issues to be addressed

How much checking by a server on method calls? How to report errors? How can a client anticipate failure? How should a client deal with failure?

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 8 / 77

slide-9
SLIDE 9

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

An example: The AddressBook Project

Create an AddressBook object. Try to remove an entry. A runtime error results. Whose fault is this? Anticipation and prevention are preferable to apportioning blame.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 9 / 77

slide-10
SLIDE 10

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Argument values

Arguments represent a major vulnerability for a server

  • bject.

Constructor arguments initialize state. Method arguments often contribute to behavior.

Argument checking is one defensive measure.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 10 / 77

slide-11
SLIDE 11

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Checking the key

public void removeDetails ( String key ) { i f ( keyInUse ( key ) ) { ContactDetails d e t a i l s = ( ContactDetails ) book . get ( key ) ; book . remove ( d e t a i l s . getName ( ) ) ; book . remove ( d e t a i l s . getPhone ( ) ) ; numberOfEntries −−; } }

✡ ✝ ✆

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 11 / 77

slide-12
SLIDE 12

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Server error reporting

How to report illegal arguments?

To the user? Is there a human user? Can they solve the problem? To the client object? Return a diagnostic value. Throw an exception.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 12 / 77

slide-13
SLIDE 13

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Returning a diagnostic

public boolean removeDetails ( String key ) { i f ( keyInUse ( key ) ) { ContactDetails d e t a i l s = ( ContactDetails ) book . get ( key ) ; book . remove ( d e t a i l s . getName ( ) ) ; book . remove ( d e t a i l s . getPhone ( ) ) ; numberOfEntries −−; return true ; } else { return false ; } }

✡ ✝ ✆

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 13 / 77

slide-14
SLIDE 14

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Client responses

Test the return value.

Attempt recovery on error. Avoid program failure.

Ignore the return value.

Cannot be prevented. Likely to lead to program failure.

Exceptions are preferable.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 14 / 77

slide-15
SLIDE 15

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Exception-throwing principles

A special language feature. No special return value needed. Errors cannot be ignored in the client.

The normal flow-of-control is interrupted.

Specific recovery actions are encouraged.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 15 / 77

slide-16
SLIDE 16

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Throwing an exception

/∗∗ ∗ Look up a name or phone number and return the ∗ corresponding contact d e t a i l s . ∗ @param key The name or number to be looked up . ∗ @return The d e t a i l s corresponding to the key , ∗

  • r

n u l l i f there are none matching . ∗ @throws NullPointerException i f the key i s n u l l . ∗/ public ContactDetails getDetails ( String key ) { i f ( key == null ){ throw new NullPointerException ( ” n u l l key in getDetails ” ) ; } return ( ContactDetails ) book . get ( key ) ; }

✡ ✝ ✆

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 16 / 77

slide-17
SLIDE 17

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Throwing an exception

An exception object is constructed:

new ExceptionType(”...”);

The exception object is thrown:

throw ...

Javadoc documentation:

@throws ExceptionType reason

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 17 / 77

slide-18
SLIDE 18

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

The exception class hierarchy

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 18 / 77

slide-19
SLIDE 19

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Exception categories

Checked exceptions

Subclass of Exception Use for anticipated failures. Where recovery may be possible.

Unchecked exceptions

Subclass of RuntimeException Use for unanticipated failures. Where recovery is unlikely.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 19 / 77

slide-20
SLIDE 20

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

The effect of an exception

The throwing method finishes prematurely. No return value is returned. Control does not return to the clients point of call.

So the client cannot carry on regardless.

A client may catch an exception.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 20 / 77

slide-21
SLIDE 21

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Unchecked exceptions

Use of these is unchecked by the compiler. Cause program termination if not caught.

This is the normal practice.

IllegalArgumentException is a typical example.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 21 / 77

slide-22
SLIDE 22

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Argument checking

public ContactDetails getDetails ( String key ) { i f ( key == null ) { throw new NullPointerException ( ” n u l l key in getDetails ” ) ; } i f ( key . trim ( ) . length ( ) == 0) { throw new IllegalArgumentException ( ” Empty key passed to getDetails ” ) ; } return ( ContactDetails ) book . get ( key ) ; }

✡ ✝ ✆

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 22 / 77

slide-23
SLIDE 23

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Preventing object creation

public ContactDetails getDetails ( String key ) { i f ( key == null ) { throw new NullPointerException ( ” n u l l key in getDetails ” ) ; } i f ( key . trim ( ) . length ( ) == 0) { throw new IllegalArgumentException ( ” Empty key passed to getDetails ” ) ; } return ( ContactDetails ) book . get ( key ) ; }

✡ ✝ ✆

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 23 / 77

slide-24
SLIDE 24

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Exception handling

Checked exceptions are meant to be caught. The compiler ensures that their use is tightly controlled.

In both server and client.

Used properly, failures may be recoverable.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 24 / 77

slide-25
SLIDE 25

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

The throws clause

Methods throwing a checked exception must include a throws clause:

public void saveToFile ( String d e s t i n a t i o n F i l e ) throws IOException

✡ ✝ ✆

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 25 / 77

slide-26
SLIDE 26

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

The try block

Clients catching an exception must protect the call with a try block:

try { Protect one or more statements here . } catch ( Exception e ) { Report and recover from the exception here . }

✡ ✝ ✆

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 26 / 77

slide-27
SLIDE 27

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

The try block

try { addressbook . saveToFile ( filename ) ; tryAgain = false ; } catch ( IOException e ) { System . out . p r i n t l n ( ” Unable to save to ” + filename ) ; tryAgain = true ; }

✡ ✝ ✆

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 27 / 77

slide-28
SLIDE 28

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

The try block

try { addressbook . saveToFile ( filename ) ; tryAgain = false ; } catch ( IOException e ) { System . out . p r i n t l n ( ” Unable to save to ” + filename ) ; tryAgain = true ; }

✡ ✝ ✆

  • 1. Exception thrown from here

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 27 / 77

slide-29
SLIDE 29

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

The try block

try { addressbook . saveToFile ( filename ) ; tryAgain = false ; } catch ( IOException e ) { System . out . p r i n t l n ( ” Unable to save to ” + filename ) ; tryAgain = true ; }

✡ ✝ ✆

  • 1. Exception thrown from here
  • 2. Control transfers to here

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 27 / 77

slide-30
SLIDE 30

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Catching multiple exceptions

try { . . . r e f . process ( ) ; . . . } catch ( EOFException e ) { / / Take action on an end−of−f i l e exception . . . . } catch ( FileNotFoundException e ) { / / Take action on a f i l e −not−found exception . . . . }

✡ ✝ ✆

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 28 / 77

slide-31
SLIDE 31

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

The finally clause

try { Protect one or more statements here . } catch ( Exception e ) { Report and recover from the exception here . } f i n a l l y { Perform any actions here common to whether or not an exception i s thrown . }

✡ ✝ ✆

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 29 / 77

slide-32
SLIDE 32

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

The finally clause

A finally clause is executed even if a return statement is executed in the try or catch clauses. A uncaught or propagated exception still exits via the finally clause.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 30 / 77

slide-33
SLIDE 33

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Defining new exceptions

Extend Exception or Runtime−Exception. Define new types to give better diagnostic information. Include reporting and/or recovery information.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 31 / 77

slide-34
SLIDE 34

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Example

public class NoMatchingDetailsException extends Exception { private String key ; public NoMatchingDetailsException ( String key ) { this . key = key ; } public String getKey ( ) { return key ; } public String t o S t r i n g ( ) { return ”No d e t a i l s matching ’ ” + key + ” ’ were found . ” ; } }

✡ ✝ ✆

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 32 / 77

slide-35
SLIDE 35

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Assertions

Used for internal consistency checks.

E.g. object state following mutation.

Used during development and normally removed in production version.

E.g. via a compile-time option.

Java has an assert statement.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 33 / 77

slide-36
SLIDE 36

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Java Assertion Statement

Two forms available:

assert boolean−expression assert boolean−expression : expression

The boolean-expression expresses something that should be true at this point. An AssertionError is thrown if the assertion is false.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 34 / 77

slide-37
SLIDE 37

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Assert Statement

public void removeDetails ( String key ) { i f ( key == null ) { throw new IllegalArgumentException ( ” . . . ” ) ; } i f ( keyInUse ( key ) ) { ContactDetails d e t a i l s = book . get ( key ) ; book . remove ( d e t a i l s . getName ( ) ) ; book . remove ( d e t a i l s . getPhone ( ) ) ; numberOfEntries −−; } assert ! keyInUse ( key ) ; assert consistentSize ( ) : ” Inconsistent book size in removeDetails ” ; }

✡ ✝ ✆

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 35 / 77

slide-38
SLIDE 38

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Guidelines for Assertions

They are not an alternative to throwing exceptions. Use for internal checks. Remove from production code. Do not include normal functionality:

/ / I n c o r r e c t use : assert book . remove (name) != null ;

✡ ✝ ✆

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 36 / 77

slide-39
SLIDE 39

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Error recovery

Clients should take note of error notifications.

Check return values. Do not ignore exceptions.

Include code to attempt recovery.

Will often require a loop.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 37 / 77

slide-40
SLIDE 40

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Attempting recovery

/ / Try to save the address book . boolean successful = false ; int attempts = 0; do { try { addressbook . saveToFile ( filename ) ; successful = true ; } catch ( IOException e ) { System . out . p r i n t l n ( ” Unable to save to ” + filename ) ; attempts ++; i f ( attempts < MAX ATTEMPTS) { filename = an a l t e r n a t i v e f i l e name; } } } while ( ! successful && attempts < MAX ATTEMPTS) ; i f ( ! successful ) { Report the problem and give up ; }

✡ ✝ ✆

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 38 / 77

slide-41
SLIDE 41

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Error avoidance

Clients can often use server query methods to avoid errors.

More robust clients mean servers can be more trusting. Unchecked exceptions can be used. Simplifies client logic.

May increase client-server coupling.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 39 / 77

slide-42
SLIDE 42

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Avoiding an exception

/ / Use the correct method to put d e t a i l s / / in the address book . i f ( book . keyInUse ( d e t a i l s . getName ( ) | | book . keyInUse ( d e t a i l s . getPhone ( ) ) { book . changeDetails ( d e t a i l s ) ; } else { book . addDetails ( d e t a i l s ) ; }

✡ ✝ ✆

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 40 / 77

slide-43
SLIDE 43

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Glossary

try catch throw finally Exception Error defensive programming Assert

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 41 / 77

slide-44
SLIDE 44

Error Handling Input-Output Writing Better Code Errors Defensive programming Exception Handling Assertions

Review

Runtime errors arise for many reasons.

An inappropriate client call to a server object. A server unable to fulfill a request. Programming error in client and/or server.

Runtime errors often lead to program failure. Defensive programming anticipates errors in both client and server. Exceptions provide a reporting and recovery mechanism.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 42 / 77

slide-45
SLIDE 45

Error Handling Input-Output Writing Better Code

Outline

1

Error Handling

2

Input-Output

3

Writing Better Code

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 43 / 77

slide-46
SLIDE 46

Error Handling Input-Output Writing Better Code

Text input-output

Input-output is particularly error-prone. It involves interaction with the external environment. The java.io package supports input-output. java.io.IOException is a checked exception.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 44 / 77

slide-47
SLIDE 47

Error Handling Input-Output Writing Better Code

Readers, writers, streams

Readers and writers deal with textual input. Based around the char type. Streams deal with binary data. Based around the byte type. The address-book-io project illustrates textual IO.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 45 / 77

slide-48
SLIDE 48

Error Handling Input-Output Writing Better Code

Text output

Use the FileWriter class.

Open a file. Write to the file. Close the file.

Failure at any point results in an IOException.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 46 / 77

slide-49
SLIDE 49

Error Handling Input-Output Writing Better Code

Text output

try { F i l e W r i t e r w r i t e r = new F i l e W r i t e r ( ”name of f i l e ” ) ; while ( there i s more t e x t to write ) { . . . w r i t e r . write ( next piece

  • f

t e x t ) ; . . . } w r i t e r . close ( ) ; } catch ( IOException e ) { something went wrong with accessing the f i l e }

✡ ✝ ✆

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 47 / 77

slide-50
SLIDE 50

Error Handling Input-Output Writing Better Code

Text Input

Use the FileReader class. Augment with BufferedReader for line-based input.

Open a file. Read from the file. Close the file.

Failure at any point results in an IOException.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 48 / 77

slide-51
SLIDE 51

Error Handling Input-Output Writing Better Code

Text Input

try { BufferedReader reader = new BufferedReader ( new FileReader ( ”name of f i l e ” ) ) ; String l i n e = reader . readLine ( ) ; while ( l i n e != null ) { do something with l i n e l i n e = reader . readLine ( ) ; } reader . close ( ) ; } catch ( FileNotFoundException e ) { the specified f i l e could not be found } catch ( IOException e ) { something went wrong with reading

  • r

closing }

✡ ✝ ✆

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 49 / 77

slide-52
SLIDE 52

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

Outline

1

Error Handling

2

Input-Output

3

Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 50 / 77

slide-53
SLIDE 53

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

Main concepts to be covered

Responsibility-driven design Coupling Cohesion Refactoring Design Patterns

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 51 / 77

slide-54
SLIDE 54

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

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

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 52 / 77

slide-55
SLIDE 55

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

Change or die

There are only two options for software:

Either it is continuously maintained

  • r it dies.

Software that cannot be maintained will be thrown away.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 53 / 77

slide-56
SLIDE 56

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

Code quality

Two important concepts for quality of code:

Coupling Cohesion

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 54 / 77

slide-57
SLIDE 57

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

Coupling

Coupling refers to links between separate units of a program. If two classes depend closely on many details of each

  • ther, we say they are tightly coupled.

We aim for loose coupling.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 55 / 77

slide-58
SLIDE 58

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

Loose coupling

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

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 56 / 77

slide-59
SLIDE 59

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

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.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 57 / 77

slide-60
SLIDE 60

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

High cohesion

High cohesion makes it easier to: understand what a class or method does; use descriptive names; reuse classes or methods.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 58 / 77

slide-61
SLIDE 61

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

Cohesion of methods

A method should be responsible for one and only one well defined task.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 59 / 77

slide-62
SLIDE 62

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

Cohesion of classes

Classes should represent one single, well defined entity.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 60 / 77

slide-63
SLIDE 63

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

Code duplication

Code duplication: is an indicator of bad design, makes maintenance harder, can lead to introduction of errors during maintenance.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 61 / 77

slide-64
SLIDE 64

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

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.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 62 / 77

slide-65
SLIDE 65

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

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

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 63 / 77

slide-66
SLIDE 66

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

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.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 64 / 77

slide-67
SLIDE 67

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

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.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 65 / 77

slide-68
SLIDE 68

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

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.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 66 / 77

slide-69
SLIDE 69

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

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.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 67 / 77

slide-70
SLIDE 70

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

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.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 67 / 77

slide-71
SLIDE 71

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

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.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 68 / 77

slide-72
SLIDE 72

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

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.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 68 / 77

slide-73
SLIDE 73

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

Using design patterns

Inter-class relationships are important, and can be complex. Some relationship recur in different applications. Design patterns help clarify relationships, and promote reuse.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 69 / 77

slide-74
SLIDE 74

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

Pattern structure

A pattern name. The problem addressed by it. How it provides a solution:

Structures, participants, collaborations.

Its consequences.

Results, trade-offs.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 70 / 77

slide-75
SLIDE 75

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

Decorator

Augments the functionality of an object. Decorator object wraps another object.

The Decorator has a similar interface. Calls are relayed to the wrapped object ... ... but the Decorator can interpolate additional actions.

Example: java.io.BufferedReader

Wraps and augments an unbuffered Reader object.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 71 / 77

slide-76
SLIDE 76

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

Singleton

Ensures only a single instance of a class exists. All clients use the same object. Constructor is private/protected to prevent external instantiation. Single instance obtained via a static getInstance method. Example: Canvas in the shapes project.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 72 / 77

slide-77
SLIDE 77

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

Factory method

A creational pattern. Clients require an object of a particular interface type or superclass type. A factory method is free to return an implementing-class

  • bject or subclass object.

Exact type returned depends on context. Example: iterator methods of the Collection classes.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 73 / 77

slide-78
SLIDE 78

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

Observer

Supports separation of internal model from a view of that model. Observer defines a one-to-many relationship between

  • bjects.

The object-observed notifies all Observers of any state change. Example SimulatorView in the foxes-and-rabbits project.

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 74 / 77

slide-79
SLIDE 79

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

Observers

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 75 / 77

slide-80
SLIDE 80

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

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

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 76 / 77

slide-81
SLIDE 81

Error Handling Input-Output Writing Better Code Maintainance Coupling - Cohesion Improving Code Design Patters

Glossary

responsibility-driven design coupling cohesion refactoring design patterns

Lecture D.10. (MDV) Programming I Academic Year 2012-2013 77 / 77