Friday 26 April 2013

Don’t reinvent the wheel; use the tools provided

Every so often I read a blog post and most of the time it’s interesting and the ideas it’s trying to portray are good however it’s the small snippets of code in them which can start to annoy me. It’s usually the little things such as re-writing functions which the .net framework will do for you.

One of the biggest culprits is when you have an array of strings, usually role names in user management, and you want a single comma separated string of them. I’ve seen for loops, for each loops, …. don’t think I’ve seen a while implementation yet. I’ve seen variations on a theme for the internal loop logic as well but still you get the idea and you end up with something like:

var roles = string.Empty;
for (var index = 0; index < Roles.Length; index++)
{
    roles += Roles[index];
    if (index != Roles.Length - 1)
    {
        roles += ",";
    }
}
return roles;

Now, it’s syntactically correct and yes it does what is required and yes this is a personal frustration of mine so I’m not pointing to anyone specifically but unless you’re doing something else in the code why not use string.Join and reduce it to …

return string.Join(",", Roles);

If we can start blogging code which harnesses the power of the frameworks we’re using then hopefully we can pass on this experience and techniques to newer developers and we can start to not reinvent the wheel, write more robust code and concentrate on the fun stuff.

No comments: