Use of Facade Pattern - language-agnostic

How can I know that I need a facade Pattern at a point in my application development?
How can I draw the line between Facade Pattern and Template Pattern?
For example: In [this] article, we see that, int placeOrder(int CustomerID, List<BasketItem> Products) has a number of predefined steps in the algorithm. So why don't the author use Template Pattern here?

Facade deals with interface, not implementation. Its purpose is to hide internal complexity behind a single interface that appears simple on the outside. In the example from your question, the facade hides four classes (Order, OrderLine, Address, BasketItem) behind a single method.
Template method deals with implementation. Its purpose is to extract the common algorithm from several ones that differ only in a 'fill in the blanks' way. The template method in the superclass implements the common algorithm and each subclass 'fills in the blanks' in its own specific way.
So why don't the author use Template Pattern here?
It would make sense to make placeOrder a template method if there were several similar versions of the operation. Maybe a few methods like placePhoneOrder, placeInternetOrder, placeManuallyEnteredOrder could be refactored into a single template placeOrder with some subclasses implementing only the {phone,internet,manual}-specific differences.

The facade pattern is appropriate when you have a complex system that you want to expose to clients in a simplified way, or you want to make an external communication layer over an existing system which is incompatible with your system. It is a structural pattern. See here: http://en.wikipedia.org/wiki/Facade_pattern
The template pattern, on the other hand, is a behavioral pattern that will help you when dealing with the inner implementation of a component. See here: http://en.wikipedia.org/wiki/Template_method_pattern

Suppose you have a few services, libraries or whatever. These libraries need interoperation in order to perform some higher level services. Then you may wish to wrap those calls and intialization code that usually go together and offer a bunch of functions to hide those details and make it simple to use those services for specific scenarios. Then it is a good use for facade pattern.
UPDATE: In the article mentioned the PlaceOrder method has one single implementation that works for all orders. Template pattern is meant to prescribe a series of steps that have to be followed but allow subclasses to offer their custom implementation of those fixed steps. For example, if you needed orders for televisions to be processed differently from orders for microwaves you could use the template pattern to redefine some imaginary DispatchParcel method (to send microwave as a simple package but television with extra service to help lift the heavy device to the upper floor). In our case there is no need for reimplementation of ProcessOrder steps so there is no need for template pattern as one single implementation suits all types of orders.

Related

How to represent standalone functions calling other standalone functions

I'm documenting the current state of a javascript package which is comprised of several modules predominantly consisting of standalone functions. As the result of using callbacks extensively, the package includes nested calls between standalone functions from multiple packages.
With this in mind, does anyone know what is the best way to represent calls between standalone functions in a sequence diagram?
Are the details of the standalone function worth it?
A common wisdom recommend to avoid the trap of UML as graphical programming language. Things that are easier expressed in code and easy to understand by readers better stay as code. Prefer to use UML to give the big picture, and explain complex relationships that are less obvious to spot in the code.
Automate obvious documentation?
Manually modelling a very precise sequence diagram is time consuming. Moreover, such diagram is quickly outdated with the next version of code.
Therefore, if your interest is to give an overview on how the function relate to each other, you may be interested to provide instead a visual overview using a simpler call graph. The reader can grasp the overall structure easily and look for more details in the code:
The advantage is that this task can be automated, using one of the many call graph generators available on the market (just google for javascript call graph generator to find some). There's by the way an excellent book on further automating documentation, that I can only recommend with enthousiasm: "Living Documentation: Continuous Knowledge Sharing by Design, First Edition"
If you have to set the focus on the detailed chronological sequencing of the calls a call graph would however not be sufficient. In this case, the sequence diagrams may then indeed be more relevant.
UML sequence diagrams with standalone functions?
A sequence diagram shows interactions between lifelines within an enclosing classifier. Usually a lifeline is used to represent an object, i.e. an instance of a class, but its definition is flexible enough to accommodate with any participant in an interaction.
Individual standalone functions can moreover be considered as individual objects that instantiate a more general class of functions (that's the concept behind a functor, like C++ std::function). This is particularly relevant in javascript where functions can be assigned to variables or used as parameters. So you may just use a lifeline that clarifies this. Up to you to decide how you will name the call message (e.g. operator()(a,b,c) or using its real name for readability ? ):
You can also group a bunch of related standalone functions into a pseudo-class that would represent in your model a module, compilation unit or namespace. Although a module is not stricto sensu an object, you may in your modeling deal with it as if it was a class with only one (anonymous) instance (i.e. its state would be the global variables defined in the module scope. The related standalone functions could be seen as operations of this imaginary class). The lifeline would correspond to a module, and function calls would be represented as synchronous messages either to another module or a message to itself with nested activation to visualise the “nested” calls.

Interfaces vs Public Class Members

I've noticed that some programmers like to make interfaces for just about all their classes. I like interfaces for certain things (such as checking if an object supports a certain behavior and then having an interface for that behavior) but overuse of interfaces can sometimes bloat the code. When I declare methods or properties as public I'd expect people to just use my concrete classes and I don't really understand the need to create interfaces on top of that.
I'd like to hear your take on interfaces. When do you use them and for what purposes?
Thank you.
Applying any kind of design pattern or idea without thinking, just because somebody told you it's good practice, is a bad idea.
That ofcourse includes creating a separate interface for each and every class you create. You should at least be able to give a good reason for every design decision, and "because Joe says it's good practice" is not a good enough reason.
Interfaces are good for decoupling the interface of some unit of code from its implementation. A reason to create an interface is because you foresee that there might be multiple implementations of it in the future. It can also help with unit testing; you can make a mock implementation of the services that the unit you want to test depends on, and plug the mock implementations in instead of "the real thing" for testing.
Interfaces are a powerful tool for abstraction. With them, you can more freely substitute (for example) test classes and thereby decouple your code. They are also a way to narrow the scope of your code; you probably don't need the full feature set of a given class in a particular place - exactly what features do you need? That's a client-focused way of thinking about interfaces.
Unit tests.
With an interface describing all class methods and properties it is within the reach of a click to create a mock-up class to simulate behavior that is not within the scope of said test.
It's all about expecting and preparing for change.
One approach that some use (and I'm not necessarily advocating it)
is to create an IThing and a ThingFactory.
All code will reference IThing (instead of ConcreteThing).
All object creation can be done via the Factory Method.
ThingFactory.CreateThing(some params).
So, today we only have AmericanConcreteThing. And the possibility is that we may never need another. However, if experience has taught me anything, it is that we will ALWAYS need another.
You may not need EuropeanThing, but TexasAmericanThing is a distinct possibility.
So, In order to minimize the impact on my code, I can change the creational line to:
ThingFactory.CreateThing( Account )
and Create my class TexasAmericanThing : IThing.
Other than building the class, the only change is to the ThingFactory, which will require a change from
public static IThing CreateThing(Account a)
{
return new AmericanThing();
}
to
public static IThing CreateThing(Account a)
{
if (a.State == State.TEXAS) return new TexasAmericanThing();
return new AmericanThing();
}
I've seen plenty of mindless Interfaces myself. However, when used intelligently, they can save the day. You should use Interfaces for decoupling two components or two layers of an application. This can enable you to easily plug-in varying implementations of the interface without affecting the client, or simply insulate the client from constant changes to the implementation, as long as you stay true to the contract of the interface. This can make the code more maintainable in the long term and can save the effort of refactoring later.
However, overly aggressive decoupling can make for non-intuitive code. It's overuse can lead to nuisance. You should carefully identify the cohesive parts of your application and the boundaries between them and use interfaces there. Another benefit of using Interfaces between such parts is that they can be developed in parallel and tested independently using mock implementations of the interfaces they use.
OTOH, having client code access public member methods directly is perfectly okay if you really don't foresee any changes to the class that might also necessitate changes in the client. In any case, however, having public member fields I think is not good. This is extremely tight coupling! You are basically exposing the architecture of your class and making the client code dependent on it. Tomorrow if you realize that another data structure for a particular field will perform better, you can't change it without also changing the client code.
I primarily use interfaces for IoC to enable unit testing.
On the one hand, this could be interpreted as premature generalization. On the other hand, using interfaces as a rule helps you write code that is more easily composable and hence testable. I think the latter wins out in many cases.
I like interfaces:
* to define a contract between parts/modules/subsystems or 3rd party systems
* when there are exchangeable states or algorithms (state/strategy)

Organizing Classes in Action Script 3

I am using Flex Builder 3 to develop my first application that will communicate with a server that has many operations, so many in fact it is overwhelming and I am grouping them together into classes that will expose the operations and also manage some client side meta data. I am calling these classes "server proxies" because they are technically similar to a proxy class in WCF. I would want to organize these classes where I can do things like the below where Authentication is a class, and ServerProxies is some feature of the language that allows me to group that class with other classes in the ServerProxies category, or subcatagories such as the Geography subcategory:
ServerProxies.Authentication.AddLoginSuccesfulListener(onLoginSuccessful);
ServerProxies.Authentication.SubmitCredentials(someParaemetersHere);
ServerProxies.Geography.Querying.GetAllTiles(someMoreParameters);
ServerProxies.Geography.Querying.MeasureTwoPoints(pointA,pointB);
ServerProxies.Geography.Display.RenderMapExtent(topLeftPoint,bottomRightPoint);
This example is kind of trivialized because some of these operations probably wouldn't go through a server, but that is not the topic at hand. (just had to say that before someone gets off on a tangent and flames me over some imaginary code)
*So my question is, what language feature of Action Script 3 would allow me to create such categories?
In C# it would have been a namespace, but namespaces in Action Script seem to be more like custom access modifiers that apply to methods and properties, rather than entire classes.
You have to use packages, in preforms the same task as namespaces in C#.
You can read more about it here:
http://www.foundation-flash.com/tutorials/packages/

Where would you use a Builder Pattern instead of an Abstract Factory?

I've seen this question rise here and there a few times, but I never found and answer I was happy with.
From Wikipedia:
Builder focuses on constructing a complex object step by step. Abstract Factory emphasizes a family of product objects (either simple or complex). Builder returns the product as a final step, but as far as the Abstract Factory is concerned, the product gets returned immediately.
But to the client isn't it the same thing? He gets the full object once it's built, so to him there is no added functionality.
The only way I see it is as a way or organizing the constructor code in steps, to force a structure for the implementation of the builders. Which is nice, but hardly a great step from the abstract factory.
This next bit from Wikipedia is a good reference to get to my point:
Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.
If that's so, what kind of complexity would have to be introduced in your system where you would change from a Abstract Factory to a Builder?
My point is that I can't find and example where it's clear that an Abstract Factory won't suffice and you would need a Builder instead.
The AbstractFactory is for a family of related products. The Builder is for one product.
The Builder is for building a complex product step by step, while the AbstractFactory is to build in an abstract way (that is, once for several implementations) a less complex product.
Examples of what the difference means to the calling code:
To the client code using an AbstractFactory, each method call builds one object. The client has to assemble them together. On the other side, a builder would assemble them internally, and deliver the full object graph as the last step of the building.
The builder allow to pass and check parameters one by one for the client code. But he may build the final product in one step (for example, a call to a constructor, passing in all parameters at once, even sophisticated ones that have been build themselves). So the product of a builder could be an immutable object (or graph of) (which is priceless in multi-threaded environment, for performance and memory reasons).
UPDATED in response to this comment :
Lino > It's still bothering me, though :). I mean, if you are building composite objects, and you take the director out, passing the responsibility of calling the builder methods to the clients, then it works for me. Only then the builder would seem a perfect fit. But with the director, it doens't seem like much...
Precisely, the Builder has no director, it lets each client create a complex product according to it's specific needs. The client is the director, because the director's implementation is not reused.
If you need to reuse a few times a complex building process, then you can have a method to encapsulate this (and this method is your "director").
On the contrary, for the AbstractFactory, you typically need a reusable Director, that create products alike (provided with a Factory implementation).
Some very good answers here already. I'm just offering an analogy.
Say you wanted a new desk for your new office. You go to a 'factory' and see selections then pick one of the shelf. If it fits your needs, great!
Now you have a larger office with really fancy shaped walls. Now you need a desk with the top shaped to fit your office. And you want a different legs to suit the rest of the furniture and also to fit your new Aeron chair.
You go back to the same factory, no luck. You go to a carpenter who can custom 'build' what you want. You give your specs and requirements and the 'builder' will tell you certain limitations. After a few iteration, you got the perfect desk!
Ok, a lame story but just to lighten things up :P
One good example where you'd want a builder is if you were building something piece by piece based on command line arguments. For example, consider a builder with methods like...
setName()
setType()
setOption()
A builder could also be combined with an abstract factory where the director asks the factory for a concrete product. Again, this could be done with just a factory pattern by passing the args list to the factory but what if the args were instead messages coming from a server or a client.
Sometimes the aesthetics of one pattern just fit nicer than the aesthetics of the other.
Builder is useful for configuration. Abstract Factory is useful when you don't want callers to care about the actual implementation. Two different purposes.
You could, in fact, mix the two patterns. For example Java's DocumentBuilderFactory is a classic abstract factory: if you read the docs, you'll see the process that it uses to pick an implementation. However, the DocumentBuilders that it produces can be configured afterward (although they don't follow the prototypical "builder" approach of having each configuration method return the object being configured).
Builder is an inversion of control, like the Template Method Pattern. The various functions on your concrete builder are customizable steps in a process. Abstract Factory is "just" polymorphism, where the output happens to be a newly-constructed object. The various functions on a concrete factory are different customizable processes, each presumably resulting in a different object.
So, you need a builder when you need there to be a common overall "plot" for constructing your objects, but with individual "scenes" within that plot being different. You need a factory when there is not necessarily anything at all in common between different implementations.
I think you could conceivably use both at once, with the Abstract Factory acting as the director in the Builder pattern, and each concrete factory directing things differently. However, that goes beyond the "napkin" limit for UML diagrams ;-)
I use an Abstract Factory when I will need to build multiple child factories to create different types of objects. These child factories all implement or extend the Abstract Factory. I use a Builder when there's only one type of object that needs to be built.
I'm not sure if this is the correct usage, but it is how I've seen it done, and how I've done it in the past.
Let's consider an analogy.
You're at a Fast Food chain, where the fast food you actually get is quite complex. Not only is it complex, but only certain people can take your order for certain types of food. Now, you don't know that, because the manager of the store decided to put one person behind one cash register. But if you look at him carefully, it's actually an advanced hologram because it's "abstract". An abstract order taker. Now, when you talk to the hologram, and place your order, the hologram computer reroutes (polymorphism) that order to an implant in the brain of a human order taker. The implant makes the human actually punch in the order to a real register. There are few of these "concrete" mind-controlled human beings being ordered about by the hologram. Now, when the real human being punches in the order, it get's sent to a computer in the back where there's an assembly line, or a "builder", for each type of food being built. Orders are sent to different kinds of assembly lines based on the human being and his cash register.
So, the hologram is the abstract factory, the mind-controlled humans at the registers are the concrete factories, and the assembly lines are the builders. This is a way you can actually visualize the flow of an abstract factory working WITH the builder pattern. Sometimes it's best to see how design patterns work together in order to see how they're different.
If you're looking for extra credit, try implementing this with generics. It doesn't require as much code as you might think.
For more information on when to use the Builder Pattern and its advantages you should check out my post for another similar question here
In practice, you'll probably use DI + IOC in order to do what a builder used to do. FYI.
Good answers, would like to add mine in the hopes I discover that my understanding is correct.
If you have a new office, and only need new desks, you would use a Builder. A desk will always be a desk, but there are many different configurations for a desk, i.e., size, shape, presence of a hutch, drawers, etc.
If you have a new office, and the inside is completely bare, you would need various objects and would use an Abstract Factory that creates Furniture, from which our Desk descends. In this case, Desk as we know is a "complex" object, so it uses the Builder pattern, but here it is part of a directing Abstract Factory. The Abstract Factory would also create simple objects, like very specific lamps (StraightFunkyLamp), via a StraightFunkyLampFactory class.

Class member order in source code

This has been asked before (question no. 308581), but that particular question and the answers are a bit C++ specific and a lot of things there are not really relevant in languages like Java or C#.
The thing is, that even after refactorization, I find that there is a bit of mess in my source code files. I mean, the function bodies are alright, but I'm not quite happy with the way the functions themselves are ordered. Of course, in an IDE like Visual Studio it is relatively easy to find a member if you remember how it is called, but this is not always the case.
I've tried a couple of approaches like putting public methods first but that the drawback of this approach is that a function at the top of the file ends up calling an other private function at the bottom of the file so I end up scrolling all the time.
Another approach is to try to group related methods together (maybe into regions) but obviously this has its limits as if there are many non-related methods in the same class then maybe it's time to break up the class to two or more smaller classes.
So consider this: your code has been refactored properly so that it satisfies all the requirements mentioned in Code Complete, but you would still like to reorder your methods for ergonomic purposes. What's your approach?
(Actually, while not exactly a technical problem, this is problem really annoys the hell out of me so I would be really grateful if someone could come up with a good approach)
Actually I totally rely on the navigation functionality of my IDE, i.e. Visual Studio. Most of the time I use F12 to jump to the declaration (or Shift-F12 to find all references) and the Ctrl+- to jump back.
The reason for that is that most of the time I am working on code that I haven't written myself and I don't want to spend my time re-ordering methods and fields.
P.S.: And I also use RockScroll, a VS add-in which makes navigating and scrolling large files quite easy
If you're really having problems scrolling and finding, it's possible you're suffering from god class syndrome.
Fwiw, I personally tend to go with:
class
{
#statics (if any)
#constructor
#destructor (if any)
#member variables
#properties (if any)
#public methods (overrides, etc, first then extensions)
#private (aka helper) methods (if any)
}
And I have no aversion to region blocks, nor comments, so make free use of both to denote relationships.
From my (Java) point of view I would say constructors, public methods, private methods, in that order. I always try to group methods implementing a certain interface together.
My favorite weapon of choice is IntelliJ IDEA, which has some nice possibilities to fold methods bodies so it is quite easy to display two methods directly above each other even when their actual position in the source file is 700 lines apart.
I would be careful with monkeying around with the position of methods in the actual source. Your IDE should give you the ability to view the source in the way you want. This is especially relevant when working on a project where developers can use their IDE of choice.
My order, here it comes.
I usually put statics first.
Next come member variables and properties, a property that accesses one specific member is grouped together with this member. I try to group related information together, for example all strings that contain path information.
Third is the constructor (or constructors if you have several).
After that follow the methods. Those are ordered by whatever appears logical for that specific class. I often group methods by their access level: private, protected, public. But I recently had a class that needed to override a lot of methods from its base class. Since I was doing a lot of work there, I put them together in one group, regardless of their access level.
My recommendation: Order your classes so that it helps your workflow. Do not simply order them, just to have order. The time spent on ordering should be an investment that helps you save more time that you would otherwise need to scroll up and down.
In C# I use #region to seperate those groups from each other, but that is a matter of taste. There are a lot of people who don't like regions. I do.
I place the most recent method I just created on top of the class. That way when I open the project, I'm back at the last method I'm developing. Easier for me to get back "in the zone."
It also reflected the fact that the method(which uses other methods) I just created is the topmost layer of other methods.
Group related functions together, don't be hard-pressed to put all private functions at the bottom. Likewise, imitate the design rationale of C#'s properties, related functions should be in close proximity to each other, the C# language construct for properties reinforces that idea.
P.S.
If only C# can nest functions like Pascal or Delphi. Maybe Anders Hejlsberg can put it in C#, he also invented Turbo Pascal and Delphi :-) D language has nested functions.
A few years ago I spent far too much time pondering this question, and came up with a horrendously complex system for ordering the declarations within a class. The order would depend on the access specifier, whether a method or field was static, transient, volatile etc.
It wasn't worth it. IMHO you get no real benefit from such a complex arrangement.
What I do nowadays is much simpler:
Constructors (default constructor first, otherwise order doesn't matter.)
Methods, sorted by name (static vs. non-static doesn't matter, nor abstract vs. concrete, virtual vs. final etc.)
Inner classes, sorted by name (interface vs. class etc. doesn't matter)
Fields, sorted by name (static vs. non-static doesn't matter.) Optionally constants (public static final) first, but this is not essential.
i pretty sure there was a visual studio addin that could re-order the class members in the code.
so i.e. ctors on the top of the class then static methods then instance methods...
something like that
unfortunately i can't remember the name of this addin! i also think that this addin was for free!
maybe someone other can help us out?
My personal take for structuring a class is as follows:
I'm strict with
constants and static fields first, in alpha order
non-private inner classes and enums in alpha order
fields (and attributes where applicable), in alpha order
ctors (and dtors where applicable)
static methods and factory methods
methods below, in alpha order, regardless of visibility.
I use the auto-formatting capabilities of an IDE at all times. So I'm constantly hitting Ctrl+Shift+F when I'm working. I export auto-formatting capabilities in an xml file which I carry with me everywhere.
It helps down the lane when doing merges and rebases. And it is the type of thing you can automate in your IDE or build process so that you don't have to make a brain cell sweat for it.
I'm not claiming MY WAY is the way. But pick something, configure it, use it consistently until it becomes a reflex, and thus forget about it.