Posts Tagged ‘casting’

Do not type cast – Fail At Once

June 16th, 2008

Avoid casting types.

Why do I write about this? What has it do do with quality and projects and architecture? Well… each thing that cannot break doesn’t have to be tested and… cannot break. Less testing, less coding, less bugs.

When working with class libraries that are dependant on the generic type one cannot avoid type casting fully. The solution then is to encapsulate and wrap the cast through inheritance or composition.

If you wrap your type cast you have 1 test case instead of a test case per call.

What about datagrids and combo boxes that have an internal Rows or Items collection or Tag attribute? How can they become type safe without having to rewrite the whole control? Unfortunately I don’t have a perfect solution but as I have seen the evil in type casts I avoid them and instead of writing test cases and tests I spend some time looking for a type safe alternative. These are typically called row.OrderTag or combobox.CustomerItems. Overriding the method or attribute is not possible since one cannot change type; but one can override and set the [Obsolete] attribute to at least get a warning. Pepper this with a Debug.Fail( ”Please use the OrderTag property instead.” ) and things will stop in any test case that runs it. Many times one can even set the compiler to fail with [Obsolete(true)] to be totally sure the call is never made.

Another problem then is when two different types really are returned. Well… write two methods then. Even overload them; as long as the compiler understands your goal.

Final thought: How should one get this type of thinking into the spine of a project? It is not something that can be ordered but has to be understood and taken to heart by the involved. If someone has an idea please drop me a line; but until then being a good example is a good beginning.