Klimatur Coding Style

advertisement
Klimatur Coding Style, rev. 1.0
2011
Revision 1.0
Klimatur
[ Coding Guidelines
]
Rules for registration of software code and general guidelines for coding in C #
Klimatur Confidential
10 March 2011
Klimatur Coding Style, rev. 1.0
INTRODUCTION
The basis of this document on the rules of registration of the source code lie corresponding document
command RSDN, which in turn was developed based on the latest coding standards and documentation.
The rules described in this document are fairly simple and do not cause problems when using.
The rules described in this document are binding on all projects ongoing within the company. Examples
in this document are given in the language C #, and generally all agreements primarily focused on the
development, ongoing using C #, but these rules apply to other language (of course, taking into account
their specificity).
LIST OF TERMS
In Russian, there are some discrepancies in the name of some parts of the program. To avoid confusion
in this section are common terms, their English counterparts, and a brief explanation.



operator - operator (eg +, -, *,!)
statement - statement (for example, «a = b;», «if (a) {}»)
expression - an expression (eg, «a - b + c», «a == 1")
Identifiers
Styles of capitalization
Pascal - an indication of the style of the identifier indicates that the first letter capitalized and all
subsequent first letters of words are also capitalized. For example, BackColor, LastModified, DateTime.
Camel - an indication of the style indicates that the first letter lowercase, and the rest of the first
letters of words capitalized. For example, borderColor, accessTime, templateName.
General rules
1. Remember! Code more readable than written, so do not skimp on the clarity and purity of the code
for speed dialing.
2. Do not use obscure prefixes or suffixes (eg Hungarian notation), modern languages and development
tools allow you to control the types of data during the design and assembly.
3. Do not use underscores to separate words in identifiers, it lengthens the IDs and difficult to read.
Instead, use the style of naming Camel or Pascal.
4. Try not to use abbreviations once again, remember those who read the code.
5. Try to keep the names of identifiers as short as possible (but not at the expense of readability).
Remember that modern languages let you create the name of the namespaces and types. The main
thing is to understand the meaning of the ID was used in context. For example, the number of items in
the collection better described as Count, not CountOfElementsInMyCollection.
6. When inventing a name for the new, publicly accessible (public) class, namespace or interface, avoid
using the names of potentially or clearly conflicting with the standard identifiers.
7. Preferable to use names that clearly and accurately describe the purpose and / or a sense of self.
Klimatur Confidential
10 March 2011
Klimatur Coding Style, rev. 1.0
8. Try not to be used for different entity names that differ only by case letters. You are developing
components can be used from languages that are not case sensitive, and some of the methods (or even
the whole component) are not available.
9. Try to use names with simple spelling. It's easier to read and to type. Do not (within reason) use of the
words with double letters, complex alternation of consonants. Before staying in choosing a name, make
sure it is easy to spell and unequivocally perceived by the ear. If it is hard to read, and you are wrong
when typing it, you may want to choose another.
Abbreviations
1. Do not use abbreviations or partial words in identifiers, unless they are universally accepted. For
example, write GetWindow, and not GetWin.
2. Do not use acronyms unless they are standard in the field of information technology.
3. Widespread use acronyms to replace lengthy phrase. For example, UI instead of the User Interface or
Olap instead of On-line Analytical Processing.
4. If there is an identifier of less than three letters, an abbreviation, then it is written in capital letters,
for example, System.IO, System.Web.UI. Names longer than two letters write in the style of Pascal or
Camel, such as Guid, Xml, xmlDocument.
Examples:
using System.IO;
using System.Web.UI;
public class Math
{
public const Double PI = ...;
public const Double E = ...;
}
The choice of words
1. Do not use names that coincide with the global namespace, such as System and Microsoft. Try
whenever possible to avoid overlap with the names of other entities. NET Framework.
2. Below is a list of names, the use of which is undesirable:
AddHandler
AddressOf
Alias
And
Ansi
As
Assembly
Auto
Base
Boolean
ByRef
Byte
ByVal
Call
Case
Klimatur Confidential
10 March 2011
Klimatur Coding Style, rev. 1.0
Catch
CBool
CByte
CChar
CDate
CDec
CDbl
Char
CInt
Class
CLng
CObj
Const
CShort
CSng
CStr
CType
Date
Decimal
Declare
Default
Delegate
Dim
Do
Double
Each
Else
ElseIf
End
Enum
Erase
Error
Event
Exit
ExternalSource
False
Finalize
Finally
Float
For
Friend
Function
Get
GetType
Goto
Handles
If
Implements
Imports
In
Inherits
Integer
Interface
Is
Let
Lib
Like
Long
Loop
Me
Mod
Module
MustInherit
MustOverride
MyBase
MyClass
Namespace
New
Next
Not
Nothing
NotInheritable
NotOverridable
Object
On
Option
Optional
Or
Overloads
Overridable
Overrides
ParamArray
Preserve
Private
Property
Protected
Public
RaiseEvent
ReadOnly
ReDim
Region
REM
RemoveHandler
Resume
Return
Select
Set
Shadows
Shared
Short
Single
Static
Step
Stop
String
Structure
Sub
SyncLock
Then
Throw
To
True
Try
TypeOf
Unicode
Klimatur Confidential
10 March 2011
Klimatur Coding Style, rev. 1.0
Until
volatile
When
While
With
WithEvents
WriteOnly
Xor
eval
extends
instanceof
package
var
Namespaces
1. To use the namespace name of the company, then the product name, and possibly the name of a
subsystem or a substantial part of the project. For example, Klimatur.Framework,
Klimatur.MegaTool.Scanner.
2. Use the style of Pascal for case-insensitive.
3. When you declare a namespace, use a single namespace directive with the full namespace name. Do
not use nested namespace declarations. This remark does not apply to C + + / MC + +, since they are no
different from the nested namespaces ability to create composite namespace.
4. The plural should be used if the namespace combines a number of different but semantically similar
entities. Conversely, when the namespace contains a certain subsystem, you should use a single
number. Compare: Klimatur.Collections, but not Klimatur.Collection; Klimatur.Controls, but not
Klimatur.Control; Klimatur.Network, but not Klimatur.Networks; Klimatur.Web, but not Klimatur.Webs;
5. Do not use the same class name and namespace. For example, do not use the Debug class and the
namespace Debug.
Examples:
namespace Klimatur.Controls {}
namespace Klimatur.Collections {}
namespace Klimatur.Common {}
namespace Klimatur.Network {}
Import namespaces (Directive using)
1. Enumerate the imported namespace to the following sequence: namespace. NET Framework, a
namespace-party, proprietary namespace from another project, the namespace of the current project.
Each such section must be separated by a blank line, and the names within a section must be sorted
alphabetically.
2. Directives using, containing alias, should go at the end of relevant sections, and also be ordered
alphabetically.
Klimatur Confidential
10 March 2011
Klimatur Coding Style, rev. 1.0
Types
1. Do not use keywords in C # for the built-in types. Use their names from the library. This is, firstly,
makes logical highlighting Visual Studio (now all types except void will be highlighted the same way),
and, secondly, improve the readability of the code. Examples:
object = Object
int = Int32
long = Int64
float = Single
double = Double
string = String
char = Char
byte = Byte
short = Int16
uint = UInt32
etc
2. All non-nested types (placed in a namespace, or directly in the global space), with the exception of the
delegates should be in separate files.
3. Try to declare nested types in the beginning of the external type.
4. Try not to make unnecessary nested types. Remember that investments should only be closely related
types.
Elements of types (type members)
1. Elements of the types must be separated by one row from each other. Nested types should be
separated by two lines. When you declare a large number of fields used within the class (not public), you
can omit the blank line (especially if the fields are separated XML-comments).
Classes / Structures
1. Use a noun (one or more adjectives and noun) for the class name.
2. Use the style of Pascal for case-insensitive.
3. Do not use special prefixes, explaining that this class. For example, FileStream, but does not
CFileStream.
4. In appropriate cases, use a compound word derived classes, where the second part of the word
explains the base class. For example, ApplicationException - quite an appropriate name for a class that
inherits from Exception, ApplicationException as an heir of class Exception. Do not, however, abused by
this method, use it wisely. For example, Button - quite an appropriate name for a class that derives from
Control. The general rule may be, for example, like this: "If a derived class only slightly changes the
properties, behavior or appearance of the base, use compound words. If a class is significantly expands
or changes the behavior of the base, use a new noun that reflects the essence of the derived class.
LinkLabel slightly changes the look and behavior of the Label and, accordingly, uses a composite name.
Klimatur Confidential
10 March 2011
Klimatur Coding Style, rev. 1.0
5. Use a compound name, when the class belongs to some specific categories, such as FileStream,
StringCollection, IntegrityException. This applies to classes that are streams (Stream), collections
(Collection, Queue, Stack), associative containers (Dictionary), exceptions (Exception).
6. For derived classes that implement the IDictionary interface is recommended to use the name as a
triple <TipKlyucha> To <TipZnacheniya> Dictionary. Instead Dictionary can use the word Map. If this is
obvious, you can omit the name of values. Examples: StringToStringDictionary, StringToIntegerMap or
KeywordMap. Variable of this type is recommended to give a more specific semantic name, for example
userToPasswordMap (user -> password), nameServiceDictionary (name -> service).
7. For the base class, intended not for direct use and for inheritance, you should use the suffix Base. For
example, CollectionBase. These classes are also worth doing abstract.
8. Collections (implementing interface ICollection / IList) should be given a name in the form of
<ImyaElementa> Collection. Variable is better to give these types of names that are plural of the item.
For example, a collection of buttons should be named ButtonCollection, and the variable buttons.
Examples:
public class FileStream {}
public class Button {}
public class String {}
public class StringCollection {}
Interfaces
1. Use describing a noun, adjective, or one or more adjectives and a noun for the interface identifier. For
example, IComponent - it describes a noun, ICustomAttributeProvider - is instantiated adjective noun,
and IPersistable - it characterizes the adjective.
2. Use the style of Pascal for case-insensitive.
3. Use prefix I (capital i) interfaces to clarify that the type is an interface. Try to avoid interfaces with two
I at the beginning, for example IIdentifiable. Try to pick a synonym, for example IRecognizable.
4. For a pair of class-based interface in which the class is a standard or reference implementation of an
interface, use the same name, differing only in the prefix I for the interface. For example,
IConfigurationManager and ConfigurationManager.
Examples:
public interface IServiceProvider {}
public interface IFormatable {}
public interface IComponent
{
Klimatur Confidential
10 March 2011
Klimatur Coding Style, rev. 1.0
/ / Declare the interface
}
public class Component: IComponent / / Standard Interface Implementation
{
/ / Implementation
}
Attributes
1. A class that attribute must have the suffix Attribute. No class, attributes are not, should not have this
suffix. If the semantics of the class requires words in the title is something like Attribute, use synonyms,
such as Descriptor, Sign, Qualifier, Specifier, Declarator.
Example:
public class ObsoleteAttribute {};
Enums
1. Use the style of Pascal for the capitalization of names and values of the enumeration.
2. Do not use the suffix in the name of the Enum type, instead use a more specific suffix, such as Style,
Type, Mode, State. To make the code easier to read, use the following rule: "The name + is + the
enumeration value must form a simple sentence." For example: BorderStyle.Single (Border style is
single, ThreadState.Aborted -> Thread state is "aborted".
3. If the transfer has the attribute [Flags], use a plural suffix, or Flags.
4. Record enumeration values on separate lines. If the elements have a certain semantic order,
describes them this way, otherwise use the alphabetical order.
5. If one member of the transfer depends on the other, use the Boolean operations (&, |, ^), rather than
literal constants.
6. The names of the members of the enumeration must not contain the name of the enumeration and
the other is not related to a particular value of the information.
Example:
public enum CodeStyle
{
Good = 1,
Normal = 2,
Klimatur Confidential
10 March 2011
Klimatur Coding Style, rev. 1.0
Bad = 3,
Ugly = 4
}
Field
1. Non-public fields (private, protected and protected internal) are referred to in the style of Camel and
prefixed with _.
2. Public fields are named in accordance with the naming of properties.
3. One of the declaration should not contain more than one field and must be on one line.
1. Public fields should be required to be documented, XML-comments. It is desirable to provide XMLcomments and a non-public fields.
class A
{
/ / You must not:
Int32 _var1, _var2;
/ / This too:
Int32 _var1,
_var2;
/ / It should be as follows:
Int32 _var1;
Int32 _var2;
...
2. Turning to public fields, avoid them passing by reference, as it is likely that in the next versions of
these fields can be properties.
Methods
1. Use verbs or a combination of verbs and nouns and adjectives for method names.
2. Use Pascal style for capitalization for the public methods and Kamal for private m methods.
Examples:
Klimatur Confidential
10 March 2011
Klimatur Coding Style, rev. 1.0
private Int32 removeAll () {}
public void GetCharArray () {}
internal static void invoke () {}
Properties
1. Use a noun or one or more adjectives and a noun for the property name.
2. Use the style of Pascal for case-insensitive.
3. In appropriate cases, use the property name that is identical to the type of its value. One of the
criteria for application of this rule is the presence of a single property with a value of some (nontrivial)
type.
4. Try to avoid using the names of the properties that match the names of any type, if the values of
these properties are not the values of these types. In this case, it would be difficult to access static
members of type or enumeration values. For example, using design public int Color {get; set;}, address
Color.Xxx will be treated as receiving the Color property and then access the properties or methods of
this value, which in this case would be the type System.Int32.
5. Consider the inclusion of the type name in the ID property, especially if this type - enumeration. For
example, OuterBorderStyle, BackColor, SocketFlags.
Examples:
public class SampleClass
{
public Color BackColor
{
/ / Code for Get and Set accessors goes here.
}
}
public class Control
{
public Color Color
{
get {/ * Insert code here. * /}
set {/ * Insert code here. * /}
Klimatur Confidential
10 March 2011
Klimatur Coding Style, rev. 1.0
}
}
Events
1. Use the suffix EventHandler to delegates that are types of events. Other classes should not use this
suffix.
2. Creating an event in the components and control-s, use the system delegate EventHandler <T>, where
the parameter T is inherited from EventArgs type.
3. Make a type that describes an event-related information derived from EventArgs, and use the suffix
EventArgs. Other classes that do not describe the information about the event should not use this suffix.
4. For event names try to use verbs that describe the effect produced on the object (eg, Click, GotFocus
or FontChanged).
5. Do not use suffixes such as On, Before, After an identifier for the event. Use the appropriate form of
the verb, for instance before closing the Closing and Closed after closing.
6. In describing the events also provide the virtual protected-method, which can be overridden in a
derived class. Call this method OnXxx, where Xxx - the name of the event. The details of such methods
should not pass sender, because - it is always the current object (this).
7. Try to pick a standard delegate and the name for their events. For example, if your control has to
react to a mouse click, you should use the standard event Click. For controls, typically, such events have
already been announced in the base class Control.
Examples:
public class MouseEventArgs: EventArgs
{
private Int32 x;
private Int32 y;
public MouseEventArgs (Int32 x, Int32 y)
{
this.x = x;
this.y = y;
}
public Int32 X {get {return x;}}
Klimatur Confidential
10 March 2011
Klimatur Coding Style, rev. 1.0
public Int32 Y {get {return y;}}
}
public class Control
{
public event EventHandler <MouseEventArgs> MouseMove;
protected virtual void OnMouseMove (MouseEventArgs e)
{
if (MouseMove! = null)
MouseMove (this, e);
}
}
Parameters
1. Of its name and parameter type must be clear its purpose and meaning.
2. Use the style of Camels for the register of letters in the name of the parameter.
3. Try to avoid specifying the type of the parameter name.
4. Keep it simple prototype of the method "reserved" parameters which may be used in future versions
of the implementation. If in the future will need a new setting, use the overloaded methods.
5. Parameter names should not coincide with the names of class members. If it still can not avoid, use
this keyword to resolve conflicts.
Examples:
Type GetType (String typeName);
String Format (String format, params Object [] args);
Klimatur Confidential
10 March 2011
Klimatur Coding Style, rev. 1.0
STYLE CODE
Making
1. Use tabs, not spaces to indent. In environments such as VS is better to use the mode tab. It can be
configured in the dialog Options -> Text Editor -> Vash_lyubimyy_yazyk -> Tabs: Indenting = Smart, Tabs
= Keep Tabs. In general, this is the default setting for many languages.
2. When you format text (except for the indentation at the beginning of the line) use spaces. For this
purpose it is convenient to use the mode Virtual Space, which is in VS 2002 is configured in the Options > Text Editor -> Vash_lyubimyy_yazyk -> General.
3. Avoid lines longer than 78 characters, carry the instructions on the next line when necessary.
4. When you transfer part of the code instructions and descriptions on the other line the second and
subsequent lines should be repelled to the right for one indentation (TAB).
5. Leave a comma on previous line just as you would in conventional languages (Russian, for example).
6. Avoid unnecessary brackets, framing the whole pattern. Unnecessary brackets complicates the code
and increase the possibility of error.
7. Do not place multiple statements on one line. Each instruction must begin with a new line.
Examples:
longMethodCall(expr1, expr2, expr3,
expr4, expr5);
var1 = a * b / (c - g + f)
+ 4 * z;
var2 = (a * (b
* (c + d)
+ e * (f / z))
+ 4);
Blank lines
1. Use two blank lines between logical sections of the original file.
2. Use two blank lines between declarations of classes and interfaces.
3. Use one blank line between methods.
4. If the variables are declared in the method of a separate block, use one blank line between their
announcement and the instruction that goes for this block.
5. Use one blank line between logical parts in the method.
Gaps in the line
1. After the decimal point should be a space. After the semicolon, unless it is the latest in a string (eg in
the instructions for), should be a space. Before a comma or a semicolon no space.
2. All operators must be separated by a space of operands on both sides.
Klimatur Confidential
10 March 2011
Klimatur Coding Style, rev. 1.0
3. Logically coherent unit of regular structure is desirable to format a table. At the same time to equalize
in the table should use spaces, not tabs. Medium type VS automate the process of formatting, inserting
spaces or tabs in sootvtestvii with custom settings. Be careful and check the final result, including the
invisible characters (for VS 2002 and older - the menu Edit-> Advanced-> View White Space).
NOTE
To simplify the work, you can use the following trick. Table can be formed by
tabs, select an area of a rectangular selection (Alt + cursor right) and then
apply to this area of Edit-> Advanced-> Untabify Selection.
Examples:
TestMethod(a, b, c);
int Bar { get; set; }
a=b;
// no
a = b;
// yes
for (Int32 i=0; i<10; ++i)
// no
{
}
for( Int32 i = 0 ;i< 10;++i)
// no
for (Int32 i = 0; i < 10; ++i) // yes
{
}
if(a==b){}
// no
if (a == b)
{
}
// yes
// table formatting
String name
= "Mr. Ed";
Int32 myValue = 5;
Test
aTest
= Test.TestYou;
Local variables
1. Use the style of Camel for capitalization in variable names.
2. Declare variables immediately before their use.
3. Counters in loops traditionally called i, j, k, l, m, n.
4. Local temporary variables used in short sections of code that can be given names that consist of initial
letters of the name type.
5. Do not declare more than one variable in one statement.
6. The names of hidden (protected, protected internal and private) member variables and static class
variables start with the single underscore character.
Klimatur Confidential
10 March 2011
Klimatur Coding Style, rev. 1.0
7. The names of the public (internal and public) variables have to be in the style of Pascal and does not
have an underscore as a prefix.
8. Comment on ads to be understandable purpose and how to use the variable.
9. Initialize variables when you declare, if possible.
Example:
class Class1
{
private Int32 _totalLineCount = 0;
void SomeFunction(Int32 startValue)
{
Int32 lineCount = startValue;
using (StreamReader sr = File.OpenText(@"c:\MyFile.txt"))
{
while (sr.ReadLine() != null)
lineCount++;
}
_totalLineCount = lineCount;
}
}
Comments
1. Do not use multi-(/*...*/) comments to describe the classes and methods used for this purpose XML
documentation-comment. Multiline comments can not be nested, so their use can create problems.
2. To describe the essence of a piece of code, explanations of algorithms and other important
information, use multiple consecutive single-line comments (//...). Between a group of comments and
the actual code put an empty string. This shows that the commentary refers to the block of code, rather
than to specific instructions. Conversely, if comments refer to specific instructions, hold him close to this
instruction.
3. Comment on declaring variables, possibly using XML-comments. If the language does not support
XML-comments, you can use single-line comments on the same line as shown below.
4. Separate the text of the comment one space "/ / Comment.."
5. Commenting on the code, try to explain what he does, not what the operation is performed. For
example, if statement corresponds to the expression "if ... then ...», with a portion going for
"something" is a code that is executed if the if expression is true. Thus, for the construction of «if
(somePath & & File.Exists (somePath))», to write a comment "/ / If the selected file exists, then ...», and
not" / / checks for file existence and if it there is, delete it. " Part of the proposal, which goes for
"something", enter just before the implementation of specific actions. For instructions on performing
the action, write "/ / produce ..." or "/ / Make ...», where instead of ellipses include your description of
the action. Describing the action, try to describe the essence of what is happening rather than what they
are doing some or other operators. So, completely useless comments like "Assign a variable a value of
b» or call the method f ».
Klimatur Confidential
10 March 2011
Klimatur Coding Style, rev. 1.0
6. Remember that you can not save on the comments. But we should not also formally approached the
process of creating comments. The task of comments - will help them understand the code. There are
many cases where the code itself is a great self-image documents.
Examples:
/// <summary>indentation level</summary>
Int32 level;
Int32 size; // size of table
// Line 1
//
ArrayList list = new ArrayList(10);
// Line 1
// Line 2
//
for (Int32 i = 0; i < list.Count; i++)
...
Declarations and definitions
Ads of classes and interfaces
1. Base classes and interfaces must be specified on the same line as the declaration of the class. If the
list does not fit in 78 characters, carry it, starting with a colon and indent one tab to the right. Place on
the line as many elements as can fit in 78 characters.
2. Opening brace must be on the line following the announcement of the class, at the same level of
indentation as the class.
3. A closing brace must be on a separate line on the same level as a class.
4. The contents of the class should be shifted one tab relative to ads.
Example:
class MySample: MyClass, IMyInterface
{
/ / The contents of the class
}
Advertisements class members and interface
1. Between a method name and opening parenthesis, a list of options can be no space.
2. The method body must be shifted by one tab relative to ads.
3. Type of access to a class member must always be explicitly specified.
Klimatur Confidential
10 March 2011
Klimatur Coding Style, rev. 1.0
4. Modifiers have to go in the following order: first, access modifiers, and then all the rest.
5. In the constructor, the constructor call the base (or the same) class (design «: base (...)»«: this (...)»)
drawn in the same manner as the list of base types in the class.
Example:
public class MySample : MyClass, IMyInterface
{
private Int32 myint;
public MySample(Int32 myint)
: base("hello, MyClass")
{
this.myint = myint;
}
[MyCustomAttribute]
private void Inc()
{
++myint;
}
protected virtual void EmptyVirtualMethod()
{
}
}
Instructions (statements)
1. Each statement must be on a separate line.
2. Compound instructions are issued an opening brace on a separate line, a list of instructions, shifted by
one tab, and a closing brace on a separate line.
3. The keyword (eg if, while, for) before the opening parenthesis (if any) must be blank.
4. Using braces to separate blocks of composite operators must, even if they contain only one
expression.
Registration If, if-else, if else-if else
if:
if (condition)
{
DoSomething();
...
}
// Не верно:
if (condition)
DoSomething();
if(condition) DoSomething();
if (condition) {
Klimatur Confidential
10 March 2011
Klimatur Coding Style, rev. 1.0
DoSomething();
}
if (condition)
{
DoSomething();
}
if (condition)
{
DoSomething();
...
}
else
{
DoSomethingOther();
...
}
// Не верно:
if (condition)
DoSomething();
else
DoSomethingOther();
if (condition) {
DoSomething();
...
} else {
DoSomethingOther();
...
}
if (condition) DoSomething(); else DoSomethingOther();
if-else:
if (condition)
{
DoSomething();
...
}
else if (condition)
{
DoSomethingOther();
...
}
else
{
DoSomethingOtherAgain();
...
}
Оформление for, foreach
for:
Klimatur Confidential
10 March 2011
Klimatur Coding Style, rev. 1.0
for (int i = 0; i < 5; ++i)
{
...
}
for (initialization; condition; update)
;
foreach:
foreach (int i in IntList)
{
...
}
Оформление while, do-while
while (condition)
{
...
}
while (condition)
;
do
{
...
}
while (condition);
Оформление switch
switch (condition)
{
case 1:
case 2:
x = ...;
break;
case 3:
x = ...;
break;
default:
x = ...;
break;
}
switch (condition)
Klimatur Confidential
10 March 2011
Klimatur Coding Style, rev. 1.0
{
case 1:
case 2:
case 3:
default:
x
x
x
x
=
=
=
=
1;
2;
3;
100;
break;
break;
break;
break;
}
Оформление try-catch
try
{
...
}
catch
{
...
}
try
{
...
}
catch (Exception ex)
{
...
}
try
{
...
}
catch (SomeException ex)
{
...
}
catch (Exception ex)
{
...
}
finally
{
...
}
Оформление инструкции using
using (initialization)
{
...
}
using (initialization1)
Klimatur Confidential
10 March 2011
Klimatur Coding Style, rev. 1.0
using (initialization2)
{
...
}
General rules for the development of classes
1. Can define the class of the public (public and internal) field, only if they are readonly.
2. Try to implement as only the properties that reflects the state of a class or object. For example, if you
are doing your collection, then the number of elements (Count) to be property, and converts it into an
array (GetArray) should be done by. And instead of Get in this case it is better to use another word, for
example, ToXxxx. That is, the method will be called ToArray ().
3. Use the methods, if the operation is a transformation that has side effects or long runs.
4. Use the method, if the order is important operations.
5. Property should not change their values from call to call, if the object's state remains unchanged. If
the result at a new call may be different for the same state of the object, use the method.
6. Do not use the "write-only." The need for such property may be a sign of bad design.
7. Functionality performed by the method must be written by you at 100% match his name. Ie the name
of the method should be clear that as the method does. The return value should also be obvious from
the name of the method. (Eg, methods, starting with Is should always return a Boolean, not throw an
exception and not do any side operations (except, perhaps, logging) but return the result)
8. Sealed (sealed) classes should not have any protected or virtual methods. Such methods are used in
derived classes, and sealed-class can not be basic.
9. Classes that define only static methods and properties that should always be marked as static.
10. Class members should be divided into regions according to the level of access.
11. Regions should be used in the following order: constants, static members (public comes first), public
constructors, public events, public properties, public methods, protected properties, protected
methods, private properties, private methods, protected fields, private fields.
12. Do not use literal constants (magic number sewn into the code buffer sizes, timeouts, etc.). Better
define the constant (if you'll never change it) or a variable read-only (though it may change in future
versions of your class). String constants stored in the corresponding table in the application resources.
13. Try to handle only the exceptions you know. If you still can handle all exceptions, either, having the
necessary processing, throws again, so that it can handle the follow-up filters, or prompting the user as
much information about the error. If the goal is to catch exceptions cleaning resources after a failure, it
is better to use section finally.
Klimatur Confidential
10 March 2011
Klimatur Coding Style, rev. 1.0
14. If you want to re-release of exceptions to the catch block, use only throw with no arguments and
does not in any way throw new Exception, because in this case is lost all the information from the
StackTrace.
15. Try not to use try / catch blocks to catch all exceptions. This unit can give rise to difficult-detectable
errors, apparently does not manifest itself. If you still use this block is necessary, this should be reflected
in the comments to this unit. Compromise in this case may be intercepting all exceptions with their
subsequent logging, but this approach also should be used only as a last resort.
16. Use TryParse method instead of Parse for basic types.
17. Try not to use the design as, since its use may be difficult to detect errors. Instead, use the standard
syntax conversion. ((Type) variable)
18. When using automatic code generation techniques are added to the automatically generated classes
should be added in a separate file.
19. Use collections of the System.Collections.Generic namespace instead of System.Collections. The use
of older generic collections can not, firstly, lead to errors associated with the transformation of types,
and, secondly, the impact on performance.
20. The code must compile without warnings.
General rules for the ASP.NET development package
1. All controls should have meaningful names in accordance with its intended use. It is desirable to
reflect in them also the control type for improved readability.
For example:
private TextBox _nameTextBox;
private Label _informationLabel;
2. HTML code in aspx files should be formatted as possible in a tree structure to facilitate its perception.
3. If the JavaScript code is used in a few pages to make sure this code into separate js files. In the same
way to proceed if the JavaScript code has a large amount compared with the contents of the entire
page.
4. HTML code is generated by the application must match XHTML specification and where possible
should be formatted in a tree structure to facilitate debugging.
5. Try whenever possible to use standard ASP.NET controls instead of writing their own.
6. If the complex set of controls with a separate behavior can potentially be used in other one form of a
separate user control.
Klimatur Confidential
10 March 2011
Klimatur Coding Style, rev. 1.0
7. When building SQL queries, use only the parameterized queries to avoid possible problems with the
SQL-Injection attacks.
8. When designing forms try to minimize the number of returns form (postback).
9. It is desirable to test the functionality of the written forms in different browsers.
10. You should use the following prefixes for controls:










ddl – DropDownList
bn – Button
lbl – Label
lbx – ListBox
div – div
lbn – LinkButton
tbx – TextBox
tbl – table
rpt – Repeater
cst – All custom controls
General Recommendations
1. Necessarily performed above recommendation on coding!
2. Before writing the code must take the time to design. Should identify for themselves the basic ways of
implementing a particular functionality, to determine the prospects for further improvement and
possible extension of this functionality. If during implementation it is necessary to use several classes of
them draw a diagram and determine the relationship between them. Perhaps in this process, you will
find the best way to implement the specified functionality.
3. Try, if possible, to find how to more flexible and elegant ways to implement the required
functionality. Perhaps this will further simplify the support you write code, and simplify its possible
upgrade. An elegant solution in any case does not mean confusion and complexity, as well as a large
number of classes. Try, if possible, costs a minimum number of small classes, perhaps the standard.
4. If the path of solutions is not completely clear do not hesitate to consult with colleagues. Remember
that lost time you can be much stronger impact on your professional credibility, rather than clearly and
specifically articulated questions to colleagues.
5. On the other hand try to pick her colleagues as little time. To do this, formulates questions as
specifically as possible. It is best to ask questions via email and as long as possible to keep these letters.
This will allow you to continue to revisit this issue and clarify the necessary details without distracting
the person with whom you are engaged in dialogue.
Klimatur Confidential
10 March 2011
Download