What naming conventions do you use for your game's variables?

It seems like I’m always choosing one extreme – abstract references like “$J3907A” that can only make sense with an accompanying reference table – or the other – giving excessive detail like “$TheFirstThingAnNPCSaysToTheCharacterOnTheirSecondVisitToTheTrainStation”.

There have to be some kind of best practices out there, right? Or common approaches?

5 Likes

For games, or any other code for that matter:

Rule #1: A variable’s name should tell you what it holds in a way that makes sense without having to read all the other code around it first.
Rule #2: Naming conventions only matter if they help serve Rule #1.
Rule#3: There is no Rule #3.

4 Likes

My conventions in Ink are horrifying and nobody should imitate them.

But in Inform, my highest priority is to make the code readable. Variables should be named so that accessing them looks like standard English as much as possible.

5 Likes

category-type or category-info-type

e.g. timer-num, library-entered-bool, ending-king-text

4 Likes

I try to keep mine short, which means they often end up being fairly unintuitive… I’ll end up with $lie and $lie2, for instance, and just trust myself to remember what each is for while I’m working on the game. Which so far hasn’t been a problem, but I expect it will be someday. :sweat_smile:

4 Likes

I started moving more in this direction after you suggested it another time, and I basically agree.

In answer to the original question, my variables (in Inform) are now mostly named the same as the way I name things in the game. English with hyphens, and sometimes fewer spaces.

The timer in the hot zone is hotzone-timer.
The hot zone recovery flag is hotzone-recovery-flag, etc.

I used to use underscores, but then you have to press SHIFT. And I hate pressing more keys.

Then, ala @Draconis, if I find myself too often writing a particular checking phrase, like

if the hotzone-timer is 6

meaning the player is about to burst into flames, I Englishify it. So in Inform I make a phrase:

To decide whether the player is about to burst into flames:
	if hotzone-timer > 5:
		decide yes;
	decide no;

Then I can write stuff like

if the player is under attack and the player is about to burst into flames:

which is both more fun, and much easier to understand, faster, later.

-Wade

7 Likes

As simple as possible: related to an item or an action. As short as possible too, but without acronyms cause I can’t keep track of them. Usually not longer than 20 characters.

If I use object variables: $main-category.sub-category (like $mc.eyecolor).

Often, it’s related to the code itself: _cycleEyes or setup.arraycycleeyes, and lots of _tempchoice :joy:
I (re-)use a lot of $choice for variation that is only used for one future passage but is not necessary to track further.

3 Likes

generally, I abbreviate to the name, eg. wght for weight, with appropriate prefix/suffix, eg. pwdrwght, shelwght for powder, shell weight (a thing called “ballistics”…)
As one should have noted from the example above, I don’t use camelCase nor CamelCase, because the non-usage under languages fond of this casing allow me to be 10000% sure that don’t conflict with predefined vars (case in point, TADS 2 & 3 libraries)

in IF coding, often I use 1 letter-hypen prefix or suffix for differentiating functionally similiar, if not near-identical, objects… an example will explain easily:

let’s have a flight of stair connecting three floors (EU count !!), so I use floor-g, floor-1 floor-2 and floor-3 for these floors, identical in every respect, aside obviously the map connections.

being a real old timer, cycle variables are always one or two lettered, and a (local/temp) counter is always A (as in Accumulator…)

Best regards from Italy,
dott. Piergiorgio.

3 Likes

I use variable names that tell what it is. like a room named mainMarket for example. (I don’t fear long variable names.) Only exception: If I have local variables (only used in one procedure/function/block/room) I sometimes only name them loop or counter or count or even i.

Understandable var names are important for me, because when I wasn’t active on a particular code for a while, I wouldn’t remember what is what.

3 Likes

Giving good names to all the things is one of the hardest tasks in programming.

Maintaining code is harder than writing it in the first place. Readability greatly impacts maintainability. Favor readability.

Future you (and anyone else reading your code six [weeks/months/years] from now) will greatly appreciate things you name well.

Readability rules:

  • Names must be clear
  • Names must be concise
  • Names must be consistent

(This works sort of like a fire triangle with heat, fuel, and oxygen: if you omit one element, the thing itself can’t exist.)

Balance clear with concise.
x tells you almost nothing, but is concise.
ThisExplicitlyNamedVariableThatStatesExactlyWhatItIsForIsClearButHardToDigest.

As with any other writing, strive to be consistent. If you can’t be globally consistent, favor local consistency.

One way to work at consistency is by convention. The source language itself will often have a certain style or specific behaviors imposed by conventions.

In Go, exported functions are written with a leading UppercaseLetter, while leading lowercaseLetter functions are not exported.

In Python and JavaScript, a leading underscore _variable often means the variable shouldn’t be exported, but it’s a naming convention rather than a language convention.

Another one you see this way is PascalCasing for class names and camelCasing for names of function parameters. (Again, generally not a convention enforced by a language.)

One thing not to do, is so-called Hungarian notation of variable names. (Microsoft did it this way for a time, and even implmented a style around it.)

One exception to that seems to be in UI. For example, in Godot, there are a number of UI container nodes that are kind of wordy. If you adopt a substitute naming convention, this kind of thing:

Control
  MarginContainer
    HBoxContainer
      PanelContainer
        VBoxContainer
      PanelContriner2
          ScrollContainer
            MarginContainer
              VBoxContainer

Can be this instead, and I think there’s some economy there:

UI
  Mat
    Col
      Left
        Row
      Right
        Scroll
          Mat
            Row

Be mindful of scope.

If a function is relatively short and has only one parameter, you could name the parameter x or value. But it doesn’t take long before a generic name for a variable becomes something you have to scroll back up the function body to read again if it’s not clearly named.

Basically, the shorter the reach and lifespan of the thing you name, the shorter and more generic the name can be.

In my own code:
i, j, k — loop variables
a, b, c — strings
x, y, z — mathematical or coordinate values
t, d, m, h, p — expressions involving time

Depending on language-enforced conventions, things like arrays or collections could be uppercase versions of the above (like A, B, C for a collection of strings). Another way to do it is item and items.

Smaller names generally lead to less cognitive load, but again, the longer that variable has to hang around, and the further you need to use it from the context it was introduced, the longer and more specific the name probably ought to be.

8 Likes

Thanks @twip , that was very informative and true.

I’m not sure which of the 2 UI schemata is better: MarginContainer or Mat. Maybe in that case both schemata are good.

I always found the Hungarian schema very “ugly” and hard to decipher. But maybe some folks appreciate it?

1 Like

I believe most now consider that style to be a mistake. I certainly do. Having the type of a variable in the name is not as important as what it is intended to represent and frankly just gets in the way.

1 Like

it’s a thing from micro$oft, nothing new…

Best regards from Italy,
dott. Piergiorgio.

For storing dialogue, you could use something like

  • scene name
  • character name
  • dialogue line number

e.g. for that example,
SceneTrainStation2_CharacterNPC1_Line1

I got this general idea from ThroughLine Games (who made Forgotton Anne) who have an automatic system in Unity where the dialog audio files are all imported automatically based on the file name. (I found this out from watching a behind-the-scenes meeting for their new upcoming game.)

3 Likes

Prefixes end up feeling pretty clunky to me when I read them. However, there are places where consistent use of prefixes is helpful during maintenance. For example, if you have a very complicated form with a lot of controls on it, if drop-down boxes are all prefixed with drp, the development environment you’re working in will usually be able to pick that up. (VS Code does.)

But it’s really easy not to be consistent. And ultimately the color-coding and squiggles and tool-tip help from the development environment makes that kind of thing unnecessary. I think the heyday of it was long before the tools were so good.

This is probably a good moment to declare very loudly: preferences and principles are usually kept in the same toolbag. Which is which matters, of course, but I think there’s room for a lot of opinions about organizing code.

Having some kind of architecture to your information ought not be optional, though. :slight_smile:

1 Like

I believe most now consider [Hungarian notation] to be a mistake. I certainly do. Having the type of a variable in the name is not as important as what it is intended to represent and frankly just gets in the way.

There are still contexts that I prefer to use Hungarian. In most places, I do not, but mostly because I’ve had to work with style guides that consider it bad.

There are actually two different styles that people call Hungarian notation: one that encodes the type of the variable or function name, and one that encodes the kind. It seems the latter was what Charles Simonyi intended when he first described it in his thesis. The former appears to have grown out of a misunderstanding of that intent.

Microsoft was the first large-scale user of the system, and they are responsible for popularizing it. Within Microsoft, both styles were popular, but in different areas of development, leading to the names “systems Hungarian” and “apps Hungarian”

Much of the criticism of Hungarian notation is specifically about systems Hungarian. Although it can be useful in low-level code (especially when the language doesn’t do strong type checking), that criticism is pretty legitimate.

Apps Hungarian, however, can be useful, even in higher level code and with programming languages that offer a more robust type system. Unfortunately, its reputation was tarnished by the critics who didn’t distinguish between the styles.

So most coding styles now avoid anything like Hungarian, and only a few offer a naming convention in its place. Sometimes this leads to an inconsistent application of suffixes, prefixes, and/or abbreviations that hurts readability at least as much as “ugly” and “indecipherable” Hungarian prefixes.

That said, in some contexts (like very high-level code, generics, duck-typed languages), there isn’t much to be gained from a systematic naming convention like Hungarian. Depending on your implementation language, such conventions probably aren’t useful for IF.

6 Likes

Thanks for the detail, I’d not heard of that split. It isn’t super clear what “kind” means in this context if not the type.

I’m not big on prefixes or suffixes. I try to name all my variables with readable english. If a variable name gets too long, then it probably means the code needs to be refactored so such specificity isn’t required. I also avoid abbreviations completely unless their meaning is obvious and virtually universal. For example: min and max would probably be OK. Using num instead of number might be, but the savings is miniscule, so I’d write it out. Things like cnt instead of count, or obj instead of object are to be avoided, and single letter variable names are anathema. I am also known to keep a thesaurus handy to pick shorter, clearer names over longer ones.

1 Like

“Kind” would mean things like whether a number is a column number or a row number. Or whether a number is a length in inches or centimeters or pixels. Maybe what modern programming-language theory would call “dependent types” if I’m understanding that terminology correctly?

But he also did mix a lot of type info in there: this was 1977, after all, so languages didn’t necessarily do that for you. And yeah, he was big on abbreviating things (again, 1977): “Names should be short to minimise writing or typing (or keypunching) time, to reduce the number of mistyped names and, perhaps, to stay within bounds of existing limitations.” (e.g. name length limitations in programming languages).

But within the bounds of the technology and knowledge of the time, my impression is that he was a pretty sensible guy.

Deciding on the name of a quantity is the prototype of decisions which are unimportant in themselves, but appear frequently enough to have an impact on productivity.
[…]
The most common mnemonic device is to express by the name an important problem of the named quantity. The association is readily made in both directions: seeing the name, one learns an important property of the quantity which, in turn, leads to other properties. Conversely, given the quantity, its important properties are known, hence the name is suggested.
[…]
A number of problems arise with this practice: a quantity may not have any significant properties, or it may have so many that it is difficult to remember which one was chosen.

If you’re into that kind of history, and can track down a copy of his PhD thesis Meta Programming: a Software Production Method, it’s an interesting read to see how far we have and haven’t come in figuring out how to make software development easier…

1 Like

Yeah, things were a lot different then, and abbreviations were definitely required. None of those reasons hold any value today.

  • Less typing: This is not a good goal. I’ve seen developers create insane designs in an effort to type less and it never ends well.

  • Mistypes: Easily caught today.

  • Limitations: Long gone.

In all my years of software development, I can’t say I’ve ever run into that scenario and I’m sceptical it is a valid concern. To me, good variable naming is of primary importance in good coding. There are others equally important, sure, but none that I can think of that are more important.

I tinker around with leetcode occasionally and it is depressing to see how badly most of the published solutions are written, especially if you look at dynamic programming problems. For something that is supposed to be a learning tool for others, it’s pretty clear that very little effort goes into writing the vast majority of them. It looks like some kind of cargo cult programming nightmare. Cryptic single letter variables are the order of the day, with little to no discernable structure to the code, and comments nowhere to be found. If you are just solving the problems, fine, but publishing a solution? Geez, no wonder software development is the crapfest it is today.

1 Like

Hi Mike, I’m just going to go off on one here (on your side i hope)…

When Hungarian came in around the 90s everyone was telling me it was the best thing since sliced bread and I had to use it. I claimed it sucked because embedding a type into a variable name in a strictly typed language (what we were using at the time), was simply retarded. More specifically, it meant if you, for example, changed something from say an “integer” to a type, it would entail renaming all your variable references throughout your codebase.

If you also remember back in those days we didn’t have concurrent versioning systems and it was “normal” for various developers to “sit on” files for days or even weeks and keep them locked. This normally didn’t cause a problem because such files tended to contain code responsible by the developer in question. Yeah, except they often referenced variables throughout the codebase.

Ten years later the Hungarian aficionados vanished but the perps never admitted their mistake. I refused to use it back then and was roundly thrashed for it. Bastards.

I’m glad to get that rant out :slight_smile:

4 Likes