Introduction
This article brings clarification on some small tips to keep your code elegant and clean.
Background
Recently i began as architect on a large e-commerce corporation. My mission is to optimize code, by using cutting edge technologies, code reviewing and code rewriting/refactoring.
The main purpose of this article is to present some techniques on how to rewrite code in elegant way.
Using the code
Refactoring and make use of coalesce:
if (Request["search"] == string.Empty || Request["search"] == null)
base.searchText = string.Empty;
else
base.searchText = Convert.ToString(Request["search"]);
return base.searchText;
base.searchText = Request["search"] ?? String.Empty;
Inversion of condition (AKA early return):
public void DoSomething(String url)
{
if (!string.IsNullOrEmpty(url))
{
if (migrate)
{
}
}
else
{
PopulatePage();
}
}
public void DoSomething(String url)
{
if(String.IsNullOrEmpty(url))
{
PopulatePage();
return;
}
if (domainMigration)
{
}
}
Avoiding double calls:
if (string.IsNullOrEmpty(Request["location"]))
url = (FacadeFactory.GetCatalog()).ValidateUrl(filter.Value, canonicalUrl);
else
url = (FacadeFactory.GetCatalog()).ValidateUrlByName(Request["location"], canonicalUrl);
var catalog = FacadeFactory.GetCatalog();
if (string.IsNullOrEmpty(Request["location"]))
url = catalog.ValidateUrl(filter.Value, canonicalUrl);
else
url = catalog.ValidateUrlByName(Request["location"], canonicalUrl);
var catalog = FacadeFactory.GetCatalog();
url = if (string.IsNullOrEmpty(Request["location"]))
? catalog.ValidateUrl(filter.Value, canonicalUrl)
: catalog.ValidateUrlByName(Request["location"], canonicalUrl);
Comparison simplification
if (store.Current == Stores.Starbucks
|| store.Current == Stores.BarnsAndNobles
|| store.Current == Stores.Amazon)
{
}
var stores = new[]{ Stores.Starbucks, Stores.BarnsAndNobles, Stores.Amazon };
if (stores.Contains(store.Current))
{
}
Defensive programming against null objects:
var categories = Platform.ECommerce.Services.GetCategories();
var location = Helper.StringHelper.RemoveSpecialChars(
categories.Where(a => a.LocationId == filter).FirstOrDefault().Name);
var someString = ConfigurationManager.AppSettings["urlSite"] + "/" + location + "/?" + Request.QueryString.ToString();
var categories = Platform.ECommerce.Services.GetCategories();
var location = Helper.StringHelper.RemoveSpecialChars(
categories.Where(a => a.LocationId == filter.Select(c=>c.Name).FirstOrDefault() ?? String.Empty));
Points of Interest
By using small tips and techniques, the code readability gets enhanced and the maintenance makes less painful. Some parts of this code can be refactored (using filters, extension methods, etc), but in this case i need to make greater changes that impacts the system.
History
Jun, 21, 2012:
- Coalesce tips;
- Avoiding double calls
- Optimizing comparison
- Defensive programming against null objects