Lets talk code quality. More specifically, variable localisation/ proximity.
It goes without saying that if you group things together it gives your mind a break from dealing with too much complexity. There are tremendous advantages to using methods and standards that minimise what you need to think about when dealing with a specific task. This is especially true for programming and keeping this in mind will make your life as a programmer much more fun.
Variable-use localisation or variable proximity is a simple concept. Simply put, its how far away your variable declaration is from where it is used.
The first very obvious advantage is an improvement in readability. I’ve heard developers say that defining all the variables used in a method at it’s beginning helps the reader know what the method will do. Like listing recipe ingredients. More often than not, this practice confuses people by introducing too much information at once. Unfortunately, methods do not always work like recipes. Having everything you need before you start a process can be overbearing to the reader. Remember, we are trying to minimise what a you need to remember in order to comprehend a piece of code.
Declaring variables as you need them will limit the information exposed to the reader of your code. He/she only sees what is necessary to perform some task. By keeping variable declarations close where they are used you also decrease the live time of the variable. In loose terms, live time is the difference between declaration time and the last read/write time of a variable. Live time is a great metric for measuring variable proximity. The shorter the live time of a variable, the higher it’s localisation to it’s use.(generally speaking)
The next advantage is making the way for method extraction. This, in itself, opens the doors to even more pros:
- Methods help in information hiding.
- Fine-grained methods aid in modifying behavior for sub-classes.
- Increases testability, re-usability, maintainability, etc.
A lot more can be said about variable localisation and the advantages it brings. Most average developers probably do this without noticing, but I hope this serves as a good reminder to consciously cultivate a habit of logically grouping your code. See this as a small investment that can make a big difference in dealing with technical dept and monster methods later on.