Code can often be simplified by adding a few convenience methods to our classes. For instance, one set of classes were littered with code like this:
CommandInitDataEntity data = CommandEntity.InitDatas.SingleOrDefault (x => x.Key == InitDataKeys.MoiBliscyUpgradeType.ToString ());
if (data != null)
{
this.UpgradeType = (UpgradeType) Enum.Parse (typeof (UpgradeType), data.Value);
}
I added the following convenience methods to the CommandEntity class:
public bool HasInitData (
string key)
{
return this.InitDatas.ToList ().Exists (x => x.Key == key);
}
public bool HasInitData (
Enum key)
{
return HasInitData (key.ToString ());
}
public string GetValueFromInitData (
string key)
{
return this.InitDatas.Single (x => x.Key == key).Value;
}
public string GetValueFromInitData (
Enum key)
{
return GetValueFromInitData (key.ToString ());
}
public T GetValueFromInitData (
Enum key)
where T : struct, IConvertible
{
Type type = typeof (T);
if (type.IsEnum)
{
return (T) Enum.Parse (typeof (T), GetValueFromInitData (key));
}
throw new NotImplementedException ("Unsupported type");
}
I could then rewrite the original code like this:
if (commandEntity.HasInitData (InitDataKeys.MoiBliscyUpgradeType))
{
this.UpgradeType = commandEntity.GetValueFromInitData (InitDataKeys.MoiBliscyUpgradeType);
}
It may not seem like a big difference, but well designed software is achieved though hundreds of little decisions that all add up.
If software architecture is more like gardening than building skyscrapers (an idea that is catching on - see http://pragprog.com/the-pragmatic-programmer and http://www.infoq.com/articles/large-scale-agile-design-and-architecture and http://www.codegardening.com/2009/04/gardening-not-architecture.html) then all you've done is a bit of pruning.
ReplyDeleteWell done :)