January, 2009 Archives
Jan
Method or Property
by Mikael Lundin in Programming
In .NET development this one question often reappears.
Should I implement this as a method or a property?
It is quite hard to distinguish the difference between a method with no arguments and a property. It is easy to say when you got it wrong, but it is much harder when you sit there and going to do the implementation. The book I’m reading has some very clear rules about this, that I would like to share with you.
Methods should represent actions and properties should represent data.
Example
// Property is data of an empty string value string s = string.Empty; // Action returns normalized string s.Normalize();
I believe this is the most common rule that we all follow. I seldom see code where an action has been implemented as a property, because it doesn’t feel natural.
Do use a property, rather than a method, if the value of the property is stored in the process memory and the property would just provide access to the value.
Example
public class User
{
private string username;
public string Username
{
get
{
return this.username;
}
}
}
This is also the most common way to use a property. You have a field that you want publicaly exposed. This statement is important because of the next guideline.
Do use a method if the operation is orders of magnitude slower than a field access would be.
Example
public IEnumerable<User> Users
{
get
{
IList<User> result = new List<User>();
using (DbConnection connection = dbFactory.GetDbConnection())
using (DbCommand command = dbFactory.CreateCommand(connection))
{
command.CommandText = "SELECT username FROM user";
using(DbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
User user = new User { Username = reader.GetString(0) };
result.Add(user);
}
}
}
return result;
}
}
The consumer of this class will not expect a database call when he accesses the property. Since it is defined as a property he will expect the property value to be retrieved in a trivial fashion and he will certainly not expect an exception to be thrown if the database is unavailable. This is the primary mistake I see when I read code.
Do use a method if the operation has a significant and observable side effect.
Example
private bool isDataSourceLoaded;
private IEnumerable dataSource;
public IEnumerable DataSource
{
get
{
// A significant side effect where the GET-property populates the field
if (this.isDataSourceLoaded)
{
this.dataSource = GetUsers();
this.isDataSourceLoaded = true;
}
return this.dataSource;
}
}
Debugging a class where the properties has side effects can be frustrating, since you will cause that side effect every time you put a watch on the property. (which in Visual Studio may happen only if you hover the property with the mouse pointer) Methods are however not executed in debug mode unless you explicitly invoke them.
All of these guidelines and more comes from the book I’m currently reading called “Framework Design Guidelines -Conventions, Idioms and Patterns for Reusable .Net Libraries” by “Krzysztof Cwalina and Brad Abrams”. It is an excellent book that I enjoy every minute of reading.
Jan
Every line, a point of failure
by Mikael Lundin in Programming
No matter how much I love to write code, there is nothing as satisfactory as removing code. Perfection is recieved when there is nothing more to take away.
Many developers I know wants to write code and is very reluctant to removing code. Even when they’re supposed to update or change the behaviour of existing code, they comment it out and leave the old version in case it will be needed.
Obsolete code is dangerous
Leaving commented code in the code base is just clutter. I don’t know if they leave it there as a backup or a substitute for version control, but I can’t see any point in it.
In addition to just cluttering the code base, the old code might give a new developer wrong ideas about the functionality. Instead of trusting the current code he will be given an alternative. “Why did the original developer leave that old stuff here? Must mean that it’s important.”
The worst kind is obsolete code that’s not intended to run. Let’s say there is one case in an else-if that is not needed anymore, but you leave it there because what harm could it do?
Remember that every line of code is a point of failure in your system. Every line has a potential of throwing an exception, and fewer the lines, the more stable your system will become.
I read in Pragmatic Programmer that writing code is like tendering a garden. You add flowers, and trees; you trim the grass. Just don’t forget to remove the weeds.
Jan
Base of operation
by Mikael Lundin in Uncategorized
I have moved from Stockholm to Uppsala, a small town about 80 km north of Stockholm. I still work in the capital, in the same firm, but decided that the noice, the smell and the filth of a big city is not what I want to spend my spare time in.
Now I travel the 80 km everyday with train which has given me a lot of time for Mint. I get up 05:30 am and take a train for about 40 minutes. That is enough for solving at least one problem. Then I have 8 hours of work where my unconsiousness may figure out the next step before I travel home and have another 40 mintues of coding.
That’ll give me roughly 6,5 hours of work every week on Mint, if I exclude weekends. That is probably more than I spent during the fall all together