TLDR: Using var
speeds up writing code but makes reading code more difficult.
It’s very tempting to use variable typing(var
keyword) when writing C# code. It makes writing code much faster, refactoring code doesn’t create too many changes and as a result you get your work done faster.
But the main problem here is reading code, when the type isn’t visible to the reader they have to rely entirely on the name of the variable. The developer has to hover their cursor over the variable to check the type. This adds considerable overhead to anyone who is reading code.
This slows down
- Code reviews
- Debugging
- Scanning code yourself
- Before committing code
- Returning to work after a break or after the weekends
There have been so many instances where I assumed the type of a variably typed object and spending more time than necessary to fix an issue.
As software engineers we know that variable naming can be a bit crazy sometimes especially when it comes to larger projects with several people working on it.
Reading code is important as that is how bugs are found, code reviews are performed. To be able to do that, the developer needs to be able to easily scan through the code. Effort must to put into making this process as easy as possible.
So while using var
is faster in the short-term, the long-term costs make it so that it’s not worth using them as a general rule for most cases.
Leave a Reply