I dare say that anyone who has worked with software developers has come to the realization that we are very proud people. We take pride in solving challenging problems, in the smart way we implement solutions, sometimes even in the sheer beauty of the code we have written. And we should, software development is not a simple trade, we must develop a strong capacity to abstract the world around us and model it into a working solution by using some arcane language that not everybody can understand. In a nutshell, we must be good at describing and communicating our world to machines.

The only problem with that is that some developers take so much pride in these things that they forget why they are doing what they are doing.

Let’s think about it for a moment. There are only two possible reasons someone would be willing to pay huge amounts of money for a piece of software: make money, or save money. That’s it! That’s all there is to it. Those are the most important goals our incredibly smart crafted solutions should meet. Those are the motivations that drove our customers’ stakeholders to sponsor the project we are currently involved in.

The implications of this are really important. I cannot tell you how many times I have been involved in projects in which the customer wants to enhance its software, add features, adapt it to new requirements because of changes in their industry or their markets, or to fix defects only to come to the realization that all of this is going to take a very large amount of resources, mainly time and money, because of the poor quality of the code in their solution.

Usually I always hear the same reasons as to why this has happened. This code might have been produced by an amazingly brilliant developer who put it together in a few hours or a few days, but it is so complex that he is the only one who knows how to modify it (patch it, and keep patching it). Maybe it was the result of a very tight deadline and the team just did not have enough time to code it properly. It could have been because the managers were always pushing the developers to finish it quickly.

Regardless of the reason, the code is there and now its owner has to invest large amounts of time and money for even the simplest modifications. Guess what? The main goals cannot be met anymore since the company is spending too much money in their software’s maintenance, hence it is not helping them to save money, and it is not helping them to make the money it was supposed to.

We, as developers, need to start thinking about Total Cost of Ownership. This means how much will it cost to own this piece of software over time, and our main objective as developers should be to keep that number as low as humanly possible.

So be proud about the code you write, but focus that pride in the ease in which other developers are capable of adding features, fixing defects or modify that code in general without breaking it all over the place. Take pride in the small investment that your customer needs to put on its maintenance. Take pride in the huge business the code that you wrote is generating for your customer.

Go young grasshopper, code responsibly and make yourself proud.

Advertisements

Nowadays is really difficult to be reading anything about software development without stumbling upon a web page, blog, book, article or the like that discusses software development / design principles. SOLID, KISS, and YAGNI are acronyms that come up in lots of discussions among developers which is good, it means that most people are aware about the importance of good practices in order to build robust applications that do not end up in a maintenance nightmare. The only problem is that I have seen people use them in such a way that they end up being the justification for poor, tightly coupled, difficult to maintain software.

But, I hear you say, how can principles that are supposed to enforce good software be used to produce the opposite? I believe is part of human nature. We can find in history too many examples of things that were created for good that end up being used for evil. In the case of these design principles I believe that a lot of developers really do not want to change the way they have always develop software because, let’s face it, once you are comfortable doing something it is really painful to do the exact same think in a completely different way, so it seems that it is much easier to try to convince others, and ourselves, that our way of doing things is the way that comply with said principles.

Unfortunately most of the time this way is not the way things should be done because it is, well, the way things have always been done that have ended in tightly coupled, spaghetti code. In particular I have been involved in some discussions in which people argued that the idea that good development techniques to decouple software like IoC or dependency injection should not be used, at least not at the beginning, under the YAGNI flag. The “You Ain’t Gonna Need It” idea does have a lot of promise of not adding unnecessary complexity to a piece of software if at that moment there are no requirements that justify it. This is always helpful when you hear someone saying something like “but what if they need to add more types of foo?” That is a valid question to which the answer can always be “what if that requirement is never defined?” The problem comes when you hear people saying that decoupling infrastructure should only be implemented as the need arises because it is not needed from the beginning and it will only add complexity to the code.

By following this last recommendation, the question that comes to mind is when will this decoupling optimization be needed? When the code is so tangled up that it would take weeks to refactor it and break all the dependencies? Is it when each time we are trying to add a feature or fix a defect we end up breaking the application in lots of different places? Maybe when you start hearing developers say they do not want to touch or change a particular section of the code? If all of these scenarios are not something we would like to have in our code then how can employing proved techniques, like IoC or dependency injection, that really do not add that much to the complexity of the code be harmful?

Now days we can even unit test all kinds of tightly coupled messes thanks to tools like TypeMock and MS Fakes. The problem is that these tools are making some people believe that IoC and dependency injection are no longer needed because those techniques’ only purpose was to achieve testability and now we can mock hard coded dependencies. But even with this kind of code all covered with tests, refactoring, fixing defects, and adding features can be a titanic endeavor just because we did not take the time to properly design the application from the beginning because of YAGNI.

As professional, software developers, coders, software engineers, or whatever you want to call us, we need to understand that if someone is going to need more than a couple of hours to at least figure out how the code we wrote works, and that includes both the production code and the tests, then it is not quality code. Having loosely coupled, isolated code aids in this understanding and we need to defend the practices and ideas that have come to improve the way we develop software and not use them to go back and do the ones that we have already left behind.

In the last few years a lot has been written about the benefits of automated testing, unit testing, TDD, and mocking frameworks. So much has been written about it, even demonstrated in the field, that I find quite surprising, and frightening, that there are some blogs out there in which their authors claim that the effort required to write the tests and let the tests drive the design is a huge overhead, not necessary, increases the complexity of both the production code and the tests themselves, a bad approach among other things.

Unfortunately I was unable to find the exact quote, but I believe that it was in his book, Architecting Applications for the Enterprise, that Dino Esposito says, I am paraphrasing, that there is no difference between a working piece of software that is testable and another one that is not, but the one that is designed with testability in mind will have a much better design. Even though I do not agree with the first part of this claim, the reasons and arguments are the subject of another post, I absolutely agree with the second part of it. When we design our software with testability in mind the end result is a much more maintainable and loosely coupled design.

With these ideas in mind, the next series of posts will aim to address some of the, what I consider, misconceptions about designing for testability, loosely coupling, and the YAGNI and KISS principles. I hope that by the end of them I will be able to add a small contribution to the development community in trying to make software development a more robust discipline.

Designing for testability does pose a number of challenges that have been addressed in a number of ways. One of these ways has been the Inversion of Control (IoC) principle, and more specifically by using Dependency Injection. Another way has been by the creation of tools like TypeMock and Microsoft Fakes. In a nutshell these tools are able to reach into unreachable code and replace static methods and tightly coupled classes with stubs so that untestable code can be unit tested. We will discuss this type of tools at another time, what I am more interested right now is to talk about an online argument in the comments section of this blog post between two people about the use of these tools.

The person who was against the use of this tools was concerned about the unmaintainable and tightly coupled software that could be developed since the limitations of replacing those hard coded dependencies were no longer there. The other person, who was not only in favor of these tools but avidly encouraged their use, claimed that his concerns were the result of the idea of “the ability for code to be unit testable in classical terms” and that the use of an abstract factory would reduce the coupling even further. This last comment was what drew the line for me. Don’t get me wrong, I love the abstract factory pattern and I think is an invaluable tool to abstract the creation of objects from the components that will use them. This does not mean that an abstract factory in itself will be loosely coupled to the code that needs to decide which concrete factory to instantiate and have it create the required object.

To be able to demonstrate these ideas, let’s think about a smart phone manufacturer that has different lines of products and these products can be subdivide into sub-products to satisfy the increasing demands of a hungry market. Of course when the manufactured products reach a certain point in the assembly line a certain number of, what do you know, tests will have to be performed to make sure each product comply with the company’s quality policies. In order to do that all products need to have a common interface to be handed to the testing process, which will not be interested in the exact model of the product.

    public interface IPhone
    {
        void DoSomething();
    }

    public class HighEnd16Gig : IPhone
    {
        public void DoSomething(){}
    }

    public class HighEnd32Gig : IPhone
    {
        public void DoSomething(){}
    }

    public class LowEnd16Gig : IPhone
    {
        public void DoSomething(){}
    }

    public class LowEnd32Gig : IPhone
    {
        public void DoSomething(){}
    }

We can see that we have a high end and a low end phone and that each of them comes in 16 and 32 gigs of storage models. Since the testing process should not care about what kind of phone it will receive at any given time, we define an abstract factory to create the concrete product before starting the tests.

    public interface IPhoneFactory
    {
        IPhone Create();
    }

    public class HighEndFactory : IPhoneFactory
    {
        private readonly StorageSize _storageSize;

        public HighEndFactory(StorageSize storageSize)
        {
            _storageSize = storageSize;
        }

        public IPhone Create()
        {
            switch (_storageSize)
            {
                case StorageSize.Gig16:
                    return new HighEnd16Gig();
                case StorageSize.Gig32:
                    return new HighEnd32Gig();
                default:
                    throw new ArgumentException("Unknown high end model.");
            }
        }
    }

    public class LowEndFactory : IPhoneFactory
    {
        private readonly StorageSize _storageSize;

        public LowEndFactory(StorageSize storageSize)
        {
            _storageSize = storageSize;
        }

        public IPhone Create()
        {
            switch (_storageSize)
            {
                case StorageSize.Gig16:
                    return new LowEnd16Gig();
                case StorageSize.Gig32:
                    return new LowEnd32Gig();
                default:
                    throw new ArgumentException("Unknown low end model.");
            }
        }
    }
    public interface IManufacturingProcess
    {
        void ProcessProduct(ProductType productType, StorageSize storageSize);
    }

    public class TestingCell : IManufacturingProcess
    {
        public void ProcessProduct(ProductType productType, StorageSize storageSize)
        {
            //Do some stuff.

            IPhoneFactory factory;
            switch (productType)
            {
                case ProductType.HighEnd:
                    factory = new HighEndFactory(storageSize);
                    break;
                case ProductType.LowEnd:
                    factory = new LowEndFactory(storageSize);
                    break;
                default:
                    throw new ArgumentException("Unknown Product Type");
            }

            var product = factory.Create();
            ExecuteTests(product);
        }

        private void ExecuteTests(IPhone product)
        {
            product.DoSomething();
        }
    }

This is a very good design, we can see that the component that is going to start the testing process is completely abstracted from the creation mechanism of the different types of products, but there is still one problem, this component is tightly coupled not only to the abstraction but to the two concrete implementations as well. This component is deciding which kind of factory it needs to instantiate to ask for the product it will send to the testing process so if new product lines are added, it will have to be modified to include the new concrete factories and this is a big maintenance issue. Even worse, this is just one step of the whole process, other processes will have to implement the same logic to determine which factory to use.

A much better approach would be to inject the factory to this component so it is completely agnostic of the kind of factory it will be calling.

    public interface IManufacturingProcess
    {
        void ProcessProduct();
    }

    public class TestingCell : IManufacturingProcess
    {
        private readonly IPhoneFactory _factory;

        public TestingCell(IPhoneFactory factory)
        {
            if(factory == null) throw new ArgumentNullException("factory");
            _factory = factory;
        }

        public void ProcessProduct()
        {
            //Do some stuff.

            var product = _factory.Create();
            ExecuteTests(product);
        }

        private void ExecuteTests(IPhone product)
        {
            product.DoSomething();
        }
    }

The benefits of this approach are so many that it just cannot be underestimated:

  • These factories are used by a lot of components throughout the manufacturing process so the code to decide which factory to instantiate will not have to be duplicated in each one.
  • If the factories, the products, and their interfaces are each defined in their own assembly the components that use them only need a reference to the one with the interfaces so, even if new factories are constantly added the assemblies that use them will not have to be recompiled making all of your assemblies truly decoupled.
  • The instantiation of the factories can be isolated in a single place of the application, preferably in the Composition Root.
  • The components that require the factories’ adhere more to the Single Responsibility Principle.
  • The component that will perform the tests can be unit tested in complete isolation without any concern of how the factories create the products.
  • Once you have made your peace with the concepts of abstract factory, dependency injection, and composition root, a nice implementation of all of these concepts working together can be used.

Even though abstract factories are a wonderful tool to isolate and abstract the creation of components from their callers, they are not, in their own sense, a way to achieve a loosely coupled design. To this day the best design technique that I have seen to achieve absolute and truly loose coupling, not only from individual classes but from full assemblies, is dependency injection. I will not presume to say that this is the golden hammer of software engineering, but so far it has proven itself to be the best we’ve got.

In the twelve years I’ve been developing software I’ve seen quite a few methods, classes, subroutines, scripts, among others. A statement that has been true ever since day one of my development years is that I have spent more time reading code than writing it and I’m sure I don’t have to tell you about some of the horrors I’ve seen during this time. Thinking about this, I’ve come to realize that after so many years of hearing and reading about best practices, self-documented code, small classes and methods, single responsibility purpose, and quite some others nifty concepts it’s amazing how you can still find 500 or more lines of code methods, huge classes that have multiple responsibilities, tightly copuled and low cohesive objects and all sort of development nightmares that make the code difficult to read and maintain.

Surely there is not a single developer who has not written a method only to come back to it some time later and not being able to understand what on earth is it doing, or at the very best to have to spend quite some time figuring it out. And of course that is even more true when we stumble upon a piece of code written by someone else.

With legions of excellent developers all over the world, I truly believe that there can never be enough talk about ways of trying to improve the readability and ease of maintainability of code so, in that tone, I would like to post here a very small demonstration of a piece of code we had at our current project that was, well quite bad, and how it became much more readable after doing some very simple refactoring.

private void SetPermissionToAdjustOrCancell(CustodyTicketDto custodyTicketDto)
{
  var userRole = PortalInternalService.GetRolesforUser(UserSettings.Current.UserId, UserSettings.Current.CompanyId);
  bool canCancelAdjustTicket = false;

  foreach (RoleDto role in userRole)
  {
     if (role.RoleName == Roles.FIELD_OPERATOR_RECEIPT && Activity.ToUpper() == “RECEIPT”)
       canCancelAdjustTicket = true;

     if (role.RoleName == Roles.FIELD_OPERATOR_DELIVERY && Activity.ToUpper() == “DELIVERY”)
       canCancelAdjustTicket = true;
  }

  _view.IsUserAllowedToAdjustOrCancel = canCancelAdjustTicket &&
    (
     (custodyTicketDto.IsCancellable.HasValue && custodyTicketDto.IsCancellable.Value) ||
     (custodyTicketDto.IsAdjustable.HasValue && custodyTicketDto.IsAdjustable.Value)
    );
}

Now this method is by far not the worst anybody has ever seen, but it’s bad enough to illustrate what we should be after. As you can see it has quite a few lines of code, there are several things going on at different levels of abstraction and you need a few moments to analyze each conditional within the method to understand what each one does.

So the first thing we had to do was to write a few unit tests just to make sure we were not breaking anything and once that was set we started breaking up this creepy method into something much more manageable and quite more readable. The end result, at least for now, was this:

private void SetPermissionToAdjustOrCancell(CustodyTicketDto custodyTicketDto)
{
   var userRoles = PortalInternalService.GetRolesforUser(UserSettings.Current.UserId, UserSettings.Current.CompanyId);

   _view.IsUserAllowedToAdjustOrCancel = IsUserInRoleThatAllowsCancelOrAdjust(userRoles) && IsTicketAdjustableOrCancellable(custodyTicketDto);
}

private bool IsUserInRoleThatAllowsCancelOrAdjust(IEnumerable userRoles)
{
   bool canCancelAdjustTicket = false;

   foreach (RoleDto role in userRoles)
   {
      if (IsReceiptRoleAndReceiptActivity(role) || IsDeliveryRoleAndDeliveryActivity(role))
         canCancelAdjustTicket = true;
   }
   return canCancelAdjustTicket;
}

private bool IsReceiptRoleAndReceiptActivity(RoleDto role)
{
   return role.RoleName == Roles.FIELD_OPERATOR_RECEIPT && Activity.ToUpper() ==
“RECEIPT”;
}

private bool IsDeliveryRoleAndDeliveryActivity(RoleDto role)
{
   return role.RoleName == Roles.FIELD_OPERATOR_DELIVERY && Activity.ToUpper() ==
“DELIVERY”;
}

private bool IsTicketAdjustableOrCancellable(CustodyTicketDto custodyTicketDto)
{
   return (custodyTicketDto.IsCancellable.HasValue && custodyTicketDto.IsCancellable.Value) ||
(custodyTicketDto.IsAdjustable.HasValue && custodyTicketDto.IsAdjustable.Value);
}

Now I am very well aware that this method could still be improved, for example the loop in the IsUserInRoleThatAllowsCancelOrAdjust method could very well be replaced by linq queries or that the IsTicketAdjustableOrCancellable could be broken in two methods, but the point is that now someone who has never seen this code will have very little trouble if at all to understand what each method is doing, and without having to add a single comment !!!!

I do not mean to say that this is THE way to go but at least it has been working for us. We’ve had a few new developers say that it is so simple to understand this kind of code and add features or fix defects in it so, if you think this kind of style could be beneficial I encourage you to give it a try and decide if it could prove to be usefull in the long run.

I bought my iPad in July, almost two months after it started selling in Montreal. Besides a couple of iPods I previously owned which were used exclusively to listen to music (none of them were an iPod Touch) this is the very first Apple device I have had.

For quite some time now I have been considering the posiblity of starting my own business and for several reasons I have not. Among those reasons I can list the fact that I had no idea what kind of business I would like to start. I love developing software, I really do, so the idea of doing something else was just out of the question. So why, anyone would ask, haven’t I started a software developing business? To be honest, especially with myself, I have always been afraid to take that kind of a risk.

Why is this discussion relevant to my openning statement of buying an iPad? I am sure most of you have already guessed it. After I took the plunge into the App Store and downloaded the first few apps, I was absolutely amazed by the sheer number of applications in existence to choose from. Some of them really great, some not so much. It did not take me much time to decide that I really wanted a piece of that action. Particularly since I thought that this option would not involve risking my life’s savings and I would be doing the exact activity that I love and hope to keep doing during my whole professional career.

Now, I do not know the first thing about Macs. My mother was a very successful executive at both IBM and HP, so I have owned Windows based desktops and laptops my whole life. And to top it all, I have been a Windows developer ever since I set foot in high school. My first job was developing in VB and ever since 2002 I have been developing in C#. This poses several challenges. For starters, the last time I saw a pointer was during the first half of University. I never learned C++ and I am sure that is going to be one of the biggest factors to make this learning curve quite steep, not to mention the fact that the very first challenge will be to get to know my way around a Mac.

So besides the fierce competion within the App Store, I seem to have quite a few hurdles to clear. I very well know that this is not going to be a “upload your great app, sit back, and wait for the big bucks” kind of deal. There is quite a lot of work ahead of me, both in development and eventually in promoting my future apps, but I am excited and quite optimistic. I have already downloaded a couple of Objective – C books on my shiny new iPad and in the next few days I will be getting my hands on my very first Mac computer. The next steps will be to get my brain in gear and make smoke come out of the keyboard. So like Timbuk3 said back in ’86 “The Future’s So Bright, I Gotta Wear Shades”.