Showing posts with label Coding. Show all posts
Showing posts with label Coding. Show all posts

Thursday, April 18, 2013

Extension Methods

I recently saw an email where a development manager was reminding his team of the value of extension methods.  This is a great method for adding base class type functionality to objects without introducing dependencies and utility classes for simple functions.

Extension methods are an easy way  to "add" functionality to existing types without having to create derived types, recompile, or otherwise modify the original type. Extension methods are a static method, but they are called as if they were methods on the target type. Using C#, there is no apparent difference between calling an extension method and the methods that are actually part of the defined type.

Here is an example extension method.  This method will extend the object string to break apart camel cased names and return a human readable name.  This can be very useful for populating drop down lists with all values of an Enumeration and other such activities.  First, we create the static method as follows.

public static string SplitCamelCase(this String input)
{
    return Regex.Replace(input, "([A-Z])", " $1", RegexOptions.Compiled).Trim();
}
This simply create a method (SplitCamelCase) and adds it to the methods available to any String variable in namepace scope with this class.

Then, this method can be called in the same format as any other method on the type String.


static void Main(string[] args)
{
    String testValue = "ThisIsACamelCasedSentence";
    Console.WriteLine(testValue.SplitCamelCase());
} 

These methods are quite simple to create and yet are a very powerful replacement for utility classes.  They can be used on native types as well as complex types.

Thursday, April 4, 2013

Inversion of Control (IoC) Pattern

I have been involved in many architectural discussion lately, where groups of people have been throwing around ideas on the correct way to build systems.  I am always coming from a position of loosely coupling and making sure that all aspects of your system are interchangeable and have the ability to be dynamically changed or replaced without system wide impact.  One topic that I find myself mentioning over and over again is the pattern known as Inversion of Control. Inversion of control (IoC) is a OOP technique by which  object coupling is bound at run time by an another object that is typically not known at compile time using static analysis.  The basic idea of this pattern is separate the creation of an object from the class which is trying to consume it.

The problem

As with every design pattern, the reasoning behind IoC is to avoid the possibility of design related problems.  For example, let's create an Appointment class which contains a Person class object. The biggest issue with the code below is tight the coupling between classes. In other words the Appointment class depends on the Person object. This main seem innocuous enough at a glance.  But, the byproduct of this design is that  if for any reason Person class changes, it will lead to a compile of the Appointment class. Then, in our world any object compilation leads to regression testing of the recompiled object, even though there was not an actual change. 
public class Person
{
}

public class Appointment
{
    private Person person;

    public Appointment()
    {
        person = new Person();
    }
}
The biggest problem with the sample code is that the appointment class controls the creation of Person object.  The patient class is directly referenced in the Appointment class which leads to tight coupling between these two objects.The Appointment class is aware of the Person class type. So if we add new Person types (like patient, sales person, employee, or pet), it will lead to changes in the Appointment class also as Appointment class is exposed to the actual Person implementation.  This also means that the creation of the Appointment class is dependent upon the successful creation of the Patient object within it's constructor.

The solution

If we are able to shift this task / control of object creation from the Appointment class to some other entity we have solved our problem. This means we are able to invert the control to a third party object and thus have found the solution. Some people call the IoC pattern the 'Hollywood' pattern because the simplest explanation of it's purpose is summed up the in phrase "Don't call us, we'll call you." This is a good summary of the idea of this pattern. There are many ways to accommodate this pattern with varying degrees of overhead. In my opinion, the simplest implementation of an IoC Container. IoC containers are used to simplify the provision of a dependant class's dependencies. In the most basic form, an IoC container is an implementation of the service locator design pattern that permits pre-instantiated objects to be registered with the container and later extracted. To substitute a new class and modify the operation of an entire solution, only the initial registration of the type need be changed.

IoC Container

Some IoC containers allow you to register types, rather than objects, and instantiate the type when requested, possibly using parameters. Others allow the registrations to be deserialised from an XML file, which could be modified in a text editor. In this article we will create a basic IoC container that does not include these additional features. This will demonstrate the use of IoC containers with the simplest possible code. You may decide to enhance the code to add extra features for your own use. However, you should also consider obtaining one of the many alternative IoC container solutions that are currently available. Following is the code to create a very a basic IoC container.
public static class IoC
{
    static Dictionary<Type, object> _registeredTypes = new Dictionary<Type, object>();

    public static void Register<T>(T toRegister)
    {
        _registeredTypes.Add(typeof(T), toRegister);
    }

    public static T Resolve<T>()
    {
        return (T)_registeredTypes[typeof(T)];
    }
}

Using the IoC Container

To illustrate the usage of the IoC container we first need to create an interface and a class that implements it. We will later register an instance of the class for the interface's type. The code for a simple interface and class that is used to grab a value are as follows:
public interface IPerson
{
    void SayYourName(string name);
}


public class Person : IPerson
{
    public void SayYourName(string name)
    {
        Console.WriteLine(name);
    }
}
We can now register the interface's type and provide a new Person object, which will be returned whenever the type is resolved. You would usually do this when your application is first started. In this example we will only register one type. In a real solution you can register as many types as are required for the operation of your software.
static void Main(string[] args)
{
    IoC.Register<IPerson>(new Person());
    IPerson person = IoC.Resolve<IPerson>();
    person.SayYourName("Jim Garrett");  
}
Once registered, any code that has access to the IoC class can resolve the type. In the sample the first line requests the object from the IoC container that implements IPerson. This returns the previous registered Person object. The object is then used to output a message to the console.

Tuesday, March 12, 2013

The argument for coding standards



Creating and enforcing coding standards, or coding style guidelines, is one method by which software companies can ensure that source code written by a software developer is easily understood, while being maintained by any other software developer in their employ.  Smashing Magazine contributor Nicholas C. Zakas penned an article titled, “Why Coding Style Matters”, illustrating the value realized by creating and adhering to coding standards.  He states that standards ensure individual members of a development team are able to tailor the visual appearance of their source code while still allowing their individual talents to flourish.  Standardized coding style also ensures better communication between team members by allowing the product of work to act as a form of documentation for the creators to leave clues for themselves and for others who come after.  Potential programming errors are more easily identified when a group of programmers adheres to a coding standard since any code that does not comply becomes more visible and draws scrutiny of other developers.  Standardizing the code comment, which is a way for developers to create non-executing code strictly designed for inter-developer communication, is a good way to ensure other engineers are able to understand why code was written in this specific way to accomplish the known task.

Zakas begins the article by discussing his own introduction to coding standards as a student in college.  One of his professors considered the style with which code was written equally as important as the execution of the code.  His definition of coding style is insightful as it illustrates that the standard can be as generalized or granular as the creator desires.  All individual developers inherently have a coding style, whether formalized and forced or inadvertently formed in seclusion over time. The biggest challenge with a standardized style to a creative group, he states, is the undeniably personal nature of any style.  Mr. Zakas created a memorable simile regarding individual musicians in a band.  While all of the musicians have a talent on their instruments, unless they are orchestrated in some fashion beyond their individual creative style, the music they produce will not likely be enjoyable to the listener.  The structure provided by band governance for items such as tempo, key, and lead timing, ensures a quality musical product without forcing the conformance of individual creativity.  That is exactly the marriage of the individual dynamic within a team structure that is required.  Prior to enforcing standards, you have to understand the challenges and resistance will be based on individual styles and creativity being 'standardized'.  It is vital to communicate that coding standards and style guides do not throttle creativity or individualism, they simply channel it into a team effort and ensure forward progress.

Communication is a natural and valuable byproduct of coding standards.  Most communication within a group of developers is resident within the source code itself.  The output of any developer’s daily work is a complete, exhaustive, and readable trail of every task he or she executed.  When one developer reads the source code created by another developer, the original developer’s view of the problem, strategy to correct it, and final solution are communicated to the second via the code itself. Once you reach this realization alone, it indicates the need for standardization.  The code communication is also useful for developers to leave clues for themselves in the future.  It is equally important for the author of the code to understand that he may need to maintain a creation of his own in the distant future.  Intellectual breadcrumbs and standardized formatting will ensure that old code and new code look the same to the maintaining programmer.

Coding standards bring potential software errors into view more easily.  As programmers become more acclimated to specific patterns, they will more naturally notice code that does not adhere.  This ultimately draws the attention of programmers and causes them to consider the segment of code more closely, as it is an anomaly.  Since the coding standard itself is designed to enable consistently stable source code, one must focus on which items to standardize with direct intent.  You will probably not find a coding style guide with too much detail, but can find them with too little detail.  The importance in your level of detail is based on the importance of ensuring items that are standardized are complete and targeted at specific items important to the individual team.  In other words, its not a good idea to standardize every aspect of development, just for the sake of doing it.  You should focus on standards as they align with your business need and allow the developers to leverage their creativity and talent within the style guide.

Thursday, January 17, 2013

Javascript is a Free-For-All....

As part of a boot camp I am teaching this week, we decided to see how much insanity we could inject into Javascript before it would fail.  The group is made up of experienced C# programmers and we decided to experiment with blowing up the sort of structure and type restrictions we have all grown accustomed to in a structured language.  We created the following code block just to see how far we could push the 'undefined ' functionality, along with the variable typing being a basic free-for-all.


var arr = function()
{
  alert(arr['testB']);
}

arr['testA'] = true;
arr['testB'] = false;
arr['testC'] = true;
arr[arr[0]] = arr;

document.write(arr[arr[0]]);
document.write("<br/>");

document.write(arr['testC']);
document.write("<br/>");

document.write(arr[0]);
document.write("<br/>");

arr[arr[0]]();
document.write("<br/>");

document.write("foreach...<br/>");

for (var i in arr)
{
  document.write(arr[i]);
  document.write("<br/>");
}


This is not only viable syntax, but this code will run and output values consistent with the index resolution of the array (when it is an array and not a function, that is).  Interestingly, it appears to be a valid strategy to have an undefined value as a key in a key value pair.  My favorite aspect of this is declaring a function, array and key/value list as a single variable and have it act accordingly depending on how you reference it.  Even when you make one of the values within the key/value array the array itself.

Go home Javascript, you are drunk.

Friday, July 27, 2012

Ordinals vs Column Names - Part Deux

Since the first post turned into a discussion of readability versus performance, maintainability versus speed and other very worthwhile topics, I decided to put this entire process to a road test.  I created unit tests that called a DAL services basically retrieving an entire table in each of the three presented methodologies.  To get the output, I enabled our handy-dandy unit test timer to trap the performance of the DAL list functions. In order for this to be good science, I restarted the database 3 times over the course of the testing and ran the tests in different orders each time. For retrieving just under 17000 rows consisting of 38 columns, here are the results and averages for the test run (values in Milliseconds).


Run  String  Dictionary Ordinal String Order Dictionary Order Ordinal Order Difference
1 2705 2469 2505 1 3 2 236
2 2648 2575 2506 2 3 1 142
3 2669 2520 2501 2 1 3 168
4 2570 2648 2445 3 1 2 203
5 2577 2566 2397 3 1 2 180
6 2450 2646 2575 3 1 2 196
7 2555 2606 2479 2 1 3 127
8 2843 2621 2446 1 2 3 397
9 2628 2485 2388 1 2 3 240
10 2580 2525 2400 3 1 2 180
Total 2622.50 2566.10 2464.20 0.21

So, at the end of the day, here is what I learned.  It really doesn't matter enough to worry about it.  Sure, the ordinals are consistently faster than the dictionary and the dictionary is faster than string, but the variance is hardly worth worrying about.  When retrieving 17000 rows, the average difference from the best performance to the worst performance was a matter of 2/10 of one second.  I think I got wrapped up in a common distraction know as micro-optimization, where we spend a ton of mental energy and rewrite code to gain a millisecond on a routine. Yes, you should care about performance, and yes, faster code should always be your goal, but there comes a point in time where it stops being worth the development time.  Yes, we should avoid the blatantly poor performing code mistakes that everyone knows about. But after that, we should be equally worried about the scalability, portability, maintainability and readability of our code. We should ask if saving 2/10 second while retrieving 17000 rows is the matter to discuss, or should we be discussing why we would ever be retrieving 17000 often enough in our application to have 2/10 second be an issue.  Yes, I started the discussion, thinking it was a creative way to gain performance.  Honestly, I enjoy trying to work through things like this too, which fed the distraction.  I believe now that these mental exercises should always be framed with realistic improvement potential weighed against the time and effort of the pursuit. At that point, only pursue until it starts becoming a net loss of productivity.  On this particular subject, after doing this research, count me firmly in the "It really doesn't matter, aim at code readability and object design" camp.

Thursday, July 19, 2012

Ordinals vs. Column Names on DataReader

There is some contention on whether you should use the name of a column versus hard coding the ordinal when using a DataReader to retrieve data from a procedure call. While using the name is more easily maintained and agnostic on the order of columns, there is an inherent overhead with using the column name. While I understand the performance hit of using the named column, I find the value in code readability and column ordering independence worth it.  While, the hit is negligible on a single row result set, the compounding nature may result in a performance change worth avoiding. I came up with a neat little trick that can be used prior to looping through the result set of a list return.  I created a helper class that will give you the ordinals back locally and allow them to be used on each loop.

public Dictionary<String, Int32> GetOrdinals(IDataReader reader)
{
   Dictionary<String, Int32> retVal = new Dictionary<String, Int32>();
   for (int i = 0; i < reader.FieldCount; i++)
   {
     retVal.Add(reader.GetName(i), i);
   }
   return retVal;
}
 
This enables us to hit the reader row one time and bring back a local variable containing all of the column names as the key of a dictionary with ordinal as a value.  At this point, you can simply use the keyed reference as follows and get the best of both worlds when retrieving large result set.

Boolean hasData = reader.Read();
List<Contract> listItems = new  List<Contract>();
Dictionary<String,Int32> ordinals = null;
if (hasData)
{
   ordinals = GetOrdinals(reader);
}
 
while (hasData)
{
   Contract item = new Contract();            
   item.ID =  Convert.ToInt64(reader[ordinals["ID"]]);
   item.Name = reader[ordinals["Name"]].ToString();
   listItems.Add(item);
   hasData = reader.Read();
}

This method would be a performance hit when using against a single row return value. And the break-even point of a large result set may take a few rows to gain back the hit of the first loop. However, it is a nice little trick to get the best of both worlds when hitting a large query.

Monday, June 25, 2012

Dynamic Types Using C#


I ran across a scenario the other day for creating a function to perform similar work on similar classes without having to be tightly coupled to any concrete type.  I found a few viable options and will be doing some examples of each to work through the exercise completely.  The first I want to talk through is the use of the dynamic keyword.

In short, using dynamic tells the compiler to ignore types at compile time and instead determine dispatch based on the actual type at run time.  Static binding of types does the exact opposite and performs a dispatch based on the concrete type.  Since code always illustrates these academic discussions more clearly, I created a simple project.  I have two examples of dynamic typing built into this single example.  I created some classes to illustrate a few types that are completely unrelated to each other. I also created a single class that was an example of type inheritance.

public class Account
{
    public String Name { get; set; }
    public Double Balance { get; set; }
    public Int16 AccountType { get; set; }
    public Account()
    {
        Name = "Account";
        Balance = 100.00;
    }
}
 
public class Customer
{
    public String Name { get; set; }
    public Double Balance { get; set; }
    public String CustomerType { get; set; }
    public Customer()
    {
        Name = "Customer";
        Balance = 900.00;
    }
}
 
public class Employee
{
    public String Name { get; set; }
    public Double Balance { get; set; }
    public String Department { get; set; }
    public Employee()
    {
        Name = "Employee";
        Balance = 500.00;
    }
}
 
public class Payable : Account
{
    public Payable()
    {
        Name = "Payable";
        Balance = -100;
    }
}

As you can see, the classes are completely independent of each other, but they have similar members.  Using the dynamic keyword, we can create a function that deals with these types at runtime and interacts with expected members at that time.

static void WriteDynamicObject( dynamic thing)
{
    Console.WriteLine("Name: "+ thing.Name + ", Balance: " + thing.Balance.ToString());
}
 
As long as the types I pass to this function have publicly accessible members named Name and Balance, this code will work with a complete disregard for compilation of any known type.  Next, to illustrate using the dynamic keyword for instructing the runtime to resolve the type regardless of declaration, I created overloaded functions that take a concrete type at each level of inheritance.

static void WriteConcrete(Account thing)
{
    Console.WriteLine("I am an Account Thing");
}
static void WriteConcrete(Payable thing)
{
    Console.WriteLine("I am a Payable Thing");
}

Finally, a simple console application that illustrates how these items work and are either statically or dynamically resolved.  The difference between the 'Concrete' functions is shown by the dynamic keyword telling the runtime to resolve this class at run time regardless of it's declaration.  Also, notice the last item is not even a class at all, but rather a dynamic type declared simply to be passed to this helper function.


static void Main(string[] args)
{
    // call writedynamicobject function for all concrete classes
    Account a = new Account();
    WriteDynamicObject(a);
            
    Employee e = new Employee();
    WriteDynamicObject(e);
            
    Customer c = new Customer();
    WriteDynamicObject(c);
 
    //call function for a concrete class, but resolve type at runtime
    Account p = new Payable();
    WriteConcrete(p);
    WriteConcrete((dynamic)p);
    // dynamically create values and pass as a dynamic type.
    WriteDynamicObject(new {Name="TotallyDynamicNonClass", Balance=250});
 
}
 
The output of this project illustrates how the runtime deals with each of these scenarios.


If you are like me, the first thought you have on using the dynamic typing pattern is along the lines of, "Couldn't you just use an interface or inheritance to accomplish the same thing?"  The answer is yes, assuming you are able to know those types at compile time.  But, there are also times where you can't know the definitions at compile time.  You can't compile the internet, but you can interface with it.  I would be remiss if I didn't get into the downsides of this practice as well.  This can open you up to having a program that is hard to maintain, difficult to debug and unit test and many similar issues. But, guns don't kill people, people with guns do.  Dynamic typing doesn't make code difficult to manage, a programmer does those things with his or her architecture.  This is not a magic bullet and should be used with great caution. The reason for using it is that some problems are inherently dynamic (e.g. web requests).  While you may use reflection for this sort of problem today, you may find dynamic typing a more expressive approach to the same problem.  Simply being dynamic in itself is a compelling argument. Reflection introduces a tightly coupled dependency on a static mechanism.  Dynamic methodologies are intent-based and trust the receiver to act upon the passed intent which creates a scalability unachievable by other means.  The source files are available for download here. 

Tuesday, June 12, 2012

Object Design Principles - Part 5

Dependency Inversion Principle

The DIP states that high level classes should not depend on low level classes.  Both should depend on abstractions.  Details should depend on abstractions.  Abstractions should not depend on details.  The DIP is about reversing the direction of dependencies from higher level components to lower level components such that lower level components are dependent upon only the interfaces owned by the higher level components.  This is a method for moving to a more loosely coupled architecture.  Basically, you have to depend on a standard interface used by objects and not depend on their details.  This one might be best illustrated by example. 

In the following example, the BadCar class is tightly coupled to the actual implementation of the BadMotor function.  This means that these two objects are married, and changes to one directly impact the other.


public class BadMotor
{
    public Boolean Start()
    {
        Console.Write("Starting");
        return true;
    }
}
 
//tightly coupled to details.
public class BadCar
{
    public BadMotor Motor {get;set;}
 
    public Boolean Start(BadMotor badMotor)
    {
        Motor = badMotor;
        return Motor.Start();
    }
}
 
 
While this does function, it creates a dependency relationship between two objects at their implementation level.   This creates hardships for maintenance and scalability long term.   The proper way to build this relationship would be to invert dependencies onto interfaces to ensure no object has knowledge or visibility into implementation of any other object. Consider the following examples:

public interface IEngine
{
    bool Start();
}
 
public interface IGreenEngine : IEngine
{
    bool IsCharged ();
}
 
public class FourCylEngine : IEngine
{
    public bool Start()
    {
        Console.WriteLine("4Cyl Starting");
        return true;
    }
}
 
public class V8Engine : IEngine
{
    public bool Start()
    {
        Console.WriteLine("V8 Starting");
        return true;
    }
}
 
public class HybridEngine : IGreenEngine
{
    public bool Start()
    {
        if (IsCharged())
            Console.WriteLine("Hybrid Starting");
        return true;
    }
    public bool  IsCharged()
    {
        Console.WriteLine("Hybrid is charged");
        return true;
    }
}
 
public class Car
{
    public Car(IEngine engine)
    {
        Engine = engine;
    }
    public IEngine Engine{get ; set ; }
    public Boolean Start()
    {
            
        return Engine.Start();
    }
}
 
I built this interface dependency and inheritance to ensure that objects are loosely coupled and only share an interface.   This allows for actual base implementations to come and go and even be recognized dynamically without causing lower level objects to update their implementation.   Here is an example of hot swapping and scaling with the previously defined objects and interfaces.

class Program
{
      
    static void Main(string[] args)
    {
        //  Cars are only dependant upon an Engine interface
        Car BigThing = new Car(new V8Engine());
        BigThing.Start();
        //  Cars are only dependant upon an Engine interface
        Car SmallThing = new Car(new FourCylEngine());
        SmallThing.Start();
        // Since we have an interface dependency, it is easy to hot swap.
        BigThing.Engine = new HybridEngine();
        BigThing.Start();
    }
}

The output is as follows:


As you can see, this allows for maintainability and long-term scalability by ensuring that the objects stay out of each other's business. By adhering to the spirit of this principle as well as the previous SOLID principles, you can keep your code base healthy and easy to maintain when the requirement changes come.

Friday, June 8, 2012

Object Design Principles - Part 4

Interface Segregation Principle (ISP)

The ISP says that an interface should not become too 'fat' but be split into smaller and more specific interfaces so that only methods that pertain to a client need to be implemented.  You should focus on designing abstractions that have a very small, focused and sleek design.  Basically, no client should be forced to implement methods or properties it does not need to use.  We should always start at the most granular level and extend interfaces as needed.  You can create new interfaces that are extensions, or groupings, of other interfaces to form classes and objects desired.  Rather than forcing everyone to consume the entirety of a polluted interface, you are allowing them to implement an array of more focused interfaces.  I like analogies for getting my hands around design principles.  I think of this one much like eating at a restaurant.  If you sit down and order a burger, how do you react if you are given soup; then a burger, fries, and a coke; then an ice cream sundae?  And you are expected to pay for all of it.  Apparently, the only way to get a burger is to implement the IThreeCourseMeal interface.  If it doesn't make sense in life, it doesn't make sense in design. 

During application design we should pay close attention to how we abstract modules that contain several sub-modules. Granularity is always the side on which to err when doing interface design.  It is much easier to couple interfaces than to decouple a polluted interface (just as it would be very difficult to 'un-salt' your food.)  As I look through existing interfaces, it seems that this principal is easily and repeatedly violated, probably without intent.  In reviewing for this piece, I saw that months ago I created an interface that flagrantly violated this principle as a quick means to an end.  I plan to decouple it as part of this mental exercise.

Using the restaurant analogy above, I created some interfaces that, while silly, illustrate the principle.  First, I would go for the most granular interface that could logically be shared for all iterations of this type.  I landed on a menu item:

public interface IMenuItem
{
    String Item { get; set; }
    String Price { get; set; }
}


Then, I started creating logical abstractions of a menu item into various aspects of a meal:

public interface IEntree : IMenuItem
{
    String CookingInstructions { get; set; }
}
 
public interface ISide : IMenuItem
{
    Boolean IsVeggie { get; set; }
}
 
public interface IDrink : IMenuItem
{
    Int16 CupSize{ get; set; }
}
 
public interface IAppetizer : IMenuItem
{
    //...
}
 
public interface IDessert : IMenuItem
{
    //...
}


Next, I moved onto large interfaces that would have enough real world implementations to justify a single abstraction:

public interface IValueMeal : IEntree, ISide, IDrink
{
    //...
}
 
public interface IThreeCourseMeal : IAppetizer, IEntree, ISide, IDrink, IDessert
{
    //...
}

The advantage is that I can always come in at the implementation level and create my own dynamic abstraction.  Notice which properties' objects are created when I choose to implement the interface:

public class MyCustomMeal : IEntree, IDrink
{
 
    #region IEntree Members
 
    public string CookingInstructions
    {
        get
        {
            throw new NotImplementedException();
        }
        set
        {
            throw new NotImplementedException();
        }
    }
 
    #endregion
 
    #region IMenuItem Members
 
    public string Item
    {
        get
        {
            throw new NotImplementedException();
        }
        set
        {
            throw new NotImplementedException();
        }
    }
 
    public string Price
    {
        get
        {
            throw new NotImplementedException();
        }
        set
        {
            throw new NotImplementedException();
        }
    }
 
    #endregion
 
    #region IDrink Members
 
    public short CupSize
    {
        get
        {
            throw new NotImplementedException();
        }
        set
        {
            throw new NotImplementedException();
        }
    }
 
    #endregion
}

Hopefully, you can see how this principle allows for much scalability and dynamism of types without the inherent bloat from linear bulge.  This is a great principle to keep in focus during design.

Friday, May 25, 2012

Object Design Principles - Part 1

Singular Focus and Coupling


This will be the first installment of a multiple part posting on object design principles.  These are vital to keep in mind as we go through creation of large product platforms with many interaction services and objects that must be maintained and enhanced over time.

Object Responsibility

In my mind, the most vital question you can ask yourself at the outset of an object design is, "What is this object's core responsibility?"  Your entire design should flow from that very basic question. You should consistently look for the most granular object definition possible and work back from that.  It's really easy to get blinded by the vastness of the entire project and the complete set of user stories and completely misjudge where to segregate your logic.  Once you have defined the core responsibility and focus of an object, you can immediately start creating an inheritance path as well as supplemental interfaces to bring your object into full functionality.  This is the most vital step in ensuring a scalable and easily maintainable system long term.  Consider the following basic user requirement:  "I need to be able to view images and apply enhancements to them."  The first thing that comes to my mind is that although the user requirement is to always view images, every image view session will not ultimately result in an image enhancement session.  So, I immediately break into two objects, a viewer and an editor : viewer.  At its core, the viewer object should do nothing more than accept image data and render in a viewable state. The viewer should have no concept of any data or state outside of the image itself.  It should interact via an interface with a standardized image format so that it doesn't need to have any system context. 

The system also should have no specific knowledge of the viewer (more on that when we talk about coupling).  Then, the editor class should start by extending the known viewer class.  It should not extend any operation that pertains to the loading and displaying of the base image.  That aspect of responsibility should be a black box to the editor.  The editor should contain an interface for advertising its list of manipulations as well as a standardized message based interface for executing them.  This object is not responsible for a menu or toolbar system, it is simply an image manipulator requiring system input to launch an execution of its internally known action.  It also would not have any context for displaying an image history listing.  It would maintain a list of events, based on its internally known list of manipulations and allow an outside source to interact with that list via a standardized message or interface.

Loosely Coupled Objects

The main point of the granularity of the design listed above is to ensure a loosely coupled framework.  These controls and objects should all be interacted with via their interface over standardized messages.  If each object is singularly purposed and has a black box for its implementation, the only exposure and ultimate point for breakdown is the interface itself.  The loosely coupled system (or systems) interacts with itself based on standard messages or interfaces. The granularity, once released to production, allows for a dynamically upgradeable system with hot swap components.  In this scenario, we could easily swap out our image viewer or image editor in any given system with a very limited impact on the system as a whole. The change would be contained in a singularly purposed object that is loosely coupled with its housing system.  We would be able to quickly respond to a requirement for viewing a new image format without having to make changes to our image editor control.  Additionally, this transforms every control, service or object in every system into a plausible enterprise level base class by never assuming product knowledge or any aspect of external state.

By thoroughly investigating singular focus and coupling as part of every design, we can work toward a much more stable and dynamic system in the future.