49c552e21b2fcbff0ff6567507ef1715

I see a lot of code like in snipper 1.1 which I refactor in snippet 1.2. I was wondering however which one you find the most readable/maintainable/performant?
(I've included 2 cases, containing an if and a while if)

int x, y;
if (x > y)
{
  x = y;
}
int x, y;
x = Math.Min(x, y);
protected void fill(FileStream stream)
{
  byte[] buffer = new byte[bufferSize];
  int remainingLength = fileSize;

  while (remainingLength > bufferSize)
  {
    loadBufferData(buffer);
    stream.Write(buffer, 0, bufferSize);
    remainingLength -= bufferSize;
  }
  if (remainingLength > 0)
  {
    loadBufferData(buffer);
    stream.Write(buffer, 0, remainingLength);
  }
}
protected void fill(FileStream stream)
{
  byte[] buffer = new byte[bufferSize];
  int remainingLength = fileSize;

  while (remainingLength > 0)
  {
    loadBufferData(buffer);
    stream.Write(buffer, 0, Math.Min(bufferSize, remainingLength));
    remainingLength -= bufferSize;
  }
}

Refactorings

No refactoring yet !

5a00a3a98dcf6f9cd717440fd2b606e5

Eineki

January 3, 2009, January 03, 2009 09:13, permalink

No rating. Login to rate!

The first refactoring is, to me, a little confusing, I had to look at it a second time to be sure that x mantain his value if lesser equal than y. Maybe you can use the ternary operator to compact the if into a single liner.

For the second refactoring, I prefer the version 2.2. It is terse as needed and more direct, clear and intuitive than the original version.

By the way, this is just my point of view.

int x, y;
x = x > y? y : x;
34e84f15cc083aaf9931b8af419b6ed3

Rainer Schuster

January 16, 2009, January 16, 2009 09:20, permalink

No rating. Login to rate!

In both cases I would agree with the second snippet. Avoiding Conditional statements containing if or switch decreases the readability and increases complexity.

I suggest you reading Robert C. "Unclebob" Martins books about Agil OO. (Clean Code, Product Image
Agile Principles, Patterns, and Practices in C#)

Your refactoring





Format Copy from initial code

or Cancel