Click here to Skip to main content
Click here to Skip to main content
Go to top

Refactor C# code to become more expressive

, 26 Jul 2012
Rate this:
Please Sign up or sign in to vote.
Refactor C# code to become more expressive

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:  

/*  Coalesce: */
if (Request["search"] == string.Empty || Request["search"] == null)
    base.searchText = string.Empty; 
else 
    base.searchText = Convert.ToString(Request["search"]);
return base.searchText;
/*  Can be written as:  */
base.searchText = Request["search"] ?? String.Empty; 

Inversion of condition (AKA early return):

/*Inversion of condition:*/
public void DoSomething(String url)
{
    if (!string.IsNullOrEmpty(url))
    {
        if (migrate)
        {
            // code here
        }
    }
    else
    {
        PopulatePage(); 
    }
}
/*  Can be written as:   */
public void DoSomething(String url)
{
    if(String.IsNullOrEmpty(url))
    {
	PopulatePage();
	return;
    }        
    if (domainMigration)
    {
        // code here
    }        
}

Avoiding double calls:

/*  Double calls:   */

if (string.IsNullOrEmpty(Request["location"]))
    url = (FacadeFactory.GetCatalog()).ValidateUrl(filter.Value, canonicalUrl);
else
    url = (FacadeFactory.GetCatalog()).ValidateUrlByName(Request["location"], canonicalUrl);

/*  Can be written as:  */
var catalog = FacadeFactory.GetCatalog();
if (string.IsNullOrEmpty(Request["location"]))
    url = catalog.ValidateUrl(filter.Value, canonicalUrl);
else
    url = catalog.ValidateUrlByName(Request["location"], canonicalUrl);

/*  or */
var catalog = FacadeFactory.GetCatalog();
url = if (string.IsNullOrEmpty(Request["location"]))
    ? catalog.ValidateUrl(filter.Value, canonicalUrl)
    : catalog.ValidateUrlByName(Request["location"], canonicalUrl);

Comparison simplification

/*  compare using Contains  */
if (store.Current == Stores.Starbucks
    || store.Current == Stores.BarnsAndNobles
    || store.Current == Stores.Amazon)
{
    //do something
}

/*  can be written as:  */
var stores = new[]{ Stores.Starbucks, Stores.BarnsAndNobles, Stores.Amazon };
if (stores.Contains(store.Current))
{
    //do something
}

Defensive programming against null objects:

/*  defensive programming   */
var categories = Platform.ECommerce.Services.GetCategories();

var location = Helper.StringHelper.RemoveSpecialChars(
                    categories.Where(a => a.LocationId == filter).FirstOrDefault().Name);
//line above: possible NullReferenceException

var someString = ConfigurationManager.AppSettings["urlSite"] + "/" + location + "/?" + Request.QueryString.ToString();

/* can be written as:   */

var categories = Platform.ECommerce.Services.GetCategories();

var location = Helper.StringHelper.RemoveSpecialChars(
    categories.Where(a => a.LocationId == filter.Select(c=>c.Name).FirstOrDefault() ?? String.Empty));
//safe property access

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 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Rafael Nicoletti
Architect
Brazil Brazil
No Biography provided

Comments and Discussions

 
GeneralMy vote of 5 PinmemberRamkumar_S12-Nov-13 4:35 
GeneralThoughts PinmemberPIEBALDconsult27-Jul-12 8:34 
GeneralRe: Thoughts PinmemberRafael Nicoletti9-Apr-14 4:02 
QuestionAvoiding double calls... PinmvpPaulo Zemek26-Jul-12 9:14 
GeneralRe: Avoiding double calls... PinmemberRafael Nicoletti27-Jul-12 4:34 
GeneralMy vote of 3 PinmemberPhilippe Mori26-Jul-12 5:20 
GeneralRe: My vote of 3 PinmemberRafael Nicoletti27-Jul-12 4:37 
GeneralMy vote of 3 PinmemberMadDoc8725-Jul-12 22:33 
GeneralMy vote of 3 PinmemberKlaus Luedenscheidt22-Jun-12 18:07 
GeneralRe: My vote of 3 PinmemberRafael Nicoletti26-Jul-12 2:42 
Question[My vote of 2] Your tips are quite debatable, especially since you hardly give an reason for your advises... PinmemberAndreas Gieriet22-Jun-12 16:10 
AnswerRe: [My vote of 2] Your tips are quite debatable, especially since you hardly give an reason for your advises... PinmemberRafael Nicoletti26-Jul-12 2:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 26 Jul 2012
Article Copyright 2012 by Rafael Nicoletti
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid