Menu

Programming Concepts

Defensive coding is bundling of known programming best practices so as the software works as expected even under unforeseen circumstances.

The basis of defensive coding are clean code and testable code. “Separation of Concerns” and unit tests or following TDD creates a good base for defensive coding. Even small but significant stuff like using named arguments (C#) goes a long way towards clean and defensive code.

A key aspect of defensive coding is validating the input parameters of methods and throwing appropriate exceptions if they are not as expected.

On the other hand, presence of a suitable mechanism to notify the calling method whether the call to a method succeeded or otherwise is equally important. This mechanism can be different for different family of methods.

We only want to know whether the call to a method succeeded or failed then it is fine that the method returns “Boolean”.

We also want to know the reason for failure then a good technique is to return a custom object which has two properties a) Success = true/false b) List<string> = failure messages.

Also returning null or use of “NULL Object” design pattern is also an option (I prefer the later)

Due to intersection of words in these three terms i.e. inversion is common between IOC and DIP and dependency is common between DIP and DI, its fairly easy to think the three are sides of an equilateral triangle (they are one and the same). Otherwise they give an impression that there is some relationship between these three. For example something like Fig 1 or Fig 2

Fig 1 Fig 2

However nothing can be farther away from truth than the above premise. Reality is Fig 3

Fig 3

or to be more precise reality is like Fig 4

That means IOC & DIP are two disjoint sets and DIP is the super set of DI, service locator and some other patterns.

inversion of control (IoC) describes a design in which custom-written portions of a computer program receive the flow of control from a generic, reusable library. A software architecture with this design inverts control as compared to traditional procedural programming: in traditional programming, the custom code that expresses the purpose of the program calls into reusable libraries to take care of generic tasks, but with inversion of control, it is the reusable code that calls into the custom, or problem-specific, code.

Difference between IOC and DIP

First of all the confusion, that there exists a relationship between IOC and DIP arises because of the presence of word related in the statement “The term (IOC) is related to but different from the dependency inversion principle” in the Wikipedia definition. However probably the author meant that they are related by being part of OOP and OOAD, but clarifies that they are different by usage of word different in the same sentence.

Inversion of Control (IOC)

The Wikipedia definition of IOC is quite a mouthful and its not so easy to understand the meaning or the context in which the words generic / reusable library/ custom code / generic tasks are being used. In my opinion, simply put it is “methods written in class(es) are called by a higher level class who knows in which order they should be called, instead of a function knowing what next function it should call”. [This understanding is inline with the first half of the first paragraph. And the second half talk us in a wrong direction and is irrelevant.]

A simple program to read and save name, id and date of birth of a person from console in C# , without IOC would look like :

Code Snippet 1

using System;

namespace ConsoleApplication1

{

classProgram

{

privatestaticstring _name, _id, _dob;

staticvoid Main()

{

GetName();

}

privatestaticvoid GetName()

{

Console.WriteLine(“Name : “);

_name = Console.ReadLine();

GetId();

}

privatestaticvoid GetId()

{

Console.WriteLine(“ID : “);

_id = Console.ReadLine();

GetDateofBirth();

}

privatestaticvoid GetDateofBirth()

{

Console.WriteLine(“ID : “);

_dob = Console.ReadLine();

}

}

}

In the above “Code Snippet 1” GetName() method knows that after execution of its logic, it has to call GetId(), then GetId() calls GetDateOfBirth() and so on. In this fashion methods have a very strong coupling, low cohesion and you can’t simply just get the name or the Id without calling another method. This is really very procedural.

Now, lets apply IOC and the program would look like “Code Snippet 2”

Code Snippet 2

using System;

namespace ConsoleApplication1

{

classProgram

{

privatestaticstring _name, _id, _dob;

staticvoid Main(string[] args)

{

_name = GetName();

_id = GetId();

_dob = GetDateofBirth();

}

privatestaticstring GetName()

{

Console.WriteLine(“Name : “);

returnConsole.ReadLine();

}

privatestaticstring GetId()

{

Console.WriteLine(“ID : “);

returnConsole.ReadLine();

}

privatestaticstring GetDateofBirth()

{

Console.WriteLine(“Date of Birth : “);

returnConsole.ReadLine();

}

}

}

The “Code Snippet 2” wouldn’t look like a big deal, because we have been doing it like this all along. However many years ago the way of doing things was like in “Code Snippet 1” and this was a welcome change. This example is inline with the definition on Wikipedia that IOC makes code more modular and extensible i.e. now the methods can be called in any sequence / optionally by a framework (Main method in this case).

If we write equivalent html as in “Code Snippet 3”, then the generic / reusable browser decides the order in which to draw the text boxes on the screen (may be it draws the one for DOB, then for Id and finally for Name) i.e. the control of drawing exists with the browser

Further more in case of Asp.net we write the custom code against the events like Page_Load() etc. where in the Asp.net runtime (framework) knows when and how to call those methods. With this we close the case of Inversion of control i.e. the flow of control in a program should not be with the lower lever methods, but the flow of control should be inverted and should lie with a high level class.

Dependency Inversion Principle (DIP)

In object-oriented programming, the dependency inversion principle refers to a specific form of decoupling software modules. When following this principle, the conventional dependency relationships established from high-level, policy-setting modules to low-level, dependency modules are inverted (i.e. reversed), thus rendering high-level modules independent of the low-level module implementation details. The principle states:

A. High-level modules should not depend on low-level modules. Both should depend on abstractions.

B. Abstractions should not depend on details. Details should depend on abstractions.

The principle inverts the way some people may think about object-oriented design, dictating that both high- and low-level objects must depend on the same abstraction.[1]

First of all the word inversion doesn’t literally mean that now instead of high level classes depending on low level classes with DIP; low level classes would depend on high level classes. It means that the higher level classes should not directly depend on the instances of low level classes instead they should deal with the low level classes via interface or abstract class. This is achieved by low level classes implementing interface or abstract classes and high level classes using the using same interface or abstract classes of low level classes. That is the inversion in DIP literally means change i.e. instead of depending on objects of concrete low level classes, high level classes should change their dependency to their interface / abstract class.

For example, we want our Program to perform some business logic, then save some data in a SQLServer database and at the end do some logging. This would be something like :

Code Snippet 4

namespace ConsoleApplication1

{

publicclassFileLogger

{

publicvoid DoLogging()

{

//Do logging

}

}

publicclassSQLDatabase

{

publicvoid SaveSomething()

{

//Persisit data in DB

}

}

publicclassProgram

{

publicvoid DoBusinessLogic()

{

// Some Business Logic

SQLDatabase sqlDatabase = newSQLDatabase();

sqlDatabase.SaveSomething();

FileLogger fileLogger = newFileLogger();

fileLogger.DoLogging();

}

}

classStart

{

staticvoid Main()

{

Program program = newProgram();

program.DoBusinessLogic();

}

}

}

Note how the database and logger object are instantiated by the Program class. However instead of SQLDatabase if we have MySQL and Oracle database also then I would have a if-else or switch-case inside my DoBusiessLogic() method, which is bad or low cohesion because this method should focus on doing business logic and not with figuring out and then instantiating the database and logger objects. Moreover if we have DoBusiessLogic1(), DoBusiessLogic2(), DoBusiessLogic3(),…, then in all of these methods the same if-else / switch-case for database and logger objects will make life tough.

Now, with DIP the above code would look like :

Code Snippet 5

namespace ConsoleApplication1

{

publicinterfaceILogger

{

void DoLogging();

}

publicclassFileLogger : ILogger

{

publicvoid DoLogging()

{

//Do logging

}

}

publicinterfaceIDatabase

{

void SaveSomething();

}

publicclassSQLDatabase : IDatabase

{

publicvoid SaveSomething()

{

//Persisit data in DB

}

}

publicclassProgram

{

publicvoid DoBusinessLogic()

{

// Some Business Logic

IDatabase database = SomeHowGetInstanceofDatabase();

database.SaveSomething();

ILogger logger = SomeHowGetInstanceofLogger();

logger.DoLogging();

}

}

classStart

{

staticvoid Main()

{

Program program = newProgram();

program.DoBusinessLogic();

}

}

}

Here the high level class Program’s DoBusinessLogic() method only deals with the objects of low level classes via interface and its not concerned about the actual concrete types of IDatabase and ILogger. So now what happens of the scenario when we have MySql and Oracle database. Also we have a Console logger. For such a scenario the code would look like :

Code Snippet 6

namespace ConsoleApplication1

{

publicinterfaceILogger

{

void DoLogging();

}

publicclassFileLogger : ILogger

{

publicvoid DoLogging()

{

//Do logging

}

}

publicclassConsoleLogger : ILogger

{

publicvoid DoLogging()

{

//Do logging

}

}

publicinterfaceIDatabase

{

void SaveSomething();

}

publicclassSQLDatabase : IDatabase

{

publicvoid SaveSomething()

{

//Persisit data in DB

}

}

publicclassMySQLDatabase : IDatabase

{

publicvoid SaveSomething()

{

//Persisit data in DB

}

}

publicclassOracleDatabase : IDatabase

{

publicvoid SaveSomething()

{

//Persisit data in DB

}

}

publicclassProgram

{

publicvoid DoBusinessLogic()

{

// Some Business Logic

IDatabase database = SomeHowGetInstanceofDatabase();

database.SaveSomething();

ILogger logger = SomeHowGetInstanceofLogger();

logger.DoLogging();

}

}

classStart

{

staticvoid Main()

{

Program program = newProgram();

program.DoBusinessLogic();

}

}

}

Now MySqlDatabase and Oracle database also implements IDatabase and similarly ConsoleLogger implements ILogger. With this we need not to make any changes to DoBusinessLogic() and it will work just fine with any type of database object as long as it implements IDatabase and any logger if it implements ILogger.

One problem still remains unsolved i.e. SomeHowGetInstanceofDatabase() and SomeHowGetInstanceofLogger(). That’s why DIP is a principle, it doesn’t give us all the answers, it shows us the path but not the means to walk on that path.

Come patterns in picture, patterns give us something concrete or are example on how to adhere to principles. For example GOF Design Patterns shows how to adhere to KISS, DRY, SOLID etc. As for DIP, we have Dependency Injection, Service Locator and other patterns. [DIP is the principle, DI is the pattern to achieve it] With DI we will be able to do something for SomeHowGetInstanceofDatabase() and SomeHowGetInstanceofLogger().

An injection is the passing of a dependency (a service) to a dependent object (a client). The service is made part of the client’s state. Passing the service to the client, rather than allowing a client to build or find the service, is the fundamental requirement of the pattern.

Now in this definition, the first part is ambiguous and what’s difficult to comprehend is how DI implements IOC and the first part of definition should be ignored. Rest all is right on the mark.

There are three or more ways of implementing DI

Martin Fowler identifies three ways in which an object can receive a reference to an external module:[7]

constructor injection: the dependencies are provided through a class constructor.

setter injection: the client exposes a setter method that the injector uses to inject the dependency.

interface injection: the dependency provides an injector method that will inject the dependency into any client passed to it. Clients must implement an interface that exposes a setter method that accepts the dependency.

Constructor Injection

Code Snippet 7

namespace ConsoleApplication1

{

publicinterfaceILogger

{

void DoLogging();

}

publicclassFileLogger : ILogger

{

publicvoid DoLogging()

{

//Do logging

}

}

publicclassConsoleLogger : ILogger

{

publicvoid DoLogging()

{

//Do logging

}

}

publicinterfaceIDatabase

{

void SaveSomething();

}

publicclassSQLDatabase : IDatabase

{

publicvoid SaveSomething()

{

//Persisit data in DB

}

}

publicclassMySQLDatabase : IDatabase

{

publicvoid SaveSomething()

{

//Persisit data in DB

}

}

publicclassOracleDatabase : IDatabase

{

publicvoid SaveSomething()

{

//Persisit data in DB

}

}

publicclassProgram

{

publicvoid DoBusinessLogic(IDatabase db, ILogger lgr)

{

// Some Business Logic

IDatabase database = db;

database.SaveSomething();

ILogger logger = lgr;

logger.DoLogging();

}

}

classStart

{

staticvoid Main()

{

// these two objects should actually come from their respective factory

IDatabase db = newSQLDatabase();

ILogger lgr = newConsoleLogger();

Program program = newProgram();

program.DoBusinessLogic(db, lgr);

}

}

}

As stated in “Code Snippet 7” the instantiation of database and logger objects ideally should be done by means of using the Factory Method pattern.

Setter Injection

Code Snippet 8

namespace ConsoleApplication1

{

publicinterfaceILogger

{

void DoLogging();

}

publicclassFileLogger : ILogger

{

publicvoid DoLogging()

{

//Do logging

}

}

publicclassConsoleLogger : ILogger

{

publicvoid DoLogging()

{

//Do logging

}

}

publicinterfaceIDatabase

{

void SaveSomething();

}

publicclassSQLDatabase : IDatabase

{

publicvoid SaveSomething()

{

//Persisit data in DB

}

}

publicclassMySQLDatabase : IDatabase

{

publicvoid SaveSomething()

{

//Persisit data in DB

}

}

publicclassOracleDatabase : IDatabase

{

publicvoid SaveSomething()

{

//Persisit data in DB

}

}

publicclassProgram

{

privateIDatabase _database { get; set; }

privateILogger _logger { get; set; }

publicvoid SetDatabase(IDatabase db)

{

_database = db;

}

publicvoid SetLogger(ILogger lgr)

{

_logger = lgr;

}

publicvoid DoBusinessLogic()

{

// Some Business Logic

_database.SaveSomething();

_logger.DoLogging();

}

}

classStart

{

staticvoid Main()

{

// these two objects should actually come from their respective factory

IDatabase db = newSQLDatabase();

ILogger lgr = newConsoleLogger();

Program program = newProgram();

program.SetDatabase(db);

program.SetLogger(lgr);

program.DoBusinessLogic();

}

}

}

Instead of explicit methods to Set dependencies Properties can be uses, also in .net framework Properties compile into Get() and Set() method in the assembly so ultimately its one and the same thing.

Code Snippet 9

namespace ConsoleApplication1

{

publicinterfaceILogger

{

void DoLogging();

}

publicclassFileLogger : ILogger

{

publicvoid DoLogging()

{

//Do logging

}

}

publicclassConsoleLogger : ILogger

{

publicvoid DoLogging()

{

//Do logging

}

}

publicinterfaceIDatabase

{

void SaveSomething();

}

publicclassSQLDatabase : IDatabase

{

publicvoid SaveSomething()

{

//Persisit data in DB

}

}

publicclassMySQLDatabase : IDatabase

{

publicvoid SaveSomething()

{

//Persisit data in DB

}

}

publicclassOracleDatabase : IDatabase

{

publicvoid SaveSomething()

{

//Persisit data in DB

}

}

publicclassProgram

{

publicIDatabase Database { get; set; }

publicILogger Logger { get; set; }

publicvoid DoBusinessLogic()

{

// Some Business Logic

Database.SaveSomething();

Logger.DoLogging();

}

}

classStart

{

staticvoid Main()

{

// these two objects should actually come from their respective factory

IDatabase db = newSQLDatabase();

ILogger lgr = newConsoleLogger();

Program program = newProgram();

program.Database = db;

program.Logger = lgr;

program.DoBusinessLogic();

}

}

}

Interface Injection

Code Snippet 10

namespace ConsoleApplication1

{

publicinterfaceILogger

{

void DoLogging();

}

publicclassFileLogger : ILogger

{

publicvoid DoLogging()

{

//Do logging

}

}

publicclassConsoleLogger : ILogger

{

publicvoid DoLogging()

{

//Do logging

}

}

publicinterfaceIDatabase

{

void SaveSomething();

}

publicclassSQLDatabase : IDatabase

{

publicvoid SaveSomething()

{

//Persisit data in DB

}

}

publicclassMySQLDatabase : IDatabase

{

publicvoid SaveSomething()

{

//Persisit data in DB

}

}

publicclassOracleDatabase : IDatabase

{

publicvoid SaveSomething()

{

//Persisit data in DB

}

}

internalinterfaceIDependency

{

void SetDatabase(IDatabase db);

void SetLogger(ILogger lgr);

}

publicclassProgram:IDependency

{

privateIDatabase _database { get; set; }

privateILogger _logger { get; set; }

publicvoid SetDatabase(IDatabase db)

{

_database = db;

}

publicvoid SetLogger(ILogger lgr)

{

_logger = lgr;

}

publicvoid DoBusinessLogic()

{

// Some Business Logic

_database.SaveSomething();

_logger.DoLogging();

}

}

classStart

{

staticvoid Main()

{

// these two objects should actually come from their respective factory

IDatabase db = newSQLDatabase();

ILogger lgr = newConsoleLogger();

Program program = newProgram();

program.SetDatabase(db);

program.SetLogger(lgr);

program.DoBusinessLogic();

}

}

}

Interface Injection is similar to Setter Injection, here we have formalized the signature of the methods (or properties) used to inject the dependency.

Service Locator Pattern

The service locator pattern is a design pattern used in software development to encapsulate the processes involved in obtaining a service with a strong abstraction layer. This pattern uses a central registry known as the “service locator”, which on request returns the information necessary to perform a certain task.[1]

In “Service Locator”, there is a service locator interface, which promises to provide the requisite services(dependencies) which is implemented by a concrete class. The concrete service locator object can be provided to the high level class via constructor or methods or properties. This concrete service locator object ultimately provides the objects of required services (dependencies). In the below example the concrete object of service locator is provided via constructor of the high level class

Code Snippet 11

namespace ConsoleApplication1

{

publicinterfaceILogger

{

void DoLogging();

}

publicclassFileLogger : ILogger

{

publicvoid DoLogging()

{

//Do logging

}

}

publicclassConsoleLogger : ILogger

{

publicvoid DoLogging()

{

//Do logging

}

}

publicinterfaceIDatabase

{

void SaveSomething();

}

publicclassSQLDatabase : IDatabase

{

publicvoid SaveSomething()

{

//Persisit data in DB

}

}

publicclassMySQLDatabase : IDatabase

{

publicvoid SaveSomething()

{

//Persisit data in DB

}

}

publicclassOracleDatabase : IDatabase

{

publicvoid SaveSomething()

{

//Persisit data in DB

}

}

publicinterfaceIServiceLocator

{

IDatabase LocateDatabaseService();

ILogger LocateLoggerService();

}

publicclassServiceLocator : IServiceLocator

{

privateIDatabase _database { get; set; }

privateILogger _logger { get; set; }

public ServiceLocator(IDatabase db, ILogger lgr)

{

_database = db;

_logger = lgr;

}

publicIDatabase LocateDatabaseService()

{

return _database;

}

publicILogger LocateLoggerService()

{

return _logger;

}

}

publicclassProgram

{

privateIDatabase _database { get; set; }

privateILogger _logger { get; set; }

public Program(IServiceLocator serviceLocator)

{

_database = serviceLocator.LocateDatabaseService();

_logger = serviceLocator.LocateLoggerService();

}

publicvoid DoBusinessLogic()

{

// Some Business Logic

_database.SaveSomething();

_logger.DoLogging();

}

}

classStart

{

staticvoid Main()

{

// these two objects should actually come from their respective factory

IDatabase db = newSQLDatabase();

ILogger lgr = newConsoleLogger();

IServiceLocator srvLctr = newServiceLocator(db,lgr);

Program program = newProgram(srvLctr);

program.DoBusinessLogic();

}

}

}

This concludes my long post on IOC, DIP & DI with bit of “Service Locator” thrown in. Its was my small attempt to help anyone else and to increase my own understanding. (phew…)