I'm looking for some guidance on how to name my variables and functions more effectively. I tend to use very generic names like `get_name()` for a function that actually retrieves usernames based on age, and I often declare variables as `user1` and `user2`. While these names work for me, I realize they can be confusing for others. I'm also guilty of sometimes writing conditionals like `if (age > 60)` instead of something more descriptive like `if (age > max_age)`. I know I should probably write more comments, especially when my code might not be clear to someone else. Any tips on how to make my code more understandable for others?
3 Answers
Be descriptive! Imagine someone else needs to read your code in six months, which spoiler alert, often turns out to be you! Instead of `user1`, use something like `username` to clarify what it holds. Function names should be verbs that clearly indicate their action. So, instead of wishing your functions were named a certain way, just go with what they actually do.
It's important to consider that all code involves at least three people: past, present, and future you. Naming things clearly helps everyone get along. When thinking about constraints, you might want to have the function `get_name` but add options for more specific cases. Just be careful about causing duplication in your code.
When naming things, aim for clarity over brevity. Instead of using `get_name()` for a function, it should be `get_username_by_age()`, which tells exactly what it does. If a name feels too long, that might mean your function is handling too many responsibilities and should be broken down. For your conditionals, using `age > 60` can be clean because it's specific, but it's also beneficial to avoid 'magic numbers.' Using descriptive constants can help clarify what those numbers represent. Also, instead of `user1` and `user2`, think about their roles—for example, `current_user` and `previous_user`. And remember, you'll forget your own logic over time, so it's better to write as if others will read your code!
Absolutely! You'd be surprised how many times I’ve opened my old code and had no idea what I was thinking. Clear naming saves a ton of headaches later.

I totally agree! Naming things based on what they actually do makes a huge difference. And you don’t want to leave future you confused! That’s always the worst.