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: 130
Joined: 19 Feb 2013, 20:33



IF you want to ((lose weight) OR (have unbelievable (brain function AND mental clarity))) THEN click:




cron
free counters

eXTReMe Tracker