Blog
- Home
- elegant code
- Why I always think twice before using casting
Why I always think twice before using casting
Casting is not inherently bad, it can be usefull sometimes and it's an operation the developer has to know about, but in the most if the cases, casting is misused and means one of this two bad situation :
- I have special knowledge about the code I'm writing that the compiler doesn't have, so I'm giving a hint to the compiler about reality
"hey compiler! this thing of type User is actually of type Customer"
- I need to perform a mapping from a type to another
"hey compiler! this information is a double but I need that corresponds to a int"
Both of this cases are yellow/orange flags, and need the developer pays more attention to it.
In the first case, the developer has to ask himslef : "Why I have information about the code the compiler doesn't have ?". It means that the compiler doesn't really handle the reality, maybe it is better to change the code to fix that.
In the second case, the developer has to ask himslef : "Why I have to do this ? Why I get a thing in a type whereas I need it in another one ?"
Personaly, I avoid casting as much as I can because in the majority of cases, casting is at least one of this bad thing :
1) A non-sense
Just think about it. When you ask to the runtime to cast an object into another one, you tell him : "Hi! Take this thing and turn it into this other thing, for some reasons I don't explain".
2) A leak of knowledge
If a developer casts an object into another one, there must be some reason to perform this operation but with a simple cast, this reason is lost. The result is a code hard to understand and hard to maintain.
3) A symptom of a bad design
If when you get something, you need another thing, it's probably the sign of a perfectible design who can be improved. In this situation, you can be two totally different developers :
- The lazy one; "Hum ... I don't care, just let's cast this"
- The curious one; "Why this situation happens in the first place ? Is there an incomprehension somewhere ? What can I do ?"
If casting have to be used with precaution and a good understanting of what it is and what the situation is, it's clearly not consistently a bad thing. If they were, the languages would not support it and they are. Like any other language feature, it has its utility and its reason to exist. It's just preferable to think twice before using it.