Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice regarding returning from using blocks [duplicate]

Which way is better practice: return a value from a method inside an using statement or declare a variable before, set it inside and return it after?

public int Foo()
{
  using(..)
  {
     return bar;
  }
}

or

public int Foo()
{
  var b = null;
  using(..)
  {
    b = bar;
  }
  return b;
}
like image 694
abatishchev Avatar asked Aug 03 '09 18:08

abatishchev


2 Answers

I prefer the first example. Fewer variables, fewer lines of code, easier to follow, easier to maintain...

public int Foo()
{
  using(..)
  {
     return bar;
  }
}
like image 147
Scott Ivey Avatar answered Sep 18 '22 13:09

Scott Ivey


Following the "less is more" principle (really just a variant of KISS), the former. There are fewer lines of code to maintain, no change in semantics and no loss of readability (arguably this style is easier to read).

like image 32
jason Avatar answered Sep 19 '22 13:09

jason