Monday 24 November 2014

An important Software Design Property - Context Independence

We could start by asking what Context really means in terms of Software Design and why having Context Independence is good? Firstly, lets define Context:

Context -  it is  everything that needs to be set in order to use a given data structure (i.e a Class). This is mostly about its relationships and their dependencies.

Basically the Context of a given structure is what it needs to be functional, so without Context you can't use It. In other words, this is something that you can't avoid, you need to deal with it when designing your software. BTW, there are some very known design issues that follow  Data Structures with Heavy Context. Some of them are:
  • Make them hard to test;
  • Make them hard to use/reuse and extend;
  • Deal with this kind of structures is always hard, so it'll naturally make the them hard to change and maintain
Lets look to an example, Consider the following classes relationship:


Here are them exchanging messages:


AS far we can see, Class B, Class C and Class D have their own Context. This something they need in order to make their job. Class A is using them, and also it dealing with their contexts, as soon it needs to initialize them.  Here is where problems get started. What about the effort needed to test Class A? Avoid dealing with each individual Context  would be something desirable by any  Class which needs to the those classes. The property we are looking forward here is Context Independence.

A technique that can be used on this case is Dependency Injection. DI can make Class A free from the Context Initialization. By consequence it will also be flexible and make the design more susceptible to changes. This is how  it could looks like:



Now Class A is Context Free once it does not deal with all details with Context from other classes. Implementation on Class A will be more clear, testable and easier to extend and change.

Another technique that can be used in order to be sure if a given Structure is Context Free is checking how it is communicating  with other Structures. If it is asking other Structures How to things instead of What,  it means you are on the wrong. You probably have a Structure that knows too much about others  and it is probably dealing Contexts you should avoid.

Context Independence is a technique that can help you to keep the healthiness  of your design. It works pretty well with SOLID principles. I am actually not able to see them work separately  in a more complex solution.




No comments:

Post a Comment

Note: only a member of this blog may post a comment.