czwartek, 21 lutego 2013

C++ in Action (Industrial Strength Programming) by Bartosz Milewski

http://www.relisoft.com/book/index.htm


  1. Don’t use pointers where an index will do.

    a) Strlen using indexes

    int StrLen (char const str [] ) {
       for (int i = 0; str [i] != '\0'; ++i)
          continue;
       return i;
    }


    b) Strlen using pointers

    int StrLen (char const * pStr) {
       char const * p = pStr;
       while (*p++);
       return p - pStr - 1;
    }

     
    "If your compiler is unable to optimize the human readable, maintainable version of the algorithm, and you have to double as a human compiler-- buy a new compiler! Nobody can afford human compilers any more. So, have mercy on yourself and your fellow programmers who will have to look at your code."
  2. Fighting Defensive Programming

    "Defensive programming" sounds good, doesn’t it? A program written by a defensive programmer should be safer and more robust, right? Wrong! Defensive programming is a dangerous form of engineering malpractice (in a show of self-abasement I’ll shortly expose examples of such practices in my own code). Defensive programming promotes writing code that is supposed to work even in the face of programmers’ errors, a.k.a. bugs. In practice, it gives the bugs the opportunity to cover their tracks. Anybody who spent a sleepless night chasing a bug that could have been caught early on, if it weren’t for defensive programming, will understand my indignation. In most cases defensive programming is a result of not understanding the exact contract between various parts of the program. A confused or lazy programmer, instead of trying to understand the logic of the program, might write something that should work no matter what. That code will obscure the program's logic even more, making further development even sloppier. The programmer will eventually lose control of the code.


Brak komentarzy:

Prześlij komentarz