Encoding specification, objective-C encoding Specification

Source: Internet
Author: User

<C ++ programming specifications 101 rules, guidelines and best practices>

1. Hungary naming and do not blindly use Hungary naming

Naming Conventions are the most important and the most controversial part of the procedural writing norms. They have been a place for military personnel since ancient times. What is the use of naming conventions? Four words: proper name. A good dance shoe is a dance shoe that makes a dancer feel invisible. A bad dance shoe is used to make the dancer dance with handcuffs.

The cost of the Hungarian naming method: the Hungarian method is used to add a type name prefix to the variable name. For example, nfoo, szfoo, pfoo, and cpfoo indicate integer and string variables respectively, pointer variables and constant pointer variables. It can be seen that hunfa copies the type information of a variable from a single location (where the variable is declared) to multiple locations (where the variable is used), which is a redundancy method. One of the costs of redundancy is to maintain copy consistency. This cost is required to change the variable type during code writing and maintenance. The second advantage of the redundancy method is that it occupies additional space. A good writer will consciously follow a rule: the minimum length of the Organization Unit of the Code should be 30 rows or less, and should be reorganized if there are more than 50 lines. The writing space of a variable adds unnecessary difficulty to this rule.

The benefits of the Hungarian naming law are vague and unpredictable.

 

Charles Simonyi (who later became a famous programmer at Microsoft) designed a post-fix-based naming method known as "Hungary notation" to remember him. his idea is to give each identifier a prefix based on its meaning. microsoft later adopted this idea to give each identifier a prefix to describe its data type. therefore, the prefix of the integer variable is N, the long integer variable is NL, the numeric array variable is ca, and the string (character array ending with an empty type) is prefixed with Sz. these names may be odd. for example, lpszfoo indicates that "foo" is a long integer pointer to a string ending with an empty character.

The advantage of this method is that you can identify the type of a variable by its name, instead of looking for its definition. Unfortunately, this method not only bypasses the variable name, but also makes it very difficult to change the variable type. in windows3.1, the integer variable is 16 in width. if we use an integer variable at the beginning, but after using the 30---40 function, we find that the width of the integer variable is not enough. In this case, we should not only change the type of this variable, in addition, you need to change the variable name in the 30--40 functions.

Because it is impractical, no one except some stubborn windows programmers can use "Hungary notation. There is no doubt that it still exists on some occasions, but most people have abandoned it now. Generally, an input prefix is a bad idea because it binds a variable closely with its type.

Http://www.cppblog.com/justin-shi/archive/2008/05/02/48615.html
Http://www.cnitblog.com/ffan/archive/2005/09/21/2815.html
Hungary naming convention table
Http://dev.csdn.net/htmls/34/34000.html


The method of merging type information into variable names is to mix the facilities in unsafe language (especially C) of the type, which can exist in object-oriented language, but is harmful, it is not feasible in generic programming. Therefore, any c ++ programming specification should not require the Hungarian notation, but it is reasonable to disable this notation in the specification.

The compiler knows much more about object types than you do. Changing the name of a variable contains type information, which has limited benefits and makes it more vulnerable. If there are still some reasons for using the Hungarian notation in a C-style language (even if this is controversial), it is harmful to use it in a type-safe language.

If you know the type name, the variable name will be prompted, that is, the variable name itself can reflect its own type. If you add a type identifier, you must modify the variable name in case the type changes. For example, int is changed to long.

It is more useful for programmers to instantly know the scope of a variable than to know its type.

The Hungarian naming method is not suitable for the current object-oriented language.

However, for variables whose types are arrays and dictionaries, it is better to identify the type information at the end of the name. This method can also be used in a very short local scope.

2. About someone blindly recommending "don't define variables in a loop", http://topic.csdn.net/t/20061229/10/5263622.html

Refer to Java: String blog.

Variable declaration does not have much difference between GC and. Regardless of the GC timing and the uncertainty of the collected heap content, the two write methods only create n new heap objects regardless of the Relationship Between Stack reference and heap object, at any time, only one stack references one heap object.

Variables defined in vitro are generated only once. In theory, variables defined in vivo are returned for each cycle. To generate a variable, the system still needs to allocate memory space, so the efficiency is low, but the current compilers are all optimized, and the optimization is the same during compilation. It may be optimized to declare the statement only in the first loop. the compiler will remember this Declaration and the subsequent loop will not be declared.

For example:

For (...)
{
Int I = 5; // It is declared only in the first loop.
}

Think about it. If we assume that every cycle is defined, we can expand this loop.
Int I = 5;
Int I = 5;
......
The display cannot be accepted by the compiler.

In addition, debugging in VC
Void main ()
{
For (INT I = 0; I <5; I ++)
{
Int * num = new int;
}
}
We can find that & num is the same value in each loop, and the 32-bit integer of the pointer itself remains unchanged.
It is a bad habit to declare a variable that is used only in the circulatory body in vitro. This is a typical programming style of the old-fashioned C language, just like abusing global variables in the C language, this will disrupt the definition and semantics of context variables and cause the program to become unreadable. The declaration of non-persistent state variables should be as localized as possible. This is a general principle of modularity and object-oriented thinking.

With the increase in hardware level, clear and easy-to-understand code is better than non-clear, easy-to-understand, but only slightly more efficient code.
In a general sense, "do not define variables in a circular body" is only applicable to the experts who have high psychological requirements for low efficiency.

Automatic survival variable: its memory space is allocated only when the program executes a composite statement that defines them. When the composite statement that defines them ends, the space is reclaimed, local variables and function parameters generally have automatic lifetime.
When a variable is defined in a code block, Java allocates memory space for the variable in the stack. When the scope of the variable is exceeded, java will automatically release the memory space allocated for the variable, and the memory space can be used for another use immediately.
Stack unwinding is called Stack unwinding ). Stack expansion is the core technology of exception handling. As the stack expands, the life cycle of the local variables declared in the exited compound statements and function definitions is also over. Resources occupied by the partial volume allocated in the stack are also released and recycled by the system.

3. Google's c ++ coding specification in English

Http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#File_Names

Google objective-C style guide Chinese Version

Http://www.cocoachina.com/macdev/objc/2011/0328/2740.html

4. iOS coding standard summary

4. 1. format the code

* Location

Bracket alignment

No space is left between the method name and Parameter

When the parameter is too long, each parameter occupies one line and is aligned with a colon. If the method name is shorter than the parameter name, each parameter occupies one line and is Indented by at least four characters, and vertical alignment (rather than colon alignment)

Use a piecewise macro to indicate the function source

4. 2. Name

Class names use uppercase letters to separate words, camel case, and camel commands.
In code for specific applications, class names should avoid prefix. Each class uses the same prefix to affect readability.
Prefix is recommended in multi-application-oriented code, which avoids duplicate names and declares the code source. Example: gtmsendmessage

The method name starts with lowercase letters and uses uppercase letters to separate words. The method parameters use the same rules.
The method name + parameter should be read as much as possible like a sentence (for example :). Here, let's look at Apple's naming rules for methods.
The method name and variable name of getter must be the same. You cannot use the "get" prefix.
This rule is only applicable to objective-C code and C ++ code.

The variable name should use the full name of the application that is easy to understand, and the first letter is lowercase, and the word is separated in the form of an upper letter, refer to Symbian, the parameter starts with.
The member variables use "_" as the prefix (for example, "nsstring * _ varname ;". Although this conflicts with Apple's standard (using "_" as the suffix for tokens), "_" is still used as the prefix for the following reasons. When "_" is used as the prefix, it is easier to distinguish between "property Summary (self. userinfo)" and "member variable (_ userinfo)" in the IDE with Automatic Code complementing function )"

The member variable is the same as the member variable whose prefix "_" is removed. Use @ synthesize to associate the two variables.
Constants (# define, enums, const, etc.) Use lowercase "K" as the prefix, and the first letter is capitalized to separate words. For example, kinvalidhandle

Functions starting with alloc/New/copy/mutablecopy generate only objects, not their owner.

4. Logic

In the initialization method, do not initialize the variable to "0" or "nil", which is redundant. But it must be fully initialized in C ++.
Use # import to introduce Ojbective-C and Ojbective-C ++ header files, and use # include to introduce C and C ++ header files.
Import the root framework (root frameworks) instead of a single file catalog, although sometimes we only need a few header files of the framework (such as cocoa or foundation), but introduce the root file Compilation
It runs faster. Because the root framework (root frameworks) is usually precompiled, loading is faster.
When creating a temporary object, try to remove autorelease in the same line at the same time, instead of using a separate release statement.
Although this will be a little slow, it can prevent memory leakage caused by early return or other unexpected situations. Overall, this is worthwhile. For example:
The order of dealloc should be the same as that of variable declaration, which is conducive to the review code callback. If dealloc calls other methods to release the variable, it will be clearly marked as a comment by the release variable.

The setter of the nsstring attribute uses "copy" and the retain is not allowed to prevent accidental modification of the value of the nsstring variable. For example:
Throwing exceptions)
The NIL check handler only checks nil when there is a business logic requirement, not to prevent the crash
Sending messages to nil does not cause system crash, and objective-C is responsible for processing during runtime.
Be careful when converting int values to bool. Avoid direct comparison with yes
In objective-C, bool is defined as unsigned char, which means that it can be other values except Yes (1) and no (0. Direct int conversion (cast or convert) to bool is prohibited.
The delegate object uses assign, and retain is not allowed. Because retain will cause memory leakage caused by cyclic indexes, and memory leakage of this type cannot be detected by instrument, which is extremely difficult to debug.
The member variable is named _ delegate, and the attribute name is delegate variable.

Do not add too many business logic code to the view-related classes, which makes the code reusable poorly. The Controller is responsible for the business logic code, and the Controller code is irrelevant to the view as much as possible.

If not all callback methods are required, use @ optional to mark

The init method and dealloc method are the most common methods, so they are placed at the beginning of the class implementation.

When a class is extended, the added category is preferred.

5. Standard naming rules

Http://blog.csdn.net/bill1315/article/details/1698202

Naming method:
(1) Camel naming: the first letter is in lowercase, and the first letter of each word is in uppercase. Example: studentname
(2) Pascal naming: the first letter of each word is capitalized. Example: studentname
(3) Hungarian naming method: prefix. Such as btnname and txtname.

6. Key points for processing network request objects:

Reference request handle,

After the request ends, request = nil,

Request. Delegate = nil; [request cancel]; Request = nil;

7. Defensive Programming requires the use of nsassert statements to ensure the occurrence of some essential errors. For example, the parameters are correct classes.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.