Refractoring Code: Design for the future

by sunil ravulapalli /4. September 2013 07:17 /software-design /Comments (0)
AccountInformation accountInformation = getInfo();
string allNames = accountInformation.SignerName  + " " +  accountInformation.CoSignerName  + " " +  accountInformation.CoSignerName2;

Lets say you have a class like this which you are using in multiple places in your program:

public class AccountInformation
{
	public string SignerName { get; set; }
	public string CoSignerName { get; set; }	
}

One of the instances where it is being used is as follows:

AccountInformation accountInformation = getInfo();
string allNames = accountInformation.SignerName + " " + accountInformation.CoSignerName;

One fine day you are informed of a business rule which states that AccountInformation can have second Co Signer.
How would you redesign this class?
One option would be to do this:

public class AccountInformation
{
	public string SignerName { get; set; }
	public string CoSignerName { get; set; }
	public string CoSignerName2 { get; set; }
}

Now, next thing you have to do is find all places where AccountInformation is used and add CoSignerName2 for the additional information like follows:

public class AccountInformation
{
	public string SignerName { get; set; }
	public List<string> CoSignerNames { get; set; }	
}

This seems easy. But what if you need to add another Co Signer? Will you add CoSignerName3? This can go on endlessly.
A good programmer would recognize this possibility and he/she would have made a provision for this scenario. AccountInformation could have been changed as follows:

public class AccountInformation
{
	public string SignerName { get; set; }
	public List<string> CoSignerNames { get; set; }	
}

All the usages of AccountInformation would have to be changed to something like this:

AccountInformation accountInformation = getInfo();
string allNames = accountInformation.SignerName + getAllCoSignerNames(accountInformation.CoSignerNames);

where

public string getAllCoSignerNames(List<string> coSignerNames)
{
	string allCoSignerNames = String.Empty;
	foreach(string coSignerName in coSignerNames)
	{
		allCoSignerNames += coSignerName + " "
	}
	return allCoSignerNames;
}

Yes, this definitely more work than just adding CoSignerName2. But we have to realize that this is future proof! No matter how many Co Signers are allowable in future, you don't have to touch a line of code. You are done! This saves both the programmer and the business so much time, just because you though ahead and designed your system.

 

 

blog comments powered by Disqus