OOP Lessons Learnt Archives - Anuj Varma, Hands-On Technology Architect, Clean Air Activist https://www.anujvarma.com/category/technology/languages-platforms-object-oriented-observations/object-oriented-software/ Production Grade Technical Solutions | Data Encryption and Public Cloud Expert Thu, 27 Aug 2020 15:06:39 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://www.anujvarma.com/wp-content/uploads/anujtech.png OOP Lessons Learnt Archives - Anuj Varma, Hands-On Technology Architect, Clean Air Activist https://www.anujvarma.com/category/technology/languages-platforms-object-oriented-observations/object-oriented-software/ 32 32 Abstract Factory Pattern vs. Dependency Injection https://www.anujvarma.com/abstract-factory-pattern-vs-di/ https://www.anujvarma.com/abstract-factory-pattern-vs-di/#respond Tue, 19 Jun 2018 21:17:59 +0000 http://www.anujvarma.com/?p=5326 This is a frequent misunderstanding – Why use Dependency Injection when you can ask a factory for your object and have it returned to you? The answer is that DI […]

The post Abstract Factory Pattern vs. Dependency Injection appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
This is a frequent misunderstanding – Why use Dependency Injection when you can ask a factory for your object and have it returned to you?

The answer is that DI does more than just create an object for you. It enables you to delegate the construction of the object, while also preserving information about the type you are trying to create. This is ideal because when you write a test around your class, you can pass in Mock Objects as easily as real objects.

Dependency Injection

Passing in the object that a method  needs as an argument (IAccount account). This way, mock objects could be passed in as easily as real objects.

void CheckingAcct(IAccount account) 
{ 
 account.Open(); 
}

static void Main()
{
     IAccount acct = AccountFactory.CreateAccount();    
     acct.Open();
}

Abstract Factory

void CheckingAccount() // example #1 – Difficult to do mock objects because there is no idea of what the method needs
{
    IAccount acct = AccountFactory.CreateAccount();
    acct.Open();
}

void CheckingAccount(IAccountFactory acctFactory) // example #2 – There is SOME idea of what the method needs, but is not ideal
{
    IAccount acct = acctFactory.CreateAccount();
    acct.Open();
}

Summary

An abstract factory can be used in conjunction with D.I. as shown above. D.I. serves a different purpose and is the chosen method of delineating object creation from actual object usage. This has several advantages in addition to the mock unit testing example shown above. 

The post Abstract Factory Pattern vs. Dependency Injection appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/abstract-factory-pattern-vs-di/feed/ 0
Publish Subscribe Pattern in C# and some gotchas https://www.anujvarma.com/publish-subscribe-pattern-in-c-and-some-gotchas/ https://www.anujvarma.com/publish-subscribe-pattern-in-c-and-some-gotchas/#respond Wed, 17 May 2017 22:27:21 +0000 http://www.anujvarma.com/?p=4710 The eventing mechanism built into the .NET runtime makes it a piece of cake to implement a simple publisher – subscriber pattern (C# code follows). public class EmployerPublisher { public […]

The post Publish Subscribe Pattern in C# and some gotchas appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
The eventing mechanism built into the .NET runtime makes it a piece of cake to implement a simple publisher – subscriber pattern (C# code follows).

public class EmployerPublisher
{
   public event  PayrollArrivedHandler PayrollArrived;
   public void FireEvent(DateTime today)
   {
     if(PayrollArrived != null) 
         PayrollArrived(today);
   }
}

// Subscriber class - Employee
public class Employee 
{
  public void OnPayrollArrival(DateTime day)
  { // Round up from friends and go spend the money!
  }
}

// Hooking up the publisher and subscriber(s) in the client code
EmpoyerPublisher publisher = new EmployerPublisher();
Employee employee1 = new Employee();
Employee employee2 = new Employee();
publisher.PayrollArrived += employee1.OnPayrollArrival;
publisher.PayrollArrived += employee2.OnPayrollArrival;

// Now that the subscribers are hooked up, the event can be fired

 

DateTime now = DateTime.Now;publisher.FireEvent(now.date);

However – there are a couple of gotchas to watch out for:

  1. When multiple subscribers are present – how do you ensure that the publisher does not get blocked – i.e. – will each subscriber be well-behaved enough to only perform short tasks?
  2. What if a subscriber is added while notification is in progress – i.e. – a list of subscribers is being notified – and a new subscriber happens to come along (this is not a rare event – especially if any one of the subscribers happens to contain time-consuming code – i.e. is badly behaved.

Let us look at these one by one:

Problem 1 – The badly-behaved (subscriber) problem

The well-behaved problem is best solved by working under the assumption that all subscribers will be badly behaved! So what is a publisher to do? One solution is to launch each notification on a new thread – that way even if a subscriber is badly behaved – it does not tie down the notification of other subscribers. Since the CLR in .NET provides a ready-made thread-pool, this is a seemingly simple solution. In fact, all one needs to do is use the built in support for asynchronous delegates (the event defined in the publisher class is really just a delegate). How would this look?


We are almost there. The only problem with the above code is a c# restriction – if you want to call BeginInvoke, your delegate (our event) can only have one target.

public class EmployerPublisher
  { 
    public event  PayrollArrivedHandler PayrollArrived // This event firing is synchronous - i.e. the publisher instance is tied down until the subscriber finishes processing 
   OnPayrollArrivalpublic void FireEvent(DateTime today) 
    { 
        if(PayrollArrived != null) 
           PayrollArrived(today); 
     }
   // This is an asynchronous version of the same event-firing - just fire it - and do not worry about how long the subscriber takes - since subscriber processing 
   // is on a different thread. 

public void FireEventAsynchronous(DateTime today) 
  { 
     if(PayrollArrived != null) 
       PayrollArrived.BeginInvoke(today, null, null); 
  }
}
Problem 1 (the badly-behaved subscriber problem) is essentially taken care of - by letting the subscribers stay badly behaved - we just don't care - we've still managed to notify all the subscribers successfully. 
Problem 2 : A subscriber is added while notification is in progress
This is a slightly trickier problem to solve. We still want to allow the new subscriber to add itself - but we do not want to interfere with the current notification process.
 This solution is borrowed from Holub on Patterns - and works well in our scenario as well. The basic idea is that instead of having just ANY collection of subscribers - use a linked list to store subscribers.
Notification of the list of subscribers boils down to traversing the linked lists one node at a time. Say you are on some intermediate node - and a new subscriber arrives. Simply add the new subscriber (as a node) to the head of the list!
The head of the list is not affected by where the traversal’s current pointer is. This way - it doesn't interfere with the existing notification process - and is successfully added to the list of subscribers whenever the next notification comes around.

The post Publish Subscribe Pattern in C# and some gotchas appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/publish-subscribe-pattern-in-c-and-some-gotchas/feed/ 0
Static classes versus regular classes https://www.anujvarma.com/instance-state-versus/ https://www.anujvarma.com/instance-state-versus/#respond Wed, 22 Feb 2017 00:49:01 +0000 http://www.anujvarma.com/?p=4531 What is a static class? How is it different from an object? A class in which everything (all fields and methods) is static is equivalent to an object. It has […]

The post Static classes versus regular classes appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
What is a static class? How is it different from an object?

A class in which everything (all fields and methods) is static is equivalent to an object. It has state and behavior. However – such an ‘object’ may not work – since everything about the object needs to be known at compile time. For e.g. – if the type of O.S. was one of the fields, it would need to be determined at runtime.

Why not just make every class static?

The strength of OO programming is in the fact that each instance of a given class can contain different data/behavior than another instance.  The only way to maintain state is to instantiate regular (non static) classes.

The post Static classes versus regular classes appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/instance-state-versus/feed/ 0
Component based design versus Object oriented design https://www.anujvarma.com/component-based-design-versus-object-oriented-design/ https://www.anujvarma.com/component-based-design-versus-object-oriented-design/#respond Thu, 15 Jan 2015 16:24:31 +0000 http://www.anujvarma.com/?p=2806 Object oriented design starts with either an inheritance hierarchy or an interface based design. Component based design also uses Object oriented concepts, but instead of inheritance (or interfaces), utilizes object […]

The post Component based design versus Object oriented design appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
Object oriented design starts with either an inheritance hierarchy or an interface based design. Component based design also uses Object oriented concepts, but instead of inheritance (or interfaces), utilizes object composition.

The post Component based design versus Object oriented design appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/component-based-design-versus-object-oriented-design/feed/ 0
A flexible service oriented architecture that handles multiple platforms (multiple devices, multiple databases…) https://www.anujvarma.com/a-flexible-service-oriented-architecture-that-handles-multiple-platforms-multiple-devices-multiple-databases/ https://www.anujvarma.com/a-flexible-service-oriented-architecture-that-handles-multiple-platforms-multiple-devices-multiple-databases/#respond Tue, 24 Apr 2012 18:57:15 +0000 http://www.anujvarma.com/a-flexible-service-oriented-architecture-that-handles-multiple-platforms-multiple-devices-multiple-databases/ The Problem Statement Imagine that you have just built a sophisticated application to work against a SQL Server database. You followed a best-practices approach and separated out your presentation, business […]

The post A flexible service oriented architecture that handles multiple platforms (multiple devices, multiple databases…) appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
The Problem Statement

Imagine that you have just built a sophisticated application to work against a SQL Server database. You followed a best-practices approach and separated out your presentation, business logic and data access layer. Your application is service oriented – and exposes a set of services to the outside world. For e.g. – your application offers an Account Service and a Security Service for consumption by the outside world.

  1. Now – you are told that this application needs to work against not just SQL Server – but Oracle as well.
  2. However, the services (AccountService, SecurityService) – will be somewhat different for the Oracle version. 
  3. While the services may be different, a lot of the functionality between the platforms will be similar.
  4. In addition, your design must be flexible (extensible). If more database platforms were added down the road – or more services to go along with the AccountService and the SecurityServices, the design should accommodate these with minimal changes.

This can be summarized as supporting multiple services for multiple platforms (these platforms do not have to be multiple databases – can be multiple OSes, multiple device platforms –e.g. Mobile and Desktop).   One of the key issues that this design presents is that of code commonality –  and code differentiation. Some of the code for the multiple platforms may be common to both the platforms. Example – when the AccountService creates an Account, there may be exception handling code that is common to both Oracle and SqlServer. In addition – a good deal of code would be completely unique to each platform – so – a SQLServer account creation would use SQLServer authentication whereas an Oracle account creation would use Oracle specific authentication.

This article presents an architecture to solve both of the problems above (keeping common code as well as differentiation platform specific code) – and provides a full sample implementation. This implementation can be used for various problems that require accommodating multiple services and multiple platforms. The possibilities are limitless – and I have used this on at least 2 projects successfully.  It allows for extensibility by allowing more services to be added – as well as more platforms to be added down the road.

Starting Point – Make it simple for the client

What would a sample client need to do to invoke a sample platform-specific service ? Say – a client wanted to use the AccountService specific to SqlServer. The snippet below shows everything that a client should need to do – get a handle to the SqlServer factory. This factory is responsible for all SqlServer specific services – so getting an AccountService back from this factory should be as simple as a GetService call. The snippet below shows everything that a client should need to do.

Code Snippet
  1.  
  2. ServiceFactory.SqlServerServiceFactory sqlFactory = new ServiceFactory.SqlServerServiceFactory();
  3. IAccountService acctService = sqlFactory.GetService<IAccountService>();

An Introduction to the overall architecture

To model the various services (AccountService, SecurityService…), we notice firstly that these services are unrelated to each other. A prospective implementation could implement both the AccountService and the SecurityService.  This leads us to explore an interface based approach for the set of services.

Services by Feature (Account, Security) Architecture – An Interface Based Approach

Code Snippet
  1. interface IAccountService
  2.   {
  3.       void CreateAccount();
  4.   }

 

Code Snippet
  1. interface ISecurityService
  2.     {
  3.         void AuthenticateUser();
  4.     }

Services By Platform (SQLServer, Oracle…) Architecture – An Inheritance Based Approach

For the platform differentiation, we note that some of the code may be common to both platforms – for e.g. – error handling and exception logging from the AccountService would need to be identical for both Oracle and SqlServer. We use an inheritance based approach – which allows us to use a Template pattern. The template pattern would provide a template method – that consists of a) Common Code b) Platform Specific Code

Code Snippet
  1. public virtual void CreateAccount()
  2. {
  3.  
  4.     //  common code – example – Initialize
  5.     Console.WriteLine("Account Service: Common Initialization Code");
  6.  
  7.     // Platform specific code
  8.     SomePlatformSpecificOperation();
  9.  
  10.     // common code again – example – cleanup()…
  11.     Console.WriteLine("Account Service: Common Cleanup Code");
  12.  
  13. }
  14.  
  15. protected virtual void SomePlatformSpecificOperation()
  16. {
  17.     Console.WriteLine("Some BASE operation that is common to both ORACLE and SQLServer. This can be over-riddent in the child classes for PLATFORM speficic functionality");
  18. }

The Overall Architecture – using Inheritance for Platform Variation – and interfaces for services

services_architecture_object_model_thumb

 

The Service Factory

The only other component (apart from the interface based services and the inheritance based platforms) that we need is a service factory – one that will return the appropriate feature service (e.g. Account Service) – along with the appropriate platform (e.g. SqlServerAccountService).

Code Snippet
  1. interface IServiceFactory
  2.     {
  3.        T GetService<T>();
  4.     }

A simple dictionary is used to store the list of services (AccountService, SecurityService…) – and a lookup method is provided as shown below:

Code Snippet
  1. private IDictionary<string, object> allservices = new Dictionary<string, object>();
  2.  
  3. public T GetService<T>()
  4. {
  5.     object service = null;
  6.     T returnedService = (T)service;
  7.     string serviceName = typeof(T).FullName;
  8.     if (allservices.TryGetValue(serviceName, out service))
  9.     {
  10.         returnedService = (T)service;
  11.     }
  12.  
  13.     return returnedService;
  14.  
  15. }

Summary

Almost every app today follows a service oriented architecture which exposes multiple services. If our app was limited to just that, the above interface based approach coupled with our Service Factory (to return a specific service) would be all that is needed. However, today’s services are not just feature based – but also tend to support multiple platforms. These multiple platforms could be multiple databases (e.g. SQLServer and Oracle on the backend), multiple devices (e.g. Desktop and Mobile), multiple OSes etc.

This post provides a full object oriented implementation that supports multiple platforms along with multiple services (features). The multiple services were modeled using interfaces. Then, to account for the different platform implementations of each service, we defined an inheritance hierarchy – coupled with a template pattern to handle code commonality between the different platforms.

  This proves to be an elegant solution for a common, real-world problem in Object Oriented projects. There are a multitude of possible applications of the above architecture. 

Perhaps the greatest strength of the above architecture is the extensibility it provides. One can add new database platforms and new services down the road – with ease and minimal code changes.

NOTE: Ideally, you would want to design a Data Access Layer that was agnostic of the underlying database. This layer would generate all your SQL statements (CRUD) without caring about what the underlying database platform was. Such a database agnostic data access layer is described in an earlier post here.

Full Solution Download

Services_By_Platform_Architecture Download Solution

The post A flexible service oriented architecture that handles multiple platforms (multiple devices, multiple databases…) appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/a-flexible-service-oriented-architecture-that-handles-multiple-platforms-multiple-devices-multiple-databases/feed/ 0
Refactoring Interfaces– separating concerns https://www.anujvarma.com/refactoring-interfaces-separating-concerns/ https://www.anujvarma.com/refactoring-interfaces-separating-concerns/#respond Wed, 19 Oct 2011 20:40:11 +0000 http://www.anujvarma.com/?p=974 Interfaces are the starting point for designing any service oriented architecture – whether they be externally facing web services or internally facing local services. Hence, the correct design of interfaces […]

The post Refactoring Interfaces– separating concerns appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
Interfaces are the starting point for designing any service oriented architecture – whether they be externally facing web services or internally facing local services. Hence, the correct design of interfaces is an important step in achieving scalability down the road. Too often, when we see an interface class, it looks something like this (an example interface for an Account Service)….

interface IAccountServiceLargeInterface
  {
      // These are actions carried out by the user (account holder)
       void CreateAccount();
       void UpdateAccount();
       void DeleteAccount();
      //.....

      // These are actions carried out by the bank
       void BackupAccount();
       void InternalAuditAccount();
      //.....
  }

The Problem

The problem with this interface is that it has methods belonging to two different aspects of an account. The first three actions are those that an end user (Account Holder) would need to perform on the Account object. The next two are actions performed by the bank for internal bookkeeping. There is a clear distinction between these two aspects of an Account. Consider what happens if we leave these combined in the form shown above.  An ‘Account Management’ Application used internally by the bank  – and a ‘Web Based User Banking Application’ (which allows the creation, deletion etc. of Accounts), BOTH need to implement this common interface. When they have nothing (no functionality) in common.   This may seem trivial but it leads to maintainability problems down the road.

The Solution

An appropriate way of dealing with this is to simply break this interface up into two separate interfaces (one that captures all the user actions – and one that captures all the bank actions)

interface IAccountServiceUserActions
 {
     // These are actions carried out by the user (account holder)
     void CreateAccount();
     void UpdateAccount();
     void DeleteAccount();
 }
interface IAccountServiceBankActions
  {
      // These are actions carried out by the bank
      void BackupAccount();
      void InternalAuditAccount();
  }

Summary

A typical symptom of a poorly designed interface is the number of methods it contains. In general, if it has a dozen or so methods, chances are there are several different aspects rolled into one interface. It is an ideal candidate for refactoring. This helps avoid code maintainability issues down the road – and provides a better architecture for building multiple applications around the same domain object (Account class in our example above).

The post Refactoring Interfaces– separating concerns appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/refactoring-interfaces-separating-concerns/feed/ 0
Architecture for multiple services differentiated by Feature and by Platform https://www.anujvarma.com/architecture-for-multiple-services-differentiated-by-feature-and-by-platform/ https://www.anujvarma.com/architecture-for-multiple-services-differentiated-by-feature-and-by-platform/#respond Wed, 05 Oct 2011 22:32:53 +0000 http://www.anujvarma.com/?p=833 Say you have a set of services that your application (the server side) exposes. These could be categorized by feature: Account Service – contains methods for Creation, Deletion, Updating of […]

The post Architecture for multiple services differentiated by Feature and by Platform appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
Say you have a set of services that your application (the server side) exposes. These could be categorized by feature:

  • Account Service – contains methods for Creation, Deletion, Updating of Account Info
  • Security Service – contains methods for authenticating users, controlling access to objects etc.
  • Other Services….

In addition to having these ‘by feature’ services, your services also support multiple platforms (e.g. multiple devices (mobile versus desktop), multiple database platforms (oracle versus sqlserver)). For this article, we will assume that you are trying to support multiple devices – and are interested in a mobile version of each service as well as a desktop version of each service.

So – here is our problem statement. We need to accommodate:

  • Feature based variation (example Account Service, Security Service…)
  • Platform based variation (example Mobile service, Desktop Service…)
  • Possible Common Functionality between different platforms – Chances are, a good chunk of your service methods will be doing the same thing for each of the different platforms –and only doing a little bit of platform specific stuff.

Overview of Solution (full solution download available at the end)

We will use an interface based approach to model the various feature based services (since each feature based service is completely unrelated to the other) – and inheritance to model the platform specific services (since these share some amount of common code).

services_architecture_object_model

Client Code

It is always instructive to start with the Client Code. What the client has to do relates directly to how the service code is structured. The client needs to have:

a) Easy access multiple feature based services (Account, Security…).  All the client should need to say is GetService() – and it should have the correct service. A simple Service Factory can be used to accomplish this.

b) Easy access to specific platform based services.

Here is all a client should have to do:

class Client
   {
       static void Main(string[] args)
       {
           ServiceFactory.MobileServiceFactory mobileFactory = new ServiceFactory.MobileServiceFactory();
           IAccountService acctService = mobileFactory.GetService<IAccountService>();

           acctService.CreateAccount();
       }
   }

Feature Based Variation

We simply capture the set of feature based services in their own interface – IAccountService, ISecurityService…  For the client to get a handle to any of these services, we will use a simple ServiceFactory. All the client will need to do is say GetService()  – and it should be able to get the desired service back.

Platform Based Variation (with common functionality across platforms)

We use a combination of interface implementation and inheritance. We define an abstract base class which implements the feature specific interface. This base class will contain the common functionality (in the form of virtual methods). The child classes will contain the platform specific functionality. The common functionality may be spread out over different parts (see the example below) – where we have common code at the start of a method – and common code again toward the end of the method (or elsewhere). To account for this, we use a Template pattern as shown below.

Common Functionality

Problem: Common Code – Spread out over the method

public void CreateAccount()
{
      //  common code – e.g. initialization

      // Platform specific code – e.g. calculate resolution of UI
      // common code again – e.g. cleanup
}

Solution: Template Pattern to the rescue

This pattern simply defines a template method that contains all the spread out common code – and a method call to the Platform specific code. The Platform specific code is moved out to its own method.

public virtual void CreateAccount()
{

           //  common code - example - Initialize
           Console.WriteLine("Account Service: Common Initialize Code");

           // Platform specific code
           SomePlatformSpecificOperation(); // example - calculate resolution of UI

           // common code again - example - cleanup()...
           Console.WriteLine("Account Service: Common Cleanup Code");

 }
protected virtual void SomePlatformSpecificOperation()
{
   Console.WriteLine("Base: Platform specific operation");
}

Summary

To deal with the multiple features we followed an interface based approach – where each service exposed its own interface. Then, to account for the different platform implementations of each service, we defined an abstract class which implements the feature interface to start out. The particular platform specific code is defined in child classes which inherit from this base abstract class.  This proves to be an elegant solution for a common, real-world problem in Object Oriented projects. There are a multitude of possible applications of the above architecture. Almost every app today follows a service oriented architecture which exposes multiple services. If our app was limited to just that, the above interface based approach coupled with our Service Factory (to return a specific service) would be all that is needed. However, today’s services are not just feature based – but also tend to support multiple platforms.  These multiple platforms could be multiple databases (e.g. SQLServer and Oracle on the backend), multiple devices (e.g. Desktop and Mobile), multiple OSes  etc. 

NOTE: If your service needs to work against multiple database platforms on the backend (e.g. SQLServer and Oracle), ideally, you would want to design a Data Access Layer that was agnostic of the underlying database. This layer would generate all your SQL statements (CRUD) without caring about what the underlying database platform was. Such a database agnostic data access layer is described in an earlier post here.

The post Architecture for multiple services differentiated by Feature and by Platform appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/architecture-for-multiple-services-differentiated-by-feature-and-by-platform/feed/ 0
The most powerful pattern of all–The State Pattern (with C# source code) https://www.anujvarma.com/the-most-powerful-pattern-of-allthe-state-pattern/ https://www.anujvarma.com/the-most-powerful-pattern-of-allthe-state-pattern/#respond Thu, 29 Sep 2011 22:07:31 +0000 http://www.anujvarma.com/the-most-powerful-pattern-of-allthe-state-pattern/ If there was a pattern that could be used just about anywhere, in any situation – and still work, what would that pattern be? For me, the answer is the […]

The post The most powerful pattern of all–The State Pattern (with C# source code) appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
If there was a pattern that could be used just about anywhere, in any situation – and still work, what would that pattern be? For me, the answer is the State Pattern. Using a couple of simple modeling scenarios (modeling a Moving Car and modeling a Data Access Layer), I attempt to explain why this pattern is universally applicable.

Modeling a Moving Car

  1. Step 1: Identify all the States that your system can be in. For e.g. – if we are modeling a moving car , the possible states are Moving and Stopped.
  2. Step 2: Identify all the Events (aks actions) that can be taken by your object.  For e.g. – in our car example, the car can Speed up (Accelerate) or Slow Down (Brake).

That’s it! The hard part is over. Once you have identified the states and events as described in the two steps above, it is a matter of following the steps below to completely implement the State pattern.

Define an interface IState which contains the actions (that’s right – the actions (events), not the States! – The states will be the implementers of IState).

DEFINE YOUR EVENTS (Actions)

/// <summary>
/// Place all the possible 'events' in this interface. This will enforce all implementers to implement each event 
/// </summary>
interface IState
{
        void Accelerate();

        void Brake();
}

DEFINE YOUR STATES

Now define your two states – each as a class implementing the above interface. So, the two classes would be MovingState and StoppedState – each of which would have its own implementation of Accelerate and Brake

public class MovingState : IState 
{
       public void Accelerate()
       {
           // speed up the car
           Console.WriteLine("Going faster...");
       }

       public void Brake()
       {
           // slow down the car            
           Console.WriteLine("Slowing down...");

       }
}
public class StoppedState:IState 
{
       public void Accelerate()
       {
           // speed up the car
           Console.WriteLine("Speeding up...");

       }

       public void Brake()
       {
           // stop the car
           Console.WriteLine("Already Stopped..."); 
      }
} 

As you can see, each state has its own implementation of the two events Accelerate and Brake. That’s all there is to the  State Pattern.

SUMMARY

This (the State Pattern) is one of the most powerful patterns in that, it is universally applicable. Consider the example of modeling a DataAccessLayer where you are a) Connecting to a database and b) Fetching Data

Viola – you have your two events (Connect and FetchData). Now, you need to figure out your states. Since your data access layer sits between the database and the domain layer, these states could be – RetrievingData and PushingDataToDomainLayer. And all you have to do is use these events and states as described above – and you will have a full blown State Pattern implementation of your data access layer. Try implementing the State Pattern for any other modeling scenario – example flying a plane or baking cookies. You will find that it is equally applicable.

Download Solution

The post The most powerful pattern of all–The State Pattern (with C# source code) appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/the-most-powerful-pattern-of-allthe-state-pattern/feed/ 0
Command Pattern to the rescue https://www.anujvarma.com/command-pattern-to-the-rescue/ https://www.anujvarma.com/command-pattern-to-the-rescue/#respond Thu, 29 Sep 2011 20:24:58 +0000 http://www.anujvarma.com/command-pattern-to-the-rescue/ Recently, I was asked to take an existing library of methods (written in c#) that worked against a particular platform (say Oracle on the backend) and build an equivalent set […]

The post Command Pattern to the rescue appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
Recently, I was asked to take an existing library of methods (written in c#) that worked against a particular platform (say Oracle on the backend) and build an equivalent set to work against another platform (say SQLServer).  The methods were part of classes that implemented an interface – so for e.g. CheckUserCredentials would be a method inside a SecurityService class which implemented an interface (ISecurityService). I call this problem – the problem of having an existing set of services support multiple platforms (in our case SQL Server and Oracle, but the platforms could easily be ‘Mobile’ and ‘Desktop’).

Approach 1 : Create separate implementations for SqlServer and Oracle

The knee-jerk approach would be to say ‘A-Ha’ – we have an interface – All we need to do is make our SqlServer specific code implement that interface and we are done.  So – ‘knee jerk’ approach would be to create a class called SqlSecurityService (which implemented the same ISecurityService)  and have a similar OracleSecurityService. While this would have served our purpose, this isn’t our typical interface design problem. You typically use an interface based design to design services that aren’t related to each other. So – if we have a set of security services and a set of Account services, we can use an ISecurityService and an IAccountService interface to expose these separately. There isn’t any common factor between these services. An implementer has the choice of implementing any one or both of the services.

In our current problem though, both the Oracle and the Sql Server platforms share a great deal of commonality. The commonality calls for an inheritance based approach to capture all the common functionality in a base class. However, we still need to leave the interface intact to support existing implementers. This calls for a interface combined with inheritance approach. Just such an approach is described in this related post. However, for the sake of completeness, I wanted to mention a pattern that could be used as an alternative to using the combined inheritance and interface approach. This is the common Command Pattern – described below. 

Approach 2 : Leave Current Implementation Intact – use a Command Pattern to handle platform specific code

Leave the current implementation intact – no need for a second implementation. Use a command pattern whenever we encounter a database touch point.

Example SecurityService contains a method CheckUserCredentials. This mostly contains code that is common code to SqlServer and Oracle. When we get to the database specific part, we use a command pattern –

SecurityCommand.Execute(CheckUserCredentials)

public class SecurityCommand : ICommand
   {
       public void Execute(string commandName)
       {
           if(SQlServer)
               // SqlServer specific code for CheckUserCredentials
            else
               //  Oracle specific code for CheckUserCredentials
       }
   }

Advantages of Approach 2

  1. No duplication of code

Disadvantages of Approach 2

  1. We managed to avoid a separate implementation – but it doesn’t really use our interface based design. The whole purpose of having an interface ISecurityService is wasted.

SUMMARY

Almost every app today follows a service oriented architecture which exposes multiple services. If our app was limited to just that, the above interface based approach coupled with our Service Factory (to return a specific service) would be all that is needed. However, today’s services are not just feature based – but also tend to support multiple platforms.  These multiple platforms could be multiple databases (e.g. SQLServer and Oracle on the backend), multiple devices (e.g. Desktop and Mobile), multiple OSes  etc.  To deal with these multiple platforms, one can take a shortcut approach by using the Command pattern as described in this post.  To implement a more complete (not a shortcut) solution, read this related post.

The post Command Pattern to the rescue appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/command-pattern-to-the-rescue/feed/ 0
Property Bags–A Life Saver for the practicing OO Developer https://www.anujvarma.com/property-bagsa-life-saver-for-the-oo-developers/ https://www.anujvarma.com/property-bagsa-life-saver-for-the-oo-developers/#respond Thu, 22 Sep 2011 21:04:19 +0000 http://www.anujvarma.com/property-bagsa-life-saver-for-the-oo-developers/ (Full Source Code Available at the end of this article) The basic idea is simple enough – you have a type (class) with certain properties that is being used by […]

The post Property Bags–A Life Saver for the practicing OO Developer appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
(Full Source Code Available at the end of this article)

The basic idea is simple enough – you have a type (class) with certain properties that is being used by various consumers.  The type represents some entity – say ‘Employee’. Let us assume that all your employees were in India – where they do not have Social Security Numbers.  Recently though, your company hired employees in the U.S.  – and now, your employee type needs to support a SSN field.  You need to add an additional property (SSN) to your ‘Employee’ type. Ordinarily, this would mean:

  1. Modification (and recompilation) of your Server Side Object (Employee class).
  2. Re-Deployment of the server side assemblies containing the Employee class.
  3. Modification of all clients using the object to consume the new property.

That is obviously, a lot of work, for a simple change to a single domain object (the Employee class).  What we need instead, is a way for us to support such additional properties without modifying the server side object – and with minimal changes to the client code.  It is instructive to start with the Client – and what we expect the client code to do.

The Code (Client) – what do we want each client to be able to do?

// This is all that the client should need to do – add the new SSN property to an existing collection of properties.
Employee empl = new Employee();
empl.Properties["SocialSecurityNumber"].Value = "123456789";

Now  that we have an idea of what we expect the client code do, we can start looking at what the server side object needs in order to support this.

The Code (server side Employee class) – what do we need to change in the Employee class to accommodate the PropertyBag?

The main change to our Employee type is to add a member level variable for storing the PropertyBag collection. We use Composition (as shown below) to add an instance of the PropertyBag class to our Employee class:

        // START Everything you need to add to the Employee class to make it handle PropertyBags
        private PropertyBag _properties; // COMPOSITION

        public PropertyBag Properties
        {
            get { return _properties; }
            set { _properties = value; }
        }

        public Employee()
        {
            this._properties = new PropertyBag();
        }
        // END Everything you need to add to the Employee class to make it handle PropertyBags

 

The Code (The PropertyBag class) – what does the PropertyBag class look like?

We use a HashTable to store property names and property values. A simple Indexer (public Property this[string name]), acts as the lookup for a specific property. It accepts a string (name of the property) and returns the entire Property object (name-value pair).

public class PropertyBag
    {
        private Hashtable _propertyBag = new Hashtable();
        private string _name;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

      
        // Indexer which takes the name of the property and retrieves it from the PropertyBag  
        public Property this[string Name]
        {
            get
            {
                Property prop;
                // if a property with this name already exists, return it     
                if (_propertyBag.Contains(Name))
                    prop = (Property)_propertyBag[Name];
                else // else, create a new property with this name
                {
                    prop = new Property(Name);
                    _propertyBag.Add(Name, prop);
                }
                return prop;
            }
        }

         public class Property : System.Object
         {
               private string _name;                         // name of property
               private System.Object _value;                 // value of property

                public System.Object Value
                {
                  get { return _value; }
                  set{
                      // ensure thread safety
                      lock(this)
                      {                          
                          _value = this.GetType().GetProperty(_name);
                      }
                    }
                }
         
               public Property(string _inName)
               {
                    this._name = _inName;  
               }
         }
    }

With just these simple classes PropertyBag and Employee class that uses PropertyBags, we arrive at a solution which lets us add new properties without requiring re-deployment of server side code.  The above design works great if we build it into our original design. What if our product has already shipped – and we did not implement PropertyBags ?

What if our product is already deployed – Is it still possible to add PropertyBags after deployment?

Yes – with the caveat that you will need a one time re-deployment of the new server side assemblies containing the modified Employee type. However, the good news is that none of the existing clients will be affected by this modification (i.e. none of the clients will break) since the only change we made was adding a new class level member (PropertyBags) to the Employee type.

Summary

Property bags are extremely useful constructs that allow the ability to dynamically expand the (list of) properties that a given type supports. Using a simple hashtable for defining the PropertyBag and composition for including it within your original type (Employee), we have a powerful construct allowing us to change the type after we have already shipped and deployed it.  If you thought about exposing this PropertyBag when your original class design took place, you would have saved yourself a lot of trouble. You do not have to worry about recompiling and re-deploying your server side code. Even if your code is already deployed/in production, you can still add PropertyBags without breaking any of the clients using the type. The newly compiled version of your type (Employee along with PropertyBag) will need to be made available to the clients interested in using your propertyBag.

Future Thought(s)

In addition to using the PropertyBag to expand the list of properties, how about using it to expand the list of capabilities (methods) exposed by a type?

The post Property Bags–A Life Saver for the practicing OO Developer appeared first on Anuj Varma, Hands-On Technology Architect, Clean Air Activist.

]]>
https://www.anujvarma.com/property-bagsa-life-saver-for-the-oo-developers/feed/ 0