Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Refactoring Tips - Tip 3

2.42/5 (8 votes)
28 Feb 2010CPOL 1  
Refactoring Tips - Tip 3Tip 3In a class,if the expression is repeating across the methods. Then encapsulate/wrap that with either a Property or Method as shown below.This increases the code reuse,easy to extend and maintainBad practicepublic class A{ private int Var1;...
Refactoring Tips - Tip 3

Tip 3

In a class,if the expression is repeating across the methods. Then encapsulate/wrap that with either a Property or Method as shown below.

This increases the code reuse,easy to extend and maintain

Bad practice
public class A
{
 private int Var1;
 private int Var2;

 private void Method1()
 {
   string s = this.Var1 * this.Var2
   //Some more statements..
 }
 private void Method2()
 {
  string s = this.Var1 * this.Var2
  //Some more statements..
 }
}


Good practice


C#
 public class A
 {
  private int Var1;
  private int Var2;
  private int Expression
  {
    get
    {
      return this.Var1 * this.Var2;
    }
  }
  private void Method1()
  {
    string s = this.Expression
    //Some more statements..
  }

  private void Method2()
  {
    string s = this.Expression;
    //Some more statements
  }

}


I hope this helps!.

Regards,
-Vinayak

License

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