Making Wrong Code Produce Compiler Errors

Joel, of Joel on software wrote an interesting blog (Making Wrong Code Look Wrong) last week that I just found time to read. I would largely agree with him. Really quick summary: he argues for variable prefixes to prevent accidentally doing the wrong thing with variables that are the correct 'type' (example: string), but not the correct 'kind' (example: trusted string vs. untrusted string). 

I would largely agree with Joel. However, I would like to make one critique – where possible, I would prefer 'types' over 'kinds'. Joel starts out with an example of using 'kinds' to prevent cross site scripting (XSS) attacks. It sounds like a good programming practice, but I think it would be even better to create two classes: 'UserString' and 'ResponseString'.

What I like about classes:

  • You can make the compiler do the work of verifying safety. It is pretty easy to use the wrong variable. Compilers do a better job of finding problems then I could.

  • Easier for the guy down the hall. In order for 'kinds' to be practical, they need to be abbreviations. This means that when the guy down the hall reads my code, he probably won't understand all of my 'kinds'. Hopefully the guy down the hall is just reading my code. If I decided to go join a different team, all of my 'kinds' might loose their value forever. This is not the true for classes.

  • Easier to review. Using Joel's example, come security review time, I would need to look through my entire code base to make sure that I did use my kinds correctly. If I used types, I would just have one file to review.

Anyway, that is my two cents.

Comments (8)
  1. MSDN Archive says:

    Right on, Gregg!

    That’s exactly the reaction we had over here in C# IDE land. There’s all kinds of cool stuff you can do with the type system to make wrong code look wrong, and even the compiler can tell when it’s wrong!

  2. Gregg writes about his response to a recent Joel article.

    I had the precise same response, based on…

  3. Of course, you understand that the whole point of Joel’s post was to explain why Hungarian is good, right?

    Hungarian DOES use types – most true Hungarian apps have an SZ type for instance.

  4. No, it has an SZ ‘class’. The type for all strings is char*.

  5. mmh. Sure, but string is sealed in many languages. Nothing that can’t be worked around, but it tends to make things messier. And in Joel’s example, you would have to write your own special version of Write that only takes a TrustedString if you want a compiler error, right?.

Comments are closed.

Skip to main content