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 useful sometimes and it's an operation the developer has to know about, but in most cases casting is misused and means one of these two bad situations:
- 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 one type to another
"hey compiler! this information is a double but I need something that corresponds to an int"
Both of these cases are yellow/orange flags, and require the developer to pay more attention.
In the first case, the developer has to ask themselves: "Why do I have information about the code that 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 themselves: "Why do I have to do this? Why do I get something in one type whereas I need it in another one?"
Personally, I avoid casting as much as I can because in the majority of cases, casting is at least one of these bad things:
1) A non-sense
Just think about it. When you ask the runtime to cast an object into another one, you are telling it: "Hi! Take this thing and turn it into this other thing, for some reasons I won't explain".
2) A loss 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 code that is hard to understand and hard to maintain.
3) A symptom of a bad design
If, when you get something, you need something else, it's probably the sign of a design that can be improved. In this situation, you can be one of two totally different developers:
- The lazy one; "Hum ... I don't care, just let's cast this"
- The curious one; "Why does this situation happen in the first place? Is there a misunderstanding somewhere? What can I do?"
Although casting has to be used with caution and a good understanding of what it is and what the situation is, it's clearly not always a bad thing. If it were, languages would not support it, and they do. Like any other language feature, it has its usefulness and its reason to exist. It's just preferable to think twice before using it.