- Learning C# by Developing Games with Unity 2020
- Harrison Ferrone
- 329字
- 2021-06-11 18:44:49
Naming variables
Picking names for your variables might seem like an afterthought in light of everything we've learned about access modifiers and types, but it shouldn't be a trivial choice. Clear and consistent naming conventions in your code will not only make it more readable but will also ensure that other developers on your team understand your intentions without having to ask.
Best practices
The first rule when it comes to naming a variable is that the name you give it should be meaningful; the second rule is that you use camel case. Let's take a common example from games and declare a variable to store a player's health:
public int health = 100;
If you find yourself declaring a variable like this, alarm bells should be going off in your head. Whose health? Is it storing the maximum or minimum value? What other code will be affected when this value changes? These are all questions that should be easily answered by a meaningful variable name; you don't want to find yourself confused by your code in a week or a month.
With that said, let's try to make this a bit better using a camel case name:
public int maxHealth = 100;
Remember, camel casing starts the variable's name with a lowercase letter, then capitalizes the first letter in each word thereafter. It also makes a clear distinction between variable and class names, which start with an uppercase letter.
That's much better. With a little thought, we've updated the variable name with meaning and context. Since there is no technical limit in terms of how long a variable name can be, you might find yourself going overboard and writing out ridiculously descriptive names, which will give you problems just as much as a short, non-descriptive name would.
As a general rule, make a variable name as descriptive as it needs to be – no more, no less. Find your style and stick to it.
- PHP程序設計(慕課版)
- Vue.js 2 and Bootstrap 4 Web Development
- Developing Middleware in Java EE 8
- Visual Basic程序設計與應用實踐教程
- Amazon S3 Cookbook
- 可解釋機器學習:模型、方法與實踐
- UI設計全書(全彩)
- Spring 5 Design Patterns
- Flink技術內(nèi)幕:架構(gòu)設計與實現(xiàn)原理
- Practical Maya Programming with Python
- 深入理解Kafka:核心設計與實踐原理
- Python計算機視覺與深度學習實戰(zhàn)
- HTML5 Game Development by Example:Beginner's Guide(Second Edition)
- Neo4j權(quán)威指南 (圖數(shù)據(jù)庫技術叢書)
- Elasticsearch實戰(zhàn)(第2版)