Exercise Session 11 Adriana Ispas

Document Sample
Exercise Session 11 Adriana Ispas Powered By Docstoc
					Chair of Software Engineering




                                   Languages in Depth
                                Series: Java Programming
                                    Prof. Dr. Bertrand Meyer



                        Exercise Session 11
                           Adriana Ispas
Today’s Exercise Session

Pattern of the Day
      Decorator
Quizzes




                           Languages in Depth series: Java Programming
                                                                         2
Decorator Pattern

Object structural pattern
      Describe how objects can be composed into larger
       structures using object composition, or the inclusion of
       objects within other objects
Intent
      Attach additional responsibilities to an object dynamically
      Provide flexible alternative to sub-classing for extending
       functionality
        Add functionality to individual objects, not to an entire class




                                                 Languages in Depth series: Java Programming
                                                                                               3
Decorator Pattern - Structure




                            Languages in Depth series: Java Programming
                                                                          4
Decorator Pattern - Structure

Component
     Defines the interface for objects that can have
      responsibilities added to them dynamically
ConcreteComponent
     Defines an object to which additional responsibilities can
      be attached
Decorator
     Maintains a reference to a Component object and
      defines an interface that conforms to Component's
      interface
ConcreteDecorator
     Adds responsibilities to the component
                                            Languages in Depth series: Java Programming
                                                                                          5
Decorator Pattern - Collaborations

Decorator forwards requests to its Component object.
It may optionally perform additional operations before and after
   forwarding the request




                                            Languages in Depth series: Java Programming
                                                                                          6
Decorator Pattern - Example
Draw a special border around some of the buttons in a toolbar.
     If we created a new derived button class, this means that
      all of the buttons in this new class would always have
      this same new border, when this might not be our intent.
     Instead, create a Decorator class that decorates the
      buttons.
     Then derive any number of specific Decorators from
      the main Decorator class, each of which performs a
      specific kind of decoration.




                                           Languages in Depth series: Java Programming
                                                                                         7
Decorator Pattern - Example




Decorator has to be a graphical object, containing the object
  it is decorating.
      It may intercept some graphical method calls, perform
       some additional computation and may pass them on to
       the underlying object it is decorating.




                                          Languages in Depth series: Java Programming
                                                                                        8
Decorator Pattern - CoolDecorator




                            Languages in Depth series: Java Programming
                                                                          9
Decorator Pattern – CoolDecorator …




                           Languages in Depth series: Java Programming
                                                                         10
Decorator Pattern – SlashDecorator




                           Languages in Depth series: Java Programming
                                                                         11
Decorator Pattern – Using a Decorator




                            Languages in Depth series: Java Programming
                                                                          12
Non-Visual Decorators

FilterInputStream
     Can be wrapped around any input stream class.
     Abstract class that doesn’t do any processing
     Layer where the relevant methods have been duplicated.
     Forwards method calls to the enclosed parent stream
      class.




                                         Languages in Depth series: Java Programming
                                                                                       13
FilterInputStream – Derived Classes

BufferedInputStream
        Adds buffering to stream so that every call does not cause I/O to
         occur.
CheckedInputStream
        Maintains a checksum of bytes as they are read
DataInputStream
        Reads primitive types (Long, Boolean, Float, etc.) from the input
         stream.
DigestInputStream
        Computes a MessageDigest of any input stream.
InflaterInputStream
        Implements methods for uncompressing data.
PushbackInputStream
        Provides a buffer where data can be “unread,” if during parsing you
         discover you need to back up.
                                                     Languages in Depth series: Java Programming
                                                                                                   14
Decorator Pattern – Consequences
Provides a more flexible way to add responsibilities to objects
  than can be had with static inheritance.
      Responsibilities can be added and removed at run-time
       simply by attaching and detaching them.
        In contrast, inheritance requires creating a new class for
         each additional responsibility (e.g.,
         BorderedScrollableTextView, BorderedTextView).
        This gives rise to many classes and increases the
         complexity of a system.
      Decorators   also make it easy to add a property twice.
        For example, to give a TextView a double border, simply
         attach two BorderDecorators.



                                                Languages in Depth series: Java Programming
                                                                                              15
Decorator Pattern – Consequences …

Pay-as-you-go approach to adding responsibilities.
     Instead of trying to support all foreseeable features in a
      complex, customizable class, you can define a simple
      class and add functionality incrementally with Decorator
      objects.
     Functionality can be composed from simple pieces. As a
      result, an application needn't pay for features it doesn't
      use.
     Easy to define new kinds of Decorators independently
      from the classes of objects they extend, even for
      unforeseen extensions.
     Extending a complex class tends to expose details
      unrelated to the responsibilities you're adding.
                                            Languages in Depth series: Java Programming
                                                                                          16
Decorator Pattern – Consequences ……

A decorator and its component aren't identical.
      A decorator acts as a transparent enclosure.
      But from an object identity point of view, a decorated
       component is not identical to the component itself.
      Hence you shouldn't rely on object identity when you use
       decorators.
Lots of little objects.
      A design that uses Decorator often results in systems
       composed of lots of little objects that all look alike.
        The objects differ only in the way they are interconnected,
         not in their class or in the value of their variables.
     Easy  to customize by those who understand them, but
      they can be hard to learn and debug.
                                               Languages in Depth series: Java Programming
                                                                                             17
Quiz 1: What does it print?

The decision method returns true. But it also returns
  false. What does it print? Is it even legal?




                                                        False




                                         Languages in Depth series: Java Programming
                                                                                       18
Quiz1: Solution

In a try-finally statement, the finally block is always
   executed when control leaves the try block.
      This is true whether the try block completes normally
       or abruptly.
Abrupt completion of a statement or block occurs when
      it throws an exception
      executes a break or continue to an enclosing
       statement
      executes a return from the method.
When both the try block and the finally block complete
   abruptly, the reason for the abrupt completion in the try
   block is discarded, and the whole try-finally statement
   completes abruptly for the reason in the finally block.
                                          Languages in Depth series: Java Programming
                                                                                        19
Quiz 1: Solution

Discarding the reason for abrupt completion is almost never
  what you want, because the original reason for abrupt
  completion might be important to the behavior of a program.
Every finally block should complete normally.




Never exit a finally block with a return, break,
  continue, or throw, and never allow a checked exception
  to propagate out of a finally block.



                                          Languages in Depth series: Java Programming
                                                                                        20
Quiz 2: What does it print?




                                Hello world




                              Languages in Depth series: Java Programming
                                                                            21
Quiz 2: Solution

It is true that a finally block is executed when a try block
    completes execution whether normally or abruptly.
In this program, however, the try block does not complete
    execution at all.
The System.exit method halts the execution of the current
    thread and all others dead in their tracks.
The presence of a finally clause does not give a thread
    special permission to continue executing.




                                          Languages in Depth series: Java Programming
                                                                                        22
Quiz 2: Solution

When System.exit is called, the virtual machine executes all
 shutdown hooks that have been registered with
 Runtime.addShutdownHook before shuting down.
    This is useful to release resources external to the VM.
    It is possible to halt the VM without executing shutdown
     hooks by calling System.halt.




                                          Languages in Depth series: Java Programming
                                                                                        23
Quiz 2: Solution

Use shutdown hooks for behavior that must occur before the
  VM exits.

The following version of the program prints both Hello world
  and Goodbye world, as expected:




                                         Languages in Depth series: Java Programming
                                                                                       24
Quiz 3: What does it print?




                                                                0


                              Languages in Depth series: Java Programming
                                                                            25
Quiz 3: Solution

The program tests each element of the array tests with the
  thirdElementIsThree method.
The loop through this array is certainly not traditional:
     Rather than terminating when the loop index is equal to
      the array length, the loop terminates when it attempts to
      access an array element that isn't there.
     Although nontraditional, this loop ought to work.
     The thirdElementIsThree method returns true if its
      argument has three or more elements and the third
      element is equal to 3.
     This is true for two of the five int arrays in tests, so it
      looks as though the program should print 2.

                                             Languages in Depth series: Java Programming
                                                                                           26
Quiz 3: Solution

Do not use exceptions for loop control; use exceptions only for
   exceptional conditions.
    for (int i = 0; i < tests.length; i++)
      if (thirdElementIsThree(tests[i]))
             successCount++;
Or
    for (int[] test : tests)
      if (thirdElementIsThree(test))
             successCount++;
                 Exception in thread "main"
                 java.lang.ArrayIndexOutOfBoundsException: 2 at
                 Loop.thirdElementIsThree(Loop.java:19) at
                 Loop.main(Loop.java:13)
                                             Languages in Depth series: Java Programming
                                                                                           27
Quiz 3: Solution

The thirdElementIsThree method does return true if its argument has
  three or more elements and the third element is equal to 3.
The problem is what it does when these conditions do not hold.

&
       commonly used as the bitwise AND operator
       overloaded to function as the logical AND operator when applied to
        boolean operands.
&&
      conditional AND operator
      
Where they differ
     The & operator always evaluates both of its operands
     The && operator does not evaluate its right operand if its left
      operand evaluates to false.

                                                     Languages in Depth series: Java Programming
                                                                                                   28
Quiz 4: Does the method work?




It doesn't; it returns the wrong answer one quarter of the time.
       Half of all int values are negative, and the isOdd
        method returns false when invoked on any negative
        value, whether even or odd, as i%2 is equal to -1 rather
        than 1.




                                             Languages in Depth series: Java Programming
                                                                                           29
Questions?




             Languages in Depth series: Java Programming
                                                           30
Next Week

Project presentations
     L
     FV E41




                        Languages in Depth series: Java Programming
                                                                      31