Search code examples
variablesnaming-conventions

Reusing variables nomenclature


Often variables get "reused" with the help of a bit of maths to trigger other events or amounts. For example in a game: variable v is an integer which exists between 0 and 3 and is the basis for a scoring mechanism where

  • score += Math.pow(2,(v)) * 100

Another example would be changing a variable which could be from 0 to an variable maximum amount into a percentage.

My question is this: Does this type of thing have a formal or special name at all? Excuse the vague nature of this question but I've never formally been taught how to code.


Solution

  • Perhaps 'multiple assignment' or 'aliasing' might be the closest? If you wanted to cast it in a positive light, you could call it something like 'transformation' or having been mapped.

    To be honest, this kind of thing is generally frowned on because it makes code harder to understand.

    In fact, there are several programming languages that only allow you to set a variable once, called single assignment languages. Even in procedural languages setting a variable only once is very nice for readability. There are some cases where you need mutable variables for performance reasons, but most of the time the compiler/interpreter is smart enough to deal with single assignment efficiently. Many compilers will actually convert programs written with multiple assignment into static single assignment form internally because it makes many optimizations easier to perform.

    So in your case, you could have v, and then if you wanted v scaled from 0 to 1, I'd make a new variable called v_pct or something. This is also related to the concept of apps Hungarian.