domingo, 19 de abril de 2015

Labeled as:

How important is not invent the wheel again... Programming Challenge #2

C# and Developing
Intended for: C# programmers of all levels


A few days ago I've found a similar code than the above one... I guess that was due to I was very very tired, o because I wasn't expecting a creation like this but, is a fact that I need some seconds (lots of them) in undertand what the hell this code does.

After a conscious analisys finally I understand that it's creator only wants one thing: make a DateTime object that retrieves the current date using the useful DateTime.Now be converted in a string object, to be painted in the screen.

I don't want to blame this guy or it's proffessional capabilities, I don't want to freely complain because I know that EVERYBODY (I'm the first one) make mistakes sometimes at this job. What I want to say is that if we take 3 seconds to surf in Internet, we realize that this is not so far the best way to do this simple thing.

My reasons for this, but there will be million more, are the following:
  1. Each call to DateTime.Now have a useless and stupid additional cost, from the first call to the last one, besides beign small, there will be milliseconds difference between them (in the image you can realize that there are several calls to the functions, you only need to know the Now property).
  2. Concat operator ("+") is the slowest one for strings and is not good to use it for so extense concatenation. For it there is StringBuilder class (one of the tricks that I've learned in the official Microsoft course).
  3. This code is so far away of beign clear. I insist, my more that nine year's experience not allow me to understand it untial a difficult analisys so, a rookie trying to understand it fighting a dragon like this... Our code must be as clear as possible (there's sometimes where the code couldn't be more clear for several reasons.
No doubts about the best way to do this is the following one (people that knows about this realize at first for sure):


Both functions make EXACTLY THE SAME, but the second one is infinitely faster and clear than the first one. This means that in an application than needs a good performance, if we don't care about simple things like this it's possible that the response time will be penalized.

Because of all explained in this article I insist: don't invent the wheel again. The rule of lazy developer that will be explained in a future article must be the one that is with us every day. If we make "science" or "sorcery" like this, is normal that people cames with a crane and deletes our code.

I want feedback from you with similar experiences...

Unknown

Author y editor

0 comentarios:

Publicar un comentario

 

Friendly Websites:

  • Manuel Enrique Díaz Rodríguez
  • CuRadio
  • Copyright © DotNet Pathways 2015
    Distributed By My Blogger Themes | Designed By Templateism