Unity game framework: Named forces - Variable

Getting started naming variables

First to try to understand this code:

var todoList = new TodoList();
todoList.Todos = new List<Todo>();

var todo = new Todo() { Id = 0, Finished = false, Content = "测试" };

todoList.Todos.Add(todo)

todo.Finished = true;

The code itself is very simple, do not even look at TodoList Todo class and class definitions, but also can read the code above.

Well, this is how to do it?

The answer is: be suitable name.

To achieve the effect of the code above is mainly named variables.

Because of the above classes are emerging Model class, while Model is used to describe what the business is, and the Model class most of the code is variable.
For example, this is a TodoList App (to-do), where:

  • There do list
  • There do list to-do list
  • To-do can be done and not done.
  • Do list can edit the text.

The above points are generally we received and understood the task to sort it out after business. If the code is designed as a structure, the structure is as follows:

  • To Do List
    • To Do
      • Successful /
      • text

Naturally Model of code written, the code is as follows.

TodoList.cs

public class TodoList
{
	public List<Todo> Todos;
}

Todo.cs

public class Todo
{
	public int Id;

	public bool Finished;

	public string Content;

}

To make it easier to understand the above category in other documents, the author name on what had been done it?

TodoList class Todos variables:

  • Todos complex is described which may be an array type, List or other collection.
  • Todos capitalized, indicating the type of access is public.
  • Todos name itself is a noun, it is interpreted as Chinese: things to do (to-do), itself accurately convey the meaning of variables.

Todo Deliverable

  • Id, and Todos like to convey the access rights, and meaning (identity), but does not convey its type. However, whether it is int or string does not matter.
  • Finished, it is the same, public authority, meaning (completed). Also did not convey its type, but here it can be understood, Finish is a verb, plus ed is the past tense, and sometimes state illustrate the state, which has only two, and the completion of unfinished, so is the bool type, which is the author a habit, of course, can also be named as IsFinish, and so on.
  • Content, Chinese meaning is the content, the content is text, usually string type, since the first letter capitalized, it is also a public authority.

A few simple lines of code, you can convey so much information, so the name is an art .

summary

In the time of a variable name, nothing more than to think about the following three points:

  • description
  • Competence
  • Types of

Authority and type of expression is easy, because the methodology in this regard (routine) is fixed and can easily grasp.

Comparison of test foundation is to describe variables that need long-term training.

Description, permissions, type

Next to these three main, were introduced methodology.

To start with the simplest, easiest is the authority expressed

Competence

Authority refers to the access, there are public, private, protected, internal types in C #.

During two types of variable name here.

  • External and internal public can access.
  • And private and protected can not be accessed outside.

Express permission of the author's own habits, it can be accessed using variable external capitalized.

such as:

public string Name;
internal static int ReferenceCount;

And the variable is not accessed using external prefix m.

such as:

private string mShowedText;
protected int mMgrId;

This is a long-term habit of the author, it is also the author of QFramework maintain their own naming conventions.

Therefore, the expression of competence is very simple, relying on code specification will be able to get, given how norms on how to use.

This is by far the most easy to achieve.

If you have not started naming care about this matter, from the beginning to get started authority is easiest.

Types of

Variables are typed, it is the best type that can be expressed.

Type of expression, of course, also be some code in accordance with the specification solved.

Hungarian specification code such as:

private int m_nAge;   // n 代表数量
private string m_strName // str 代表 string

However, this specification requires a period of adaptation, where the author is not recommended for newbies to solve the problem with this type of expression norms.

Instead of using a relatively simple, elegant way to express the type of the variable.

such as:

public int Age;

Age of age, it is easy to think of type int.

public string Name;

Name name is very easy to think of type string.

public int PetCount;
public int PetNumber;

The number of pets, it is easy to think of type int.

public bool Completed;

Completed completed, it is bool type.

The details of this part will be introduced in the next section of a detail.

description

Content description of variables is more and more, but the principle is very simple, two words: accurate.

When the variable name the most important consideration is that the name should fully and accurately describe the things that variable represents. - "Code Complete"

How to achieve accurate? This section will also introduce a next section.

In this section, we give a simple classification of the type of word variables used:

  • thing
    • string
      • Name
      • NickName
    • int
      • Age
      • XXXCount
      • Times
  • status
    • Past tense
      • Finished
    • When carried out
      • Waiting
    • Some deprecated (IsXXX):
      • IsFinished
      • IsFinish
      • IsWaiting
    • adjective
      • active
  • other
    • C # unique to the commission, events.
      • OnXXXFinished
      • OnBeforeDestroy
      • OnLoadDone
      • OnLoadStart

So after a detailed description about the expression of the variable portion will be described in accordance with these three points.

summary

Readers read here, the expression of authority is the most easy to do, if not aware of children's shoes, you can begin to express rights at work trained.

Express permission of a variable name is more suitable as the first step of training.

Part of the contents of competence on this end, and will not go below.

The rest of the type described and is described in detail with two large sections.

Let's get the type of expression is relatively easy, so that so that we can learn and quick to practice in their work.

Type of expression

About collections (List, Array, Dictionary and so on)

List, Array can be used to get a plural noun.

such as:

var todos = new List<Todo>();
var todos = new Todo[]{};

Collection type may also be expressed as a suffix

var todoList = new List<Todo>();
var todoArray = new List<Todo>();

Dictionary

Because it is a collection of key-value type, you can use xxx4yyy are named (4 = for), this is my personal habits, not mandatory.

var todo4Id = new Dictionary<string,Todo>();

You can also use type as a suffix.

var todoDict = new Dictionary<string,Todo>();

However, the type of key-value type used as a suffix expression less effective, it is recommended xxx4yyy manner.

Other collection types, such as Queue, Stack et al., Also be employed type of a suffix.

var panelStack = new Stack<UIPanel>();
var msgQueue = new Queue<Msg>();

Stack Queue and technical concept, it is generally used in the frame / plug / tool level, less frequently used in the business layer.

Collection type section described here.

Value / data type, string / char, etc. (something)

Value type (int / flout / double):

Int type common suffixes (qualifiers):

Number

var todoNumber = todos.Length;

Index

var todoIndex = todos.IndexOf(todo);

Count

var todoCount = todos.Count;

Common int type prefix words:

on one

var numTodos = todos.Length;  // number of todos 缩写,不太常用。

Common float / double type suffixes
Average, Sum and so on.

var ageAverage = ageSum / peopleCount;

This type of suffixes and prefixes word often used in the calculation.

It referred to herein is calculated qualifiers.
The following lists the calculation used to determine qualifiers:

Count、Number、Num、Index、Total、Sum、Average、Max、Min、Record 等。

"Code Complete" recommendations, in addition to all the other recommendations put Num suffix

There are some numeric type name itself expresses its type.

age(int)、times(int) 等。

Data type (string / char):

Data Types nothing to say, try to select the name itself can only express the name of its type, and content considered this part of the expression described in the section, where the first part of the list:

username(string)、password(string)、name(string)、content(string)、title(string)、description(string)、id(int/string) 等。

bool, enum (state)

bool type:

  • + Verb tenses.
    • done
    • finished
    • completed
    • updating
    • enabled
  • Use Is + noun.
    • isEnemy
  • adjective
    • active

Principle to bool type name is very simple, as long as their status is like only two.
For example GameObject either an active state (active is true), or to the active state (active is false). This is in line with a good bool variable names, there can be a third state.

As another example, a task either complete (finished as true), or is not completed (finished to false).

enumerate

Enumeration part to speak in two parts, one is the definition part, a variable part.
Enum definition:

// 事件
public enum UIMainPanelEvent
{
	// 事件监听
	OnModelDataChanged,
	
	// 指令 (动宾短语、动词)
	UpdateView
}

// 状态 (与 bool 类型一样)
public enum ResLoadState
{
	LoadBegan,
	Loading,
	LoadEnded,
}

// 结果 (名词、形容词)
public enum ResLoadResult
{
	Success,
	Fail,
}

Bool type definition part and like, such manner is ModelDataChanged + verb tenses.

Unity-specific GameObject, Transform, Button, Image, etc.

GameObject heroObj;
GameObject heroGameObj;
Transform  heroTrans;
Button btnEnterMainPanel;
Image logoImage;

The above is a common prefix and suffix.

About the expression of the type described on here.

summary

Here we have the type of expression for a detailed description.
Methodology of the type of expression of the author also introduce all over, you can practice whichever is the author's methodology, called for continuous improvement of their thinking based on this methodology.

What thinking?
How to think for others (or themselves) use variables in other file types will be able to guess that it?
So not the point the author describes the methodology nor the authority, the focus is constantly thinking.

Described expression

And finally to the main event.
The expression describes a developer can test foundation work.

For variables Model class name.

  • To have a good description, we must be very understanding of the business.
  • Because only very familiar with the business, to find a very accurate description.

Chat is like the beginning of this entry as:

  • Business should at least be carded once, carded they can understand.
  • After combing once again conduct a structured sort out, so more improvement into code.
  • After combing in order to define the structure of the Model class and its variables.

Members of the above requirements will be relatively high, so I recommend here, we mastered the practice after making authority and type of expression described.

Prior to this, the Chat just introduced the Model variable naming.
This is because the variable definition Model is relatively easy. But our work is not only the definition of Model, there are a lot of other classes we need to define, and define how much class to define some variables. Chat and this can not cover all the variable naming scenarios, it will give some guidelines and practice steps for your reference.

Exercise Step one: all the code section in English.

In Unity few adjustments need to display variable parameters provided in the editor can use some Chinese characters. While the remaining and preferably all in English.
Here is best when encoding readily prepared with a word search software, you can quickly query by keyboard shortcuts. To develop this habit. To the best found in a certain field or some kind of business terms commonly used on those, himself remember, when using a search word rarely re-encoding software.

Exercise Step two: business name rather than technical name

The title is the author's own understanding, "Code Complete" is a description of variable names should describe the what, not how. That is, what variables are and not how to do it.
Because the concept is realistic business simulation, and technical concept is only a means. So I understood as a name for the business rather than technical name.

To understand this very simple guidelines. Excerpt "Code Complete" passage for everyone to understand:

Usually issue a catchy name reflects, not the solution. A good name is usually expressed as "what" (what), rather than "how" (how). In general, if a name reflects certain aspects of computing rather than the problem itself, then it reflects is "how" rather than the "what" of. Avoid selecting this name, which should reflect the problem itself in the name.

An employee data record may be referred inputRecord or employeeData. inputRecord is a reflection of input, the computer calculates the term of these concepts record. employeeData it refers to the problem areas, regardless of the computing world. Similarly, for bit field for indicating a state for printing, bitFlag more than, printerReady computer features. In the financial software inside, calculateValue calculation marks (how) also significantly better than sum (what).

Original book explained very clearly, and say no more.

Exercise Step three: make it clear when to use the technical name

Here to say a little attention, to make it clear at what level. As an author frame SerializeHelper (serializer), serialization technology concept, is "how?" (How), but it can do to store game data and other operations. So why is it not called the DataSaver / DataLoader these names?

This is because SerializeHelper this class is not in the business layer, but in the framework layer. Framework itself provides more of a tool.

summary

Exercise gives 1,2,3 steps, very easy to use, it named itself is relatively easy to grasp, very rare beginners do not care. Generally veteran trip pit lay more naturally realized. The beginner then go to look at these pits a waste of time, as a start to realize the importance of this matter on the name.

This does, permissions, type, practice steps and principles (criteria) described gave. Next simple chat, why naming and how to more easily implement naming it to work it?

Why name?

The nature of the information code, which carries the information, this information may be appreciated that the compiler should be understood.

First of all you, the code is to be understood by the compiler, which is a basic requirement, but also represents developers and computer can communicate, let the computer to help deal with the task.

Secondly, it is to be understood.

These people may be:

  • Own (daily)
    • With their daily life is the longest code, if the code is very clean and easy to read, every day working condition will be different.
    • In debug time, or to read the code, good code is easier to read, the time it takes to read easily debug will be reduced.
    • Increased functionality, it is still the same need to read the code, more than empathy.
    • Make yourself more profound understanding of the project, clearly.
  • Colleagues (collaboration)
    • The same code is easy to read, also improved the efficiency of my colleagues, my colleagues will be recognized,
  • leader (promotion)
    • Many teams have the code review culture, good code more easily recognized by superiors and colleagues.
    • Recognized by colleagues and superiors, promotion is a very natural thing.
  • To people (departure) took over the project
    • Departure time will be saved and will not be dragged asked what it what it is.
  • All developers (open source)
    • Very many people save time, time is life.
  • Readers (teaching, they are readers of the chat is this range)

The final benefit most or their own, and put each variable more than just spend a few seconds thinking time only.

In short term there is a collaboration co-word, can be understood as a compromise association can also be understood as the assistance of the Association.

To the variable named both a suitable compromise is also a help.

This is why I opened a single to write a chat we think that such a simple thing.

How landing variable named

Write Once this section is hope that we not only read this chat to get away, but naming this matter should implement variable output up to their own code.

A habit at work have a lot of obstruction.
The most common reason is that tight project time.

This problem solved, as long as the training time is adjusted according to the actual situation just fine.

For beginners or very urgent project developers, when writing the first pass logic, variables can be easily first name (according to their own habits), but as long as the current test point or verified by function point is complete, you should go back to variable names under good think, rename. General IDE have brought reconstruction function, as long as the change in one place, along with all the other code section will change.

The aim is to prevent the same time to do two things.

  • Write logic
  • Variable naming

Named for the novice, the same time to do two things will be very difficult.
Write logic itself is very difficult, and the variables need to think together with the name, will be more difficult.
So for the novice named the same time requires only thinking one thing.

Time is very urgent for developers, if the schedule will affect the thinking of naming projects, or projects that are not urgent enough time to re-implement.

As long as can do, during the time of writing logic, only consider how to do or how to achieve just fine.
When naming variables, only focus on how to take a proper name, only consider the variable description, type, permissions like.
as follows:

  • Whether the variable naming an accurate description?
  • Named for the tag is a type of expression?
  • Named variables indicate whether the rights?

After so over time, be able to do the same time you can do two things.

Just remember that beginners enough:

  • When you can not create a variable named suitable complete.

But the ultimate goal is to be an appropriate name this matter habit, while creating variable has taken a very appropriate name for the variable.

Finally, thank you very much QFramework the edge of the sea predecessors of this column errata and some very valuable advice to offer.

more content

Guess you like

Origin www.cnblogs.com/liangxiegame/p/12591418.html