Sei sulla pagina 1di 9

Высшая Школа Программирования

Правила программирования на C#

Programming in C#
Rules and Recommendations

Этот документ представляет собственность Высшей Школы Программирования. Все права защищены  2002.
Высшая Школа Программирования Правила программирования на C#

INTRODUCTION................................................................................................................4
CODE STYLE......................................................................................................................4
NAMING...............................................................................................................................4
THE NAMES OF CLASSES SHOULD BE DESCRIPTIVE NOUNS OR NOUN PHRASES IN MIXED CASE WITH THE FIRST LETTER OF EACH WORD
CAPITALIZED....................................................................................................................................................................4
THE NAMES OF INTERFACES SHOULD BEGIN WITH I.
ICONTROL
ITEXTBOX....................................................................................................................................................................4
METHOD NAMES SHOULD BE VERBS OR VERB PHRASES, IN MIXED CASE, WITH THE FIRST LETTER UPPERCASE AND THE FIRST LETTER
OF ANY SUBSEQUENT WORDS CAPITALIZED............................................................................................................................4
NAMES OF FIELDS SHOULD BE IN MIXED CASE WITH A LOWERCASE FIRST LETTER AND THE FIRST LETTERS OF SUBSEQUENT WORDS
CAPITALIZED. FIELDS SHOULD HAVE NAMES THAT ARE NOUNS, NOUN PHRASES, OR ABBREVIATIONS FOR NOUNS................................4
PROPERTY NAMES SHOULD BE NOUN WITH THE FIRST LETTER UPPERCASE..................................................................................4
AVOID LOCAL VARIABLE OR PARAMETER NAMES THAT CONSIST OF ONLY TWO OR THREE UPPERCASE LETTERS.................................4
USE UPPERCASE LETTER FOR CONSTANT NAMES....................................................................................................................4
VARIBLES NAMES ASSIGNMENT:........................................................................................................................................5
FOR LOCAL TEMPORARY VARIABLES MAY BE USED ONE-CHARACTER NAMES:............................................................................5
COMMENTS........................................................................................................................6
USE THE XML DOCUMENTATION FEATURE.
FOR MORE INFORMATION, SEE:
MS-HELP://MS.VSCC/MS.MSDNVS/CSREF/HTML/VCORIXMLDOCUMENTATION.HTM.........................................................6
FILES, WHICH ARE CHECKED IN VERSION CONTROL SYSTEM MUST BE ACCOMPANIED BY COMMENTS OF CHANGES THAT WERE MADE
(HISTORY SECTION)..........................................................................................................................................................6
AT THE BEGINNING OF EVERY ROUTINE, IT IS HELPFUL TO PROVIDE STANDARD, BOILERPLATE COMMENTS, INDICATING THE ROUTINE'S
PURPOSE, ASSUMPTIONS, AND LIMITATIONS.
A BOILERPLATE COMMENT SHOULD BE A BRIEF INTRODUCTION THAT EXPLAINS WHY IT EXISTS AND WHAT IT CAN DO........................6
AVOID CLUTTER COMMENTS, SUCH AS AN ENTIRE LINE OF ASTERISKS.
INSTEAD, USE WHITE SPACE TO SEPARATE COMMENTS FROM CODE............................................................................................6
AVOID SURROUNDING A BLOCK COMMENT WITH A TYPOGRAPHICAL FRAME.
IT MAY LOOK ATTRACTIVE, BUT IT IS DIFFICULT TO MAINTAIN..................................................................................................6
AVOID SUPERFLUOUS OR INAPPROPRIATE COMMENTS, SUCH AS HUMOROUS SIDEBAR REMARKS.....................................................6
COMMENT ANYTHING THAT IS NOT READILY OBVIOUS IN THE CODE..........................................................................................6
SEPARATE COMMENTS FROM COMMENT DELIMITERS WITH WHITE SPACE.
DOING SO WILL MAKE COMMENTS OBVIOUS AND EASY TO LOCATE WHEN VIEWED WITHOUT COLOR CLUES......................................6
IF YOU NEED COMMENTS TO EXPLAIN A COMPLEX SECTION OF CODE, EXAMINE THE CODE TO DETERMINE IF YOU SHOULD REWRITE IT.
IF AT ALL POSSIBLE, DO NOT DOCUMENT BAD CODE — REWRITE IT. ALTHOUGH PERFORMANCE SHOULD NOT TYPICALLY BE SACRIFICED
TO MAKE THE CODE SIMPLER FOR HUMAN CONSUMPTION, A BALANCE MUST BE MAINTAINED BETWEEN PERFORMANCE AND
MAINTAINABILITY.............................................................................................................................................................6
USE COMPLETE SENTENCES WHEN WRITING COMMENTS.
COMMENTS SHOULD CLARIFY THE CODE, NOT ADD AMBIGUITY................................................................................................6
THE CODE THAT IS LEFT UNFINISHED MUST BE DOCUMENTED WITH AN INTRODUCTORY ‘!!!’. NEVER USE ‘!!!’ IN OTHER PLACES......6
PRIMARILY USE STRATEGIC COMMENTS, UNLESS TRYING TO EXPLAIN VERY COMPLICATED CODE....................................................6
DECLARATIONS................................................................................................................6
ALL VARIABLES, METHODS, CLASSES AND CONSTANTS SHOULD BE DEFINED IN THE LEAST POSSIBLE SCOPE.....................................6
MODIFIERS SHOULD ENFORCE THE STRICTEST POSSIBLE ACCESS TYPE.......................................................................................7
DON’T DECLARE VARIABLES OF DIFFERENT TYPES IN ONE LINE OF CODE...................................................................................7
MISCELLANEOUS.............................................................................................................7
ESTABLISH A STANDARD SIZE FOR AN INDENT, SUCH AS 4 SPACES, AND USE IT CONSISTENTLY. ALIGN SECTIONS OF CODE USING THE
PRESCRIBED INDENTATION..................................................................................................................................................7
ESTABLISH A MAXIMUM LINE LENGTH FOR COMMENTS (80 SYMBOLS) AND CODE TO AVOID HAVING TO SCROLL THE SOURCE CODE
EDITOR AND TO ALLOW FOR CLEAN HARD-COPY PRESENTATION...............................................................................................7

03/06/09 Page 2

Этот документ представляет собственность Высшей Школы Программирования. Все права защищены  2002.
Высшая Школа Программирования Правила программирования на C#

USE WHITE SPACE TO PROVIDE ORGANIZATIONAL CLUES TO SOURCE CODE. DOING SO CREATES "PARAGRAPHS" OF CODE, WHICH AID
THE READER IN COMPREHENDING THE LOGICAL SEGMENTING OF THE SOFTWARE. ........................................................................7
WHEN A LINE IS BROKEN ACROSS SEVERAL LINES, MAKE IT OBVIOUS THAT IT IS INCOMPLETE WITHOUT THE FOLLOWING LINE BY
PLACING THE CONCATENATION OPERATOR AT THE END OF EACH LINE INSTEAD OF AT THE BEGINNING..............................................7
AVOID METHODS, WHICH CONTAINS MORE THAN 80 ROWS. ...................................................................................................7
DO NOT USE SPACES BETWEEN THE FOLLOWING OPERATORS AND OPERANDS, AND THEIR EXPRESSIONS:..........................................7
ALWAYS PLACE SPACES BETWEEN OPERANDS AND EXPRESSIONS OF THE FOLLOWING OPERATORS:..................................................7
NEVER PLACE SPACES BETWEEN A METHOD NAME AND ITS OPENING PARENTHESIS......................................................................8
NEVER PLACE SPACES BETWEEN THE LEADING AND CLOSING PARENTHESES (), SQUARE BRACKETS [], ANGLE BRACKETS <> AND THEIR
ENCLOSED STATEMENT(S)..................................................................................................................................................8
NEVER PLACE A SPACE BETWEEN A STATEMENT AND ITS CLOSING SEMICOLON(;) OR COMMA(,)...................................................8
DO NOT PLACE TWO DIFFERENT STATEMENTS ENDING BY SEMICOLON (;) ON THE SAME LINE UNLESS IT IS AN EXPRESSION OF A FLOW
CONTROL PRIMITIVE..........................................................................................................................................................9
IF STATEMENTS ARE WRITTEN ON THE SAME LINE, THEY MUST BE SEPARATED BY SPACES.............................................................9

03/06/09 Page 3

Этот документ представляет собственность Высшей Школы Программирования. Все права защищены  2002.
Высшая Школа Программирования Правила программирования на C#

Introduction
The document contains additional rules and recommendations that supplement the requirements
provided under the C# Coding Techniques MSDN article. Basing on the C# Coding Techniques
these additions help to improve source code quality and readability and help to avoid some
common programmer‘s mistakes and faults.

Code style
Naming
The names of classes should be descriptive nouns or noun phrases in mixed case with the
first letter of each word capitalized.
ClassLoader
SecurityManager
Thread
Dictionary
BufferedInputStream
The names of interfaces should begin with I.
IControl
ITextBox
Method names should be verbs or verb phrases, in mixed case, with the first letter uppercase
and the first letter of any subsequent words capitalized.
Use the verb-noun method for naming routines that perform some operation on a given object, such as
CalculateInvoiceTotal().
A name of the method should tell "what" rather than "how." By avoiding names that expose the underlying
implementation, which can change, you preserve a layer of abstraction that simplifies the complexity. For
example, you could use GetNextStudent() instead of GetNextArrayElement().
Include a description of the value being returned, such as GetCurrentWindowName().
Names of fields should be in mixed case with a lowercase first letter and the first letters of
subsequent words capitalized. Fields should have names that are nouns, noun phrases,
or abbreviations for nouns.
Examples: buf, pos, count, bytesReceived, userName.
Property names should be noun with the first letter uppercase.
In object-oriented languages, it is redundant to include class names in the name of class properties, such as
Book.BookTitle. Instead, use Book.Title.
Avoid local variable or parameter names that consist of only two or three uppercase letters
These names should be avoided to avoid potential conflicts with the
initial country codes and domain names that are the first component of
unique package names.

Use uppercase letter for constant names.


The names of constants in interfaces and final variables in classes should be a sequence of one or more
words, acronyms or abbreviations, all uppercase, with components separated by underscore "_" characters.

03/06/09 Page 4

Этот документ представляет собственность Высшей Школы Программирования. Все права защищены  2002.
Высшая Школа Программирования Правила программирования на C#

private const int VECTOR_CAPACITY = 20;


Varibles names assignment:
Use complementary pairs in variable names, such as min/max, begin/end, and open/close.
Boolean variable names should contain Is which implies Yes/No or True/False values, such as
fileIsFound.
For local temporary variables may be used one-character names:
Name Type
b Byte
c Char
d Double
f Float
i,j,k Int
l Long
o Object
x, y int (coordinates)
e, ex Exception
s, str String
v Some type

03/06/09 Page 5

Этот документ представляет собственность Высшей Школы Программирования. Все права защищены  2002.
Высшая Школа Программирования Правила программирования на C#

Comments
Use the XML Documentation feature.
For more information, see:
ms-help://MS.VSCC/MS.MSDNVS/csref/html/vcoriXMLDocumentation.htm.
Files, which are checked in version control system must be accompanied by comments of
changes that were made (History section).
At the beginning of every routine, it is helpful to provide standard, boilerplate comments,
indicating the routine's purpose, assumptions, and limitations.
A boilerplate comment should be a brief introduction that explains why it exists and what it can do.
Avoid clutter comments, such as an entire line of asterisks.
Instead, use white space to separate comments from code.
Avoid surrounding a block comment with a typographical frame.
It may look attractive, but it is difficult to maintain.
Avoid superfluous or inappropriate comments, such as humorous sidebar remarks.
Comment anything that is not readily obvious in the code.
Separate comments from comment delimiters with white space.
Doing so will make comments obvious and easy to locate when viewed without color clues.
If you need comments to explain a complex section of code, examine the code to determine if
you should rewrite it.
If at all possible, do not document bad code — rewrite it. Although performance should not typically be
sacrificed to make the code simpler for human consumption, a balance must be maintained between
performance and maintainability.
Use complete sentences when writing comments.
Comments should clarify the code, not add ambiguity.
The code that is left unfinished must be documented with an introductory ‘!!!’. Never use ‘!!!’
in other places.
It is helpful to use consistent styles of documenting unfinished code in order to be able quickly find all such
places. We recommend using ‘!!!’ because it attracts attention.
Primarily use strategic comments, unless trying to explain very complicated code.
Comments are often said to be either strategic or tactical. A strategic comment describes what a section of
code is intended to do, and is placed before this code. A tactical comment describes what a single line of
code is intended to do, and is placed, if possible, at the end of this line. Unfortunately, too many tactical
comments can make code unreadable. For this reason, it is recommended to primarily use strategic
comments, unless trying to explain very complicated code.

// The next two lines are strategic comments.


// This loop does some complicated things. It works like this:
// blah-blah-blah...
int i = 0;
for (;;)
{
int index = i++ + ++i * i-- - --i; // a tactical comment
}

Declarations
All variables, methods, classes and constants should be defined in the least possible scope.
// Do not do this!

03/06/09 Page 6

Этот документ представляет собственность Высшей Школы Программирования. Все права защищены  2002.
Высшая Школа Программирования Правила программирования на C#

// int i;
// ... 1000 lines of code
// i = 10;

int i = 10; // Better


Modifiers should enforce the strictest possible access type.
Don't make any methods or class variable “public” without good reason. Always if it’s possible you must use
“private” modifier. Otherwise you must use “protected” modifier and only then use “public” modifier.
Don’t declare variables of different types in one line of code.
int a, []b; //not allowed

Miscellaneous
Establish a standard size for an indent, such as 4 spaces, and use it consistently. Align
sections of code using the prescribed indentation.
Establish a maximum line length for comments (80 symbols) and code to avoid having to
scroll the source code editor and to allow for clean hard-copy presentation.
Use white space to provide organizational clues to source code. Doing so creates
"paragraphs" of code, which aid the reader in comprehending the logical segmenting of
the software.
When a line is broken across several lines, make it obvious that it is incomplete without the
following line by placing the concatenation operator at the end of each line instead of at
the beginning.
Avoid methods, which contains more than 80 rows.
Exception: long “case” statement or long “if” statement.
Do not use spaces between the following operators and operands, and their expressions:
• array element operator []
arr [i] = 1; //bad
arr[i] = 1; //good
• postfix and prefix increment and decrement operators ++, --
int i = 0;
i ++; //bad
i++; //good
• logical-NOT operator !
boolean b = true;
b = ! b; //bad
b = !b; //good
Always place spaces between operands and expressions of the following operators:
• multiplication operator *
int i = 1*2; //bad
int i = 1 * 2; //good
• division operator /
double d = 1/12; //bad
double d = 1 / 12; //good
• modulus operator %
int k = 4%3; //bad
int k = 4 % 3; //good
• addition operator +

03/06/09 Page 7

Этот документ представляет собственность Высшей Школы Программирования. Все права защищены  2002.
Высшая Школа Программирования Правила программирования на C#

int k = 1+2; //bad


int k = 1 + 2; //good
• subtraction operator –
int k = 1-2; //bad
int k = 1 – 2; //good
• bitwise left shift and right shift operators <<, >>
int k = 1<<2; //bad
int k = 1 << 2; //good
• relational and equality operators <, <=, >, >=, ==, !=
boolean b = 1<2; //bad
boolean b = 1 < 2; //good
• bitwise-AND operator &
• bitwise-exclusive-OR operator ^
• bitwise-inclusive-OR operator |
int a = 1;
int b = 2;
int c = 3;
int d = 4;
a = a&b^c|d; //bad
a = a & b ^ c | d; //good
• logical-AND operator &&
• logical-OR operator ||
boolean b = true;
boolean d = false;
boolean c = true;
b = b&&d||c; //bad
b = b && d || c; //good
• assignment operators =, +=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=
int k=3; //bad
int k = 3; //good
k+=1; //bad
k += 1; //good
• conditional operator ?:
x = x>=0?x:-x; //bad
x = (x >= 0) ? x : -x; //good
Casts should be followed by a blank space.
myMethod((byte) aNum, (Object) x);
myMethod((int) (cp + 5), ((int) (i + 3)) + 1);

Never place spaces between a method name and its opening parenthesis.
public void someFunction (int a); //bad
public void someFunction(int a); //good
Never place spaces between the leading and closing parentheses (), square brackets [],
angle brackets <> and their enclosed statement(s).
someFunction( 2 ); //bad
someFunction(2); //good
arr[ 0 ]; //bad
arr[0]; //good
Never place a space between a statement and its closing semicolon(;) or comma(,).
int i = 2 ; //bad
int i = 2; //good

03/06/09 Page 8

Этот документ представляет собственность Высшей Школы Программирования. Все права защищены  2002.
Высшая Школа Программирования Правила программирования на C#

Do not place two different statements ending by semicolon (;) on the same line unless it is an
expression of a flow control primitive.
k = 3; z = 4; //bad, should be:
k = 3;
z = 4;
If statements are written on the same line, they must be separated by spaces.

03/06/09 Page 9

Этот документ представляет собственность Высшей Школы Программирования. Все права защищены  2002.

Potrebbero piacerti anche