Click here to Skip to main content
15,884,099 members
Articles / Programming Languages / C#
Tip/Trick

Refactor C# code to become more expressive

Rate me:
Please Sign up or sign in to vote.
3.92/5 (7 votes)
26 Jul 2012CPOL 33.6K   3   12
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:  

C#
/*  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):

C#
/*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

C#
/*  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:

C#
/*  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)


Written By
Architect
Brazil Brazil
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Ramkumar_S12-Nov-13 4:35
Ramkumar_S12-Nov-13 4:35 
GeneralThoughts Pin
PIEBALDconsult27-Jul-12 8:34
mvePIEBALDconsult27-Jul-12 8:34 
GeneralRe: Thoughts Pin
Rafael Nicoletti9-Apr-14 4:02
Rafael Nicoletti9-Apr-14 4:02 
QuestionAvoiding double calls... Pin
Paulo Zemek26-Jul-12 9:14
mvaPaulo Zemek26-Jul-12 9:14 
GeneralRe: Avoiding double calls... Pin
Rafael Nicoletti27-Jul-12 4:34
Rafael Nicoletti27-Jul-12 4:34 
Sure, using local variables improves readability and in some case, performance gains.
The main purpose is to avoid duplicated code than make performance improvements.
And... thanks for attention and mention the Request["location"], i forgot that Wink | ;) .
GeneralMy vote of 3 Pin
Philippe Mori26-Jul-12 5:20
Philippe Mori26-Jul-12 5:20 
GeneralRe: My vote of 3 Pin
Rafael Nicoletti27-Jul-12 4:37
Rafael Nicoletti27-Jul-12 4:37 
GeneralMy vote of 3 Pin
MadDoc8725-Jul-12 22:33
MadDoc8725-Jul-12 22:33 
GeneralMy vote of 3 Pin
Klaus Luedenscheidt22-Jun-12 18:07
Klaus Luedenscheidt22-Jun-12 18:07 
GeneralRe: My vote of 3 Pin
Rafael Nicoletti26-Jul-12 2:42
Rafael 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... Pin
Andreas Gieriet22-Jun-12 16:10
professionalAndreas 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... Pin
Rafael Nicoletti26-Jul-12 2:51
Rafael Nicoletti26-Jul-12 2:51 

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

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