02 February, 2015

New Technology Radar

This time something really short: new Technology radar was released a few days ago.

For me, as a .NET and web developer, I will:

  • Learn more about AngularJS. To be honest, I have never made anything "for real" in this framework and I think that the time has come. AngularJS is now a mature framework with big community and it offers a lot features.
  • Read more about REST without PUT. How can we replace it? Only by POST? The idea is interesting and seems to be more and more popular. I think we need to used to REST without PUT...
  • Definitly test GruntJS. It has a strong community and a lot of great plugins. I heard a about 1,5 h year ago and this year finally I will give him a chance.
  • Try the EventStore database. It is a very interesting concept of the database, that stores the data as the immutable events. It is not for every purpose, but it is free, fast and, for sure, worth testing.
  • Take a closer look on Roslyn. It is an open source .NET compiler, which might be very useful in terms of the refactoring and optimization.

... and I will take a closer look on Google Go language.

27 January, 2015

How to make an API?

Background...

For a few years I worked with different APIs delivered by the different vendors. I was also taking part in designing and creating of the APIs for the software that I was working on. In this post I would like to describe some key points, which in my opinion a good API should have and some that shouldn't have.

Subjective list of the well designed API features

  • Extensibility

    Remember, to make your API extensible. It is more than possible, that you will need to add some new features as a client request and it is better to do this as fast as possible, especially if your system and the API are new on the market.

  • Batches

    Your API should offer a possibility of using batch operations. E.g. Taking details of an object can be done either for a list of items, or only for one of them. It will decrease the number of hits to the server and increase performance.

  • Technologies easy-to-use

    Try to avoid old, complicated technologies. If you can give an access to your system using the REST service, then use it instead of the old web service. If you are designing a desktop application API, then don't use old, awful COM objects, when you have many different ways of accessing the data.

  • Return everything as a result

    This point may be controversial and I am sure that not everybody will agree with me. I think, that the best way to return any data is to return it as a defined result type. The worst thing you can do, is to throw an exception every time something unusual is happening, instead of giving the user a possibility to decide, what he wants to do. Remember, that this situation may be unusual, but it might not be an error in your clients system.

  • Meaningful error messages

    If an error appears, do not return only the code of the error. I know it is the easiest way, but not the best one. Nobody likes receiving only the number instead of the message.

  • Meaningful names of types and methods

    Names of the methods and types should be simple and meaningful. If you are not sure, if the name is simple enough, it means that it is probably too complicated and if you are not sure, if it is meaningful- ask someone who is not working on this project, what in hers / his opinion this type or method is created for.

  • Well documented

    I know, that it is not possible every time to make a good API documentation, but if you have some time try to make some documentation. It would be a great help for the users of your API and more people will be willing to try it.

  • Supported by the community

    If you have a support, it is much easier to use any API so think about making a forum, Facebook fanpage or any other place, where users of your API can exchange their experiences, ideas and ask questions. Remember, that many interesting projects failed because of the lack of community support!

The most common problems

  • Old technologies

    Sometimes developers can design a useful API, but finally they are trying to rebuild the old version of API using old technologies. If it is possible, try to make a new API and show to your clients, why it is better to use the new one. Remember- do not to give access to the old API to new clients- it causes problems.

  • No support

    API must have a support: either paid or community (free) - this is obligatory. If there is no support, then nobody will even try your API.

  • Not enough tests

    Always give your clients well tested product. If API contains errors, then it is not reliable so nobody will trust you and your API.

Things to remember

  • Listen to other developers

    Even if your API is the best in the whole galaxy, maybe it is worth to hear other developers opinion. They sometimes may have good ideas, which may help you in creating really great API :)

  • Listen to your clients

    Client is a boss. Don't forget about it. If he is saying that something might be better or easier to use - think about it and try to understand clients' needs.

10 January, 2015

How to replace "switch" with the polymorphism?

Problem

A few days ago we were discussing the coding standards, that we are going to adhere. One of the points was preventing from creating of the very big conditional statements.

Lets take the "switch" statement into consideration. It is nothing wrong in using this statement until it does one thing, but as we all know, "switch" usually makes a lot of things and it is much bigger, then it should be. If we want to adhere SOLID principles, we cannot write huge, multi-actions conditional statements.

In this post I want to show you one of the most popular methods of replacing of the "switch" with the polymorphism. Lets see how to do this?

Solution

public class DocumentsHandler
{
    public void HandleDocument(Document document)
    {
        //...
        List importedDocumentElementsIds = GetImportedDocumentElementsIds(clientName, document);
        //...
    }

    public List GetImportedDocumentElementsIds(string clientName, object document)
    {
        /* Somewhere in the code we have:
         * - entity context
         * - name of the client
         * 
         * Some operations ...
         * 
         * */
        switch typeof(document)
        {
            case Sales :
                return BaseDocumentElementsImport(clientName, context.GetSalesDocumentsElements())
            case Purchase :
                return BaseDocumentElementsImport(clientName, context.GetPurchaseDocumentsElements())
            case Custom :
                return BaseDocumentElementsImport(clientName, context.GetCustomDocumentsElements())
            // other document types...
            case default :
                return BaseDocumentElementsImport(clientName, context.GetOtherDocumentsElements())
        }
    }
}

Now we will replace an old Document with a new one. It will be an abstract class with an template method, which we are going to override.

public abstract class Document
{
    public abstract List ImportDocumentElements(string clientName)
}

In the next step we create a set of derived classes which will contain overriden template method.

    public class SalesDocument : Document
    {
        //...
          public override List ImportDocumentElements(string clientName) 
          {
            return BaseDocumentElementsImport(clientName, context.GetSalesDocumentsElements());
          } 
        //...
    }

    public class PurchaseDocument : Document
    {
        //...
          public override List ImportDocumentElements(string clientName) 
          {
            return BaseDocumentElementsImport(clientName, context.GetPurchaseDocumentsElements());
          } 
        //...
    }

    public class CustomDocument : Document
    {
        //...
          public override List ImportDocumentElements(string clientName) 
          {
            return BaseDocumentElementsImport(clientName, context.GetCustomDocumentsElements());
          } 
        //...
    }

    public class OtherDocument : Document
    {
        //...
          public override List ImportDocumentElements(string clientName) 
          {
            return BaseDocumentElementsImport(clientName, context.GetOtherDocumentsElements());
          } 
        //...
    }

Now in the code we can write simple, short line of code like below:

List importedDocumentElementsIds = document.ImportDocumentElements(clientName));

Benefits

It seems that the code is now more complicated and we wrote more LOCs, so why did we do this?

  • We do not duplicate the code because we do not have identical conditions.
  • Usage is simpler and more elegant, because we write smaller numer of LOCs.
  • Object knows everything about itself. We do not need to pass the state the the object under some conditions. We only need to tell the object to perform the operation and it will decide how to do this.
  • Now our code is extensible. We can add new class with new implementation of the overriden method instead of adding new case to the "switch". To be honest, "switch" conditions like to grow very quickly.

28 September, 2014

varchar vs nvarchar

What are the differences between varchar and nvarchar in Microsoft SQL Server? Question quite common on the recruitment tests, but the question: when and why we should use this one or this one is not so simple.

First, let’s take a look what are varchar and nvarchar:

  • nvarchar- variable-length, it takes more space than varchar, can store any Unicode data, dependent on the database collation,
  • varchar - restricted to an 8-bit codepage (but not in every collation), single-byte character data, it takes less space than nvarchar, it cannot contain Unicode characters, the database collation determines which code page the data is using.

The next question which we should ask ourselves is: when we should use varchar and in which situations we should use nvarchar ?

nvarchar: - When your application need to be translated to e.g. Arabic, Mandarin, Hebrew, Japanese or other languages with 16-bit encoding, or at least there is a big possibility that it will be translated in the future. - When your application will use very small database, you can use nvarchar (for convenience) for every text column. - When you do care more about convenience than disk space, memory and effectiveness.

varchar: - When you will NEVER use Unicode. - When performance and effectiveness is important for you. - When you want to save some space and memory.

Before choosing one of those two types remember about the following things:

  • Changing the data type from varchar to nvarchar and vice versa is very expensive, especially if the project is in a later phase.
  • When system has a big data base and the effectiveness is important, consider using varchar – it is faster.
  • You should not do this, but … if you make JOIN on the columns with varchar and nvarchar, then there is a big performance hit.
  • When you are using nvarchar in stored procedures or scripts use prefix N (e.g. DECLARE @name = N'The name';) which prevent string type conversions at runtime.

Summarizing: choice between varchar and nvarchar depends on what type of application you are writing and what is important for you (effectiveness or convenience).

31 August, 2014

UI Holy Grails part 1 - how to set two controls in one line

Everyone, who at least once was making an UI for the web application, met this problem: how to center vertically two controls, which are in one container side by side? One of them is higher, the second one lower, and when you finally set them up correctly – the div below the container double its height! Arrrrrgh! Chill out, deep breath and continue reading this post.
Imagine you have simple div with two controls: label and input like below.
    
You want label and input to be side by side with the vertical center on the same line. Nothing simpler, isn’t it? In fact … no! In simple web applications with very small, simple CSS usually there are no problems with correct position of the controls, but when there are many style sheets, which are overwriting each other classes, then the problem with the proper location is quite common. Sometimes it is very hard to determine where is the CSS line that causes the problem is.
To fix that problem you should firstly use F12 tools to find which line in which CSS is responsible for incorrect position of the controls and then you can start customization of the CSS. On the list below I have gathered, basing on my experience, some ideas which may help you in resolving of this problem. Some of them are very simple, but I was trying to make a compilation of ideas that I have seen during last 3 years.
  • Set up vertical-align value to “middle”. It seems to be obvious, but sometimes, especially when you were using some upper (or lower) index, the value of this align might be different.
  • Take a look into the height of the container which contains our two controls. Maybe it has correct setting, but our two controls are too short. In this case try to set the height property of our two problematic controls to 100%. Sometimes filling of the container height with the controls can help, especially when the container has correct settings. Remember to check the max-height and min-height properties of the container and the controls.
  • Very popular, but not easy to use with other elements in complicated structure of HTML tags (e.g. ASPX webpage) is line-height. This property changes the height of a line (“row”) which contains the given control. Sometimes it occurs that the line-height of the controls differs between each other, so it is better to set for them the same value and remember to check the line-height of the container itself. The next thing to remember is to test if the line-height did not impact other controls on the website.
  • In some cases, a good solution is to check if there are some paddings or margins added to our problematic controls itself. Changing of the padding and margin values might be helpful, especially when the controls inherits the values from the container.
  • The last solution, which is strange but sometimes helpful is using of the float property with the value “right” or “left”. “Float” removes the control from the normal object constructions. It means that some of the properties are being turned off, when we decide to use float: left or float:right. In some cases using of this property will not fix the problem, but it will give clue where you should be looking for the problem. It might occur, that the e.g. the margin, absolute position or left / right property is a problem.

If you have more ideas for resolving this problem share it in a comment.

24 August, 2014

ForEach != foreach

It is very often that we have to make some operations on every element in the collection. The most popular ways of doing this is to use a “for” or ”foreach” loop. Here are three ways of doing this:

  • “For” loop – One of the oldest loops known to the mankind. It is the easy solution to get e.g. particular element of the array, but it is not the most efficient way of iterating over collections.
  • “foreach” loop – This is a newer type of loop which iterates over the whole collection of objects. It is easy, it is fast and you can use it on every ICollection and array.
  • "ForEach" – Public method of the generic list which, from the definition: Performs the specified action on each element of the System.Collections.Generic.List. This is considered as the fastest way of doing some operations on every element of the generic List.

At first it seems that the classic “foreach” and generic List “ForEach” are the same, there are some significant differences. Here is a very simple example of them suing the most popular collection: generic list.

Let’s create a list of strings and populate it with come Guids:

List listOfStrings = new List();
            
            for (int i = 0; i < 1000000; i++)
            {
              listOfStrings.Add(Guid.NewGuid().ToString());  
            }

Now initialize a new list which will be holding changed values from our first list:

List listOfNewStrings = new List();

And now we will do some operations on each element of the collection using classic foreach:

foreach (string s in listOfStrings)
            {
                if (s.Contains("6"))
                    continue;
                else if (s.Contains("4"))
                    return;
                else
                    listOfNewStrings.Add(string.Format(s + "{0}", "SUFIX"));
            }

Everything is ok, the code is compiling and now we will do the funny part. We will make some operations on every element of the list using the generic list ForEach method:

listOfStrings.ForEach(s => 
                {
                    if (s.Contains("6"))
                        continue;
                    else if (s.Contains("4"))
                        return;
                    else
                        listOfNewStrings.Add(string.Format(s + "{0}", "SUFIX"));
                });

And here is the surprise- the code is not compiling. We do the same operations on the same list so what is going on?

The answer is quite simple: ForEach from the System.Collections.Generic.List is not a loop, but a normal method. As it is not a loop, then we cannot break it or continue.

ForEach, as an argument, takes the System.Action delegate. This action will be performed on each element of the list. In other words: we do some operations on each element of the list, but we cannot “break” the execution or “continue” the execution, we can only exit ForEach using return. Remember that ForEach is a function, so we return only from the ForEach and pass the control to the function, that started ForEach execution and in case of “foreach” loop – return will finish execution of the whole function.

The advantages of using “ForEach” are the ease of use, readability and ForEach can modify the list over which it is iterating, so if we do not need to use break or continue inside the loop, we can use the ForEach on the generic List.

12 August, 2014

Unit testing with authentication

When we are developing an application that will be integrating with third party system, we often face the problem of testing some methods, that are using common session, which ID is being returned to us as a result of Authentication process. I have met this problem many times, when I was making integration with ERP systems, WMS's and lately, with eCommerce. I was wondering: how the hell I can write the tests of many methods, using the same session, and make them independent?

I have found some ideas on the blogs and in the articles:
  • Some developers were advising to create one huge test with many assertions, which will start with Login (Authenticate, LogOn, StartSession etc.) method and end with Logout (CloseSession, LogOff, etc). This idea is OK, but it is NOT a UNIT test.
  • Other developers were advising to use some unit testing libraries that enable passing the state between test methods. This idea is also OK, but this is the way of creating integration tests, not the unit tests!
  • The last idea was to log in before and log out after every operation in each unit test. This will also work, but you have to repeat a lot of code, which is a very bad habit.

Finally I have found a solution: IUseFixture interface in xUnit. The framework is very easy to use and unit testing of e.g. API of third party web services is very easy. Here is an example...

Imagine, you want to run some methods of a WS*, which is an API for the ERP system. You want to take some data from the WS*, but you need to be logged in and have a session id. The best way to do this is to use IUseFixture interface.
It is a generic interface, which bases on type, that must by disposable. For example if you want to create session before running each test method and close it after running of each method, you can create your base type like this:

using ThirdPartySystemTests.Service;
using System;

namespace ThirdPartySystemTests
{
    public class SessionFixture : IDisposable
    {
        private SessionHelper sessionHelper;

        public SessionHelper LogOnUser()
        {
          sessionHelper = new SessionHelper();
          sessionHelper.Client = new ThirdPartySystemClient();
          sessionHelper.SessionId = sessionHelper.Client.login
                                   (
                                    sessionHelper.LOGIN, 
                                    sessionHelper.PASSWORD
                                    );
            return sessionHelper;
        }

        public void Dispose()
        {
            bool sessionClosed = 
              sessionHelper.Client.endSession(sessionHelper.SessionId);
        }
    }

    public class SessionHelper
    {
        public ThirdPartySystemClient Client { get; set; }
        public string SessionId { get; set; }
        public string LOGIN = "User";
        public string PASSWORD = "Password";
    }
}


This disposable type has 2 methods: first method creates session on the ThirdPartySystem and the second one closes this session on disposal of the SessionFixture object.
Now it is time to implement tests of ThirdPartySystem using xUnit test with our SessionFixture.

using ThirdPartySystemTests.Service;
using System;
using Xunit;

namespace ThirdPartySystemTests
{
    public class Tests : IUseFixture
    {
        private SessionHelper sessionHelper;

        public void SetFixture(SessionFixture sessionFixture)
        {
            sessionHelper = sessionFixture.LogOnUser();
        }

        [Fact]
        private void GetProductsListTest()
        {
            Product[] products = 
               sessionHelper.Client.GetProductList(sessionHelper.SessionId);
            Assert.NotEmpty(products);
        }

        [Fact]
        private void GetCustomersListTest()
        {
            Customer[] customers = 
               sessionHelper.Client.GetCustomersList(sessionHelper.SessionId);
            Assert.NotEmpty(customers);
        }

        [Fact]
        private void CreateProductTest()
        {
            Prodcut product = new Product
            {
                Name = "Laptop",
                Price = 1000,
                Quantity = 20
            };
            int productId = 
                 sessionHelper.Client.CreateProduct(sessionHelper.SessionId, product);
            Assert.True(productId > 0);
        }
    }
}

Now the LogOnUser method will run before each execution of every test in the class, that implements IUseFixture so you have a new session every time the test runs. What is more, on disposal of the IUseFixture (it means at the end of execution of the test) the session will be closed.

As a result, you have a independent set of unit tests, which do not have any connections and can be run separately. This solution is elegant, easy, safe and it observes the principles of unit tests.

You can also use IUseFixture to e.g. run methods from the base types, create configuration of some objects in the database, prepare data for further operations etc.