Archive for category Refactoring

Remove and Sort Those Ugly “using-Statements”

Visual Studio 2008 has lots of goodies in it, like LINQ syntax, CSS editing, and testing tools. There’s a lesser-known feature which I really appreciate though – the “Remove and Sort Usings” command in the C# editor.

You activate the command by placing your cursor over the using statements and clicking on the right mouse-button.

image

Read the rest of this entry »

, , , ,

3 Comments

Refactoring C# Series: Aggregation of IEnumerable

I was recently reading Programming Ruby: The Pragmatic Programmers’ Guide, Second Edition, and came across this piece of example Ruby code:

[1,3,5,7].inject(0) {|sum, element| sum+element} -> 16
[1,3,5,7].inject(1) {|product, element| product*element} -> 105

Inject is a method which acts on an array by aggregating or accumulating the values within that array. It loops through the array, and for every item in the array, it performs a function. It then saves the result for the next iteration of the loop and eventually returns the aggregated value.

In C# 1.0 you would probably write such a method like this:

int sum = 0;
int[] list = new int[] { 1, 3, 5, 7 };
foreach (int item in list)
{
  // Perform some function, then save the result
  sum = sum + item;
}

It’s a bit long-winded, and if you wanted to make it reusable, you’d have a hard time.

In C# 3.0, you can do it just like you can in Ruby.

Read the rest of this entry »

, , , ,

1 Comment

ASP.Net MVC Corollary – What to do?

Dude! I got quoted! And by none other than Rob Conery of SubSonic fame.

It seems like my last post caused quite an unexpected stir. Thanks to both Rob and Scott for taking the time to answer me. I really appreciate it.
Read the rest of this entry »

, , ,

No Comments

Calculating the Fibonacci Sequence with C# 3.0

Scott Hanselman just posted his latest article in his weekly source code series. He shows various ways of producing the Fibonacci Sequence using various languages. I found it really interesting, for two reasons:

  1. I tried to do the C#3.0 one on my own after listening to a podcast about F#, and never could work it out. (Doh!)
  2. It makes me question what I thought about coding.

You see, I spend a lot of time refactoring. Sometimes too much. I have to ask myself why. It’s usually so that I can come back to the code later, and still understand what I was trying to do. Most of the time, conciser is better. But not always!

And that’s what I see in this post.

Read the rest of this entry »

, , ,

2 Comments

Can You Pass an Anonymous Type Across Functions?

One of the biggest questions with Anonymous Types is “can I pass them around?” If not, why not? Can you do something like this, for example:

var GetAnonymousValue() {
  return new { Name = "Richard Bushnell" };
}

void Main() {
  var value = GetAnonymousValue();
  var name = value.Name;
}

The answer is simple: no, you can’t pass anonymous types across functions. var is not a dynamic variable, like in JavaScript. The CLR knows nothing about “var”, as the compiler just uses it to infer types when a variable is initialized.

At least, that was the answer until now. Using a simple extension method and generics, Alex James just showed a nice way to pass them around on his blog.

The trick is to use an example of the anonymous type you expect.

object GetAnonymousValue() {
  return new { Name = "Richard Bushnell" };
}

void Main() {
  var value = GetAnonymousValue().CastByExample(new { Name = "" });
  var name = value.Name;
}

While this might be a little dangerous, especially if you’re not testing your code regularly, this could be the solution to a few problems I can already think of.

Watch out for casting exceptions at runtime though! If you make a mistake anywhere, you’ll won’t get a compile-time exception, but a nasty runtime exception instead.

No Comments

Refactoring C# Series: Use Automatic Property

Name

Use Automatic Property

Summary

You have a property in a class which just wraps a field of the same type, and simply returns or sets that field.

private string _field1;
public string Field1
{
  get { return _field1; }
  set { _field1 = value; }
}

Becomes:

public string Field1 { get; set; }

C# Version

3.0

Motivation

Encapsulation is quite possibly the key principle of object-oriented design. It is common practice in C# to encapsulate fields by wrapping them in a property.

When a class has many properties, much of the class is taken up by the same coding pattern for a property:

private string _field1;
public string Field1
{
  get { return _field1; }
  set { _field1 = value; }
}

In C# 3.0 this block of code can be removed by using automatic properties. The compiler will do the same thing that you would have done before if you just define the property name and the getter and setter.

public string Field1 { get; set; }

Reducing the property code like this makes it much easier to understand the code later, as only the necessary details are defined. Even if you use a terse syntax formatting, as in the previous example, you are saving 5 lines of code per property. The way I usually format my code with extra linefeeds, I save 9 lines for each one. When there are a lot of properties in a class, that is a large amount of code which can be removed.

Removing code isn’t just good for making it easier to understand; it makes it easier to test too. You wouldn’t have to test properties to see if they are simply setting and getting the correct values with this syntax, as the compiler is doing the work for you. So if you have unit tests, you might be able to remove lots of property testing code.

Of course, if the property does not just simply set or get a field value, you must use the previous C# 1.0 syntax for properties. In addition, you cannot specify get or set alone, but you can include scope identifiers to make a set private, for example:

// The following are not valid:
// Automatically implemented properties must define both get and set accessors
public string GetOnly { get; } // Not valid
public string SetOnly { set; } // Not valid either

// But this is okay
public string GetWithPrivateSet { get; private set; }

Mechanics

  • Remove the body of the property, replacing the code between the get and set blocks with a semicolon “;” .
  • Compile.
  • If there is a compiler warning that the field is no longer being used, you can now simply remove the field which the property was wrapping.
  • If there is no compiler warning, other methods or properties are using the field directly. You can remove the field and recompile anyway, which will give you the location in the code where the field is being used. Replace each reference with a reference to the property instead.
  • Compile.

Repeat for each property.

If the field was a protected field, not private, then you might have subclasses which access the field. They will have to be changed to access the property instead of directly accessing the field.

Tip: For new code, you can simply use the code snippet “prop” in Visual Studio 2008 to get an automatic property.

Examples

I’ll just do an example with one property, even though it looks a lot better with a longer class.

class Account
{
  private long _id;
  public long ID
  {
    get { return _id; }
    set { _id = value; }
  }
}

First, remove the body of the property getter and setter (and apply a bit of reformatting too, if you like):

class Account
{
  private long _id;
  public long ID { get ; set ; }
}

Compile, to make sure the code is happy, then remove the field:

class Account
{
  public long ID { get ; set ; }
}

5 Comments

A not-so-simple Mixin with C# 3.0

My last post gave a simple idea of how to do a Mixin with C#. Rather than repeating what someone else has already done, if you want to see a more complex example of what can be done, check out Create Mixins with Interfaces and Extension Methods by Bill Wagner at MSDN.com.

No Comments

New series: Refactoring C# 1.0 code to C# 3.0

I really like Scott Hanselmann’s idea to write an indefinite series of posts about reading code to be a better developer. I’m going to copy his idea, and write a series of my own.

Since its first version, C# has evolved from being a Java clone to something much more dynamic. I’ve noticed that developers often find themselves stuck long projects, and its sometimes hard to keep up with all the changes. I know a lot of developers who are still using .Net 1.1 because the project they are working on forces them too. For them, C# is still very much like Java.

So for all those who want to know what has changed since the first version, I’ve decided to make a new series of posts called “Refactoring from C# 1.0 to C# 3.0”. I will show through examples how you can make your code easier to understand and maintain by using the new features in C#. I’m not necessarily going to do it in historical order – I won’t show any preference for C# 2.0 Generics over C# 3.0 Extension Methods, for example. And C# 2.0 anonymous methods will take second place to C# 3.0 lambda expressions, which generally replaces them. I’m going to try to show how things have changed, and when you should or should not use the new features.

Some of the things I’ll cover are:

  • Anonymous types
  • Anonymous methods and lambda expressions
  • Extension Methods
  • Yield statements and iterators
  • Generics
  • List comprehensions (ala LINQ)
  • Mixins
  • Partial types
  • Type and Array inference
  • Property visibility
  • Automatic properties
  • Static classes
  • The Global namespace
  • Object, Collection and Dictionary initializers

I’ll try to treat each one as a refactoring opportunity, and not as a “must” or “must-not”. The idea is to write more maintainable code using the new features, not just go along with the trends.

Note: I’m not going to treat the .Net base library at all. Just the C# language.

No Comments