[Import] IDesign C # programming specifications

Source: Internet
Author: User

[Transferred from http://blog.csdn.net/zlei12/]

IDesign released the C # programming specification. The chicken shooter downloads and browses the code from Only4Gurus and is determined to take the time to translate the code for better learning.

The directory content is as follows:

1. Naming rules and styles

2 encoding Convention

3. Project Settings and Structure

4 Framework special guide

4.1 Data Access

4.2 ASP. NET and Web Service

4.3 serialization

4.4 Multithreading

4.5 Remoting

4.6 Security

4.7 Service Components

5 resources

Today, only the naming rules are translated. the translated text and the original text are compared as follows, where the tip is appended ,:-)

 

Naming rules and styles

1. Use the class and method namesPascal Style 

Public class SomeClass

{

Public SomeMethod (){}

}

2. Use local variables and method parametersCamel Style 

Int number;

Void MyMethod (int someNumber)

{}

3. The interface name uses I as the prefix.

Interface IMyInterface

{..}

4. The private member variable uses m _ as the prefix.

Public class SomeClass

{

Private int m_Number;

}

5. The custom Attribute class name uses Attribute as the suffix.

6. Use Exception as the suffix for the custom Exception class name

7. Use the verb-object naming method, such as ShowDialog ()

8. A method with a return value should be named to indicate its return value, for example, GetObjectState ()

9. use descriptive variable names.

A) Avoid using single-letter variable names, such as I or t. Instead, use index or temp.

B) Avoid using public and protected membersHungarian naming convention.

C) do not use the abbreviation (for example, abbreviated number as num ).

10. Always use the C # predefined type, instead of the alias in the System namespace. For example, if you use object instead of Object, use string instead of String, and use int instead of Int32.

11. For generic types, uppercase letters are used. Type is retained when the. NET Type is processed.

// Correct:

// Correct:

Public class upload list
// Avoid using:

// Avoid:

Public class upload list  

12. Use meaningful namespace names, such as product names or company names.

13. Avoid using the full name of the class, but use the using statement.

14. Avoid using the using statement in the namespace.

15. Put all the framework namespaces together, followed by custom or third-party namespaces.

Using System;

Using System. Collections;

Using System. ComponentModel;

Using System. Data;

Using MyCompany;

Using MyControls;

16. Use delegate inference. Do not explicitly instantiate the delegate.

Delegate void SomeDelegate ();

Public void SomeMethod ()

{}

SomeDelegate someDelegate = SomeMethod;

17. strictly abide by the indent format.

A) three spaces are used for indentation.

B) do not use tab or non-standard indentation, such as 1, 2, or 4 spaces.

18. The annotation indentation is at the same level as the annotated code.

19. All comments must be spelled out. Misspelled comments indicate a hasty development.

20. All member variables should be defined in front, and a blank line should be opened between attributes or methods.

Public class MyClass

{

Int m_Number;

String m_Name;

Public void SomeMethod1 ()

{}

Public void SomeMethod2 ()

{}

}

21. The definition of a local variable should be as close as possible to its initial use.

22. The file name should reflect the class it contains.

23. When you use the partial type and allocate a file to each part, name each file with the type name plus P and ordinal number.

// In MyClassP1.cs

Public partial class MyClass

{}

// In MyClassP2.cs

Public partial class MyClass

{}

24. The left braces are always placed in the new line.

25. The anonymous method imitates the layout of the common method and puts the anonymous delegate definition in one row.

A) follow the rule of placing the left braces on the new line.

Delegate void SomeDelegate (string someString );

// Correct

// Correct:

Public void InvokeMethod ()

{

SomeDelegate someDelegate = delegate (string name)

{

MessageBox. Show (name );

};

SomeDelegate ("Juval ");

}

// Avoid using:

// Avoid

Public void InvokeMethod ()

{

SomeDelegate someDelegate = delegate (string name) {MessageBox. Show (name );};

SomeDelegate ("Juval ");

}

26. Empty brackets are used for anonymous methods without parameters.

A) parentheses are omitted only when the anonymous method may be used for any delegate.

Delegate void SomeDelegate ();

// Correct

SomeDelegate someDelegate1 = delegate ()

{

MessageBox. Show ("Hello ");

};

// Avoid

SomeDelegate someDelegate1 = delegate

{

MessageBox. Show ("Hello ");

};

2 encoding Convention

1. Avoid placing multiple classes in a file.

2. A file should only provide the type for one namespace. Avoid having multiple namespaces in the same file.

3. Avoid file length exceeding 500 lines (except the automatically generated code ).

4. Avoid defining more than 25 rows.

5. Avoid more than five parameters. Use the structure to pass multiple parameters.

6. Each line should not exceed 80 characters.

7. Do not manually edit the code generated by any machine.

A) if you modify the code generated by the machine, modify the code format and style to conform to the encoding standard.

B) Use the partial class whenever possible to break down the parts to be maintained.

8. avoid commenting on the obvious content.

A) the code should be self-explanatory. Good code composed of highly readable variables and methods should not be annotated.

9. Write documents only on the premise of the operation and internal algorithms.

10. Avoid document at the method level.

A) a large number of external documents are used for API documents.

B) method-level annotations are only used as prompts to other developers.

11. Never hard-coded values, but always declare a constant.

12. Only use the const modifier for the value originally a constant, such as the number of days in a week.

13. Avoid using the const modifier for Read-Only variables. In this case, the readonly modifier is used.

Public class MyClass

{

Public readonly int Number;

Public MyClass (int someValue)

{

Number = someValue;

}

Public const int DaysInWeek = 7;

}

14. Use assert for any assumptions.

A) On average, one row in every five rows is an assertion.

Using System. Diagnostics;

Object GetObject ()

{

Object obj = GetObject ();

Debug. Assert (obj! = Null );

15. Each line of code should be tested in white box.

16. Only exceptions that have been explicitly handled are captured.

17. In catch statements that throw exceptions, the initial exception is always thrown to keep the stack location of the original error.

Catch (Exception exception)

{

MessageBox. Show (exception. Message );

Throw; // Same as throw exception;

}

18. Avoid using the error code as the return value of the method.

19. Avoid custom exception classes.

20. When a custom exception occurs:

A) inherit from ApplicationException

B) provides custom serialization.

21. Avoid having multiple Main () methods in an assembly.

22. Mark the type as public and internal only.

23. Avoid using the friend assembly, because this increases the coupling between the assembly.

24. Avoid using code that depends on an assembly running from a specific location.

25. Minimize application assembly (client EXE assembly) code. Use a class library instead of the business logic layer code.

26. Avoid providing clear values for enumeration.

// Correct

Public enum Color

{

Red, Green, Blue

}

// Avoid

Public enum Color

{

Red = 1, Green = 2, Blue = 3

}

27. Avoid specifying the type of enumeration.

// Avoid

Public enum Color: long

{

Red, Green, Blue

}

28. if statements always use parentheses, even if they contain a statement.

29. Avoid using? : Condition operator.

30. Avoid calling a function in a Boolean Condition Statement. Assign values to local variables and check their values.

Bool IsEverythingOK ()

{...}

// Avoid:

If (IsEverythingOK ())

{...}

// Use:

Bool OK = IsEverythingOK ();

If (OK)

{...}

31. Always use an array starting from 0.

32. Always use a for loop to explicitly Initialize an array of the reference type.

Public class MyClass

{}

MyClass [] array = new MyClass [2, 100];

For (int index = 0; index <array. Length; index ++)

{

Array [index] = new MyClass ();

}

33. Use attributes instead of providing public or protected member variables.

34. Avoid using the new inheritance modifier, but use override.

35. For non-sealed classes, the public and protected methods are always marked as virtual.

36. Never use Insecure code unless interoperability is involved.

37. Avoid explicit type conversion. Use the as algorithm to safely convert data types.

Dog dog = new GermanShepherd ();

GermanShepherd shepherd = dog as GermanShepherd;

If (shepherd! = Null)

{...}

38. When a class member has a delegate:

A) copy the delegate to a local variable before use to avoid concurrency conflicts.

B) always check whether the delegate is empty before calling.

Public class MySource

{

Public event EventHandler MyEvent;

Public void FireEvent ()

{

EventHandler temp = MyEvent;

If (temp! = Null)

{

Temp (this, EventArgs. Empty );

}

}

}

39. do not provide public event member variables, but use the event accessors.

Public class MySource

{

MyDelegate m_SomeEvent;

Public event MyDelegate SomeEvent

{

Add

{

M_SomeEvent + = value;

}

Remove

{

M_SomeEvent-= value;

}

}

}

40. Use the EventsHelper class defined in Programming. NET Components to securely publish events.

41. Always use interfaces.

A) See Chapter 1 and chapter 3 of Programming. NET Components.

42. The ratio of class to interface method and attribute is at least.

43. Avoid using a member interface.

44. Strive to make each interface have 3-5 members.

45. no more than 20 members are required for each interface.

A) 12 may be the limit of the actual application.

46. Avoid using events as interface members.

47. Avoid using abstract methods, instead of using interfaces.

48. Expose interfaces in the class hierarchy.

A) See Chapter 3 Programming. NET Components.

49. Clear interface implementation is preferred.

A) See Chapter 3 Programming. NET Components.

50. Never assume that one type supports an interface. The interface is checked for protection.

SomeType obj1;

IMyInterface obj2;



/* Some code to initialize obj1, then :*/

Obj2 = obj1 as IMyInterface;

If (obj2! = Null)

{

Obj2.Method1 ();

}

Else

{

// Handle error in expected interface

}

51. strings that will be presented to the user will never be hard-coded, but resources will be used.

52. The strings that may be modified during publishing will never be hard-coded, for example, the connection string.

53. When constructing a long string, use StringBuilder instead of string.

54. Avoid providing structured methods.

A) parameterized constructors are encouraged.

B) the operator can be overloaded.

55. When static member variables are provided, a static constructor is always provided.

56. Do not use post-binding as long as you can use pre-binding.

57. log and track applications.

58. Do not use the goto statement unless it is redirected in the switch statement.

59. In the switch statement, default is always used to add assertions.

Int number = SomeMethod ();

Switch (number)

{

Case 1:

Trace. WriteLine ("Case 1 :");

Break;

Case 2:

Trace. WriteLine ("Case 2 :");

Break;

Default:

Debug. Assert (false );

Break;

}

60. You do not need to use this unless you call another constructor In the constructor.

// Example of proper use of this

Public class MyClass

{

Public MyClass (string message)

{}

Public MyClass (): this ("hello ")

{}

}

61. Do not use base to access base class members unless the Member name conflicts when the base class constructor is called.

// Example of proper use of sort ase?

Public class Dog

{

Public Dog (string name)

{}

Virtual public void Bark (int howLong)

{}

}

Public class GermanShepherd: Dog

{

Public GermanShepherd (string name): base (name)

{}

Override public void Bark (int howLong)

{

Base. Bark (howLong );

}

}

62. Implement the Dispose () and Finalize () Methods Based on the template in Chapter 4 of Programming. NET Components.

63. Avoid type conversion with System. Object in generic code, but use a limit or as operator.

Class SomeClass

{}

// Avoid:

Class MyClass  

{

Void SomeMethod (T t)

{

Object temp = t;

SomeClass obj = (SomeClass) temp;

}

}

// Correct:

Class MyClass Where T: SomeClass

{

Void SomeMethod (T t)

{

SomeClass obj = t;

}

}

64. do not define limits for generic interfaces. Restrictions on the interface layer can be replaced by strong types.

Public class Customer

{...}

// Avoid

Public interface IList Where T: Customer

{...}

// Correct

Public interface ICustomerList: IList  

{...}

65. do not define restrictions related to methods in interfaces.

66. C # generics are always preferred in data structures.

3. Project Settings and Structure

1. A project is always created with a level 4 warning (shown in the figure below ).

2. warning will be taken as an error in the release version (note that this is not the default setting of VS. NET) (Figure omitted ).

A) although optional, this standard also recommends warning as an error in the debugging version.

3. never suppress specific compilation warnings (omitted ).

4. The supported runtime versions are always explicitly described in the application configuration file. See Chapter 5 Programming. NET Components.

5. Avoid explicitly customizing version redirection and binding to CLR assembly.

6. Avoid explicit pre-compilation definition (# define ). Use Project settings to define conditions for constant compilation.

7. Do not put any logic in AssemblyInfo. cs.

8. Do not place assembly attributes in any file except AssemblyInfo. cs.

9. Provide all fields in AssemblyInfo. cs, such as company name, description, and copyright.

10. All assemblies should be referenced using relative paths.

11. circular reference in a dataset is not allowed.

12. Avoid Multi-Module assembly.

13. The check mode is always run in non-checking mode by default (for performance consideration), but the check mode is explicitly used for easy overflow or underflow operations (Figure omitted ).

Int CalcPower (int number, int power)

{

Int result = 1;

For (int count = 1; count <= power; count ++)

{

Checked

{

Result * = number;

}

}

Return result;

}

14. Avoid using the Exception window (Debug | Exceptions) to tamper with the Exception.

15. Try to use a unified version number for all the programs and clients in the same logical application (usually a solution.

16. The configuration file of the Visual Studio. NET application is named App. config and included in the project.

17. Avoid using explicit Code to exclude methods (# if # endif), but use conditional methods.

Public class MyClass

{

[Conditional ("MySpecialCondition")]

Public void MyMethod ()

{}

}

18. Change the default project structure of VS. NET to a standard layout, and apply a unified structure to the project folders and files.

19. link a global shared file containing all solution-level information (Figure omitted ).

20. Select "insert Space" for the tab, and use three spaces to replace the tab.

A) set it in the tool | option | text editor | C # | Tab

21. The release version should contain debugging symbols.

22. Always Sign the assembly, including client applications.

23. Always use the SNK file of the project to sign the interoperability assembly (Figure omitted ).

4 Framework special guide

4.1 Data Access

1. Always Use Type-safe datasets or data tables. Avoid using the original ADO. NET.

2. transactions are always used to access the database.

A) always use service component transactions.

B) do not use ADO. NET transactions.

3. always set the transaction isolation level as a sequence.

A) Other isolation levels must be determined by the management.

4. Do not drag the database connection to Windows Forms, ASP. NET forms, or Web services using the Server Browser. In this way, the interface layer and data layer are coupled.

5. Avoid using SQL Server for verification.

A) Windows authentication is used.

6. the SQL Server component will be accessed to run with different identities of the client that calls the component.

7. Always use a type-safe class to package the stored procedure on the top. The stored procedure is called only in that class.

8. Avoid putting any logic in the stored procedure.

A) IF the Stored Procedure contains IF, you may have made a mistake.

To be continued. I suddenly thought that I had read an article about the business layer. In general, I asked how many programs really have business layer. In this article, I even suggested that System should not be referenced in the presentation layer. data namespace, do you get it? The chick shooter is not good yet...


Source: http://herald.seu.edu.cn/blog/shiningray/archive/2005/04/07/16751.aspx

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.