Code Smells : Dispensable

Continuing on our discussion on Code Smells and Refactoring techniques, we will discuss Dispensable in this post.

Dispensables are avoidable components whose absence would make the code much more cleaner, readable and efficient.

Comments

A joke is not a good one if needed to be explained. A similar philosophy holds for code as well. If you feel that the code requires comments to understand, then it is better to refactor  it such a way that it eliminates the need of comments.

You could start with refactoring techniques like Rename Method, Rename Variable, along Extract Variable and Extract Method. Quite often using asserts (introduce assertions) can also aid in increasing the readability of the code.

Duplicate Code

When you have a larger team, there is a distinct possibility that two developers working different parts of the project might end up developing similar/same method. The similarity could could be subtle as well, where similarity is visible to only in certain parts of code, while performing the same job.

Extract Method, Extract superclass and Extract class are some of the refactoring methods that can be applied. If two methods do same job but using different algorithms, refactoring techniques like Substitute algorithm (Strategy Pattern) can be applied. Similarly, if the duplicated code is only visibly similar, but isn’t quite identical, Form Template Method technique (Template Method Pattern) can be applied.

Lazy Class

There could exist classes in your code which has become obsolete or the functionalities are near-useless, you could employee techniques like Inline Class to remove it.

Maintaining code is expensive and any unused code should be carefully eliminated.

Data Class

Classes are identified by two factors – Properties and Behaviours.  If you stumble upon a class that has only properties, then it is a good candidate for Data Class code smell.

 The first step you need to take is to review the client code that uses the class, and review if the functionality could exist in the Data Class itself. You could also review if the conventional collection such as Arrays could be used to store the Data in the class, thus eliminating the need for class.

Dead Code

Dead Code is often resultant of changing requirements/specifications, and a development team that was unsure/lazy to clean up the code. A good IDE such as the Visual Studio can aid in detecting such code and can be eliminated.

Remember, it doesn’t need to be a method, the dead code could also be a unused parameter, which can be eliminated using the Remove Parameter refactoring technique.

Speculative Generality

How often have we been guilty of creating functionality in anticipation of future requirements, but ended up never having to use them ? It is a common trait in teams, which is highly infectious and needs to be avoided. XP Principles like YAGNI, KISS can be highly useful in this regard in educating the team to avoid such pitfalls.

Refactoring techniques such as Collapse Hierarchy an Inline class can be used for eliminating such code.

Design Pattern : Memento Pattern

Memento Design Pattern allows to capture internal state of an object in an external object and restore it to the desired checkpoint when required, all the while being in compliance with encapsulation.

The Memento Design Pattern comprises of 3 actor classes.

  • Originator : The class which needs to have the ability to store its internal state and restore itself to checkpoint when required.
  • Memento : Contains the internal state of Originator.
  • Caretaker : The shepherd class who is in charge of storing and restoring Originator from Memento.

Let’s go ahead and implement the actor classes

Classic Approach

public class Memento
    {
        public string FName { get; set; }
        public string LName { get; set; }

    }

 public class Caretaker<TSource>
    {

        private IList<Memento> _stateMemory;

        public Caretaker()
        {
            _stateMemory = new List<Memento>();
        }

        public Memento GoBack(int level) =>  _stateMemory.Reverse().Skip(level-1).First();

}

 public class Originator: IOriginator
    {
        public string FName { get; set; }
        public string LName { get; set; }

        public void RestoreState(Memento memento)
        {
            this.FName = memento.FName;
            this.LName = memento.LName;
        }

        public Memento Save()
        {
            return new Memento() {
                LName = this.LName,
                FName = this.FName
            };
        }

    }

The above code showcases the implementation of Memento in its simplest form. You could step up things by making the Memento generic so that it can be reused with other classes as well.

Generic Memento with Serialization.

Instead of defining each properties of the Originator class, we could create a completely generic version by utilizing the powers of serialization.

In the following example implementation of Memento class, I have used ProtoBuf for serializing the class.

public class Memento<TSource>
    {
        private byte[] _state;

        public Memento(TSource data)
        {
            using(var stream = new MemoryStream())
            {
                ProtoBuf.Serializer.Serialize<TSource>(stream, data);
                _state = stream.ToArray();
            }
        }

        public TSource Value
        {
            get
            {
                using(var stream = new MemoryStream(_state))
                {
                    return ProtoBuf.Serializer.Deserialize<TSource>(stream);
                }
            }
        }
    }

The entire source code shown in this example are available in my GitHub.

Stairway Pattern

How do you feel when you invite your friend for a private family function and he brings along a dozen strangers (his friends) ?

 

Entourage Anti-Pattern

This is similar to the scenario when you want to add a library as reference and in turn ends up referring a different set of libraries which you are not directly dependent. This scenario is perfectly defined by the Entourage Anti-Pattern. The Entourage pattern also describes the (avoidable) practice of packaging the abstraction and implementation in the same assembly.

The Stairway Pattern

The stairway pattern describes a better alternative by organizing your abstractions and implementations in separate assemblies, which in turn allows both to evolve and vary independently.

It also means the references now doesn’t bring an entire entourage of assemblies along. One of the thumb rules you can adhere too is to ensure the abstraction assembly doesn’t depend on any external references.

Looking back at DRY

Continuing with our series to bring together the common design patterns and principles, we will, in this particular post, look into arguably the most famous design principle known to programmers – DRY. Don’t Repeat Yourselves – or DRY, is possibly the easiest to practice, at the same time, one that could go wrong in the ‘rush hours’ of project deadlines.  The principle, as you would be aware of, aims in reducing/eliminating duplicate software patterns in the system.  The Pragmatic Programmer describes DRY principle as follows

Every piece of knowledge must have a single, unambiguous, authoritative representation within a system – Andrew Hunt, Dave Thomas

The evils of a non-DRY system is obvious.If you have same functionality defined in two places, and you forget to change in one of the place when the functionality changes, you are left with a system that is self-contradicting. The principle doesn’t exclusively apply to code, but rather it applies to documentation, comments in code as well. Consider a scenario when the developer changes the code, but forgets to change the comments associated with the code, the result could be a future developer banging his head to understand what is now an obsolete comment.

The duplication could be broadly categorized into four categories (again thanks to Pragmatic Programmer).

Imposed Duplication
There could be scenario’s when the Project Specifications or the technology limitations imposes duplication on the development team. Such scenarios are hard to tackle and the near perfect solution would be localize the impact of violation.

Inadvertent Duplication
This kind of duplication involves scenario when the developer doesn’t realize they are guilty of duplication. This could be resultant of a rather imperfect design.

Impatient Duplication
This is the most avoidable of the four categories of duplication and describes the scenarios when the developers are lazy or pressurized with deadlines, and end up finding shortcuts via duplicating. However, the develop team as a whole needs to remember that this tiny shortcut could lead to catastrophic impacts in latter stages of project

Interdeveloper Duplication
Most commonly seen in large disconnected teams and possibly the hardest to detect. The developer in one sub team could duplicate a functionality which was already developed.

DRY, as seen from above, is possibly the most easiest of Design Principles to master, if you are always on your toes. The key lies in keeping an eye on the bigger picture of project, refactor your code regularly.

Design Patterns : Bridge Pattern

The essence of Bridge Pattern lies in the fact that it not just decouples the abstraction from implementation, but in doing so, allows both to evolve independently. Let’s consider the examples of smartphones.

The underlying OS (for sake of example, let’s assume its Android) improving every year. The Android has seen atleast 7 versions in past decade. At the same time, the hardware has also evolved, giving way to new age smartphones. The Abstraction and Implementation has evolved independently here. Let’s mock the scenario using Bridge Pattern.

public interface IAndroid
{
  void Call(string name);
  void Recieve();
  void SendMessage(string name);
  void RecieveMessage();
}
public class KitKat : IAndroid
{
  public void Call(string name) => Console.WriteLine($"Calling {name} using  KitKat");
  public void Recieve() => Console.WriteLine("Recieve using KitKat");
  public void RecieveMessage()=> Console.WriteLine("Recieve Message using  KitKat");
  public void SendMessage(string name) => Console.WriteLine($"Send {name}  Message using KitKat");
}
public class Lollipop : IAndroid
{
  public void Call(string name) => Console.WriteLine($"Calling {name} using  Lollipop");
  public void Recieve() => Console.WriteLine("Recieve using Lollipop");
  public void RecieveMessage() => Console.WriteLine("Recieve Message using  Lollipop");
  public void SendMessage(string name) => Console.WriteLine($"Send {name}  Message using Lollipop");
}
public class Nougat : IAndroid
{
  public void Call(string name) => Console.WriteLine($"Calling {name} using  Nougat");
  public void Recieve() => Console.WriteLine("Recieve using Nougat");
  public void RecieveMessage() => Console.WriteLine("Recieve Message using  Nougat");
  public void SendMessage(string name) => Console.WriteLine($"Send {name}  Message using Nougat");
}

Evolution of Abstraction which Customer/Client sees, the Phone , can be seen in following code.

public class SmartPhone
{
  protected IAndroid _android;
  public SmartPhone(IAndroid android) => _android = android;
  public virtual void Phone(string name) => _android.Call(name);
  public virtual void SendMessage(string name) =>  _android.SendMessage(name);
}
public class NewAgeSmartPhone : SmartPhone
{
  public NewAgeSmartPhone(IAndroid android) : base(android) { }
  public override void Phone(string name)
  {
    Console.WriteLine("New Age Phone Call, Optimization started");
    base._android.Call(name);
  }
  public override void SendMessage(string name)
  {
    Console.WriteLine("New Age Message");
    _android.SendMessage(name);
  }
}

 

Client Code can be shown as following

static void Main(string[] args)
{
  var phone = new SmartPhone(new KitKat());
  var newAgePhone = new NewAgeSmartPhone(new KitKat());
  phone.Phone("Wife");
  newAgePhone.Phone("Wife");
}

 

As seen in the code above, the Bridge Pattern allows the Abstraction and Implementation to vary and evolve independently. Complete Code Sample in this example can found in my GitHub

Design Patterns : Prototype Pattern

Falling under Creational Patterns, Prototype Pattern aims in creating a clone of your object and is used in scenarios when creating a object is considered costly (may be the creation involves a long Database or Web Service Operation). The formal definition of the pattern is as follows.

 

Specify the kind of objects to create using a prototypical instance, and create new objects by copying this prototype.
It is one of the most easiest patterns to implement using .Net Framework.  Let’s define our target class first.
public interface IPerson
{
  string FirstName { get; set; }
  string LastName { get; set; }
  int Age { get; set; }
}
public class Person : IPerson
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public int Age { get; set; }
}

What we need next is an interface that defines our Clone method. One option we have is to define a custom interface which exposes our required method, such as following.

public interface ShallowClone
{
   IPerson Clone(IPerson person);
}

The alternative is to use framework interface ICloneable. For this example, we would be using the framework interface. So let’s go ahead and update the Person Class with implementation of ICloneable.

public class Person : IPerson, ICloneable
{
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public int Age { get; set; }
  public object Clone() => MemberwiseClone();
}

That’s all we need to do. The MemberwiseClone() method does the trick for us. We will complete the example by writing the Client code.

static void Main(string[] args)
{
  Person personA = new Person { FirstName = "John", LastName= "Burton",  Age = 35 };
  Person personB = personA.Clone() as Person;
  Console.WriteLine($"Person A : {personA.LastName},{personA.FirstName}  - Age : {personA.Age}");
  Console.WriteLine($"Person B : {personB.LastName},{personB.FirstName}  - Age : {personB.Age}");

}

All code samples in this example is available in my GitHub.

Design Patterns : Decorator Pattern

While Inheritance/Sub Classing seems to be most natural way of extending functionality, it might not be always the best option. Especially when you want to avoid subclassing as it might result in too many classes. Consider the following scenario.

Your nearest Dominos has many varieties of Pizzas. On top of it, you could decorate each of those pizzas with extra toppings and choose from a variety of crusts. If we were go with the conventional sub classing approach, we could end up with a lot of sub classes as seen below.
Pizza

For each combination of Pizza and topping, we would need to create a separate sub class. Add to it, options available for crust, and the sub classes could go up higher. This is here Decorator Pattern comes into picture. Decorator Pattern allows us to add functionality/feature to existing classes without having to go through the pain of too many sub classes. Of course, Decorator Pattern too does make use of inheritance, but in a more efficient way.

 

Let’s go ahead and Implement Pizza Classes using Decorator Pattern, beginning with the Contract Interface and choice of base Pizzas.
public interface IPizza
{
  string Description { get; }
  int CalculatePrice();
}

public class MexicanGreenWavePizza : IPizza
{
  public string Description => "Mexican Green Wave Pizza";
  public int CalculatePrice() => 105;
}

public class MargheritaPizza : IPizza
{
  public string Description => "Margherita Pizza";
  public int CalculatePrice() => 100;
}

public class ChickenTikkaPizza : IPizza
{
  public string Description => "Chicken Tikka Pizza";
  public int CalculatePrice() => 115;
}

We will now add our decorators.

class CheeseCrust : IPizza
{
  private IPizza _PizzaInstance;
  public CheeseCrust(IPizza pizza) => _PizzaInstance = pizza;
  public string Description => $"{_PizzaInstance.Description} With Cheese  Crust";
  public int CalculatePrice() => _PizzaInstance.CalculatePrice() + 7;
}

public class ExtraGoldenCorn : IPizza
{
  private IPizza _PizzaInstance;
  public ExtraGoldenCorn(IPizza pizza) => _PizzaInstance = pizza;

  public string Description => $"{_PizzaInstance.Description} with Extra  Golden Corn";
  public int CalculatePrice() => _PizzaInstance.CalculatePrice() + 5;
}

As you might have already noticed, the decorator classes not just inherit from IPizza interface, but it also have an instance of Pizza with it, injected using Dependency Injection.  This allows us to use the decorators with any combination of base classes (and with each other) without having to write too many sub classes as we had observed in the image above. The client can now use any combination of Pizza’s with their decorators.

IPizza vegPizza = new MargheritaPizza();
var vegPizzacheezeCrust = new CheeseCrust(vegPizza); // Added  Decorator

IPizza nonVegPizza = new ChickenTikkaPizza();
var chickenPizzacheezeCrust = new CheeseCrust(nonVegPizza); // Added  Decorator
var chickenPizzacheezeCrustAndExtraGoldenCoren = new  ExtraGoldenCorn(chickenPizzacheezeCrust); // Added Decorator

Console.WriteLine($"{vegPizzacheezeCrust.Description}, Price  :  {vegPizzacheezeCrust.CalculatePrice()}");
Console.WriteLine($"{chickenPizzacheezeCrustAndExtraGoldenCoren.Description},  Price  : {chickenPizzacheezeCrustAndExtraGoldenCoren.CalculatePrice()}");

Output

Margherita Pizza With Cheese Crust, Price  : 107
Chicken Tikka Pizza With Cheese Crust with Extra Golden Corn, Price  : 127<span id="mce_SELREST_start" style="overflow:hidden;line-height:0;"></span>

The complete reference source code for the example can be found in my Github. To learn more on Design Patterns, refer here.