Skip to main content

Java Script code refactoring - hands on code

Let's see how we can create a mechanism that based on some flags; it will able to determine the status of some objects. The first version of code would look like this:
ItemStatus = {
    Status1: "Status1",
    Status2: "Status2",
    Status3: "Status3"
}();

ItemTypes = {
    Item1: "Item1",
    Item2: "Item2",
    Item3: "Item 3"
}();

var ItemConfiguration = function () {

    function ItemConfiguration() {

    }

    ItemConfiguration.prototype = function () {
        getItemConfiguration: function (itemTypes, flag1, flag2, flag3, flag4) {
            switch (itemTypes) {
                case ItemTypes.Item1:
                    if (flag1 && flag2) {
                        return ItemStatus.Status1;
                    } else if (flag3 || flag4) {
                        return ItemStatus.Status2;
                    }
                    break;
                case ItemTypes.Item2:
                    if (flag3 || flag2) {
                        return ItemStatus.Status3;
                    } else if (flag1 || flag2) {
                        return ItemStatus.Status1;
                    }
                    break;
                case ItemTypes.Item3:
                    if (flag3 || flag1 && flag3) {
                        return ItemStatus.Status1;
                    } else if (flag2 && flag4) {
                        return ItemStatus.Status3;
                    }
                    break;
            }
        }
    };
   
    return ItemConfiguration;
} ();

First problem is related to default values. If the flags combination from switch doesn’t return any value, that we should notify one way or another user about this issues. We end up throwing an expectation.
var ItemConfiguration = function () {

    function ItemConfiguration() {

    }

    ItemConfiguration.prototype = function () {
        getItemConfiguration: function (itemType, flag1, flag2, flag3, flag4) {
            switch (itemType) {
                case ItemTypes.Item1:
                    if (flag1 && flag2) {
                        return ItemStatus.Status1;
                    } else if (flag3 || flag4) {
                        return ItemStatus.Status2;
                    }
                    break;
                case ItemTypes.Item2:
                    if (flag3 || flag2) {
                        return ItemStatus.Status3;
                    } else if (flag1 || flag2) {
                        return ItemStatus.Status1;
                    }
                    break;
                case ItemTypes.Item3:
                    if (flag3 || flag1 && flag3) {
                        return ItemStatus.Status1;
                    } else if (flag2 && flag4) {
                        return ItemStatus.Status3;
                    }
                    break;
            }

            throw {
                message: "No flags matching for " + itemType + "with the flags combination"
                + "flag1: " + flag1 + ", "
                + "flag2: " + flag2 + ", "
                + "flag3: " + flag3 + ", "
                + "flag4: " + flag4 + ", "
            };
        }
    };

    return ItemConfiguration;
} ();
Almost okay we think. When we look over the requirements we notify that the user will need the status for all items. Because of this he will need to make 3 different calls. For each call he would need to add all the parameters over and over again. We can have two possible solutions. One is to create an object that has all this flags. The other option is to change our method to return the status for all our item types. I would go with the second approach.
var ItemConfiguration = function () {

    function ItemConfiguration() {

    }

    ItemConfiguration.prototype = function () {
        getItemsConfiguration: function(flag1, flag2, flag3, flag4) {
            var itemsStatus = new Object();
            itemsStatus[ItemTypes.Item1] = _getStatusForItem1(flag1, flag2, flag3, flag4);
            itemsStatus[ItemTypes.Item2] = _getStatusForItem2(flag1, flag2, flag3, flag4);
            itemsStatus[ItemTypes.Item3] = _getStatusForItem3(flag1, flag2, flag3, flag4);

            return itemsStatus;
        },

        _getStatusForItem1:function(flag1, flag2, flag3, flag4) {
            if (flag1 && flag2) {
                return ItemStatus.Status1;
            } else if (flag3 || flag4) {
                return ItemStatus.Status2;
            }

            _noStatusHandler();
        },

        _getStatusForItem2:function(flag1, flag2, flag3, flag4) {
            if (flag3 || flag2) {
                return ItemStatus.Status3;
            } else if (flag1 || flag2) {
                return ItemStatus.Status1;
            }

            _noStatusHandler();
        },

        _getStatusForItem3:function(flag1, flag2, flag3, flag4) {
            if (flag3 || flag1 && flag3) {
                return ItemStatus.Status1;
            } else if (flag2 && flag4) {
                return ItemStatus.Status3;
            }

            _noStatusHandler();
        },

        _noStatusHandler:function() {
            throw {
                message: "No flags matching for " + itemType + "with the flags combination"
                + "flag1: " + flag1 + ", "
                + "flag2: " + flag2 + ", "
                + "flag3: " + flag3 + ", "
                + "flag4: " + flag4 + ", "
            };
        }
    };

    return ItemConfiguration;
} ();
For each item type we extracted a method that calculates the item status. In the case for the input flags we cannot retrieve a status we throw an exception. In our public method, we create an object that contains our item types and status. In this way we removed the switch and the code looks better.
The thing that has a smell is the 4 parameters that are send each time in our private method. We could create an internal object with these 4 parameters and send it as parameter for each private method. Another option is to create 4 private fields and each private method can use them. Because we don’t have any problem with thread concurrency in JavaScript we can go with the second approach without any problem.
var ItemConfiguration = function () {

    var flag1, flag2, flag3, flag4;
   
    function ItemConfiguration() {

    }

    ItemConfiguration.prototype = function () {
        getItemsConfiguration: function(flag1, flag2, flag3, flag4) {
            this.flag1 = flag1;
            this.flag2 = flag2;
            this.flag3 = flag3;
            this.flag4 = flag4;
           
            var itemsStatus = new Object();
            itemsStatus[ItemTypes.Item1] = _getStatusForItem1();
            itemsStatus[ItemTypes.Item2] = _getStatusForItem2();
            itemsStatus[ItemTypes.Item3] = _getStatusForItem3();

            return itemsStatus;
        },

        _getStatusForItem1:function() {
            if (this.flag1 && this.flag2) {
                return ItemStatus.Status1;
            } else if (this.flag3 || this.flag4) {
                return ItemStatus.Status2;
            }

            _noStatusHandler();
        },

        _getStatusForItem2:function() {
            if (this.flag3 || this.flag2) {
                return ItemStatus.Status3;
            } else if (this.flag1 || this.flag2) {
                return ItemStatus.Status1;
            }

            _noStatusHandler();
        },

        _getStatusForItem3:function() {
            if (this.flag3 || this.flag1 && this.flag3) {
                return ItemStatus.Status1;
            } else if (this.flag2 && this.flag4) {
                return ItemStatus.Status3;
            }

            _noStatusHandler();
        },

        _noStatusHandler:function() {
            throw {
                message: "No flags matching for " + itemType + "with the flags combination"
                + "flag1: " + flag1 + ", "
                + "flag2: " + flag2 + ", "
                + "flag3: " + flag3 + ", "
                + "flag4: " + flag4 + ", "
            };
        }
    };

    return ItemConfiguration;
} ();
It seems that the code looks cleaner in this way and is easier to read. For the private method, I would let the user to specify all the parameters because is more clear for him and he don’t need to create a new object to send the parameters and use it only in one place.
One thing that came to my mind is to create an object or a dictionary that contains the private functions for each item type. But it would be to complex and I don’t know if is worth it.
What do you think? Do you see another way to implement it?



Last edit: Another option is to create a mapping based on the flags (for example each combinations of flag has a unique key that point to an object that has our item types configuration –ex: flag1*2^0+flag2*2^1+flag3*2^3 in base 10 or we could use a mapping in base 2). What is my concern for this solution is the complexity of the code increase, even if the numbers of line are less and we don’t have the IF statements anymore.
 

Comments

  1. Hi, Radu!
    Could you explain what does the code below actually do?

    if (this.flag3 || this.flag1 && this.flag3) {
    return ItemStatus.Status1;
    } else if (this.flag2 && this.flag2) {
    return ItemStatus.Status3;
    }

    I guess you carried some typos through-out the article.

    ReplyDelete
    Replies
    1. Based on some Booleans values send by the caller we need to be able to return a list of status for some object. We can imagine that we have a big table with a lot of combinations of flags and based on this combination we can determine the status of some items.

      Delete
    2. flag2 && flag2
      If was a type mistake Thank you. I update the code.

      Delete
    3. The condition in the first If statement is either wrong or contains a typo since it is equivalent to "if(this.flag3)". Proof: http://jsfiddle.net/DenisPostu/2cQe3/3/

      Delete
  2. Some suggestions:
    - I hope that in the real code the parameters have meaningful names, not flag1, flag2, ...

    - without some real context, it's hard to understand if the solution is appropriate: are you sure that there will always be 3 'items' and that they have a fixed number of types?

    - using _ in JS to mark 'private' members is an anti-pattern: there are methods to simulate real private members in JS objects, using closures (http://javascript.crockford.com/private.html)

    ReplyDelete
  3. In the lack of knowing the whole context, it seems to me that you need something like a logic grid (http://www.codeguru.com/cpp/misc/misc/math/article.php/c9629/LogicGrid-An-Elegant-Alternative-to-Your-IfElse-Nightmare.htm), seen very often in digital circuit design. Another way would be having some kind of state machine.

    Regarding the JS part, you should avoid accessing private variables from methods added by prototyping.

    Happy refactoring :)

    ReplyDelete

Post a Comment

Popular posts from this blog

How to check in AngularJS if a service was register or not

There are cases when you need to check in a service or a controller was register in AngularJS.
For example a valid use case is when you have the same implementation running on multiple application. In this case, you may want to intercept the HTTP provider and add a custom step there. This step don’t needs to run on all the application, only in the one where the service exist and register.
A solution for this case would be to have a flag in the configuration that specify this. In the core you would have an IF that would check the value of this flag.
Another solution is to check if a specific service was register in AngularJS or not. If the service was register that you would execute your own logic.
To check if a service was register or not in AngularJS container you need to call the ‘has’ method of ‘inhector’. It will return TRUE if the service was register.
if ($injector.has('httpInterceptorService')) { $httpProvider.interceptors.push('httpInterceptorService&#…

ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

Today blog post will be started with the following error when running DB tests on the CI machine:
threw exception: System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information. at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName) This error happened only on the Continuous Integration machine. On the devs machines, everything has fine. The classic problem – on my machine it’s working. The CI has the following configuration:

TeamCity.NET 4.51EF 6.0.2VS2013
It seems that there …

Run native .NET application in Docker (.NET Framework 4.6.2)

Scope
The main scope of this post is to see how we can run a legacy application written in .NET Framework in Docker.

Context
First of all, let’s define what is a legacy application in our context. By a legacy application we understand an application that runs .NET Framework 3.5 or higher in a production environment where we don’t have any more the people or documentation that would help us to understand what is happening behind the scene.
In this scenarios, you might want to migrate the current solution from a standard environment to Docker. There are many advantages for such a migration, like:

Continuous DeploymentTestingIsolationSecurity at container levelVersioning ControlEnvironment Standardization
Until now, we didn’t had the possibility to run a .NET application in Docker. With .NET Core, there was support for .NET Core in Docker, but migration from a full .NET framework to .NET Core can be costly and even impossible. Not only because of lack of features, but also because once you…