Skip to content

Latest commit

 

History

History
33 lines (24 loc) · 1.18 KB

GCop160.md

File metadata and controls

33 lines (24 loc) · 1.18 KB

GCop 160

"This is not readable. Either refactor into a method, or use If / else statement."

Rule description

Writing long conditional expression will reduce code readability and increase misunderstanding. You should define an abstraction for the long expression. That abstraction can either be a method or a variable.

If you can't think of any good abstraction name for that concept, at least rewrite it in an if/else statement to make it more readable.

Example

var code = currentAccount.ID + (currentProduct.ProductId.ToString().Length > 3 ? 
       currentProduct.ProductId.ToString() : 
       (currentProduct.ProductId.ToString().Length == 2 ? "00" + currentProduct.ProductId : "0" + currentProduct.ProductId)
     );

should be 🡻

var code = currentAccount.ID + PadProductId(currentProduct.ProductId);

string PadProductId(int productId)
{
    if (productId.ToString().Length > 3) return productId.ToString();
    else if (productId.ToString().Length == 2) return "00" + currentProduct.ProductId;
    else return "0" + currentProduct.ProductId;
}

// Note: This is for illustration only. The logic in this example could be written in a cleaner way.