defensive coding

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)

Avoid nested if statements, proper switch case (use enum and appropriately handle default case)  and cast operations will do no harm

Last but not the least, do catch only expected exceptions, have a global exception handler (technology specific) and perform logging as when needed.

A good starting point for Defensive Coding is http://www.pluralsight.com/courses/defensive-coding-csharp

References :

  1. http://en.wikipedia.org/wiki/Defensive_programming
  2. http://danielroop.com/blog/2009/10/15/why-defensive-programming-is-rubbish/
  3. http://geekswithblogs.net/sdorman/archive/2008/07/04/what-is-ldquodefensive-programmingrdquo.aspx
  4. http://blog.ploeh.dk/2013/07/08/defensive-coding/

Essential windows keyboard shortcuts for developers

To be efficient, I try to be least dependent on laptop track-pad . The below set of shortcuts helps to do so for many developers and me alike.

Win = Windows logo key

  Win + E   Launch Windows Explorer
  Ctrl + Home   Move to Top of a document
  Ctrl + End   Move to End of a document
  Ctrl + O   Open a document
  Alt + Tab   Switch between open windows
  Win + Tab   Switch between open windows
  Win + D   Show the desktop or minimize all windows
  Win + Down Arrow Key   Minimize the current window
  Win + Up Arrow Key   Maximize the current window
  Win + Left or Right Arrow Key   Snap to Left or Right of Monitor
  (Useful for quick compare and contrast, works for multi monitor too)

* Not mentioning the most famous “Ctrl + Key” family

Inversion Of Control, Dependency Inversion Principle & Dependency Injection

  1. Inversion of Control (IOC)
  2. Dependency Inversion Principle (DIP)
  3. Dependency Injection (DI)

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

image                     image

                               Fig 1                                                                      Fig 2

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

image

                        Fig 3

or to be more precise reality is like Fig 4

image

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

As per Wikipedia

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.

Inversion of control is used to increase modularity of the program and make it extensible,[1] and has applications in object-oriented programming and other programming paradigms. The term was popularized by Robert C. Martin and Martin Fowler. The term is related to but different from the dependency inversion principle, which concerns itself with decoupling dependencies between high-level and low-level layersthrough shared abstractions.

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
  1. using System;
  2. namespace ConsoleApplication1
  3. {
  4.     class Program
  5.     {
  6.         private static string _name, _id, _dob;
  7.         static void Main()
  8.         {
  9.             GetName();
  10.         }
  11.         private static void GetName()
  12.         {
  13.             Console.WriteLine(“Name : “);
  14.             _name = Console.ReadLine();
  15.             GetId();
  16.         }
  17.         private static void GetId()
  18.         {
  19.             Console.WriteLine(“ID : “);
  20.             _id = Console.ReadLine();
  21.             GetDateofBirth();
  22.         }
  23.         private static void GetDateofBirth()
  24.         {
  25.             Console.WriteLine(“ID : “);
  26.             _dob = Console.ReadLine();
  27.         }
  28.     }
  29. }

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
  1. using System;
  2. namespace ConsoleApplication1
  3. {
  4.     class Program
  5.     {
  6.         private static string _name, _id, _dob;
  7.         static void Main(string[] args)
  8.         {
  9.             _name = GetName();
  10.             _id = GetId();
  11.             _dob = GetDateofBirth();
  12.         }
  13.         private static string GetName()
  14.         {
  15.             Console.WriteLine(“Name : “);
  16.             return Console.ReadLine();
  17.         }
  18.         private static string GetId()
  19.         {
  20.             Console.WriteLine(“ID : “);
  21.               returnConsole.ReadLine();
  22.         }
  23.         private static string GetDateofBirth()
  24.         {
  25.             Console.WriteLine(“Date of Birth : “);
  26.             return Console.ReadLine();
  27.         }
  28.     }
  29. }

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

Code Snippet 3

<html>
    <body>
    <form>
        Name: <input type="text" name="name"><br>
        Id:&nbsp; &nbsp;&nbsp;<input type="text" name="id"><br>
        DOB : <input type="text" name="dob">
    </form>
    </body>
</html>

 

image

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)

As per Wikipedia

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
  1. namespace ConsoleApplication1
  2. {
  3.     public class FileLogger
  4.     {
  5.         public void DoLogging()
  6.         {
  7.             //Do logging
  8.         }
  9.     }
  10.     public class SQLDatabase
  11.     {
  12.         public void SaveSomething()
  13.         {
  14.             //Persisit data in DB   
  15.         }
  16.     }
  17.     public class Program
  18.     {
  19.         public void DoBusinessLogic()
  20.         {
  21.             // Some Business Logic
  22.             SQLDatabase sqlDatabase = new SQLDatabase();
  23.             sqlDatabase.SaveSomething();
  24.             FileLogger fileLogger = new FileLogger();
  25.             fileLogger.DoLogging();
  26.         }
  27.     }
  28.     class Start
  29.     {
  30.         static void Main()
  31.         {
  32.             Program program = new Program();
  33.             program.DoBusinessLogic();
  34.         }
  35.     }
  36. }

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
  1. namespace ConsoleApplication1
  2. {
  3.     public interface ILogger
  4.     {
  5.         void DoLogging();
  6.     }
  7.     public class FileLogger : ILogger
  8.     {
  9.         public void DoLogging()
  10.         {
  11.             //Do logging
  12.         }
  13.     }
  14.     public interface IDatabase
  15.     {
  16.         void SaveSomething();
  17.     }
  18.     public class SQLDatabase : IDatabase
  19.     {
  20.         public void SaveSomething()
  21.         {
  22.             //Persisit data in DB   
  23.         }
  24.     }
  25.     public class Program
  26.     {
  27.         public void DoBusinessLogic()
  28.         {
  29.             // Some Business Logic
  30.             IDatabase database = SomeHowGetInstanceofDatabase();
  31.             database.SaveSomething();
  32.             ILogger logger = SomeHowGetInstanceofLogger();
  33.             logger.DoLogging();
  34.         }
  35.     }
  36.     class Start
  37.     {
  38.         static void Main()
  39.         {
  40.             Program program = new Program();
  41.             program.DoBusinessLogic();
  42.         }
  43.     }
  44. }

 

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
  1. namespace ConsoleApplication1
  2. {
  3.     public interface ILogger
  4.     {
  5.         void DoLogging();
  6.     }
  7.     public class FileLogger : ILogger
  8.     {
  9.         public void DoLogging()
  10.         {
  11.             //Do logging
  12.         }
  13.     }
  14.     public class ConsoleLogger : ILogger
  15.     {
  16.         public void DoLogging()
  17.         {
  18.             //Do logging
  19.         }
  20.     }
  21.     public interface IDatabase
  22.     {
  23.         void SaveSomething();
  24.     }
  25.     public class SQLDatabase : IDatabase
  26.     {
  27.         public void SaveSomething()
  28.         {
  29.             //Persisit data in DB   
  30.         }
  31.     }
  32.     public class MySQLDatabase : IDatabase
  33.     {
  34.         public void SaveSomething()
  35.         {
  36.             //Persisit data in DB   
  37.         }
  38.     }
  39.     public class OracleDatabase : IDatabase
  40.     {
  41.         public void SaveSomething()
  42.         {
  43.             //Persisit data in DB   
  44.         }
  45.     }
  46.     public class Program
  47.     {
  48.         public void DoBusinessLogic()
  49.         {
  50.             // Some Business Logic
  51.             IDatabase database = SomeHowGetInstanceofDatabase();
  52.             database.SaveSomething();
  53.             ILogger logger = SomeHowGetInstanceofLogger();
  54.             logger.DoLogging();
  55.         }
  56.     }
  57.     class Start
  58.     {
  59.         static void Main()
  60.         {
  61.             Program program = new Program();
  62.             program.DoBusinessLogic();
  63.         }
  64.     }
  65. }

 

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().

Dependency Injection (DI)

As per Wikipedia,

Dependency injection is a software design pattern that implements inversion of control and allows a program design to follow the dependency inversion principle. The term was coined by Martin Fowler.[1]

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
  1. namespace ConsoleApplication1
  2. {
  3.     public interface ILogger
  4.     {
  5.         void DoLogging();
  6.     }
  7.     public class FileLogger : ILogger
  8.     {
  9.         public void DoLogging()
  10.         {
  11.             //Do logging
  12.         }
  13.     }
  14.     public class ConsoleLogger : ILogger
  15.     {
  16.         public void DoLogging()
  17.         {
  18.             //Do logging
  19.         }
  20.     }
  21.     public interface IDatabase
  22.     {
  23.         void SaveSomething();
  24.     }
  25.     public class SQLDatabase : IDatabase
  26.     {
  27.         public void SaveSomething()
  28.         {
  29.             //Persisit data in DB   
  30.         }
  31.     }
  32.     public class MySQLDatabase : IDatabase
  33.     {
  34.         public void SaveSomething()
  35.         {
  36.             //Persisit data in DB   
  37.         }
  38.     }
  39.     public class OracleDatabase : IDatabase
  40.     {
  41.         public void SaveSomething()
  42.         {
  43.             //Persisit data in DB   
  44.         }
  45.     }
  46.     public class Program
  47.     {
  48.         public void DoBusinessLogic(IDatabase db, ILogger lgr)
  49.         {
  50.             // Some Business Logic
  51.             IDatabase database = db;
  52.             database.SaveSomething();
  53.             ILogger logger = lgr;
  54.             logger.DoLogging();
  55.         }
  56.     }
  57.     class Start
  58.     {
  59.         static void Main()
  60.         {
  61.             // these two objects should actually come from their respective factory
  62.             IDatabase db = new SQLDatabase();
  63.             ILogger lgr = new ConsoleLogger();
  64.             Program program = new Program();
  65.             program.DoBusinessLogic(db, lgr);
  66.         }
  67.     }
  68. }

 

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
  1. namespace ConsoleApplication1
  2. {
  3.     public interface ILogger
  4.     {
  5.         void DoLogging();
  6.     }
  7.     public class FileLogger : ILogger
  8.     {
  9.         public void DoLogging()
  10.         {
  11.             //Do logging
  12.         }
  13.     }
  14.     public class ConsoleLogger : ILogger
  15.     {
  16.         public void DoLogging()
  17.         {
  18.             //Do logging
  19.         }
  20.     }
  21.     public interface IDatabase
  22.     {
  23.         void SaveSomething();
  24.     }
  25.     public class SQLDatabase : IDatabase
  26.     {
  27.         public void SaveSomething()
  28.         {
  29.             //Persisit data in DB   
  30.         }
  31.     }
  32.     public class MySQLDatabase : IDatabase
  33.     {
  34.         public void SaveSomething()
  35.         {
  36.             //Persisit data in DB   
  37.         }
  38.     }
  39.     public class OracleDatabase : IDatabase
  40.     {
  41.         public void SaveSomething()
  42.         {
  43.             //Persisit data in DB   
  44.         }
  45.     }
  46.     public class Program
  47.     {
  48.         private IDatabase _database { get; set; }
  49.         private ILogger _logger { get; set; }
  50.         public void SetDatabase(IDatabase db)
  51.         {
  52.             _database = db;
  53.         }
  54.         public void SetLogger(ILogger lgr)
  55.         {
  56.             _logger = lgr;
  57.         }
  58.         public void DoBusinessLogic()
  59.         {
  60.             // Some Business Logic
  61.             _database.SaveSomething();
  62.             _logger.DoLogging();
  63.         }
  64.     }
  65.     class Start
  66.     {
  67.         static void Main()
  68.         {
  69.             // these two objects should actually come from their respective factory
  70.             IDatabase db = new SQLDatabase();
  71.             ILogger lgr = new ConsoleLogger();
  72.             Program program = new Program();
  73.             program.SetDatabase(db);
  74.             program.SetLogger(lgr);
  75.             program.DoBusinessLogic();
  76.         }
  77.     }
  78. }

 

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
  1. namespace ConsoleApplication1
  2. {
  3.     public interface ILogger
  4.     {
  5.         void DoLogging();
  6.     }
  7.     public class FileLogger : ILogger
  8.     {
  9.         public void DoLogging()
  10.         {
  11.             //Do logging
  12.         }
  13.     }
  14.     public class ConsoleLogger : ILogger
  15.     {
  16.         public void DoLogging()
  17.         {
  18.             //Do logging
  19.         }
  20.     }
  21.     public interface IDatabase
  22.     {
  23.         void SaveSomething();
  24.     }
  25.     public class SQLDatabase : IDatabase
  26.     {
  27.         public void SaveSomething()
  28.         {
  29.             //Persisit data in DB   
  30.         }
  31.     }
  32.     public class MySQLDatabase : IDatabase
  33.     {
  34.         public void SaveSomething()
  35.         {
  36.             //Persisit data in DB   
  37.         }
  38.     }
  39.     public class OracleDatabase : IDatabase
  40.     {
  41.         public void SaveSomething()
  42.         {
  43.             //Persisit data in DB   
  44.         }
  45.     }
  46.     public class Program
  47.     {
  48.         public IDatabase Database { get; set; }
  49.         public ILogger Logger { get; set; }
  50.         public void DoBusinessLogic()
  51.         {
  52.             // Some Business Logic
  53.             Database.SaveSomething();
  54.             Logger.DoLogging();
  55.         }
  56.     }
  57.     class Start
  58.     {
  59.         static void Main()
  60.         {
  61.             // these two objects should actually come from their respective factory
  62.             IDatabase db = new SQLDatabase();
  63.             ILogger lgr = new ConsoleLogger();
  64.             Program program = new Program();
  65.             program.Database = db;
  66.             program.Logger = lgr;
  67.             program.DoBusinessLogic();
  68.         }
  69.     }
  70. }

Interface Injection

Code Snippet 10
  1. namespace ConsoleApplication1
  2. {
  3.     public interface ILogger
  4.     {
  5.         void DoLogging();
  6.     }
  7.     public class FileLogger : ILogger
  8.     {
  9.         public void DoLogging()
  10.         {
  11.             //Do logging
  12.         }
  13.     }
  14.     public class ConsoleLogger : ILogger
  15.     {
  16.         public void DoLogging()
  17.         {
  18.             //Do logging
  19.         }
  20.     }
  21.     public interface IDatabase
  22.     {
  23.         void SaveSomething();
  24.     }
  25.     public class SQLDatabase : IDatabase
  26.     {
  27.         public void SaveSomething()
  28.         {
  29.             //Persisit data in DB   
  30.         }
  31.     }
  32.     public class MySQLDatabase : IDatabase
  33.     {
  34.         public void SaveSomething()
  35.         {
  36.             //Persisit data in DB   
  37.         }
  38.     }
  39.     public class OracleDatabase : IDatabase
  40.     {
  41.         public void SaveSomething()
  42.         {
  43.             //Persisit data in DB   
  44.         }
  45.     }
  46.     internal interface IDependency
  47.     {
  48.         void SetDatabase(IDatabase db);
  49.         void SetLogger(ILogger lgr);
  50.     }
  51.       public class Program:IDependency
  52.     {
  53.         private IDatabase _database { get; set; }
  54.         private ILogger _logger { get; set; }
  55.         public void SetDatabase(IDatabase db)
  56.         {
  57.             _database = db;
  58.         }
  59.         public void SetLogger(ILogger lgr)
  60.         {
  61.             _logger = lgr;
  62.         }
  63.         public void DoBusinessLogic()
  64.         {
  65.             // Some Business Logic
  66.             _database.SaveSomething();
  67.             _logger.DoLogging();
  68.         }
  69.     }
  70.     class Start
  71.     {
  72.         static void Main()
  73.         {
  74.             // these two objects should actually come from their respective factory
  75.             IDatabase db = new SQLDatabase();
  76.             ILogger lgr = new ConsoleLogger();
  77.             Program program = new Program();
  78.             program.SetDatabase(db);
  79.             program.SetLogger(lgr);
  80.             program.DoBusinessLogic();
  81.         }
  82.     }
  83. }

 

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
  1. namespace ConsoleApplication1
  2. {
  3.     public interface ILogger
  4.     {
  5.         void DoLogging();
  6.     }
  7.     public class FileLogger : ILogger
  8.     {
  9.         public void DoLogging()
  10.         {
  11.             //Do logging
  12.         }
  13.     }
  14.     public class ConsoleLogger : ILogger
  15.     {
  16.         public void DoLogging()
  17.         {
  18.             //Do logging
  19.         }
  20.     }
  21.     public interface IDatabase
  22.     {
  23.         void SaveSomething();
  24.     }
  25.     public class SQLDatabase : IDatabase
  26.     {
  27.         public void SaveSomething()
  28.         {
  29.             //Persisit data in DB   
  30.         }
  31.     }
  32.     public class MySQLDatabase : IDatabase
  33.     {
  34.         public void SaveSomething()
  35.         {
  36.             //Persisit data in DB   
  37.         }
  38.     }
  39.     public class OracleDatabase : IDatabase
  40.     {
  41.         public void SaveSomething()
  42.         {
  43.             //Persisit data in DB   
  44.         }
  45.     }
  46.     public interface IServiceLocator
  47.     {
  48.         IDatabase LocateDatabaseService();
  49.         ILogger LocateLoggerService();
  50.     }
  51.     public class ServiceLocator : IServiceLocator
  52.     {
  53.         private IDatabase _database { get; set; }
  54.         private ILogger _logger { get; set; }
  55.         public ServiceLocator(IDatabase db, ILogger lgr)
  56.         {
  57.             _database = db;
  58.             _logger = lgr;
  59.         }
  60.         public IDatabase LocateDatabaseService()
  61.         {
  62.             return _database;
  63.         }
  64.         public ILogger LocateLoggerService()
  65.         {
  66.             return _logger;
  67.         }
  68.     }
  69.     public class Program
  70.     {
  71.         private IDatabase _database { get; set; }
  72.         private ILogger _logger { get; set; }
  73.         public Program(IServiceLocator serviceLocator)
  74.         {
  75.             _database = serviceLocator.LocateDatabaseService();
  76.             _logger = serviceLocator.LocateLoggerService();
  77.         }
  78.         public void DoBusinessLogic()
  79.         {
  80.             // Some Business Logic
  81.             _database.SaveSomething();
  82.             _logger.DoLogging();
  83.         }
  84.     }
  85.     class Start
  86.     {
  87.         static void Main()
  88.         {
  89.             // these two objects should actually come from their respective factory
  90.             IDatabase db = new SQLDatabase();
  91.             ILogger lgr = new ConsoleLogger();
  92.             IServiceLocator srvLctr =  new ServiceLocator(db,lgr);
  93.             Program program = new Program(srvLctr);
  94.             program.DoBusinessLogic();
  95.         }
  96.     }
  97. }

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…)

Fixing the Sedentary Lifestyle

1. Sedentary lifestyle of a Software Developer will cause big time health problems in future if appropriate actions are not taken. Also it’s like a slow poison or if you like occupational hazard, so bad affects will be visible very subtly and after a long time

2. Actions to be taken :

  • Follow Ergonomics
  • Balanced Diet
  • Exercise (or any kind of physical activity)

3. Ergonomics

  • Stuff you should invest in

– An ergonomic chair.  (If your organization is not willing to buy one for you, buy your own. / If they don’t allow you to buy and bring your own chair, explain them about your future back problem ) or at least buy a decent backrest like this one

– An ergonomic keyboard and mouse like this one

  • Pay attention to symptoms; that wrist pain may be sign for Carpal tunnel Syndrome or slight neck / back pain needs to be checked by a doctor

4. Apart from ergonomics, Diet is I say 90% responsible for your physical well being. Also with our busy lifestyle regular exercise is hard, so Diet is the key and should be controlled and balanced.

5. A healthy body weight in a nutshell depends on Calorie Intake = Calorie Burned. Also With exercise only a very small portion of your daily calorie intake can be burned. For Example: Running for One Hour continuously will burn only 500 calories, however one ice-cream is equal to 500 calories. (this is just an approx. calculation). So limiting the calorie intake is The Key.

6. This can be only done by avoiding or totally stopping food indulgences like Ice Creams , Sweets, Greasy Curries , Fast Food etc. & by Limiting your calorie intake during breakfast, lunch and dinner

7. There is a difference between Hunger (body) and Physiological need for Food (mind) like when you are depressed, you want to take a break and eat out or when you are tensed you want to have cup of tea or coffee which has sugar.

8. On the other hand, Exercise helps to have a toned , strong body and fresh mind. But while exercise do not push yourself too much or you can hurt yourself especially for lifting weights. Mantras like “No Pain No Gain” is for professional athletes not for professional software developers

9. Every food intake for Non-Hunger Reasons(body) like clearing leftovers , over eating at restaurants , over eating at special occasions increases weight and reduces fitness.

10. Weight measured is usually not accurate as you don’t know how much water is in your body and you can’t measure daily how much fat you have. Only way is to monitor your average weight over a period of time.

Object Oriented Programming : Revisited

Firstly it is OOP and not OOPS, probably OOPS as an acronym became popular and has been widely used for many years so everyone just tags along. Anyways, OOP has 4 pillars

1. Abstraction 2. Polymorphism 3. Inheritance 4. Encapsulation

1. Abstraction :

It is the ability to generalize types i.e. it gives us the freedom to think about higher level concepts without going into too much details. Practically it is implemented with Abstract Classes and Interfaces. By using Abstract Classes or Interfaces we can create a software solution by focusing on broader concepts like AbstractCloudStorage or ICloudStorage and focus on what and how of AbstractCloudStorage or ICloudStorage  or how they will interact with browser, OS, data center etc. instead of diluting our attention towards their concrete implementations like GoogleDrive or SkyDrive or iCloud etc.

2. Polymorphism

Polymorphism (from the Greek meaning “having multiple forms”) is the characteristic of being able to assign a different meaning or usage to a variable, a parameter, a field, a property, a function, or an object in different contexts. There are fundamentally three types of Polymorphism, the first two of which were originally informally described by Christopher Strachey in 1967.

a. Ad-hoc Polymorphism which is popularly known as Method (function) and Operator Overloading.

b. Parametric Polymorphism allows us to have variable or field or parameter or property or function parameters of a function or a data type to be written generically instead of dependent on a particular type. This is popularly called as Generics in C# and one of the most popular example of it is List<T>.

c. Subtype Polymorphism (or inclusion polymorphism) is also popularly known as Overriding (though this is debatable). In C# a property or a method can be declared as virtual in base class which then we can override in derived class.

Another aspect of Subtype Polymorphism allows a function to be written to have parameter of a certain type T, but also work correctly if passed a parameter of a type S that is a subtype of T (according to the Liskov Substitution Principle). Subtype Polymorphism is complimentary to Inheritance.

3. Inheritance

Inheritance is a way to create new classes that absorb data and behavior of an already existing class and then enhancing them.

In other words, Inheritance is a way to establish “Is-a” relationship between objects

In classical inheritance where objects are defined by classes, classes can inherit attributes and behavior from pre-existing classes called base classes, superclasses, or parent classes. The resulting classes are known as derived classes, subclasses, or child classes. The relationships of classes through inheritance gives rise to a hierarchy.

However Inheritance more often than not results in the below Issues :

a) It is often confused as a way to reuse the existing code which is not a good practice because inheritance for implementation reuse leads to Tight Coupling i.e between the base class and derived class. This means when changes are done in the Parent class, mostly changes need to be done in the derived class or how the derived class is used; resulting in low maintainability. To understand this kindly visit this link.  Re-usability of code should be achieved through composition (Composition over inheritance). Another link I would highly recommend which tells why we naturally (i.e. our thought process) lean more towards Inheritance and why usually that is not such a good idea.

b) yo-yo problem is an anti-pattern that occurs when a programmer has to read and understand a program whose inheritance graph is so long and complicated that the programmer has to keep flipping between many different class definitions in order to follow the control flow of the program.

d)  Inheritance breaks encapsulation by exposing subclasses to implementation details in the superclass. That is the sub class will always have all the data and behavior of parent class and we can not choose a specific data and behavior of base class to available for derived class. 

4. Encapsulation

It is the ability to wrap “something complex” or “something which had many steps” into a single; easy to use container. Practically it is implemented with Functions or Methods. For example the below method does many things like validating customer information, opening data base connection, firing a query or SP, or use ORM framework to persist customer information in a DB. But the caller of this method need not to worry all this and just need to eat this capsule or call this method.

Code Snippet
  1. private void AddCustomerData(Customer customer)
  2. {
  3.     // Validation Logic
  4.  
  5.     // DB Connection
  6.  
  7.     // Fire Query etc..
  8. }

 

One more thing Information Hiding / Data Hiding / Hiding (in General):

It is the ability to hide unnecessary data and behavior from the end user. Here if you are writing a library your end user is some other software, if it is a class, end user is other classes of the same program etc. Practically it is implemented with Access Modifiers i.e. public, internal, protected, private in .Net world and with Properties and Fields.

By using Access Modifiers we are limiting the visibility and usage of methods (especially), fields, properties to the end user and hiding unnecessary stuff.

On the other hand, by using Properties to Get and Set data we are hiding how actually data is actually processed or manipulated or persisted by the class.

For example in the below example if the end user i.e.Program class’s Start method forget to assign Currency field of Amount object, then while setting the Amount property we can check this and set it as per current region of the computer. What I am trying to demonstrate is; by using Property we have hidden the behavior of checking and assigning currency and this will make sure whenever we Get the Amount it always has Currency.

A similar example of Data Hiding can be when Setting Amount we can normalize it to USD and store it and then while Getting it we can do the appropriate currency conversion as per the computer’s culture.

Code Snippet
  1. using System.Globalization;
  2.  
  3. namespace HidingConsoleApplication
  4. {
  5.     class Program
  6.     {
  7.         public void Start()
  8.         {
  9.             this.Amount = new Amount() { Value = 2.0 };
  10.         }
  11.  
  12.         private Amount _Amount;
  13.         public Amount Amount
  14.         {
  15.             get { return _Amount; }
  16.             set
  17.             {
  18.                 if (string.IsNullOrEmpty(value.Currency))
  19.                 {
  20.                     value.Currency = GetCurrencySymbol();
  21.                 }
  22.                 _Amount = value;
  23.             }
  24.         }
  25.  
  26.         private string GetCurrencySymbol()
  27.         {
  28.             var ri =
  29.             new RegionInfo
  30.             (System.Threading.Thread.CurrentThread.CurrentUICulture.LCID);
  31.             return ri.ISOCurrencySymbol;
  32.         }
  33.     }
  34.  
  35.     class Amount
  36.     {
  37.         public double Value;
  38.         public string Currency;
  39.     }
  40. }

All these concepts are complimentary (rather than competing), so when you are discussing about one, you will never know when you have ventured into the territory of other concept. In my opinion a pragmatic programmer would be able to create elegant code by having strong hands on with OOP concepts. Thus OOP truly results in a code base which is Extendible, Maintainable(Changeable), Scalable,  with Low Coupling and High Cohesion.

Side Notes :

  • A pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class, if that class (the derived class) is not abstract. Classes containing pure virtual methods are termed “abstract”; they cannot be instantiated directly. In C# pure virtual functions are known as abstract methods.
  • Overloading is Compile time polymorphism, Overriding is runtime polymorphism.
  • We can create a long class hierarchy (using) inheritance, however it doesn’t mean we should.
calvin-and-hobbes

SSRS – Crazy Issues; Stupid Solutions

calvin-and-hobbes-e1328550590232

1. Interactive Sorting Garbling Table Header Text

As per best of my knowledge and googling capabilities there is no way to place the interactive sorting up and down arrows as per your choice and they will always appear on the right hand side of the cell / textbox /column header. And this wrecks havoc rendering your SSRS report if the cell / textbox /column header are not wide enough.  Check the below image :

Interactive Sorting Issue 2

A workaround is to have a dummy row below the header row and turn on the interactive sorting for the columns of this dummy row like below :

image

image

And then the when you run the report it will come out like this :

image

2. Image with Transparent Background Getting Garbled When Exported to pdf

This one is really weird, when the image you want to display in footer had a transparent background like below and the footer has a background (sky blue in my case):

image

then when the report is exported to pdf it looks like below, which is not really sharp:

image

So the workaround for this is to provide the image a background i.e. sky blue instead of transparent and then if you export your report in pdf it should be fine as below :

image

3. Display only the Currency Symbol

Typically we want to show the currency next to the numbers whenever we are displaying money in the report and the currency symbol has to be as per the client machine or browser locale, for example like below :

image

For this what we do is :

1. Set the Language property of report to User!Language

2. Set Format property of cells to C0 or something similar

As you can see, the currency symbol is also going to occupy some cell space and when the numbers has many digits this will cause a line break which will not be nice. So the ideal case is to display the currency symbol next to the column header like below :image

However the is no way to directly display the currency symbol because you need numbers so you can format them in currency but you have text

So the hack is

1. Create a placeholder instead of label for the column header and set the placeholders label as the column header text

2. Write a expression for the placeholder value which is

=”Column Header Text”
+ “<br>”
+ “(” + Replace(FormatCurrency(“0″,0),”0″,””) + “)”

which actually adds “Rs. 0” after the header text and then replaces the 0 with blank space

3. Set the markup type of the placeholder to HTML

4. Expand Drilldown while Exporting or Subscribing a Report

Drilldown is a great feature of SSRS, however if the drilldown is collapsed by default if you export or deliver a report by email by subscriptions then still the report content will be collapsed and for some use cases that’s what you will not want.

A workaround can be to add a report parameter ShowDetails with values Yes / No, default No , the drilldown visibility of groups / UI elements is governed by an expression based on this parameters value and when you subscribe the report, you subscribe it with ShowDetails = Yes

image

image

image

image