In the realm of coding, the way we name our elements – be it variables, classes, or functions – serves as the hero behind comprehensible and maintainable code. Imagine it as giving names to chapters in a book; if done right, it guides the reader effortlessly through the storyline.
Why Adopt a Naming Convention?
- Enhanced Code Readability: Proper naming conventions reduce the cognitive load on the reader, making source code easier to understand at a glance.
- Focused Code Reviews: When we standardize naming, code reviews become more efficient, concentrating on core issues rather than getting bogged down by syntax and naming debates.
- Effective Use of Code Quality Tools: With a unified naming approach, code quality tools can hone in on significant matters, steering clear of superficial syntax and style discrepancies.
Though the choice of a naming convention can stir passionate debates (some even equate it to dogma), what’s pivotal is adhering to a convention that resonates with the team’s shared values.
The Significance of Naming
Though seemingly trivial, naming plays a colossal role in coding. Treat naming with respect. When naming Projects, Folders, Files, Class Names, Functions, Variables, or Parameters, choose wisely.
Picture this: you’re working in multiple projects. A year down the line, you or a teammate may need to tweak the code. Wouldn’t it be splendid if the code itself narrated its intent? That’s the power of good naming.
Tips for Good Function/Variable Naming:
- Descriptive Names: The name should clearly convey the purpose or functionality of the function or the role of the variable. calculate_average() is more descriptive than calc().
- Keep It Concise: While descriptiveness is key, brevity also matters. findLargestNumberInArray() might be too long; findMaxInArray() works better.
- Use Standard Conventions: Adhere to the naming conventions of the language you're using. For example: Camel case for Java and JavaScript: calculateTotalAmount() Snake case for Python: calculate_total_amount()
- Avoid Abbreviations: Unless the abbreviation is universally known (like id for identity), it's better to spell out names. calculateAvg() might be clear for you, but calculate_average() is unambiguous.
- Begin Boolean Variables with "is", "has", or "can": This makes the variable's purpose clear. Examples include is_valid, has_access, or can_edit.
- Avoid Meaningless Names: Names like foo, bar, temp1, data2 don't convey any meaningful information.
- Stay Away from Magic Numbers: Instead of hardcoding numbers, use named constants. For instance, instead of if (days > 365), you could use if (days > DAYS_IN_YEAR).
- Scope Matters: For variables with a small scope, shorter names might be acceptable because the context is clear. For instance, using i for loop counters is generally acceptable. But for global or class-level variables, more descriptive names are crucial.
- Avoid Using Type in Names: Names like string_name, list_of_students are discouraged in favor of names that describe the purpose, not the type, like username or students.
- Plural for Collections: If a variable represents a collection of items, use a plural term, e.g., users, products.
- Use Verb-Subject for Functions: Functions usually perform actions, so names like get_total(), save_record(), and delete_user() make their intentions clear.
- Avoid Negative Names: Instead of is_not_empty(), you can use is_empty() and invert the boolean logic where used. This makes for more readable code.
- Consider Domain Terminology: Use terms and abbreviations that are well-known in the problem domain. For instance, in finance, terms like APR, ROI, and EBITDA are acceptable.
- Avoid Name Collisions: Don't name your functions or variables the same as standard library functions or common third-party library functions in your project. This can lead to confusing bugs.
- Consistency Across the Project: If you've named a function retrieve_data() in one module, avoid using fetch_data() in another unless there's a clear distinction in functionality.
Remember, code is read more often than it's written. By putting in the effort to name functions and variables thoughtfully, you make the codebase more accessible and maintainable for everyone who interacts with it.
Code Examples: The Good, The Bad, & The Ugly
def f():
p = 3.14
r = 5
return p * r * r
Explanation: It's unclear what f does. What do p and r represent?
def calculate_circle_area():
PI = 3.14
radius = 5
return PI * radius * radius
Explanation: The function and variables are descriptively named, making the purpose clear.
def upd_rec(u, i, r):
for j in r:
if j['id'] == i:
j['name'] = u
Explanation: The intent of this function and its parameters is shrouded in mystery.
def update_record_name_by_id(username, record_id, records):
for record in records:
if record['id'] == record_id:
record['name'] = username
Explanation: The revised function clarifies its purpose, and the parameter names provide context.
Some other examples
- stuff/
- new_folder/
- data_1/
- docs_for_proj/
- assets/
- user_profiles/
- invoice_data/
- project_documents/
- a.txt
- newdoc1.docx
- img2.jpg
- func_v2.py
- meeting_notes_2023_10_02.txt
- annual_report_2022.docx
- profile_picture_jane_doe.jpg
- calculate_revenue.py
Tips for Good File / Folder Naming:
- Descriptiveness: The name should describe the content or purpose without needing to open it.
- Avoid Spaces: Use underscores (_) or hyphens (-) instead of spaces to avoid potential problems, especially in programming or web contexts.
- Consistency: Be consistent in the naming convention you adopt. If you start with camelCase, stick with it; if you use underscores, continue to use them.
- Timestamps where necessary: For files that get updated regularly, it might be useful to have a date in the filename, e.g., backup_2023_10_02.sql.
- Versioning (if needed): Instead of vague terms like "final" or "v2", consider more descriptive versioning, e.g., report_v1_2_draft.docx.
- Avoid Special Characters: Characters like !, @, #, $, etc., can sometimes cause issues, especially on web servers or programming environments.
Remember, the objective of good naming is clarity and ease of retrieval. If someone else were to look at your folders or files, they should get an immediate sense of the content or purpose.
??Pro Tip: Harness the Power of ChatGPT
Struggling to find the perfect name for a function or variable? Remember, you're not alone! Leverage the power of ChatGPT. Pose your naming challenge, and let this advanced AI guide you toward a more intuitive and descriptive name. It's like having a code-naming guru right at your fingertips, ready to assist when naming conundrums arise.
?? Join Us
Stay tuned with Product Development Playbook where we share insights and knowledge from our journey in product innovation.