Showing posts with label Design Patterns. Show all posts
Showing posts with label Design Patterns. Show all posts

Monday, July 11, 2016

Getting rid of the billion dollar mistake – null references

Null reference exceptions are one the most common errors that programmers make while writing code. Compilers cannot check this errors and will only happen at runtime. Null reference exceptions is thrown when an attempt to access an object is made in a code, and the reference to that object is null. To avoid this exception, before using this object in the code a check to verify whether the object is not null has to be performed.
For e.g. the Welcome method in the below code, throws a null reference exception if the Identity object is null.

public class User
{
    public IIdentity Identity { get; private set; }

    public User(IIdentity identity)
    {
        Identity = identity;
    }
    public string Welcome()
    {
        return $"Hello {Identity.Name}";
    }
}

To avoid null reference exceptions, it’s a common practice to create guarded statements for the logic that executes on a possible null instance. Every single statement which operates on a potential null object becomes an if-then-else statement, which results in creation of multiple execution paths in the code, resulting in increased code complexity and reduces testability.

public class User
{
    public IIdentity Identity { get; private set; }

    public User(IIdentity identity)
    {
        Identity = identity;
    }
    public string Welcome()
    {
        if(Identity == null)
        {
            return string.Empty;
        }
        return $"Hello {Identity.Name}";
    }
}

How to get rid of the null checks?

Null object pattern


A null object is used to encapsulate the absence of an object by providing a dummy alternative that does nothing when a method on the object is invoked.  To create a null object implementation, we create an abstraction specifying various operations to be done, concrete classes extending this class and a null object class providing do nothing implementation of this class. Instead of passing a null instance to the higher methods, the null object instance will be used to provide a nothing implementation or default implementation to avoid guarded null checks in the subsequent methods. Our previous sample code can be refactored as below to avoid null checks. To create an abstraction we can use the extract interface refactoring as given below.

public interface IUser
{
    IIdentity Identity { get; }

    string Welcome();
}

The new implementation for the User class looks like.

public class User : IUser
{
    public IIdentity Identity { get; private set; }

    public User(IIdentity identity)
    {
        Identity = identity;
    }
    public string Welcome()
    {
        return $"Hello {Identity.Name}";
    }
}

The null object implementation for the IUser interface as can be written as

public sealed class NullUser : IUser
{
    public IIdentity Identity
    {
        get
        {
            return new NullIdentity();
        }
    }

    public string Welcome()
    {
        return string.Empty;
    }
}

public sealed class NullIdentity : IIdentity
{
    public string AuthenticationType
    {
        get { return string.Empty; }
    }

    public bool IsAuthenticated
    {
        get { return false; }
    }

    public string Name
    {
        get { return string.Empty; }
    }
}

This new structure can be used in the code, that does not need any guarded statements. We’ll create a UserFactory sample code that will now return a null object implementation and later consume in a test method, that does not need an if-then-else statement for null checks.

public static class UserFactory
{
    public static IUser Create(string name)
    {
        if(name == "Admin")
        {
            return new User(new GenericIdentity(name));
        }
        return new NullUser();
    }
}

[TestMethod]
public void NullObjectImplementationDoesNotThrowExceptionsOnNullReferences()
{
    var user = UserFactory.Create("Dummy");
    var actual = user.Welcome(); // No need to check the null instance here
    Assert.IsTrue(string.IsNullOrEmpty(actual));
}

Maybe pattern

The null object pattern is useful in situations where the caller does not need to take any actions based on the type of object returned. When using the null object pattern we would treat the result of calling the IUser implementation the same regardless of whether we get a real User or not. If we want to explicitly let the caller decide whether or not they need to check for a null value or not, we need to create a way to know whether the object is a null or not. The Maybe pattern can be used in this scenario.

We can create a generic implementation of the Maybe pattern using the Maybe class in C# as
                                                                                                                                             
public class Maybe<T> where T : class
{
    public T Value { get; private set; }

    public Maybe(T value)
    {
        Value = value;
    }

    Maybe() { }

    public static Maybe<T> Default
    {
        get
        {
            return new Maybe<T>();
        }
    }

    public bool HasValue
    {
        get
        {
            return Value != default(T);
        }
    }
}

To use this implementation in our user factory we can change the code like.

public static class UserFactory
{
    public static Maybe<User> Create(string name)
    {
        if (name == "Admin")
        {
            return new Maybe<User>(new User(new GenericIdentity(name))) ;
        }
        return Maybe<User>.Default;
    }
}

Compared to the previous implementation, the Maybe object denotes the caller that there is an ‘Option’ of the object exposed via the value property being null.  It’s the responsibility of the caller to make sure that the HasValue property is checked before performing operations on the object.
Coupled with some extension methods and delegates, you can now perform different operations without using the if-then-else statements as given below.

public static K Execute<T, K>(this Maybe<T> instance, Func<K> action, Func<K> emptyAction) where T : class
{
    if (instance.HasValue)
    {
        return action.Invoke();
    }
    return emptyAction.Invoke();
}

[TestMethod]
public void ExecuteInvokesTheEmptyExecutionDelegateWhenMaybeObjectDoesNotHaveAValue()
{
    var actual = UserFactory
        .Create(string.Empty)
        .Execute(NonEmptyFunc, EmptyFunc, 10);

    Assert.AreEqual(actual, 9);
}

Where EmptyFunc and NonEmptyFunc are simple functions written as

int NonEmptyFunc(int value)
{
    return ++value;
}

int EmptyFunc(int value)
{
    return --value;
}

Summary

As you can see from the above examples, both these approaches reduces branching in code and prevents you from dealing with null objects. Based on the requirements of the caller whether to take actions based on the state of the object or not, you can decide whether to use a NullObject or Maybe implementation in the code.  

Quoted from:

"I call it my billion-dollar mistake." - Sir C. A. R. Hoare, on his invention of the null reference

Saturday, July 18, 2015

Whitepaper - Creating CodedUI tests like an automation Ninja

UI tests allows developers to automate important end-to-end scenarios which can replace the manual regression tests and can be used to provide early feedback on the regression set. While these tests are easy to create using frameworks like CodedUI/ Selenium, one of the major challenges teams faces is to ensure that these tests remain resilient and can be easily maintainable along with the application code. The paper focuses on some of the practices/ patterns that can be used while creating UI automated tests using the CodedUI framework for web applications.


Like the actual production code, test code also has to be used for a long term and maintainable. The idea is to use the same object oriented principles and practices used in programming code for test code also.  You should make use of the SOLID principles and other design patterns to create test code if it has to be useful in the long term.  In this paper we’ll see some of the useful techniques that can be used for structuring the code of the automation tests, along with some tips that can be used to make the tests efficient. The examples used are based on CodedUI, but the concepts can be adapted and used in any similar UI automation framework.

The whitepaper addresses topics like

  • Extension methods on CodedUI objects
  • Using page objects pattern for cleaner code
  • Using fluent api for better readability
  • Page factories to create page objects
  • Reusing the browser window object for faster tests
  • Enabling tracing and HtmlLogger for better debugging and error logging
You can download the whitepaper from the link http://1drv.ms/1OcMP69 

Sunday, July 27, 2014

Continuous Delivery – Patterns for zero downtime requirements

One of the main problems teams face when practicing continuous delivery is to manage zero downtime deployments to the production environments. The goal is to deploy as soon as possible and depending on the heartbeat of the organization, this becomes a higher priority to manage active users without losing their data and sessions during a deployment process. In this post I'll share some of the ideas and approaches that are been used for achieving the goal of zero downtime deployments.

An important process for reducing risks and managing a zero deployment downtime is by following the blue-green deployment technique. In a blue-green deployment scenario, the approach is to bring up a parallel green environment and once everything is tested and ready to go, you simply switch all the traffic to the green environment and leave the blue environment idle. This also helps in easy rollback and switch to the blue environment if anything goes wrong in the current installation.


In a horizontally scaled environment, where you have multiple servers handling the load where the traffic is routed to one of the servers based on the load balancer scheduling algorithm, you can update the servers one-by-one and bring them online after the updates. The same approach will be used in this scenario also, but with the only difference that there will be N blue and N-1 green servers where N is the number of servers in each group in the web farm.


As long as deployment of application code is only considered, there is no problem managing that with a zero downtime requirement. But consider the deployment scenario which involves changes in the database schema as well. You can’t now update the DB schema first and continue using the old application code to use the new schema as it will create inconsistencies considering the code is written to work on an old DB schema. This involves taking extra precautions or considerations with updates that involve DB schema changes. When it involves database changes two approaches that helps the most are:

Strive for backward compatibility by performing schema changes that won't affect the existing code and also by ensuring that the deployed code can work with the old schema.
Some of the points to consider would be to:
  • Perform schema changes in a way that won’t break existing code
  • New columns added are always NULLABLE
  • New columns provide a default value if it does not exist.
  • Don't delete columns until none of the code uses them, or can handle their absence.
  • Use triggers or similar mechanisms to populate values that are important for one deployed version of the application.
  • Enforce referential integrity only when it makes sense.

Have an expansion and contraction database script:
This allows you to handle database changes that are safe to apply without breaking backward compatibility with the application code. Changes like creating new tables, adding columns or tweaking indexes etc. can be handled using the expansion scripts with a trigger or scripts that fills the default values. Once the application code is updated, you can execute the contraction script to clean up any database structure or data that is no longer needed.
You should plan to execute the expansion scripts prior to updating the application code and the contraction scripts once the application code has been updated and is in a stable state. This produces a nice benefit of decoupling database migrations from application deployments.

Tuesday, March 25, 2014

Law of Demeter - Refactoring to Hide Delegate

The Law of Demeter is a design guideline for developing software, particularly object-oriented programs. In its general form, the law is a specific case of loose coupling. The fundamental notion of the law is that a given object should assume as little as possible about the structure or properties of anything else (including its subcomponents), in accordance with the principle of "information hiding".
For E.g. the code given below shows that the client calls the method on the dependent object of the client rather than on the object itself. This increases the coupling between classes.
var manager = john.GetDepartment().GetManager();
The Hide Delegate refactoring principle can be applied to this design to solve the issue.












public Manager GetManager()

{
    return Department.GetManager();

}

Monday, May 20, 2013

Distributing custom stylecop rules in a scrum team


The Microsoft source analyzer for C#, StyleCop can be used to enforce a set of styling and consistency rules among .Net teams in a project/ company. StyleCop can be run as a visual studio plugin or can be integrated with an MSBuild project.
StyleCop provides an extensible framework for plugging in custom rules for the developers.  For implementing a custom rule, the user needs to create a custom rules analyzer class which inherits the SourceAnalyzer and overrides the AnalyzeDocument method to check for violations.
In this post, I’ll show how you can implement extensible custom rules in stylecop by using the visitor pattern.

Creating the custom rule analyzer class:
[SourceAnalyzer(typeof(CsParser))]
public class MyCodeStandardAnalyzerRules : SourceAnalyzer
{

    public override void AnalyzeDocument(CodeDocument document)
    {
        var csDoc = document as CsDocument;
        if(csDoc == null) return;
        if(csDoc.HasEmptyRootElement() || csDoc.IsAutoGeneratedCode()) return;

        csDoc.WalkDocument(
                ElementVisitor, null, null
            );

    }

    private bool ElementVisitor(CsElement element, CsElement parentelement, object context)
    {
        //Implementing the custom rules for CsElement goes here
    }
}

Creating the visitor interface
public interface IVisitor
{
    void SetSourceAnalyzer(SourceAnalyzer alanyzer);
    void Visit(CsElement element);
}

Writing the first visitor
public class CheckForConstantsHaveUpperCaseNameVisitor : BaseVisitor, IVisitor
{
    public void Visit(CsElement element)
    {
        if (element.ElementType != ElementType.Field || !element.Declaration.ContainsModifier(CsTokenType.Const))
            return;

        if(element.Name.Any(char.IsLower))
            AddViolation(element, RuleNames.CONSTANTS_SHOULD_BE_IN_UPPERCASE, element.Name, element.LineNumber);
    }
}
public class BaseVisitor
{
    private SourceAnalyzer _sourceAnalyzer;

    public void SetSourceAnalyzer(SourceAnalyzer sourceAnalyzer)
    {
        if (sourceAnalyzer == null) throw new ArgumentNullException("sourceAnalyzer");
        _sourceAnalyzer = sourceAnalyzer;
    }

    protected void AddViolation(ICodeElement element, string rule, params object[] values)
    {
        _sourceAnalyzer.AddViolation(element, rule, values);
    }
}

Creating the Element class to accept the visitor
public class CodeElement
{
    private readonly SourceAnalyzer _analyzer;
    private readonly CsElement _element;

    public CodeElement(SourceAnalyzer analyzer, CsElement element)
    {
        _analyzer = analyzer;
        _element = element;
    }

    public void Accept(IVisitor visitor)
    {
        visitor.SetSourceAnalyzer(_analyzer);
        visitor.Visit(_element);
    }
}

The visitor dispatcher to resolve all visitors (Using a dependency injection container is much easier J)
public class VisitorDispatcher
{
    private static VisitorDispatcher _dispatcher;
    private static readonly object _lockObject = new object();

    public List<IVisitor> Visitors { get; private set; }

    public static VisitorDispatcher Instance
    {
        get
        {
            if (_dispatcher == null)
            {
                lock (_lockObject)
                {
                    _dispatcher = new VisitorDispatcher();
                    var visitors = from type in Assembly.GetExecutingAssembly().GetTypes()
                                    where type.IsAssignableFrom(typeof(IVisitor))
                                    select Activator.CreateInstance(type) as IVisitor;

                    _dispatcher.Visitors = new List<IVisitor>(visitors);

                }
            }
            return _dispatcher;
        }
    }
}

Finally visiting the element with the visitors
private bool ElementVisitor(CsElement element, CsElement parentelement, object context)
{
    if (element.IsAutoGenerated()) return true;

    var codeElement = new CodeElement(this, element);
    VisitorDispatcher.Instance.Visitors.ForEach(codeElement.Accept);
    return true;
}

The last step is to build your project and drop the new project’s dll into the StyleCop installation directory and run the style cop rules on your projects. Style cop will automatically look for assemblies in the directory and pick up the new rules for your team.