Abusing abbreviations (e.g., 'usrPwdChk' instead of 'userPasswordCheck')
Abuse of Abbreviations (e.g., 'usrPwdChk' instead of 'userPasswordCheck')
The code is filled with various abbreviations, such as writing userPasswordCheck
as usrPwdChk
, calculateTotalPrice
as calcTotPrc
, and getUserInformation
as getUsrInf
. These abbreviations may seem to save typing time, but in reality, they create a disaster for code readability and maintainability.
Why Abbreviations Are a Maintenance Nightmare
The biggest issue with abbreviations is their ambiguity. The same abbreviation can have multiple interpretations, and different people may understand it differently. For example, usr
could mean user
or username
; pwd
could mean password
or print working directory
(in Unix systems). This ambiguity makes the code hard to understand and can even lead to errors.
// Bad example: Abbreviations cause ambiguity
function valUsrInpt(inpt) {
// Is "val" short for "validate" or "value"?
// Is "usr" short for "user" or "username"?
// Is "inpt" short for "input" or "integer part"?
// It's impossible to tell what this function does
return inpt.length > 0;
}
The Cost of Abbreviations Far Exceeds Your Imagination
While abbreviations may seem to save time, the maintenance costs they introduce far outweigh the minimal typing time saved. When other developers (or even your future self) read the code, they must spend extra time deciphering these abbreviations. This cognitive burden significantly reduces development efficiency and increases the likelihood of errors.
// Good example: Clear and explicit naming
function validateUserInput(input) {
// The function's purpose is immediately obvious
return input.length > 0;
}
The "Contagious" Nature of Abbreviations
Abbreviations are also contagious. Once you start using them in your code, others are likely to follow suit, often taking it to extremes. Eventually, the entire codebase becomes filled with obscure abbreviations, turning into an unmaintainable "abbreviation hell."
// Bad example: The contagious nature of abbreviations
function procOrd(ord) {
const ordDet = getOrdDet(ord.id);
const custInf = getCustInf(ord.custId);
const totAmt = calcTotAmt(ordDet);
// ... more abbreviations
}
How to Gracefully Avoid Abbreviations
Avoiding abbreviations is simple: Use complete, clear words. While this may make variable and function names slightly longer, their readability and maintainability will improve dramatically. Modern IDEs support code completion, so typing is not a concern.
// Good example: Clear and complete naming
function processOrder(order) {
const orderDetails = getOrderDetails(order.id);
const customerInfo = getCustomerInfo(order.customerId);
const totalAmount = calculateTotalAmount(orderDetails);
// ... clear code
}
Common Abbreviation Pitfalls
Here are some common abbreviation pitfalls and their full forms:
usr
→user
pwd
→password
chk
→check
calc
→calculate
val
→validate
orvalue
inf
→information
det
→details
amt
→amount
ord
→order
cust
→customer
When Abbreviations Are Acceptable
While abbreviations should generally be avoided, they are acceptable in cases where they are widely accepted and unambiguous. For example:
i
,j
,k
for loop countersid
foridentifier
max
formaximum
min
forminimum
avg
foraverage
// Acceptable abbreviations
for (let i = 0; i < array.length; i++) {
// "i" as a loop counter is widely accepted
}
Naming Conventions in Team Collaboration
In team collaboration, establishing consistent naming conventions is crucial. Ensure all members follow the same naming rules to prevent personal preferences for abbreviations from creeping into the codebase. Tools like ESLint can enforce naming conventions.
// ESLint rule example: Enforce full words
{
"rules": {
"id-length": ["error", { "min": 3 }], // Avoid overly short abbreviations
"camelcase": ["error", { "properties": "always" }] // Enforce camelCase
}
}
Abbreviations and Code Minification
Some may worry that using full words will increase code size and impact performance. However, modern code minification tools (e.g., Webpack, UglifyJS) shorten variable and function names to single letters or brief identifiers during the build process. Thus, using full words in source code has no impact on the final production code.
// Source code: Full words
function calculateTotalPrice(items) {
return items.reduce((total, item) => total + item.price, 0);
}
// Minified code: Variable names are shortened
function n(t){return t.reduce((t,e)=>t+e.price,0)}
Abbreviations in Legacy Code
If you inherit a legacy codebase filled with abbreviations, don't despair. Refactor gradually by replacing abbreviations with full words. Fix abbreviations whenever you modify related code. Add clear comments and documentation to help others understand these abbreviations until they are fully replaced.
// Legacy code
function updUsrInf(usrId, inf) {
// ... obscure logic
}
// Refactored code
function updateUserInformation(userId, information) {
// ... clear logic
}
Abbreviations in International Teams
In international teams, abbreviations are even more problematic. Non-native speakers may struggle to understand certain abbreviations, leading to communication barriers and code comprehension difficulties. Using full words significantly reduces this communication cost.
// Bad example: Non-native speakers may not understand
function chkAuthTok(tok) {
// Is "chk" short for "check" or "chalk"?
// Is "tok" short for "token" or "talk"?
}
// Good example: Clear naming
function checkAuthorizationToken(token) {
// Any developer can understand
}
Abbreviations and Autocomplete
Modern IDEs and editors support powerful autocomplete features. Using full words can actually improve coding efficiency because you only need to type the first few letters, and the IDE will autocomplete the entire word. In contrast, abbreviations require you to remember more "secret codes."
// Using autocomplete
// Type "val" → Autocomplete to "validate"
// Type "user" → Autocomplete to "userInformation"
// Much easier than remembering "usrInf"
Abbreviations and Code Search
Full words make code searches more efficient. You can easily search for userInformation
without guessing whether it might be abbreviated as usrInf
, userInf
, usrInfo
, or some other variation.
# Searching for full words in the codebase
grep -r "userInformation" src/
# If abbreviations are used, you may need to search for multiple variants
grep -r "usrInf\|userInf\|usrInfo" src/
Abbreviations and Documentation Generation
Many documentation tools (e.g., JSDoc) rely on function and variable names to generate documentation. Using full words makes the generated documentation clearer and more professional.
/**
* Calculate the total order amount
* @param {Array} orderDetails - List of order details
* @returns {number} Total amount
*/
function calculateTotalAmount(orderDetails) {
// ... clear implementation
}
// The generated documentation will be very clear
// If abbreviations like "calcTotAmt" are used, the documentation will appear unprofessional
Abbreviations and Code Reviews
In code reviews, abbreviations often trigger more discussions and debates. Reviewers may spend extra time deciphering these abbreviations, reducing review efficiency. Using full words makes code reviews smoother.
// Conversation during code review
// Reviewer: What does "usrPwdChk" mean?
// Developer: Oh, it's "userPasswordCheck"
// Reviewer: Then why not just write "userPasswordCheck"?
// ... Time-wasting discussion
Abbreviations and Junior Developers
For junior developers, abbreviations are a significant obstacle. They may not yet be familiar with all abbreviation conventions, and reading code filled with abbreviations can confuse and frustrate them. Clear naming helps juniors integrate into the team faster.
// A junior's confusion
// "What does 'calcTotPrc' mean? Is it 'calculateTotalPrice' or 'calculateTotalProcess'?"
// "Is 'valUsrInpt' validating user input or getting the value of user input?"
Abbreviations and Code Reusability
Clear naming improves code reusability. When other developers reuse your code, they don’t need to spend time deciphering abbreviations and can quickly understand the code’s functionality and usage.
// Clear naming makes code easier to reuse
function validateEmailAddress(email) {
// ... clear implementation
}
// Other developers can easily understand and use this function
// If named "valEml", they might hesitate or misunderstand
Abbreviations and Debugging
During debugging, clear naming helps you locate issues faster. Seeing userPassword
is more immediately understandable than usrPwd
when determining the variable’s purpose and potential issues.
// Debugging confusion
// "Why is 'usrPwd' empty? Where does it come from?"
// If named 'userPassword', you might immediately think of the password field in the login form
Abbreviations and Code Aesthetics
Some believe abbreviations make code look more "concise" or "professional," but in reality, clear naming is the true mark of professionalism. The primary goal of code is to convey intent, not to showcase the author’s typing speed.
// Truly professional code
function calculateMonthlyRevenue(salesData) {
// ... clear implementation
}
// Seemingly "concise" but actually obscure code
function calcMthRev(slsDt) {
// ... hard-to-understand implementation
}
Abbreviations and Variable Scope
The larger a variable’s scope, the clearer its name should be. Global or module-level variables should never use abbreviations because they are widely visible and have far-reaching impacts. Even local variables should use clear naming whenever possible.
// Bad example: Global variable with abbreviation
let usrSess = getCurrentSession();
// Good example: Global variable with full name
let userSession = getCurrentSession();
// Even local variables should use clear naming
function processOrder(order) {
const shippingAddress = order.shippingAddress; // Clear
// Not const shpAddr = order.shippingAddress;
}
Abbreviations and Constant Naming
Constants represent unchanging values, so their names should be especially clear. Since their values don’t change during runtime, the names must convey sufficient information.
// Bad example: Constant with abbreviation
const MAX_USR_CNT = 100;
// Good example: Constant with full name
const MAXIMUM_USER_COUNT = 100;
Abbreviations and Boolean Variables
Boolean variables often represent states or conditions, so their names should clearly express their meaning. Abbreviations can lead to confusing logic.
// Bad example: Boolean variable with abbreviation
let isAuth = checkAuthorization();
if (isAuth) {
// Is "isAuth" short for "isAuthorized" or "isAuthenticationValid"?
}
// Good example: Boolean variable with full name
let isUserAuthorized = checkAuthorization();
if (isUserAuthorized) {
// Clear and unambiguous
}
Abbreviations and API Design
When designing APIs, clear naming is especially important. APIs are frequently used by other developers, and obscure abbreviations can lead to excessive documentation needs and confusion.
// Bad API design: Using abbreviations
class UsrMgr {
addUsr(usrInf) {
// ...
}
}
// Good API design: Using full names
class UserManager {
addUser(userInformation) {
// ...
}
}
Abbreviations and Test Code
Test code requires particularly clear naming because its purpose is to verify correctness. Obscure abbreviations make tests hard to understand and maintain.
// Bad example: Test code with abbreviations
it('shld val usr inpt', () => {
const rslt = valUsrInpt('test');
xpct(rslt).toBe(true);
});
// Good example: Test code with full names
it('should validate user input', () => {
const result = validateUserInput('test');
expect(result).toBe(true);
});
Abbreviations and Error Messages
Error messages should be as clear as possible to help developers quickly identify issues. Abbreviations make error messages harder to understand.
// Bad example: Error message with abbreviation
throw new Error('Inv usr pwd');
// Good example: Error message with full name
throw new Error('Invalid user password');
Abbreviations and Logging
Log messages also need to be clear because they are often used for troubleshooting. Obscure abbreviations make log analysis difficult.
// Bad example: Log with abbreviation
console.log('Usr login fail: inv cred');
// Good example: Log with full name
console.log('User login failed: invalid credentials');
Abbreviations and Configuration Items
Configuration items are often viewed and modified by developers at different levels, so clear naming is especially important.
// Bad example: Configuration item with abbreviation
const config = {
dbConnStr: '...',
maxConn: 10,
srvTimeout: 5000
};
// Good example: Configuration item with full name
const config = {
databaseConnectionString: '...',
maximumConnections: 10,
serverTimeoutMilliseconds: 5000
};
Abbreviations and Enums
Enum values should be particularly clear because they typically represent fixed sets of options.
// Bad example: Enum with abbreviation
const UserRole = {
ADM: 'Admin',
MGR: 'Manager',
USR: 'User'
};
// Good example: Enum with full name
const UserRole = {
ADMINISTRATOR: 'Administrator',
MANAGER: 'Manager',
USER: 'User'
};
Abbreviations and Type Definitions
When using type systems like TypeScript or Flow, type names should clearly express their purpose.
// Bad example: Type definition with abbreviation
type UsrInf = {
nm: string;
eml: string;
};
// Good example: Type definition with full name
type UserInformation = {
name: string;
email: string;
};
Abbreviations and React Components
React component names should clearly express their functionality and purpose.
// Bad example: Component name with abbreviation
function UsrCard({ usrInf }) {
return <div>{usrInf.nm}</div>;
}
// Good example: Component name with full name
function UserCard({ userInformation }) {
return <div>{userInformation.name}</div>;
}
Abbreviations and CSS Class Names
CSS class names also need to be clear because they affect style maintainability.
/* Bad example: CSS class name with abbreviation */
.usr-prof {
/* ... */
}
/* Good example: CSS class name with full name */
.user-profile {
/* ... */
}
Abbreviations and Performance Optimization
Some may argue that abbreviations reduce file size and improve performance. However, such minor optimizations are negligible in modern web development and can be achieved through build tools without sacrificing code readability.
// Not worth the "optimization"
// Changing "userInformation" to "usrInf" saves 12 characters
// But makes the code harder to understand
// Better to use build tools for minification
Abbreviations and Code Examples
When writing code examples or tutorials, clear naming is especially important because readers need to quickly grasp the code’s intent.
// Bad tutorial example
function calcTot(arr) {
return arr.reduce((a, b) => a + b, 0);
}
// Good tutorial example
function calculateTotal(numbers) {
return numbers.reduce((sum, number) => sum + number, 0);
}
Abbreviations and Open-Source Projects
In open-source projects, clear naming is even more critical because the code will be read and contributed to by developers worldwide. Obscure abbreviations become barriers to contribution.
// Bad practice in open-source projects
function prsMd(mdTxt) {
// ... Markdown parsing logic
}
// Good practice
function parseMarkdown(markdownText) {
// ... clear implementation
}
Abbreviations and Career Development
Writing clear, maintainable code is a hallmark of professional developers. Over-reliance on abbreviations may create an unprofessional impression and hinder career growth.
// Unprofessional code
function updOrdSts(ordId, sts) {
// ... obscure implementation
}
// Professional code
function updateOrderStatus(orderId, status) {
// ... clear implementation
}
Abbreviations and Code Review Tools
Modern code review tools (e.g., GitHub PR) show diffs. Clear naming makes these diffs easier to understand.
// Clear diff
- function validateUserInput(input) {
+ function validateUserInput(input, options) {
// Obscure diff
- function valUsrInpt(inpt) {
+ function valUsrInpt(inpt, opts) {
Abbreviations and Mobile Development
In mobile development, resources may be more limited, but clear naming remains more important than minor savings. Modern mobile devices can easily handle slightly longer variable names.
// Bad practice in Android development
String usrNm = getUserNm();
// Good practice
String userName = getUserName();
Abbreviations and Functional Programming
In functional programming, function names should clearly express their purpose and intent.
// Bad example: Abbreviations in functional programming
const addUsr = usr => users => [...users, usr];
// Good example: Clear naming
const addUserToCollection = user => users => [...users, user];
Abbreviations and Asynchronous Code
Asynchronous code is inherently complex, so clear naming helps clarify the execution flow.
// Bad example: Abbreviations in async code
async function getUsrData(usrId) {
const usr = await fetchUsr(usrId);
const ords = await fetchOrds(usrId);
return { usr, ords };
}
// Good example: Clear naming
async function getUserDataWithOrders(userId) {
const user = await fetchUser(userId);
const orders = await fetchOrders(userId);
return { user, orders };
}
Abbreviations and Regular Expressions
Even for regular expressions, related variable names should clearly express their purpose.
// Bad example: Regex with unclear naming
const p
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn