Archive for the ‘oop’ Tag

Martin Fowler is a Regular Guy

I didn’t think that before I met him, as brief of an encounter as it was. After all, he’s the author of Refactoring, Patterns of Enterprise Application Architecture and UML Distilled. He’s helped set the course of XP/Agile and regularly refers to my personal software hero, Kent Beck, as just “Kent”. Martin Fowler is respected, experienced and his name is dropped in regular software parlance to justify, or condemn, a given practice.

But – he’s still a regular guy. A software engineer. A developer. A coder. Here is why.

I attended a “Friends and Family” ThoughtWorks event at their headquarters in Chicago. The ThoughtWorks office is on the 25th floor of the ever imposing Aon Center building, which as some know, is a twin to the now gone World Trade Center buildings in New York City.

Their office space is designed to do two things: 1) induce violent jealousy of cube workers, and 2) show that they are hip coders and like Ruby. Since ThoughtWorks is a consultancy no one is ever there though. And if they are, you wonder what is wrong with them. However, they get to wear Puma’s, hoodies and generally expensive (a.k.a. designer) jeans. I wear “slacks”.

I attended a TW event before, so I had a general idea of the flow. For instance, I knew they would have some pizza so I didn’t cram my lunch in before I left. I also knew there would be mingling which I was ready for this time. I expected to schmooze with some developers at the CME or some random interactive shop.  Instead, there he was – Martin Fowler – just walking along. So I engaged him and it went something like this:

Me: “I love your books. I live by Refactoring.” (I’m a fanboy.)
Fowler: “Thank you.” (What else could he say?)
Me: “What are you thinking about nowadays? Like today? What’s on your mind?”
Fowler: “Well, really, I have a problem with my website and I need to fix it. But I have to be here as well. It’s small, but it’s bothering me.”
Me: “Your website?”
Fowler: “Yes, there is a style issue.”
Me: “On your site?”
Fowler: “It’s minor, probably just CSS really.”
Me: “But annoying?”
Fowler: “Frustrating, yes.”
Me: “So, let me get this right, Martin Fowler is concerned about CSS on his website. So, in that way you’re like all the other software engineers here leaving some problem behind at their desk to be here…”
Fowler: “Very much, except, I don’t do any real work besides writing and talking.”

And so it came and went.  I didn’t occupy him much longer with additional inane questions and politely excused myself so he could do his expected mingling with the crowd.  After all, even though there was a panel, most people were probably there for him.  Like me.  I paid 8 bucks to take a cab across the Loop to see him and I hoped that shaking his hand would impart some type of wisdom via osmosis to my software skills.

So, he’s just a regular guy.  I’m probably not that different in circumstances than him when he really started rolling in the 90’s.  He has great ideas and the ability to make complex problems simple.  But, at the end of the day, little things like CSS still weigh on him; a web page not displaying correctly or a function not being optimum.  Stuff that software engineers are concerned about.  Like me and like him.

Refactoring Quickly with TDD

The situation. I have a class, Edc, that has an interface:

IEdcFinder

It needs to be composed with one of a few data lookup methods. Like a method connecting to SQL or a method connecting to XML.  I don’t want the caller to have to configure this finder object with the data method.  I’d like to make it easier.  Especially since this finder object is already being injected into another class as a pluggable object.

So, logically, move the construction of the finder to a factory method and compose the data method with it then.  I created a Factory class:

class EdcFinderFactory

But then, we have another class doing work.  So, with TDD, I switched the interface to an abstract class thinking I could use inheritance to mark all subclasses with a private constructor as well – and made the tests pass.  Good.

I was feeling OK about how things were going, but not thrilled.  I had working code but something smelled.  I realized something: there is only one class implementing IEdcFinder and that is EdcFinder.  Let’s remove duplication.

Remove: EdcFinderFactory
Remove: IEdc

(There were actually many small steps in here making sure the system still passed.)

Left with:

EdcFinder
public EdcFinder(){..}
public Create(){…inside here we create an EdcFinder composed with IReadSomeData}

So, EdcFinder became a simple concrete class with it’s public constructor and the factory method.  And, as always, I ran the tests: Pass.  Then the constructor was marked private. Pass.  Remove the old abstract class (which was an interface to start with).

Now there was less code, less interfaces and easier to read code.  I was able to implement the “Replace Constructor with Factory Method” refactoring in just minutes and I know everything still works.

With TDD and my test suites I could change with out fear.

And two days later, I looked again  and removed this entire class realizing it was unnecessary and the data method could be simplified with Func<T>.  I switched everything in about an hour. Red, Green, Refactor.

Bon.

Ajax and the Service Gateway Pattern

Introduction

It is easy to forecast how many widgets you can ship when you are creating them in the factory behind your office. It is another story when those widgets are being created in another factory that you do not own. You are now a customer of your distributor, but as a market economy would dictate, your customer’s do not care where the product comes from. They just want to know if you have it in stock, and if you do not, they would like to know how soon you will have it. Any company that ships a product that they do not produce themselves runs into this problem consistently, and often enough you will need to connect you systems to your distributors to get a virtual inventory to keep your customer happy.

The Problem of Real-Time Inventory

Let us call our fictitious company Alpha Parts. They sell computer paraphernali, thousands of items like printers and mice and laptops, and procure their inventory from the following five warehouses: MicroBell, JME, DataTech, Xenns and LargeDeutsche.

Now, as simple as this model seems from a business perspective (maybe it is more complicated than I think) it poses a very interesting technical challenge in order to display product availability on the Alpha Parts website of items that have not physically entered their inventory. How do we know how many Cannon X15 printers MicroBell has? Or the amount of Microsoft Explorer mice that is in the Xenns warehouse?

Alpha Parts could request daily files of inventory availability from their partners, but that data could become stale in minutes. It turns out that each of these partner warehouses has XML web services that can be called individually via HTTP. Now, Alpha Parts need has an interface into individual product inventory per warehouse, but needs to turn that data into a usable system that aggregates and gives meaning to these numbers to their customers.

And here lies the problem: Real time on the web. We have the following challenges: multiple long running real time method calls to a third-party service over the internet, displaying results that return at different times and handling unresponsive services.

Solution

One of the lead engineers at Alpha Parts proposes solving these challenges by using the Service Gateway pattern in the middle tier and an ASP.NET compatible Ajax component on the front end. Let us take a look at the Service Gateway.

The Service Gateway pattern is a repeatable design that “encapsulates the details of connecting to the source and performing any necessary translation.” Here is a logical overview of the pattern.

Figure 1

The web application sends its request to the Gateway. The Gateway is then responsible for translating the request into the proper format to send to the External Service. After the response comes back from the external service it is returned to the gateway where it is then translated back into a representation that the application understands. It is also at this point where the gateway can use the persistence layer for storage or retrieval of data.

The next figure is a UML breakdown of the gateway layer.

Figure 2

Class Breakdown

Gateway – responsible for providing coordination and translation for calling the external service

PartnerInventory – object that describes products availability at a particular vendor

PartnerInventoryCollection – object representing a collection of PartnerInventory objects

RealTimeInventoryAccess – this is an existing class that handles the actual post to the services

GatewayPersistence – responsible for persisting and retrieving data from cache or the database – this could also be used to perform an algorithm to decide what stock results are active enough to stay in memory cache and which should persist to the database

GatewayDataAccess – responsible for physically persisting and retrieving data to the database

The pattern is straightforward enough and only really gets complicated depending on the extent of logic that is desired in the persistence layer.

Each time a method is invoked from the Gateway to RealTimeInventoryAccess (and hence, the external service itself) it will be done with an asynchronous method. The following figure shows the idea behind this, not the exact code.

Listing 1

ThirdPartyInventoryDelegate third =
new ThirdPartyInventoryDelegate(RealTimeInventoryAccess.GetInventoryByVendorsAndItemsCode);
IAsynchResult synchResult =
 third.Invoke(parameter, new AsychCallback(method), third);
synchResult.AsynchWaitHandle.WaitOne(time, true);

The Alpha Parts engineers want to ensure that the web application continues processing while the web services are being called; so they propose calling each web service asynchronously in order to return information to the Gateway object as the services returns. This way they can be run through the persistence layer sooner. Each asynchronous method call is also done with a timeout value in order to prevent the HTTP post from waiting on the default timeout which could be too long (notice the WaitOne in the above listing). This will also enforce our own time limits for those remote method calls.

Being as such, if a method was called at 8:00:01 AM and method two was invoked right after that, if the first service call took longer to return, the second call could already be done processing the service XML and have handed the data back to the Gateway for the persistence layer. It basically allows the multiple calls to return on their own time and not queue up behind each other so that there are not wasted cycles.

The Ajax capable front end is another key facet to this design coming to life.

Alpha Parts can use an Ajax component, like ComponentArt’s CallBack. This control allows you to dynamically refresh an HTML region with JavaScript, but control it all from the ASP.NET server side code. This is a great benefit because it means they would not have to write their own JavaScript. A third party control also ensures that it has been tested, debugged and run on multiple platforms and browsers.

When a product page loads on the Alpha Parts website, the full page will load except for the real time html region. The CallBack component will call the page class which will check with the Gateway and its persistence engine to see if there is current inventory information available. If it is available, those objects are returned to the page and bound to the CallBack control. If they are not available from persistence, they are sent out to the external service(s) and the CallBack control will display a “loading” icon. The user is then free to use the rest of the page and as soon as the Service Gateway is done with its work its return objects will be bound to the CallBack control.

Conclusion

In this way, the middle tier will be working asynchronously to retrieve inventory information from multiple services and the web application will work asynchronously to display the data it will have to occasionally wait for.

References

Jim Tyhurst, Services That Reach from the Inside Out. Dr Dobbs Architecture and Design World 2006

Not All Interfaces Are Built the Same

In my last article I described using composition in the design of an object based system. In that article I included a simplified UML class diagram of some work I did to a fictitious Product object to display the use of composition. Please see Figure 1 below. At the top of that diagram sits the class ProductBase. It is an abstract class (a class that has abstract methods and cannot be instantiated). But why is it abstract?

Figure 1 – Product UML

Let us first ask what could the class be marked as if it were not an abstract class? Here, there are two options. One, it could be a concrete class and two, it could be an interface. Let us look at the concrete class first.

A concrete class is any class that is not abstract; it is just a class. The following code snippet contains a concrete class followed by an abstract class.

Listing 1 – Concrete and Abstract

public class StockStatus
 {}

public abstract class ProductBase
 {
   abstract public StockStatus InventoryStatus{get;};
 }

When a class is concrete that means the only way to extend the class is by inheriting from it. That is often referred to as implementation inheritance or class inheritance because you are in essence inheriting all of the code and logic that went into the base class. That is not something I wanted to do with the Product object because it blows up encapsulation and is very inflexible.

The second option was to use an interface. Here, we would define an interface and then have ProductBase implement that interface. In the future, we could then substitute any class that implemented the interface.

Listing 2 – Using an interface

public interface IProduct
 {
   int GetNumberInStock();
 }
public class ProductBase : IProduct
 {
    public int GetNumberInStock()
    {
       return 3;
    }
}

In my first go around, this is basically what I had. Of course, that is why design reviews are important. It was pointed out by a coworker during a review that using an interface in this instance does not buy you anything more than using an abstract class, and if an abstract class were in fact used, we could mix in a little bit of implementation. Sounds good right? At first I did not like it at all.

“That breaks encapsulation!” I bellowed across the table, and let it reverberate off the walls and deaf ears. No one wanted to hear it. Why? Because using an abstract class here was simply a better design decision.

In this instance, a Product, no matter how many times subclassed, is a product. It has properties and some core methods. So in our abstract class we defined all of our entity properties implementation but left the “Load” (of data) methods as abstract so that the implementing class could define those. It ended up as an unintentional use of the template method, which is a good side effect of paying attention to your design. I believe that the decision is a mix of the best of both worlds.

Summary

We now have a good abstract class, which behaves as a well defined interface, plus when it comes time to substitute in another class of the same type, we have a lot of the plumbing already there. If we had used an interface it would mean we would have to rewrite a lot more code. This minimized our code creation and maintenance, but still keeps us in good object hierarchy.

Wait…Compose Yourself First

Introduction
This should often be the case: Your coworker will not let you go into a presentation when you are emotional or livid about something. They tell you to pull yourself together first; compose yourself and compose your objects that I say.

Of course, I am not the only one. If you are familiar with our friends, the Gang of Four, you have already heard this mind-bending concept. Make your objects connect to each other via well defined interfaces and hide their implementation. This is a sound, modern software practice. In fact, I just spent four days this past summer listing to speakers take composition for granted at the architectural level. They were assuming (not all of them of course) that composition and abstraction is a skill that is taken for granted by most developers. We know, being the folks in the trenches, that this is not always the case.

Favor Composition

Let us look at some simple composition here and discuss what the big deal is all about. To start, here are what I believe to be the three most important and beneficial things about using composition.

- Black Box design (where inheritance is white box design)
- Does not break encapsulation
- Relationships can be defined at runtime

Black box design means that the client using the object does not know the internal operations. This is in contrast to inheritance, where the class often knows the internals of its super class. Not breaking encapsulation is as good a reason to use composition as any. After all, encapsulation of operations and data is one of the main reasons to use object orientation. And lastly, “relationships can be defined at runtime” means that other objects can be plugged into, or composed with, other objects while the program is executing. This is a common use of the Strategy pattern, where an algorithm is set to the class at runtime.

Looking at an Example of Composition

Below, you will see a snapshot of part of a fictitious product component. ProductBase is composed of StockStatus, which in turn is composed of PurchaseOrderLine and IRunRate. Here, StockStatus does not know about the implementation of IRunRate, it only knows IRunRates interface. Here, we can then substitute any other object of type IRunRate into StockStatus and it would be none the wiser. You could of course, change behavior by having StockStatus be aware of its algorithms and change depending on what it is composed of – but that is not taking advantage of composition.

Figure 1 – UML Diagram

PurchaseOrderLine is the next object. Although StockStatus is not connected to an abstract class or “interface” type, the public methods and properties of PurchaseOrderLine make up its interface. So, again, StockStatus only knows about a well defined interface.
Conclusion

It is important to look at your design and try to understand the moving parts. These will let you know what the system will be composed of. In my next article, I will talk more about identifying the objects that make up your system, as well as why this design used an abstract class at its base and built upon it with composition.