Friday, April 10, 2020

Design Patterns – The Façade

The façade is, perhaps, the second most commonly implemented design pattern. Just like the Bridge (probably the most widely used pattern of all, and certainly the most fundamental) it is usually implemented without a conscious decision having been made. Does this mean that it merely a statement of the obvious? Perhaps, but the pattern does have a very specific intent, and should definitely be taken seriously.

What is a Façade?
The formal definition for Façade offered by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides is:
Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use
Succinct, but perhaps not quite so obvious after all. Consider the basic three tier architecture so widely used in software design. How should you define the middle tier? Potentially there are going to be many different objects in that middle tier. For example you may have any, or all, of the following types of object:
·         Data Validation objects·         Business Rule Objects·         Data Transformation Objects·         Data Access/Database Connection Objects
How is your Presentation Tier going to manage all the interactions with these individual objects? You could easily end up with a frightful mess where each object in the Presentation Tier must have detailed knowledge of each of the middle tier objects and has to handle them directly. The resulting system diagram looks horribly like that shown in Figure 1.
Not only is this aesthetically displeasing, it illustrates that we have a tightly coupled system which is, as always, prone to error when things change. Changes to any of the middle tier components must be reflected in all of the Presentation Tier components that access them!

Figure 1: Cross-Tier interactions can get messy!
By implementing a Façade the system becomes much simpler as shown in Figure 2.


Figure 2: Cross Tier Interactions with a Façade Object
Not only is this aesthetically more pleasing but, obviously this is a much more robust design.
Notice that the Presentation Tier objects no longer need detailed knowledge of the individual components of the middle tier. Instead they only need to know how to access the Façade object which is then responsible for controlling all further interactions within the middle tier. This achieves a weakly coupled state that, in turn, means that we can change things at will in the lower level sub-systems without needing to make corresponding changes elsewhere. Providing that the interface exposed by the façade object does not alter, then its internal facing methods are the only places that changes to lower level systems can ever affect.
When should we use a Facade?
The purpose of the façade is to provide a simple interface to a complex system. Although most of the examples in pattern literature talk about ‘sub-systems’ you must remember that a design pattern is not dependent upon the implementation but on the design problem which it addresses. So while it is may not be very common for us, as FoxPro developers to build “complex sub-systems”, we often create complex objects which expose many methods in their interface! So whenever we find ourselves having to call multiple methods on the same object we really should be thinking in terms of implementing a façade.
The usual scenario occurs when we have to run some multi-step process or calculation. Usually our first instinct is to add the relevant methods directly to the object (usually the form!) that requires them. When this gets messy we may provide a ‘control’ method to call the various steps in the correct order and to evaluate results and act accordingly. The resulting code looks something like this:
LPARAMETERS tuInval
llStatus = This.CheckParameters( tuInval )
IF llStatus
  luResult = This.FirstStep( tuInval )
  IF VARTYPE( luResult ) = “N” AND NOT EMPTY( luResult )
    llStatus = This.SecondStep( luResult )
  ELSE
    llStatus = .F.
  ENDIF
ENDIF
RETURN llStatus
This will work perfectly well, of course, until some other object requires access to the code. Now we have a problem. The next stage is to abstract the code from our form and create a stand-alone object, but now we have to make multiple calls to that object – and from more than one place in our application – sound familiar? It should, because this is precisely the scenario that the façade pattern addresses.
Our object should not actually expose all of its methods, instead it should expose a façade consisting of just a few very simple methods which then call other methods internally as needed. By designing things this way we achieve several things:
·         The code can be called from any object·         The process detail is hidden, callers only need to know the exposed interface·         Changes to the implementation are confined to the façade object
How can we implement a façade?
The example given here is for a converter class, defined in Visual FoxPro, that can be implemented directly as a VFP application object, or as a COM component. The interface for this object is extremely simple, and consists of just TWO methods:
·         Convert             Which expects three parameters, a value and the appropriate From/To codes. This method returns the converted value or an error code
·         GetErrors           Interrogates the object’s errors collection and returns either a VFP Error Object or a COM exception, depending on how the object was instantiated
In fact the object has a number of methods which are defined as “Protected” so that they do not even appear in the COM interface, and can only be called internally.
The first thing that this method does, is to pass the received parameters through a validation method to ensure that they are of the correct (expected) data type. We are not concerned, at this point, if the values are meaningful, just that they are expected. Since this method is the only entry point, once we have checked the parameters, we can assume that they are correct in all other places because the only way that values can be sent to another method is from this, or a subordinate, method. This is an additional benefit of the façade!
  *** First thing to do is to ensure we have From/To parameters
  IF NOT .ValidateParam( tuConvFm, "C" ) OR EMPTY( tuConvTo )
    lcErrText = "Invalid 'From' Parameter" + CRLF
  ENDIF
  IF NOT .ValidateParam( tuConvTo, "C" ) OR EMPTY( tuConvTo )
    lcErrText = lcErrText + "Invalid 'To' Parameter" + CRLF 
  ENDIF
  *** And that we have a value too
  IF EMPTY( tuInpVal )
    lcErrText = lcErrText + "No input value passed" + CRLF
  ENDIF
  *** Check the results so far
  IF NOT EMPTY( lcErrText )
    ERROR lcErrText
  ENDIF
Next we need to try and figure out what method we need to call. This is the second direct method call, and the method called returns the name of the conversion method we want, based on the ‘from’ parameter. One of the “rules” I have implemented is that both “From” and “To” measures must be of the same type (you cannot convert a temperature to a length for example).
  *** Now we need to decide what method to call, using the From Parameter
  lcMethod = .GetConv( tuConvFm )
Finally we execute the relevant conversion and get the result
  *** Now just handle the conversion
  luRetVal = EVALUATE( "This." + lcMethod + "( tuInpVal, tuConvFm, tuConvTo )")
This entire block of code is enclosed in a TRY… CATCH so that any error, either here, or in a subordinate method, is caught and sent to the LogError() method for access when needed. The return value is either the converted value, or NULL and it is, of course, up to the client object to determine what to do next.
Façade Pattern Summary
As you can see the façade offers us a lot of benefits as developers by providing us with a methodology that avoids tight coupling and, at the same time, promotes better encapsulation and isolation of code so that the impact of changes are minimized.
I illustrated the façade pattern by using an object dropped on to a form and named explicitly at design time and the façade object also contained the actual code to be implemented. However, there is no absolute reason to do it this way. The façade object could simply have been a “gatekeeper” to a host of other objects and, using an implementation of the Strategy pattern, could instantiate the required object for a task at run time. Remember, patterns can be (and usually are) combined in order to solve real design problems.
Published Sunday, January 21, 2007 10:02 PM by andykr

Design Patterns - The Mediator

What is a mediator and how do I use it?

The mediator describes one solution to a key issue that we all encounter whenever we try to design a new class. How to deal with situations where one object has to respond to changes in, or control the behavior of, another.
How do I recognize where I need a mediator?
The formal definition of the mediator, as given by the “Design Patterns, Elements of Reusable Object-Oriented Software” by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides is:
Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.
This addresses one of the most fundamental problems that we have to tackle in any software development task, that of ensuring that objects can communicate with each other without actually having to include hard-coded references in our classes.
Nowhere is this more critical than when building the complex user interfaces that the current generation of computer-literate end users not only expect, but demand. Typically we have to make the entire UI respond as a single entity, enabling and disabling functions and controls in response to the user’s actions and choices, or according to their rights and permissions. At the same time we want to design and build generic, reusable classes. The two requirements are, apparently, in direct conflict with one another.
Consider the problem of kinking a couple of textboxes in a form. When a value is entered into one, the other must display the result of some sort of calculation based on that value (e.g. When entering a price in one, display the Sales Tax in the other). Obviously, if there is no value in the source, there should be no result in the target, but how can we ensure that the calculation only gets done when a value greater than 0 is entered?
Of course, the simplest solution is just to add a couple of lines of code to the Valid() of the textbox that would call the necessary functionality like this:
IF This.Value > 0
   *** Calculate the tax display

   ThisForm.TxtTax.Value = ( This.Value * (5.75/100) )
ELSE   *** Clear the tax display
   ThisForm.TxtTax.Value = 0

ENDIF
This sort of ‘tight coupling’ may be acceptable when we are dealing with just a simple pair of controls in a single form. However, we will quickly run into trouble if we try to adopt this solution when dealing with multiple controls that have to interact in complex and differing combinations. Even finding where the code that controls a particular interaction is specified can be a problem, and simply changing the name of one object becomes a major undertaking. This is where the mediator pattern comes into its own.
The basic idea is that each object communicates with a central ‘mediator’ which knows about all of the objects that are currently in scope, and how to manage their state when a given event is reported. In this way we avoid all of the issues associated with placing specific code into the method associated with the Valid() event of a control. Instead we can write completely generic code in its parent class. So, if we were using a mediator object, we could replace the specific code in the instance of our price textbox with code like this in its parent class:
This.oMediator.Notify( This )
As you can see, the textbox has no idea what the mediator will do with the information, or even what information it wants. All that it has to do is to call the mediator’s ‘Notify’ method and pass a reference to itself. Any subsequent action is up to the specific implementation of the mediator.
What are the components of a mediator?
A mediator has two essential requirements. First we need a “mediator” class that defines the interface, and generic functionality, for the “concrete mediators” that are the sub classes that define the various possible implementations. The second is that all Colleague objects must be based on classes that can communicate with their mediator. The basic structure for the mediator pattern is shown below:


You can see from the diagram that classes that need to work with a mediator need to hold a reference to the mediator object. You are probably thinking that, in Visual FoxPro we have a ready-made candidate for the mediator class in the Form (in the context of the UI anyway). Using the form as the mediator is nice because it is always available to any object through the ‘ThisForm’ reference without the need to worry about specific properties. However, when dealing with non-visual classes this may not be the best solution, so it is probably better to define a generic, non-visual, mediator class.
The second thing that you will notice from the diagram is that the mediator object needs to hold a reference to all of its colleagues. This raises the question of how it should acquire and hold those references – to which there are several possible answers. Perhaps the simplest to implement is that each control class defines a ‘RegisterMe()’ method that, whenever an instance of the class is created checks for the presence of a mediator and passes a reference to itself to the mediator. Another possibility is that the mediator class defines a ‘GoFindEm()’ method which searches its environment to discover objects. Either way the mediator class will also need to maintain a collection (array) to store references to its colleagues.
How do I implement a mediator?
In order to implement a mediator for our simple little Tax example we have quite a lot of preparation to do. First we will need a form class that can handle a mediator. Such a class will need three custom properties to deal with the mediator:
·         cmedclass     Name of the Mediator Class to Instantiate for this form
·         cmedlib         Class Library for the Mediator Class to be instantiated for this form
·         omediator     Exposed property to hold the reference to the Mediator object
and has the following code added to its Load() event (We are using Load() because we must ensure that the defined Mediator is in place before any other form control gets instantiated. Init() would be too late because it does not fire until after all controls have been instantiated).

LOCAL lcMClass, lcMLib

DODEFAULT()
WITH ThisForm
   *** If a mediator class is specified, instantiate it
   lcMClass = ALLTRIM( .cMedClass )

   lcMLib = ALLTRIM( .cMedLib )
   IF NOT EMPTY( lcMClass ) AND NOT EMPTY( lcMLib )
      .oMediator = NEWOBJECT( lcMClass, lcMLib )
   ENDIF
ENDWITH

Of course, we also have to be careful about cleaning up object references, so the form class includes the following code in its Destroy() event, to make sure that the clean up happens

IF VARTYPE( This.oMediator ) = "O"
   This.oMediator.Destroy()ENDIF

Note: This is required to avoid the problem that arises because the normal sequence of events is that objects are destroyed in the reverse order of their creation. Since the mediator is created first it would normally be destroyed last, but because it holds references to other objects they cannot be destroyed while it exists. So we need to force the mediator’s destruction ‘out of turn’ when the form is being released so that the objects can release themselves properly.
Next we will need to define new sub classes for each of the controls that will have to work with the mediator. A new custom property (oMediator) has been defined to hold a local reference to the mediator object, together with three new methods;
·         Register ()        Called from the Init() of the control. Checks for the presence of a mediator. If one is found it stores a local reference to it and then calls mediator’s Register() method, passing a reference to itself
·         Notify()             Method that calls the state change notification method (also named “notify”) on the mediator and passes a reference to the current control
·         UnRegister()      Called from the Destroy() of the control. Checks the local reference to the mediator. If found, calls the mediator’s UnRegister() method, passing a reference to itself and then releases the local reference
In addition, the following events (where applicable) have to be modified to call the control’s Notify() method either InterActiveChange() and ProgrammaticChange() for lists or Valid() for text and edit boxes.
Next we need an abstract mediator class which defines the interface, and generic behavior for the Register() Notify() and Unregister() methods and has a RegisteredObjects collection. The code to add and remove objects to the collection is very simple indeed (I typically use the concatenation of an object’s “Parent + Name” properties as the key for items in the collection because there may be objects with the same name in different containers on a form) and the only real complexity is in the Notify() method.
The way I like to implement this is by defining custom methods in the concrete sub classes to handle the interactions for each object they deal with. The code in the mediator’s Notify() method can then be generic and simply checks to see if it has a method for the current object. Here is the code for that:

LPARAMETERS toObjRef

LOCAL lcKey, lcMethod, lnItem
*** Get the parent + name into a local Variable
lcKey = UPPER( ALLTRIM( toObjRef.Parent ))
lcKey = lcKey + UPPER( ALLTRIM( toObjRef.Name ))
*** And the target method will be based on the name
lcMethod = “CHANGE_” + UPPER( ALLTRIM( toObjRef.Name ))
*** Do we have this object registered
lnItem = This.RegisteredObjects.GetKey( lcKey )
IF lnItem > 0
   *** This is registered, do we have some action for it
   IF PEMSTATUS( This, lcMethod, 5 )
      *** Call the method and pass the reference to the original object
      EVALUATE( “This.” + lcMethod + “(  toObjRef )” )
   ENDIF
ENDIF
*** Just return from here
RETURN

We can then create a specific sub class of this to implement the specific behavior that we want in our form by implementing the custom methods that will be called from the Notify() method. For our (very) simple example the ChangeTxtPrice() method might look like this:

LPARAMETERS toCalledBy

LOCAL lcKey, lnItem, loTgt, lnVal
*** do we have a tax textbox?
lcKey = UPPER( ALLTRIM( toObjRef.Parent ))
lcKey = lcKey + "TXTTAX"
lnItem = This.RegisteredObjects.GetKey( lcKey )
IF lnItem > 0
   *** Yes, it is registered, so get a reference to it
   loTgt = This.RegisteredObjects.Item( lnItem )
   *** Get the source object's value
   lnVal = toObjRef.Value
   IF lnVal > 0
      loTgt.Value = (lnVal* (5.75/100))
 
  ELSE
      loTgt.Value = 0
   ENDIF
   loTgt.Refresh()
ENDIF
RETURN

There are, of course, many ways to implement the concrete mediator but the methodology outlined here illustrates the underlying principle. 
Finally we have to create a form using the new classes.
Phew! Seems like a lot of work doesn’t it  - especially since all we want to do is to update one textbox based on the value of another! However, you will notice that everything except the creation of the concrete mediator that implements the specific behavior is entirely generic and is, therefore, completely re-usable. In other words, it only has to be done once.
It is important to emphasize just how much flexibility we have gained by doing all this. All of the code that governs the interaction between any number of objects on a form is now confined to a single object which is specific to the form, but that can be maintained outside of it. To change the behavior we can either modify the existing sub class, or create a new one and implement it by just changing a couple of properties on the form.
Mediator pattern summary
Implementing the mediator pattern undoubtedly requires more planning, and much more preparation than any of the patterns we have discussed so far. However, in situations where you have to manage complex interactions, it amply repays the effort in three ways.
·         First, it simplifies maintenance by localizing behavior that would otherwise be spread among several classes in a single object
·         Second, it avoids the necessity for tight coupling between objects
·         Third, it simplifies the logic by replacing ‘many to many’ interactions between individual controls with ‘one to many’ interactions between the mediator and colleagues
The main drawback to the pattern is that, especially when dealing with large numbers of interactions, the mediator itself can get very complicated and difficult to maintain. 
Published Sunday, January 14, 2007 12:24 PM by andykr

Design Patterns - Adapters and Wrappers

What is an adapter and how do I use it?

The adapter, as its name implies, describes a solution to the problem of making two disparate interfaces compatible by acting as a translation mechanism between them.
How do I recognize where I need an adapter?
The formal definition of the adapter, as given by “Design Patterns, Elements of Reusable Object-Oriented Software” by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides is:
Convert the interface of a class into another interface clients expect
The need for an adapter usually results from modifications or enhancements to class libraries or COM components. For example, re-factoring can often result in significant changes to the way in which the interface for a class needs to be defined. This in turn may necessitate major changes in application code that calls on the services of such classes. Making such changes is always a high risk option and should be avoided wherever possible
One solution, when source code is available is to retain the methods in the original interface to the class, but remove the implementation into new methods. The old methods are then left as “control” methods that no longer do the real work, instead they manage the calls to other methods. However, this still requires that existing code be modified.
The alternative is to create a new class which replicates the expected interface and translates calls to that interface into the correct format for the replacement. When dealing with components to which the source code is not available, this is the only method of dealing with changes to their interface.
What are the components of an adapter?
An adapter has two essential requirements. First we need a class that defines the interface that is to be adapted, the “adaptee”. Second, we need the “adapter” class that defines the expected interface, and maps the methods in that interface to those defined by the adaptee. The client calls one of the ‘expected’ methods, which is exposed on one side of the adapter, which simply passes the method call on to the appropriate method in the adaptee.
How do I implement an adapter?
In other languages an adapter is typically implemented using multiple inheritance by creating a sub class of the adaptee that inherits the implementation methods privately, and allowing it to also inherit the public interface from the class that defines the required interface.
This presents somewhat of a problem in Visual FoxPro because it does not support the multiple inheritance which is required to do it this way. A feature that was introduced in Visual FoxPro 7.0 is the IMPLEMENTS keyword that allows a Visual FoxPro class, defined in code, to inherit an interface that is defined in a type library. However, because it relies on type libraries it can only be used with COM components, and not with native Visual FoxPro classes, so it is not really much help in this context.
The best way to implement an adapter in Visual FoxPro is to create a class which exposes the methods of the expected interface, and holds an object reference to the adaptee. Client objects can then call their expected methods that in turn translate the call to the appropriate method on the adaptee. The result is that in VFP there is little difference between an adapter and a decorator except in terms of the intent. A decorator modifies behavior, while an adapter only modifies an interface.
Adapter pattern summary
The adapter pattern is used to avoid the necessity for changing code when an interface is changed, or to allow for future modifications or implementations when designing generic classes. However, because Visual FoxPro does not support multiple inheritance, the only practical implementation mechanism available is identical to that used by the Decorator.
What is a wrapper, and how do I use it?
Now that is a very good question indeed! If you study “Design Patterns, Elements of Reusable Object-Oriented Software” by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides you will not find a pattern named ‘wrapper’ anywhere in the list of primary patterns. However, a more diligent search of that resource will reveal that it is actually listed as a synonym for both the Adapter and Decorator patterns.
Now this does not make much sense to us. If “wrapper” really is a synonym for both, then logically they are also synonyms for each other and it follows that all three terms must refer to the same pattern – after alkl it is axiomatic that:
IF a = b AND b = c THEN a = c
Yet this is clearly not the case! As we have seen, Decorator and Adapter are quite different in their intent, and any similarities in their implementation are (as always) irrelevant in the context of a pattern’s definition. Whilst not wishing to disagree with the authors of the book we feel that, in this particular case at least, they have it wrong.
It seems to us that since the word “wrapper” actually means a covering, that to describe either the decorator or the adapter as “wrappers” is also semantically inaccurate. Both of these patterns rely on fooling the client into believing that an interposed object is actually the intended target by having it look like the object that the client expects. They may, therefore, both be “mimics”, or “impersonators”, but they are not really wrappers!
So, where would I use a wrapper?
We take the view that the intent of a wrapper is to manage the content.  As part of that function it may, but does not have to, include the functions provided by either, or both, the Decorator or the Adapter. Wrappers provide a means of integrating functionality that is not defined in objects into a an object-oriented environment.
What are the components of a wrapper?
A wrapper has two essential requirements. First we need an implementation that defines the functionality that we wish to access. This may, or may not be an object (one example of a non-object implementation would be a DLL whose functions we need to access). Second, we need the “wrapper” class that provides an object interface to access the implementation and methods to manage the implementation. The client calls a method on the wrapper which access the implementation as needed to fulfill the request.

 The following definitions summarize how we might differentiate between Wrappers, Decorators and Adapters which, as we have seen, are all implemented using the same basic structure:
·         Decorator            Modify behavior, without modifying an existing interface
·         Adapter       Modify interface without modifying behavior
·         Wrapper      Provide interface for, and services to, behavior that is defined elsewhere
How can I implement a wrapper?
It seems to us that most of the classes that we see referred to as ‘managers’ in VFP are actually wrappers. For example a form manager that creates and releases forms, manages a forms collection and provides an interface for accessing running forms is, by our definition above, an example of a wrapper. The distinction in name may be because it’s dealing with objects but that doesn’t alter the intent.
Another example of a wrapper would be a class to access the functions of Windows Shell DLLs. Such a class includes methods for checking that the required DLL is actually available, that it’s the correct version and is properly registered. The wrapper is also responsible for releasing the DLL from memory when it is finished with.
Wrapper pattern summary
Wrapper is clearly a pattern in its own right, and differs in intent from both Decorator and Adapter (to which it is closely allied in many VFP implementations). Wrappers provide management functions as well as access, to components that deliver functionality to an application as if they were VFP Objects – whether or not such a component is actually implemented as an object.

Published Sunday, January 07, 2007 12:25 PM by andykr

Design Patterns - The BRIDGE


As promised, I am starting a little series on Design Patterns, the first one to look at is the “Bridge” – ofter referred to as the “mother of all design patterns” because it is the most basic of all patterns and you will discover, as you become more familiar with patterns in general, that you keep finding the bridge (in some form) at the bottom of almost every other pattern.

OK, so what is a bridge?

The forma definition of the bridge, as given in “Design Patterns, Elements of Reusable Object-Oriented Software” by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides is that a Bridge:
Decouples an abstraction from its implementation so that the two can vary independently
Impressive eh? Do we really do that in our code? The short answer is that we probably should do so more often than we realize. Let us take a common example.
When writing code in our forms and classes we naturally want to trap for things going wrong and usually (being considerate developers) we want to tell the user when that happens. The most obvious, and simplest, solution is to include a couple of lines of code in the appropriate method. The result might look something like this:
IF NOT <A Function that returns True/False>
  lcText = "Check failed to return the correct value" + CHR(13)
  lcText = lcText + "Press any key to re-enter the value"
  WAIT lcText WINDOW
  RETURN .F.
ENDIF
In our entire application we may well have dozens of situations where we display a wait window like this to keep the user posted as to what is going on and this works perfectly well until one of two things happens. Either our users decide that they really hate these pesky little “wait windows” and would much prefer a windows-style message box, or, worse, we need to deploy the code in an environment that simply doesn’t support the “wait window”. Maybe as a COM component, or in a web form. Now we must go and hunt through our application and find every occurrence of this code and change it to support the new requirement. I don’t know about you, but in my experience the chances of getting such a task right first time (not missing any occurrences and re-coding every one perfectly) are so close to zero as to be indistinguishable from it. Even if we could be confident of doing it, we still have the whole issue of testing it to deal with.
Another scenario arises when we are working with colleagues. Suppose in one of my forms I call on a system function and, being a careful developer, I test to ensure that the result is what I expected and, in case of error, code up a message like this:
lcText = “Incorrect value Returned from the Function”
Meanwhile my co-worker, writing a similar piece of code in another part of the application, codes their test of the same function call’s result it as:
lcText = “The requested task could not be completed”
So even if we both show the text in the same way, the actual content is different, even though to the end user, the same thing is happening! Confusing? You bet it is. Worse, it doesn’t look very polished to the end user.
So what has this to do with the Bridge pattern? Well, the reason that we have this problem is because we failed to recognize that we were coupling an abstraction (displaying a message to the user) to its implementation (the “Wait Window”, or “MessageBox”). Had we done so we might have used a bridge instead and then we could have avoided the problem. Here’s how the same code would look if we had implemented it using a bridge pattern:
IF NOT <A Function that returns True/False>
  This.oMsgHandler.ShowMessage( 9011 )
  RETURN .F.
ENDIF
See the difference? We no longer know, or care, what message is actually going to be displayed, or how it is going to be handled All that we need to know is where to get a reference to the object which is going to handle the message for us, and the identifier that tells the handler which message we wish to display. Of course, it is a fundamental requirement that all possible handlers will implement the appropriate interface, in this case a ShowMessage() method.
It is that source of the reference that is the “bridge”. In this example the “oMsgHandler” property provides the bridge between the code that requires a message and the mechanism for dealing with a message. Now, all that is needed to change the way in which our message is handled is to change the object reference stored in that property. That is something that can easily be done at run time depending on the environment in which the parent object has been instantiated (and the mechanism for doing that is an example of another pattern, named “Strategy”, which we’ll cover later). This approach successfully de-couples the abstraction from its implementation and our code is much more re-usable as a result.

What are the components of a bridge?

A bridge has two essential components, the “abstraction”, which is the object responsible for initiating an operation, and the “implementation” which is the object that carries it out. The abstraction knows its implementation either because it holds a reference to it, or because it owns (i.e. contains) it. Note although it often happens that the abstraction creates the implementation, it is not an absolute requirement of the pattern. A bridge could also make use of a pre-existing reference to an implementation object. In fact designing bridges this way can be very efficient because different abstraction objects can utilize the same implementation object. In fact, since Visual FoxPro has a very good containership model most developers find that they have used it (unintentionally) to implement Bridges more often than they realize. Most 'manager objects' (e.g. Form Manager, Ini File Manager, Message Manager) are actually examples of the Bridge Pattern.

However, don’t confuse message forwarding with a bridge. If a method of a command button calls a method on its parent form that directly implements the necessary action, that is message forwarding, not a bridge.  However, if that form method were to call another object to carry out the action, then we would have a bridge.
Interestingly another possibility occurs when a form (or other container) is maintaining a property that holds a reference to an implementation object. A contained object (e.g. a command button on a form) may access that property directly and get a local reference to the implementation object. It can then call methods on the implementation object directly. Now, is this a bridge, or message forwarding? In fact you could probably argue either side of the case with equal justification. However, the answer doesn’t really matter. This issue only arises because Visual FoxPro exposes properties as “Public” by default, and also implements back pointers which allow objects to address their parent directly. In most Object Oriented environments it is simply not possible for objects to behave so rudely toward each other.
So to implement a bridge you need to identify which object is going to play the role of the abstraction, and which the implementation. Once you have them defined, all that is left is to decide on how the bridge between the two is going to be coded and that will depend entirely on the scenario.
Published Sunday, December 10, 2006 2:26 PM by andykr

Design Patterns – The Decorator


The decorator describes a solution to the problem of adding functionality to an object without actually changing any of the code in that object.
How do I recognize where I need a decorator?
The formal definition of the strategy, as given by “Design Patterns, Elements of Reusable Object-Oriented Software” by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides is:

Attach additional responsibilities to an object dynamically
The need to dynamically alter the functionality (or behavior) of an object arises in either of two situations. First, where the source code for the object is simply not available; perhaps the object is an ActiveX control or a third party class library is being used. Second, where the class is widely used but the specific responsibility is only needed in one or two particular situations and to simply add the code to the class would not be appropriate.
In the preceding articles  we have looked at various ways of determining the amount of tax to apply to a ‘price’ depending on the ‘location’. The basic tax calculation object in every case works by exposing  a method named CalcTax() which takes two parameters, a value and a rate, and returns the tax due. We tackled the basic problem of dealing with tax in a form by using the bridge pattern to separate the implementation from the interface. However, as we quickly saw, although more flexible than simply coding it directly, it was not flexible enough to cope with different tax rates in different locations. Both Strategy and Chain of Responsibility can handle the issue, however, both solutions involve sub classing.
The decorator pattern allows us to solve the same problem without the need to sub class the original. Instead we define a new object which has exactly the same interface as the tax calculator, but which includes the necessary code to determine the appropriate tax rate for a given location. This object ‘looks’ just like the tax calculator to its client, but, because it also holds a reference to the real tax calculator, it can “pre-process” any request for a tax rate, and then simply call the real implementation when ready.
What are the components of a decorator?
A decorator has two essential requirements. First we need the implementation class that defines the interface, and the core functionality. Second, we need a decorator that reproduces the interface of the implementation, and holds a reference to it. The client object now directs calls that would have gone directly to the implementation to the decorator object instead. The basic structure for the decorator pattern is:

This pattern is actually an extended bridge. As far as the client is concerned it can address the decorator object as if it really were the implementation at the end of a standard bridge because the interface of the two is the same. As far as the implementation is concerned, the request looks exactly the same as if it had come from directly from the client. In other words, it does not ever need to know that the decorator even exists.
How do I implement a decorator?
A new class, named “cntDecorator”, has been defined to implement the decorator example. It has three custom properties and one custom method as shown:
Name            Description
cImpclass      Name of the class to instantiate for this decorator
cImplib         Class Library for the implementation class to instantiate
oCalculator   Object reference to an instance of the class which is the real
                     implementer of the CalcTax() method.
                     This object is instantiated in the decorator’s Init()
CalcTax        The decorator’s implementation for the equivalent method
                     on the ‘real’ implementer
The decorator class is actually very simple. When it is created it instantiates the real implementation class, which is defined by its class name and library properties. In addition it implements an operational method (in this case “CalcTax” ) which is named the same as, and has the same signature as, the real implementation method. 
The code in the decorator’s CalcTax() method is quite straightforward. It expects to receive two parameters, the location ID as a string, and the price for which the tax is required.  Notice that these are not the same parameters that are required by the CalcTax() method in the real class (Over there we need to pass a price and a rate). The decorator’s CalcTax() method determines the appropriate rate based on the location ID and then calls its implementation object’s CalcTax() method passing the ‘real’ parameters. The return value is just passed back to the client without any further modification.
LPARAMETERS tcLocation, tnPrice
LOCAL lnRate, lnTax
STORE 0 TO lnRate, lnTax
*** Determine the correct rate
DO CASE
  CASE tcLocation = '01'
    lnRate = 5.75
  CASE tcLocation = '02'
    lnRate = 5.25
  CASE tcLocation = '03'
    lnRate = 0.00
  OTHERWISE
    lnRate = 0
ENDCASE
*** Now pass on the call to the real object
lnTax = This.oCalculator.CalcTax( tnPrice, lnRate )
*** And return the result
RETURN lnTax
In order to use the decorator, all that is needed is a small change to the client. Instead of instantiating the real calculation object it must, instead, instantiate the decorator object. However, remember that the calling signature for the decorator’s method is identical to that for the ‘real’ method, so no other change is needed.
LPARAMETERS tcContext, tnPrice
LOCAL lnTax
WITH ThisForm
  *** Check that we have the Decorator available
  IF VARTYPE( This.oCalc ) # "O"
    *** We don't so create it
    .oCalc = NEWOBJECT( 'cntDecorator', 'calclass.vcx' )
  ENDIF
  *** Now just call it's CalcTax() method and pass both location and price
  lnTax = .oCalc.CalcTax( tcContext, tnPrice )
  IF ISNULL( lnTax )
    *** Couldn't process the Request at all
    MESSAGEBOX( 'Unable to Process this Location', 16, 'Failed' )
    lnTax = 0
  ENDIF
  RETURN lnTax
ENDWITH
Although this is a very simple example, you can see how easy it would be to extend the functionality of the decorator. One very common real life problem that this pattern can be used to address is how to provide implementation-specific validation to a generic save routine.
Decorator pattern summary
The decorator pattern is used when we wish to modify the basic behavior of a specific instance without the necessity of either creating a new sub class, or changing the code in the original. Essentially the decorator acts as a pre-processor for its implementation by interposing itself between its client and the implementation.


Published Sunday, December 31, 2006 12:25 PM by andykr

Writing better code (Part 1)

Writing better code (Part 1) As we all know, Visual FoxPro provides an extremely rich and varied development environment but sometimes to...