Variable & Function Name Length Guide - Programming Naming Conventions

9 min read

In programming, naming is one of the most important factors affecting code readability. Names that are too short convey no meaning; names that are too long make code verbose. Choosing the right length requires judgment based on scope and complexity. This article covers naming length guidelines and language-specific conventions. For foundational reading, see search gravure photo books on Amazon. Check your identifier lengths with Character Counter.

Variable Name Length by Scope

The appropriate length of a variable name is proportional to its scope. This principle is widely endorsed in Robert C. Martin's "Clean Code" and Google's style guides. The reasoning is rooted in cognitive psychology: human working memory can hold only 4–7 information chunks simultaneously. For variables with wide scope, the name itself must restore meaning without surrounding context. Conversely, within a 2–3 line loop, the context acts as a chunk, so a short name like i keeps cognitive load low.

ScopeRecommended LengthExamplesRationale
Loop counter (1–3 lines)1–2 charsi, j, kUniversally understood convention
Lambda / short block (≤5 lines)3–8 charsitem, user, valContext makes type/role clear
Local variable in function8–15 charsuserName, totalPriceRole must be clear within the function
Class field / property10–20 charsmaxRetryCount, isAuthenticatedReferenced across the entire class
Global variable / constant15–25 charsMAX_CONNECTION_TIMEOUT, DEFAULT_PAGE_SIZEMust be unambiguous across the codebase

Naming Length Analysis of Major OSS Projects

What do identifier lengths look like in real-world open-source projects? Analyzing source code from major projects reveals clear differences in naming length depending on the language and project nature.

ProjectLanguageAvg Variable LengthAvg Function LengthCharacteristics
Linux KernelC~6 chars~12 charsShort variables; function names longer due to module prefixes
Spring FrameworkJava~12 chars~18 charsThoroughly descriptive naming; long overall
CPythonPython~8 chars~14 charsIncludes underscore separators from snake_case
ReactJavaScript~9 chars~15 charsComponent names tend long; internal variables short
KubernetesGo~7 chars~13 charsReflects Go's culture of brevity
Ruby on RailsRuby~9 chars~15 charsDSL-style method names close to natural language

A notable pattern is that C projects have short variable names, but function names include module prefixes (tcp_v4_connect, ext4_read_inode) that make them relatively long. In C, which lacks namespaces, prefixes serve as a namespace substitute. In contrast, Java's Spring Framework standardizes long names with IDE autocomplete as a given - class names exceeding 50 characters like AbstractTransactionalDataSourceSpringContextTests are not uncommon.

Function and Class Name Guidelines

Identifier TypeRecommended LengthNaming PrincipleExamples
Function name10–25 charsverb + object formatcalculateTotalPrice, sendEmailNotification
Class name10–25 charsNoun or noun phraseUserRepository, PaymentProcessor
Interface name10–25 charsAdjective or noun describing behaviorSerializable, EventListener
Constant name10–30 charsUPPER_SNAKE_CASE with specific meaningMAX_RETRY_COUNT, DEFAULT_TIMEOUT_MS
Boolean variable/function10–20 charsis/has/can/should prefixisValid, hasPermission, canExecute

Functions should always start with a verb. fetchData() is clearer than data(); validateInput() is better than validation().

Language-Specific Conventions

LanguageVariables/FunctionsClassesConstantsStyle Guide
JavacamelCasePascalCaseUPPER_SNAKE_CASEGoogle Java Style Guide
Pythonsnake_casePascalCaseUPPER_SNAKE_CASEPEP 8
JavaScriptcamelCasePascalCaseUPPER_SNAKE_CASEAirbnb Style Guide
GocamelCase / PascalCasePascalCasePascalCaseEffective Go
Rubysnake_casePascalCaseUPPER_SNAKE_CASERuby Style Guide
C#camelCase / PascalCasePascalCasePascalCaseMicrosoft C# Conventions

IDE Autocomplete and Name Length

The concern that "long names are tedious to type" is largely eliminated by modern IDEs. Comparing autocomplete features across major IDEs shows that name length has minimal impact on development speed.

IDE / EditorCompletion TriggerMatching StrategyLong Name Support
IntelliJ IDEAAutomatic on typingCamelCase initial match (gUNgetUserName)2–3 initials narrow candidates; long names cost little
VS CodeAutomatic on typingFuzzy match (usrnmuserName)Partial matches shown; exact spelling not required
Vim / Neovim (LSP)Ctrl+N or LSP integrationType-aware LSP-based completionIDE-equivalent completion via coc.nvim or nvim-cmp

IntelliJ IDEA's CamelCase matching is particularly powerful - typing ACTDSCT alone completes to AbstractConcurrentTransactionalDataSourceSpringContextTests. This means name length need not be constrained by typing effort; you can choose the optimal length purely for readability.

Naming Trivia

The Linux kernel coding style guide favors short variable names. Linus Torvalds himself has stated that loop variables should use i rather than loop_counter. In contrast, Google's Java style guide discourages single-character names outside of loop counters and lambda parameters. This contrast reflects different contexts: kernel code read by a small group of experts vs. large-scale web services read by many developers. Studies of open-source projects on GitHub suggest the average variable name length is approximately 8.5 characters.

The Problem with Too-Long and Too-Short Names

Naming failures fall into two extremes: too short to convey meaning, and too long to read comfortably. Short names like d, tmp, or val outside of loop counters become cryptic within days - even to the original author.

Overly long names are equally problematic. A variable like numberOfItemsInTheShoppingCartBeforeDiscount won't fit on a single line and actively harms readability. The sweet spot is a name that communicates its role at a glance without disrupting the flow of the surrounding code.

From a cognitive science perspective, the relationship between identifier length and reading speed follows a U-shaped curve. Names that are too short incur cognitive cost for "meaning reconstruction," while names that are too long incur cost for "visual scanning." Research suggests that English identifiers in the 8–20 character range achieve the highest reading efficiency. This stems from the balance between the string length human vision can recognize at once (~7–10 characters) and the minimum number of words needed to convey meaning (2–3 words).

Unicode and Multibyte Variable Names

Many programming languages support Unicode identifiers, but using non-ASCII characters in variable names introduces several pitfalls in practice.

LanguageUnicode VariablesExampleCaveats
Python 3Full support名前 = "Taro"PEP 8 recommends ASCII only; avoid in international teams
RubyFull support数値 = 42Magic comment # encoding: utf-8 required (pre-Ruby 2.0)
JavaScriptUnicode escapes allowedlet café = trueNFC/NFD normalization can make identical-looking names distinct
JavaFull supportint 金額 = 1000;Compiles, but discouraged by virtually all style guides
GoUnicode Letter category名前 := "Taro"Only characters in Unicode's Letter category are allowed
C / C++Limited (C11/C++11+)int données = 0;Support varies by compiler

JavaScript's Unicode normalization issue deserves special attention. The variable name café can be represented in two ways: NFC form with é as a single character (U+00E9), or NFD form with e + combining accent (U+0065 U+0301). They look identical but are treated as different identifiers. Since macOS's file system (APFS) uses NFD, unexpected bugs can occur when generating variable names from file names.

Reserved word collisions are another overlooked edge case. In Python, class, import, and return are reserved, but workarounds like cls (abbreviation of class) and klass have become established conventions. In JavaScript, class became a reserved word in ES6, causing syntax errors in pre-ES6 code that used it as a variable name - a real migration issue.

Common Mistakes

Pro Naming Techniques

Enforcing Naming Conventions with Linters

To unify naming conventions across a team, automated linter checks are essential. Here are the major linters and their naming-related rules for each language.

LanguageLinterNaming RuleConfiguration Example
JavaScript / TypeScriptESLint@typescript-eslint/naming-conventionEnforce camelCase for variables, UPPER_CASE for constants, PascalCase for types
Pythonpylint / RuffC0103 (invalid-name)Enforce snake_case; set minimum length (default: 2 chars)
JavaCheckstyleMemberName, MethodNameDefine naming rules via regex patterns
Gogolangci-lintrevive's var-namingEnforce MixedCaps; unify acronym casing (ID, URL)
RubyRuboCopNaming/VariableNameEnforce snake_case; set maximum length limits

ESLint's @typescript-eslint/naming-convention rule is particularly flexible, allowing different naming rules per identifier type (variables, functions, classes, interfaces, etc.). You can even enforce semantic constraints like "Boolean variables must start with is, has, or should." Integrating linters into your CI/CD pipeline catches naming violations automatically before merge.

Conclusion

Appropriate name length scales with scope: 1–2 characters for loop counters, 8–15 for local variables, 15–25 for global constants. This principle is grounded in cognitive science - human working memory capacity limits how much context a name must carry on its own. Analysis of major OSS projects confirms this pattern, from Linux Kernel's average 6-character variables to Spring Framework's 12-character averages. While Unicode variable name support is expanding, normalization issues and international team readability make ASCII-only naming the practical choice. Avoid excessive abbreviation and Hungarian notation, and enforce naming conventions through linters integrated into your CI/CD pipeline. Use Character Counter to check your identifier lengths.

Share this article