Click here to Skip to main content
12,247,398 members (55,870 online)
Click here to Skip to main content
Add your own
alternative version

Stats

16.2K views
3 bookmarked
Posted

Refactor C# code to become more expressive

, 26 Jul 2012 CPOL
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

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 5 Pin
Ramkumar_S12-Nov-13 5:35
memberRamkumar_S12-Nov-13 5:35 
GeneralThoughts Pin
PIEBALDconsult27-Jul-12 9:34
memberPIEBALDconsult27-Jul-12 9:34 
GeneralRe: Thoughts Pin
Rafael Nicoletti9-Apr-14 5:02
memberRafael Nicoletti9-Apr-14 5:02 
QuestionAvoiding double calls... Pin
Paulo Zemek26-Jul-12 10:14
mvpPaulo Zemek26-Jul-12 10:14 
GeneralRe: Avoiding double calls... Pin
Rafael Nicoletti27-Jul-12 5:34
memberRafael Nicoletti27-Jul-12 5:34 
GeneralMy vote of 3 Pin
Philippe Mori26-Jul-12 6:20
memberPhilippe Mori26-Jul-12 6:20 
GeneralRe: My vote of 3 Pin
Rafael Nicoletti27-Jul-12 5:37
memberRafael Nicoletti27-Jul-12 5:37 
GeneralMy vote of 3 Pin
MadDoc8725-Jul-12 23:33
memberMadDoc8725-Jul-12 23:33 
GeneralMy vote of 3 Pin
Klaus Luedenscheidt22-Jun-12 19:07
memberKlaus Luedenscheidt22-Jun-12 19:07 
GeneralRe: My vote of 3 Pin
Rafael Nicoletti26-Jul-12 3:42
memberRafael Nicoletti26-Jul-12 3: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 17:10
memberAndreas Gieriet22-Jun-12 17: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 3:51
memberRafael Nicoletti26-Jul-12 3: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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160426.1 | Last Updated 26 Jul 2012
Article Copyright 2012 by Rafael Nicoletti
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid