Systems

CleanCode

Next part of my notes from Clean Code: A Handbook of Agile Software Craftsmanship, by Robert C. Martin.

Is one person able to manage all details of a big system? Probably not. Also a city exist thanks to teams that take care of different parts of it: water supply, traffic, healthcare, electricity. Some of them know just the general concept while others concentrate on the details in some field.

Kandor_Action_Comics_866

Separate constructing a system from using it

Construction and using are two different problems that should not be mixed together. The process of running in which objects are created should be separated from the application logic.

Let’s take lazy initialization:

        private Service service;

        public Service GetService()
        {
            if (service == null)
            {
                service = new MyService();
            }
            return service;
        }

Lazy initialization is the tactic of delaying the creation of an object until the first time it is needed. Method checks whether a private member has already been initialized. If it has, it is returned. Otherwise a new instance is created, placed into the member variable and returned. The advantage of lazy initialization is that we do not take time for creating an object if we do not need it. Thus, the time of running the application can be shorter. The code above also ensures that the method does not return null value.

Disadvantages are that it brings up dependency on MyService and all elements in MyService constructor. It also makes testing more difficult and we do not know if MyService is the right object for all cases.

Objects creation should be treated as a module and separated so as construction of objects is separated from using them.

Separation of main

One of the ways to separate creation from usage is to create all objects in Main function (or modules that it contains) and then pass built and configured objects to application that simply uses them. Application does not have any information about Main function and the process of creation.

Factories

When it is necessary that application decides when the object is created, you can use factory design pattern. This way also details of creating the object are separated from its usage.

Dependency injection

Another mechanism of separating creation from usage is Dependency Injection which is an implementation of Inversion of Control. Managing dependencies means that an object should not be responsible of creating elements that depends on. It should obtain those elements from outside, for example as arguments of the constructor. Creation o the dependencies is again moved to some external module (for example Main function).

References

“Clean Code: A Handbook of Agile Software Craftsmanship” – Robert C. Martin

Leave a comment