Writing Bug-Free C/D Code
Knud Soerensen
4tuu4k002 at sneakemail.com
Mon Mar 19 07:20:31 PDT 2007
On Mon, 19 Mar 2007 11:44:54 +0100, Henning Hasemann wrote:
>
> I sometimes have some problems with this, as said before: Let SDL return
> a width as uint and have your positions int (because they also can be negative).
>
> I had this problems with C already. Examples of questions I have often when coding:
> - "Hmm okay. You're a on-screen coordinate. You will be positive.
> But I might to want to mix you with virtual and potetially negative
> Coordinates. Also you wont be larger than 32000, as long as screens
> wont get really big. But I somehow feel I should make you an int..."
> - Hm okay so I have these few things I know of they wont be negative.
> Should I make them int nevertheless? Would avoid complications and warinings,
> and the value range wouldnt be a problem.
Well, I think your problems is due to fundamental errors in your
programming method. :-)
We all know the ordinary form of Hungarian notation as described in
http://www.duckware.com/bugfreec/chapter3.html#naming
but there is also a stronger form called app-Hungarian notation
where the prefix gives a hint of the purpose for the variable.
Like rowPos for a row position and colPos for a column position.
Now it is easy to spot buggy code like rowPos=colPos etc.
Using a type system we can take the idea a step further.
typedef int ROWPOS;
typedef int COLPOS;
foo
{
ROWPOS rowPos;
COLPOS colPos;
rowPos = colPos; // error at compiler time.
}
So, the fundamental flaw is that you use raw types instead
of making a type for each purpose in your code.
Could the compiler do something about it ?
Yes, it could provide a switch called -bugfree
which trows a error every time a non user defined type is
used in the code.
It would also be useful if we could add an invariance to the type
instead of have to change it into a class or structure.
More information about the Digitalmars-d
mailing list