BadProgrammingException or On The Issue of Developer Mistakes Exceptions
Wednesday, 21. May 2008, 16:48:32
The BadProgramming exception would be used in some of the following cases:
- on stack overflow
- on null pointer or reference
- on invalid casts
- on any exception thrown from the code that is not documented
- on value out of bounds
- on assert failures
and I'm sure you can think of some examples, too. Ideally, the introduction of such an exception would create more responsibility for the developers, and make them look twice at the code they're writing.
Of course, this is not possible and it won't work because of the human factor. But this idea raises an interesting question:
Should we try to eliminate "developer exceptions" like the above from our frameworks and products? Couldn't we avoid them in some way?
The answer is: Sure we could, and there's one simple way: design by contract. But, for some reason I can't understand, no mainstream programming language has design by contract built-in. But the possiblity exists; check for example the Nice programming language.
Instead, we are condemned to look at the code and search for all kinds of possible developer mistakes, like this one (C# + LINQ):
User u = db.User.Where(p=>p.ID=150).FirstOrDefault(); System.Out.WriteLine(u.Name);
or this one (C#):
Entity entity = someObject as Entity; System.Out.WriteLine(entity.ID);
or, even worse, this one (C#):
Entity entity = (Entity)someObject;
In languages like C# or Java, the nullable pattern might work much better. Nullable was introduced for value types that should be allowed to be null. For example:
DateTime? dt = someObject as DateTime?;
if(dt.HasValue)
{
System.Out.WriteLine(dt.Value);
}
(There are many other versions of syntax, including shorter ones.)
The idea is that the compiler will tell you if you try to convert someObject to DateTime instead of DateTime? (shortcut for NullableType<DateTime>). So why couldn't we use the same pattern for all types? Disallow them to be null, and only allow them when the programmer says so.
But this is just the beginning of a would-be-very-lengthy-discussion. Any ideas?
Personal advertisement: I am PassionIT and I help teams develop high quality software. I train, I help improving and I work hands-on, depending on the needs. Contact me if you need help. Alexandru Bolboaca-Diaconu
