Declare variables with as narrow scope as possible


Link to this posting

Postby Ursego » 05 Nov 2019, 08:02

That will make code easier to understand and less bugs prone.

There are three obvious cases:

* If the value is used only within one method, then declare the variable local.

* If the value must be stored between method(s) calls (and each instance has it's own value), then declare the variable instance (object field).

* If the value must be stored between method(s) calls (and all the instances share the same value), then declare the variable static.

But...

If a value is used in more than one method with no need to persist (survive) between methods calls, then pass is as a parameter rather than declare as an instance variable (object field).

The shorter the life cycle of the variable, the easier is understanding the logic (and less the likelihood of bugs).
User avatar
Ursego
Site Admin
 
Posts: 143
Joined: 19 Feb 2013, 20:33



Ketones are a more high-octane fuel for your brain than glucose. Become a biohacker and upgrade yourself to version 2.0!



cron
Traffic Counter

eXTReMe Tracker