Design Patterns in Java Part IV Operation Patterns Chapter 20 Introducing Operations Summary prepared by Kirk Scott 1.

Slides:



Advertisements
Similar presentations
Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Advertisements

Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
Error Handling with Exceptions Concepts C and other earlier languages often had multiple error-handling schemes, and these were generally established.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
Variable types We have already encountered the idea of a variable type. It is also possible to think about variables in terms of their kind, namely: 1)
Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.
CSI 3120, Exception handling, page 1 Exception and Event Handling Credits Robert W. Sebesta, Concepts of Programming Languages, 8 th ed., 2007 Dr. Nathalie.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Design Patterns in Java Appendix D UML at a Glance Summary prepared by Kirk Scott 1.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
Modules, Hierarchy Charts, and Documentation
Chapter 10 Classes Continued
1 Exception and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
While Loops and Do Loops. Suppose you wanted to repeat the same code over and over again? System.out.println(“text”); System.out.println(“text”); System.out.println(“text”);
Chapter 12: Adding Functionality to Your Classes.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
1 Chapter Eight Exception Handling. 2 Objectives Learn about exceptions and the Exception class How to purposely generate a SystemException Learn about.
Object Oriented Programming
Slides Credit Umair Javed LUMS Web Application Development.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
SQL Unit 5 Aggregation, GROUP BY, and HAVING Kirk Scott 1.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Object Oriented Programming Elhanan Borenstein Lecture #4.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Unit 4 Prototype Summary prepared by Kirk Scott 1.
The Java Programming Language
Design Patterns in Java Chapter 1 Introduction Summary prepared by Kirk Scott 1.
Chapter 2 Introducing Interfaces Summary prepared by Kirk Scott.
Introduction to Exception Handling and Defensive Programming.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
CPS120: Introduction to Computer Science Decision Making in Programs.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Appendix D UML at a Glance Summary prepared by Kirk Scott 1.
Design Patterns in Java Part II Responsibility Patterns Chapter 7 Introducing Responsibility Summary prepared by Kirk Scott 1.
1 CS161 Introduction to Computer Science Topic #9.
Interfaces About Interfaces Interfaces and abstract classes provide more structured way to separate interface from implementation
Exceptions and Assertions Chapter 15 – CSCI 1302.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
M1G Introduction to Programming 2 3. Creating Classes: Room and Item.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Classes, Interfaces and Packages
Programming & Debugging. Key Programming Issues Modularity Modifiability Ease of Use Fail-safe programming Style Debugging.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Exceptions in OO Programming Introduction Errors Exceptions in Java Handling exceptions The Try-Catch-Finally mechanism Example code Exception propagation.
Introduction to Exceptions in Java CS201, SW Development Methods.
Winter 2006CISC121 - Prof. McLeod1 Last Time Reviewed class structure: –attributes –methods –(inner classes) Looked at the effects of the modifiers: –public.
Notices Assn 2 is due tomorrow, 7pm. Moodle quiz next week – written in the lab as before. Everything up to and including today’s lecture: Big Topics are.
Summary prepared by Kirk Scott
User-Written Functions
Summary prepared by Kirk Scott
Packages and Interfaces
Review of Previous Lesson
CMSC 202 Exceptions.
Exception Handling.
Review for Midterm 3.
Presentation transcript:

Design Patterns in Java Part IV Operation Patterns Chapter 20 Introducing Operations Summary prepared by Kirk Scott 1

This introductory chapter on operations is largely about terminology In order to talk clearly about operations and the operation design patterns it is necessary to define the term operation Part of defining the term includes explaining its relationship to and distinguishing it from the terms method, algorithm, and polymorphism 2

Operations and Methods It is helpful to remember that the term operation comes from UML Operation is a design term, not specifically an implementation term An operation is a design specification of a service that can be requested from an instance of a class 3

Method is an implementation term A method is an implementation of an operation (for a given class) Another way of pointing out the distinction between operation and method is to say that operation is a level of abstraction higher than method 4

An operation defines something that a class does and it also specifies the calling interface for this service However, different classes may implement the operation The specific methods for the different classes may themselves differ 5

The differences in implementations are not necessarily due to obscure differences between the classes They may be the direct result of what the operation means when applied to those classes The book uses the toString() method as an example 6

Each different class will have a different implementation of the toString() method This is unremarkable and normal This is because the operation specification is at a level of abstraction that says something like, “Return a string with the class name and its instance variables and values.” 7

The book makes the following useful observation: Just as operations are at level more abstract than methods (implementations), design patterns themselves are at a level more abstract than classes and their methods 8

It should not be surprising, when doing design work, to find that specifications of design patterns can be most conveniently given in terms of operations, not classes and methods Design patterns and operations are at roughly the same level of abstraction 9

Think back to the Composite design pattern In general, this pattern made it possible to apply the same kind of operation to both individual items and groups of items In the examples given, it was of interest perform a count or check to see whether something was a tree 10

You may recall that there was some mild cleverness in the way the methods were set up to accomplish these goals The point is that the general goals, count or check for a tree, are expressions of operations The implementation of the goals was the trickery involving multiple method declarations and implementations at different levels in the pattern 11

Challenge 20.1 Use the words operation and method to explain how Chain of Responsibility implements an operation. 12

Solution 20.1 Chain of Responsibility distributes an operation across a chain of objects. Each method implements the operation’s service directly or forwards calls to the next object in the chain. 13

Comment mode on: You could rewrite the previous description substituting a word like functionality for operation The meaning would still be clear, but somewhat less precise The point of the challenge is simply to illustrate the proper use of the authors’ preferred terminology 14

The next step in trying to be precise about terminology involves the declaration of methods Overall, the declaration/specification of a method consists of two parts: Header body 15

It’s clear what the body is: It’s the code between the opening and closing braces It is the implementation The header, can be broken down into four different parts: Modifiers, return type, signature, and throws clause 16

I tend to be careless when referring to the signature of a method Notice that technically it only consists of the name of the method and the parameter list that goes with it Why it was named the signature becomes clear It is the name and parameter list which distinguishes which method is intended when a method call is made 17

What the return type represents should be clear Also, there should be no mysteries about the throws clause That leaves the topic of modifiers 18

It turns out that this is kind of a grab bag There are access modifiers, but if you think about it, there have been other kinds of terms that occupy this position in a method declaration The following challenge is a handy review of what you already know, along with a few additional details (which are not of great importance) 19

Challenge 20.2 Write down as many of the nine Java method modifiers as you can. 20

Solution 20.2 A complete list of Java method modifiers, with informal definitions of their meanings, follows: public: access permitted to all clients protected: access permitted within the declaring package and to subclasses of the class 21

private: access permitted only within the class abstract: no implementation provided static: associated with the class as a whole, not with individual objects final: not allowed to be overridden synchronized: method acquires access to the object monitor or to the class’s, if the method is static 22

native: implemented somewhere else in platform-dependent code strictfp: double and float expressions evaluated according to FP-strict rules, thus requiring intermediate results to be valid according to IEEE standards 23

Solution 20.2, continued: Although some developers might be tempted to explore using all these modifiers in a single method definition, several rules limit the ability to use them in combination. Section of the Java Language Specification [Gosling et al. 2005] lists these limitations 24

Comment mode on: One limitation is obvious: A method couldn’t be both public and private at the same time, for example I would also add the following: If you’re going to list the nine different keywords, it would also be helpful to mention what happens without an access modifier 25

If a method is declared without an access modifier, by default, it has package access The following observation is slightly off the topic, but also worth remembering Local variables in methods aren’t typically given access modifiers Their scope is the body of the method 26

Signatures The book points out that in a sense, the meaning of operation and signature are similar They both specify the interface by which a service, or method is called Of course, operation is more general, because it refers to the functionality as well as the interface alone 27

The book quotes the Java language specification again: “The signature of a method consists of the name of the method and the number and types of formal parameters to the method.” Recall that the names of the parameters are not important to sorting out which method is in question On the other hand, the order of the different types of parameters makes a difference 28

The book emphasizes that the signature doesn’t include the return type On the other hand, it notes that in general, if you override a method and change the return type, you’ll get a compiler error In the answer to the following challenge it backs off from the foregoing statement by mentioning covariant return types, which come up in CS

Challenge 20.3 The method Bitmap.clone() returns Object, even though the method always returns an instance of the Bitmap class. Would it still compile if its return type were declared as a Bitmap? 30

Solution 20.3 It depends. For pre-Java 5 versions: If you were to somehow change the return value of Bitmap.clone(), the code wouldn’t compile. The clone() signature matches the signature of Object.clone(), so the return type must match as well. 31

In Java 5: The language definition has changed to allow covariant return types, whereby a subclass can declare a more specific return type. 32

The authors reiterate that operation and signature are related terms If you talk about several different classes sharing an operation, you expect that the method that implements that operation will have the same name and the same parameter list for the different classes In other words, the methods will have the same signature 33

As soon as you are specifically interested in the name and parameter list and the syntactical rules for which method or version of a method is being called given a particular name and parameter list, then you are talking about the signature Operation is conceptually abstract Signature is more concrete 34

When referring to the operation, you’re interested in the functionality being implemented When referring to the signature, you’re interested in the syntactical specifics of the implementation 35

Exceptions Recall that a method header can end with a throws clause This indicates that under certain error conditions, the method throws an exception back to whatever client code called it It is then necessary for the client to make the call in a try/catch block in order to catch an exception if it’s thrown 36

The previous statement was a bit of a simplification The client code may also choose to throw the exception rather than handling it The hierarchy of calls that throw the exception may be arbitrarily deep 37

However, ultimately the code has to catch and handle the exception The book states that not catching the exception results in a run-time crash It seems to me that the compiler keeps track of this, and typically, code that doesn’t catch an exception will trigger a compiler error before a run-time problem can result 38

Note that in the previous chapter the book showed a call to clone() without a try/catch block. I had the feeling then that the compiler would flag that. Once again it’s hard to say whether I’m confused or whether the authors are confused, or channeling the spirit of reformed C++ programmers 39

It may be helpful to note that the try/catch structure is similar to a built-in if/else structure If a call is made and no exception is thrown, execution continues normally—and the catch block is ignored If an exception is thrown, then the code in the catch block is executed—or execution of the current method stops at that point and the exception is thrown to whatever method called it 40

For beginning programmers, you typically are worried about catching exceptions that are thrown by system defined methods It is worth noting that you can also define your own exceptions and specifically write your own methods to originate and throw exceptions under error conditions The Java syntax for this is illustrated by this line of code: throw new Exception(“Good Luck!”); 41

You may recall that in Java there are checked exceptions and unchecked exceptions I can never remember which is which by name, but this is the idea: 42

There are some mistakes which programmers are responsible for which are not dealt with by the exception handling mechanism An example is dividing by 0 This doesn’t generate an exception It will cause a run-time error 43

There are other error conditions that programmers aren’t responsible for The classic example is problems when doing file operations If a program can’t open, write to, or read from a file, this may not be the program’s fault 44

If a failure occurs, the program will be notified by means of an exception, and it should try to handle the condition The idea is not to burden the programmer with solving problems that are not the programmer’s fault The idea is to give the programmer a chance to successfully deal with problems that arise external to the program 45

The book points out the following concerning the main competitors of Java: C# doesn’t require methods to declare exceptions C++ allows exception specifications to appear, but doesn’t require the compiler to check them Note that what these statements mean is not entirely clear The next challenge addresses them further 46

Challenge 20.4 Unlike Java, C# does not require methods to declare any exceptions that they might throw. Write down your opinion of whether this is an improvement on Java’s rules. 47

Solution 20.4 One argument for leaving exception declarations out of method headers: We should first note that even Java does not require methods to declare all the exceptions that might be thrown. Any method might, for example, encounter a null pointer and throw an undeclared exception. [This is the equivalent of dividing by 0 mentioned above—It’s the result of a mistake made by the programmer.] 48

It’s impractical, as Java admits, to force programmers to declare all possible exceptions. Applications need a strategy for handling all exceptions. Requiring developers to declare certain types of exceptions is no substitute for architecting in an exception-handling policy. 49

On the other hand: Programmers need all the help they can get. It’s true that an application architecture needs to have a solid exception-handling strategy. It’s also clearly impractical to force developers to declare in every method the possibility of pervasive problems, such as null pointers. 50

But for some errors, such as problems in opening a file, requiring the caller of a method to handle possible exceptions is a useful reminder. C# throws out the baby with the bathwater by removing any declaration of possible exceptions from method headers. 51

Comment mode on: The book seems to be touching on multiple, related topics First of all, it is clear that the discussion has to do with checked and unchecked exceptions In the book’s terminology, it’s a question of declared and undeclared exceptions 52

Secondly, the book seems to be concerned about one syntactical question—whether the a method is declared to throw an exception in its header Since I don’t know C#, the distinction they’re making is not clear, but I would observe the following: In Java, declaring “throws” in the header makes it possible to pass the exception back to a calling client, if desired 53

There is a second syntactical element which the book doesn’t broach, and which I can’t say much about, again because I don’t know C# However, of equal importance to the declaration in the header is the need to use a try/catch block when calling a method that throws an exception We know that this is necessary in Java Does such a structure exist in C#? 54

Coming around full circle, the real question is whether this structure is of value In the second half of their answer the authors give the Java point of view Yes, all exceptions of any kind have to be handled somehow, and the programmer is reliant on the system and language for how this is done 55

It is unreasonable to declare every possible exception Likewise, it’s unreasonable to put every statement that could generate an exception in a try/catch block 56

On the other hand, surely there are cases where writing exception handling into programmer written code can be helpful Java takes the middle path of creating a structure for this and requiring it in certain well-defined cases This allows programmer written code to gracefully handle certain kinds of error conditions that it may encounter 57

Java also makes it possible for programmers to use the same structure to deal with error conditions that the code itself might generate This is how come it is possible to construct an instance of an exception in the body of a method and to declare the method to throw it By the way, it is also possible to extend the Exception class and make application specific exceptions 58

Algorithms and Polymorphism In this section the authors return to trying to straighten out thinking about programming by being precise in the terminology used The book tackles the definition of an algorithm first It takes the definition given on the next overhead from Cormen, Leiserson, and Rivest 59

“An algorithm is any well-defined computation procedure that takes some value, or set of values, as input and produces some value, or set of values, as output.” The point is that there is no set relationship between algorithms and methods One method may contain within it the implementations of more than one algorithm 60

One method may also consist of the implementation of a single algorithm Finally, the implementation of a complex algorithm may consist of more than one method in some sort of relationship The book goes back to the Composite design pattern to illustrate the last point 61

It takes four different isTree() methods, one abstract and three concrete in order to implement the algorithm for determining whether an instance of MachineComponent is a tree The UML diagram for the Composite design pattern with the methods is shown on the next overhead 62

63

Challenge 20.5 How many algorithms, how many operations, and how many methods does Figure 20.1 depict? 64

The figure shows one algorithm—the procedure to determine whether an object model is a tree—two operations—appearing as two signatures in the MachineComponent class—and four methods. 65

The title of this section of the chapter included the word polymorphism The point the book wants to make is that this example of multiple methods for one algorithm is based on polymorphism Many methods are involved because >1 class is involved and each different class can have a different implementation of a method with a given signature Which method implementation is used depends on which kind of object it’s called on 66

It is worth noting that in a more traditional structured environment, as well as in a polymorphic environment, there is another way in which an algorithm could depend on >1 method If the algorithm is sufficiently complex, it would simply be broken down into subroutines or sub-methods 67

Summary This chapter is a preview to the chapters that give operations based design patterns The goal of the chapter was to clarify the terminology of operation, method, signature, and algorithm An operation is an abstract specification of a service Such a service may be provided by >1 method with the same signature 68

The term signature is refers to the name and parameters of a method and the rules for determining which method to use based on these characteristics A method definition includes modifiers, a return type, a signature, and potentially a throws clause A method implements an operation A method may run successfully to completion, or it may encounter an exception 69

An algorithm is a set of steps for performing some computation An algorithm may be “smaller than”, “the same size as”, or “larger than” a single method When an algorithm involves >1 method, this may be the result of multiple classes and polymorphism in the design pattern Note: As usual, with an introductory chapter, more stuff follows the summary 70

Beyond Ordinary Operations The table shown on the next overhead previews the five operation design patterns As usual, it’s not really clear what the explanations mean until you see the patterns in greater detail 71

72

As you might expect, the operation design patterns are cases more complicated that one operation = one method = one algorithm The book summarizes the preview in this way: The operation design patterns tend to have more than one method, usually with the same signature, participating in a design 73

The End 74