Dotnet Guide Lines

  • Uploaded by: Mahesh
  • 0
  • 0
  • April 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Dotnet Guide Lines as PDF for free.

More details

  • Words: 5,981
  • Pages: 20
.NET CODING STANDARDS AND GUIDELINES

Infosys

.Net Coding Standards & Guidelines © Infosys Technologies Limited

TABLE OF CONTENTS 1. INTRODUCTION................................................................................................................................................3 2. LANGUAGE........................................................................................................................................................3 3. NAMING STANDARDS.....................................................................................................................................3 3.1 Assembly, File Names and Namespaces........................................................................................................3 3.2 Interface Names..............................................................................................................................................4 3.3 Class Names...................................................................................................................................................4 3.4 Attribute Names..............................................................................................................................................5 3.5 Static Field Names..........................................................................................................................................5 3.6 Property Names..............................................................................................................................................5 3.7 Method Names...............................................................................................................................................5 3.8 Parameter names.............................................................................................................................................6 3.9 Event Names...................................................................................................................................................6 3.10 Constants......................................................................................................................................................6 3.11 Length Of Names.........................................................................................................................................6 3.12 Variable Names.............................................................................................................................................6 3.13 Naming of Controls......................................................................................................................................7 4. COMMENTS.......................................................................................................................................................8 5. CODING STYLE...............................................................................................................................................10 5.1 Line Length..................................................................................................................................................10 5.2 Wrapping Lines............................................................................................................................................10 5.3 Indentation....................................................................................................................................................10 5.4 Miscellaneous...............................................................................................................................................10 6. DECLARATIONS .............................................................................................................................................11 6.1 Number Per Line..........................................................................................................................................11 7. PROGRAMMING PRACTICES.......................................................................................................................11 7.1 Providing Access to Instance and Class Variables........................................................................................11 7.2 Constants......................................................................................................................................................11 7.3 Variable Assignments...................................................................................................................................11 7.4 Variable Scope..............................................................................................................................................11 7.5 Implementing Equality Operator..................................................................................................................12 7.6 Exception Handling......................................................................................................................................12 7.7 Threading......................................................................................................................................................12 7.8 Data types.....................................................................................................................................................13 8. GUIDELINES....................................................................................................................................................13 9. ASP.NET GUIDELINES....................................................................................................................................15 10. REFERENCES.................................................................................................................................................17 References QSD/REF/1032

Ver.Rev 8.00

i

Infosys

.Net Coding Standards & Guidelines © Infosys Technologies Limited

References QSD/REF/1032

Ver.Rev 8.00

ii

Infosys

.Net Coding Standards & Guidelines © Infosys Technologies Limited

1.INTRODUCTION The objective of this document is to address the conventions required for assemblies written in any of the .NET languages (VB.NET, C# etc) To make code consistent throughout the application To avoid most common errors To make code maintainable and readable To make development easy and fast This document is to be used along with the .NET Coding Standards Checklist document to ensure that the code written adheres to the standards defined here. MSDN has an excellent article on Design Guidelines for Class Library Developers, which covers the generic design guidelines, programming standards in great detail. This is a summary from that article and we strongly recommend reading the original article to get the full picture. Check the references in the end for a link to this article in MSDN.

2.LANGUAGE Pick up one of the VB.NET or C# for your project based on factors like already available skill sets, developer’s likings etc. Do not have more than one language in one project.

3.NAMING STANDARDS The following conventions are being used for naming the Identifiers. • Pascal casing (The first letter in the identifier and the first letter of each subsequent concatenated word should be capital). Example: PascalCasing • Camel casing (The first letter in the identifier is lower case and the first letter of each subsequent concatenated word should be capital). Example: camelCasing • Upper casing (All letters in the identifier are upper case). Example: UPPERCASING Use this convention only for identifiers that consist of two or fewer letters. Example: System.IO System.Web.UI Also does not use underscore or hyphen to separate words in identifier name except for method names. 3.1Assembly, File Names and Namespaces • • • • •

Assembly Name should be self-explanatory expressing its purpose. It must start with uppercase and the first letter of the next word should be capitalized. The file extensions should be based on the language. For example a VB.NET source file must have a .vb extension and a C# source file must have .cs extension. The filename should be same as the class it contains. Every class should be defined within a namespace. Use Pascal Casing for namespaces, and separate logical components with dot. Each word after dot should start with Capital letter. Name should be unique. For naming namespaces, use the company name followed by the technology/department name to maintain the uniqueness of namespaces.

References QSD/REF/1032

Ver.Rev 8.00

3

Infosys

.Net Coding Standards & Guidelines © Infosys Technologies Limited

• •

Example: Infosys.Intranet, Infosys.Web, etc. Do not use the same name for a namespace and a class. Assembly Name need not be same as Namespace name.

3.1.1File Name File name: Fffffff.cs Ffffffff - Meaningful file name •

Use uppercase for the first letter of the functionality as well as for the first letter of next word. Example: ManageRole.cs // Manage Roles EditTemplate.cs // Edit Template

3.2Interface Names • • • •

Use a noun or noun phrase or adjective to name an interface Example: IRemote, IPersistent Use Pascal casing. Use abbreviations sparingly. Use similar names when you define a class/interface pair where the class is a standard implementation of the interface. The names should differ only by the letter I prefix on the interface name. Example: public Interface IRemote { // Interface methods are listed here } public class Remote: IRemote { // class definition goes here }

3.3Class Names • • • • • • •

• •

Use a noun or noun phrase to name a class. Do not use a type prefix, such as C for class, on a class name. Example: use the class name FileStream rather than CFileStream. Use Pascal casing. Use abbreviations sparingly. Do not start any class name with letter “I”. Class name may begin with the letter I to describe its functionality even though the class is not an interface, its appropriate as long as I is the first letter of an entire word. Example: IconGallery Use a compound word to name a derived class. The second part of the derived class's name should be the name of the base class. For example, ApplicationException is an appropriate name for a class derived from a class named Exception, because ApplicationException is a kind of Exception. Use reasonable judgment in applying this rule. For example, Clerk is an appropriate name for a class derived from Employee. Although a Clerk is a kind of employee, making employee a part of the class name would lengthen the name unnecessarily. There can be more than one classes in one file so try to keep the filename same as the class which has entry point for the application, otherwise just give the name, which seems to be most appropriate. The following are examples of correctly named classes.

References QSD/REF/1032

Ver.Rev 8.00

4

Infosys

.Net Coding Standards & Guidelines © Infosys Technologies Limited Example: public class FileStream; public class Button; public class String;

3.4Attribute Names •

Always suffix “Attribute” to custom attribute class. Example: public class ObsoleteAttribute: System.Attribute { }

3.5Static Field Names • •

Use noun or noun phrase or abbreviations to name static fields. Use Camel Casing. Example: static int noOfEmployees;

3.6Property Names • • •

Use noun or noun phrase or abbreviations to name properties. Use Pascal casing. Create a property with the same name as its underlying type. Example: public enum Color { // Write code for Enum here. } public class Control { public Color Color { get { // Write code here. } set { // Write code here. } } }

3.7Method Names • • • •

Use the verb-noun method for naming routines that perform some operation on a given object, such as CalculateTotalInvoice (). Use Pascal Casing. The method name should start with uppercase and the next word is also to start with uppercase Example: public void CheckStatus () {…}; Avoid using Underscore in method names to separate words other than .Net framework methods. Example .Net framework has methods like Page_Load can have underscore. Some valid method names are RemoveAll()

References QSD/REF/1032

Ver.Rev 8.00

5

Infosys

.Net Coding Standards & Guidelines © Infosys Technologies Limited GetCharArray() Invoke()

3.8Parameter names • •

Use descriptive names. It should describe about the parameter more rather than its type. Example: Type GetType (string argName) Use Camel casing.

3.9Event Names • • • •

Use verb to name events. Name an event argument class with the EventArgs suffix. Do not use a prefix or suffix on the event declaration on the type. For example, use Close instead of OnClose. Use an EventHandler suffix on the Event Handler names.

3.10Constants Constants should be written in upper case letters only. Underscore can also be used to separate meaningful words. The names should be self- explanatory. Write comments if the names are not selfexplanatory. Constants should be assigned value at the time of declaration. Example: const int NUM_DAYS_IN_WEEK = 7; 3.11Length Of Names Identifiers must be as short as possible without obscuring their meaning, preferably 32 characters or less. Unambiguous abbreviations can be used if possible. For example, use custName instead of customerName. Excessively long variable names are cumbersome and irritating for programmers to use, hence chances of error during coding are higher. 3.12Variable Names • • • •

• •



Use Camel Casing (documentFormatType) where the first letter of each word except the first is capitalized. Boolean variable names must start with “is” such as isFileFound. Even for a short-lived variable that may appear in only a few lines of code, still use a meaningful name. Even for short-loop indexes use count instead of i. Do not use literal numbers or literal strings, such as For count = 1 To 7. Instead, use named constants, such as for count = 1 To NUM_DAYS_IN_WEEK for ease of maintenance and understanding. No global variables are allowed. Do not use variable names that conflicts with Keywords used in .NET Framework. For more details, refer to the following section in .NET SDK Documentation, • C# keywords in C# Programmer’s Reference • Visual Basic Language Keywords in Visual Basic Language and Run-Time Reference. Do not prefix the variable names with Hungarian type notation. Example Use string userId ; Instead of string strUserId;

References QSD/REF/1032

Ver.Rev 8.00

6

Infosys

.Net Coding Standards & Guidelines © Infosys Technologies Limited

The following table provides examples for the different types of identifiers. Identifier Class Enum type Enum values Event Exception class Read-only Static field Interface Method Namespace Parameter Property Struct Const Variable names EventHandler

Case Pascal Pascal Pascal Pascal Pascal Camel Pascal Pascal Pascal Camel Pascal Pascal UpperCasing Camel Pascal

Example DataAccess ErrorLevel FatalError ValueChange LoginException redValue IDataAccess UpdateData Infosys.Web typeName CommandType EmpAddress TOTAL documentType DataEventHandler

3.13Naming of Controls Winform Controls Naming convention is described here. This table deals only with controls that are provided by .Net Framework. For controls other than these like UserControl follow the naming convention that is defined in this document for variables and classes. Control Button CheckBox CheckListBox ColorDialog ComboBox ContextMenu DataGrid DataSet DateTimePicker DomainUpDown ErrorProvider FontDialog GroupBox HelpProvider HScrollBar ImageList Label LinkLabel ListBox ListView MainMenu MonthCalendar NotifyIcon NumericUpDown OpenFileDialog PageSetupDialog

References QSD/REF/1032

Prefix btn chk clst cdlg cmb cmnu dg ds dtp dupd errp ftdlg gpb hlp hsb imgl lbl lnk lst lvw mnu mcal nico nupd ofdlg psdlg

Example btnClick chkReadOnly clstSelectPolicy cdlgSelectColor cmbCountry cmnuFormContext dgCustRecords dsEmpDetails dtpSelectDate dupdBusiness errpCtrlError ftdlgChangeFont gpbCountries hlpShowHelp hsbShareIndex imglPictureList lblHelpMessage lnkHelpLink lstPolicyCodes lvwProjectCodes mnuChoice mcalChooseDate nicoInfo nupdDecimalPlaces ofdlgGetFile psdlgPageSetup

Ver.Rev 8.00

7

Infosys

.Net Coding Standards & Guidelines © Infosys Technologies Limited

Panel PictureBox PrintDialog PrintDocument PrintPreviewControl PrintPreviewDialog ProgressBar RadioButton RichTextBox SaveFileDialog Splitter StatusBar TabControl TextBox Timer ToolBar ToolTip TrackBar TreeView VScrollBar

pnl pic pdlg pdoc prctl ppdlg prg rdb rtx sfdlg splt stb tbctl txt tmr tb ttip trkb trev vsb

pnlWindow picDiskSpace pdlgPrint pdocPrintDoc prctlReviewPrint ppdlgBeforePrint prgCopyStatus rdbChoice rtxUserInformation sfdlgSaveFile spltExplorer stbMDIform tbctlMainMenu txtTransactNo tmrAlarm tbProjectToolbar ttipName trkbStatus trevCommuity vsbTxtArea

4.COMMENTS Comments here refer to internal documentation, which is comprised of comments that developers write within the source code. C# provides a mechanism for developers to document their code using XML. In source code files, lines that begin with /// and that precede a user-defined type such as a class, delegate, or interface; a member such as a field, event, property, or method; or a namespace declaration can be processed as comments and placed in a file. Use this XML documentation feature to put comments. Note however that this XML documentation feature is not available in other .NET languages as of now, though going forward it would be made available. For more details, refer to the following article in MSDN – XML Documentation in C# Programmer’s Reference documentation.. The following points are recommended commenting techniques. • When modifying code (bug fixing/revision/maintenance), always keep the commenting around it up to date. Add an additional comment giving details of who made the change, the date the change was made and an Issue tracking number if available. The format would be as follows // , , // Explanation of what code changes were made Have an additional comment at the end of change, marking the end of the block in which the code changes were made. This would be as follow // End code changes.

At the beginning of every routine/function, it is helpful to provide comments, indicating the routine's/function’s purpose, assumptions, and limitations. Use <summary> tag for this. The following details should be provided i.

Author :

References QSD/REF/1032

Ver.Rev 8.00

8

Infosys

.Net Coding Standards & Guidelines © Infosys Technologies Limited ii. Functionality description : What it is supposed to do. Any algorithms used or books referred. iii. Globals Modified : The global variables modified. iv. External Functions Called : v.

Known Bugs and/or side effects : These are added during testing or if some decision has to taken during coding that you foresee to cause problems. It can also mention things like workarounds implemented or deliberate coding for some specific reasons

vi. Start Date : vii. Modification log : • • •

• • • • • • • •

Avoid clutter comments, such as an entire line of asterisks. Instead, use white space to separate comments from code. Prior to deployment, remove all temporary or extraneous comments to avoid confusion during future maintenance work. 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. Comment as you code because you will not likely have time to do it later. Also, should you get a chance to revisit code you have written, that which is obvious today probably will not be obvious six weeks from now. Avoid superfluous or inappropriate comments, such as humorous sidebar remarks. Use comments to explain the intent of the code. They should not serve as inline translations of the code. Comment anything that is not readily obvious in the code. To prevent recurring problems, always use comments on bug fixes and work-around code, especially in a team environment. Also include the data (if any) that fixed the bug. Use comments on code that consists of loops and logic branches. These are key areas that will assist source code readers. Throughout the application, construct comments using a uniform style with consistent punctuation and structure. If needed, inline comments can be put using the following format. Single line comments // Write comment here Multiline comments /* Write comments here */

References QSD/REF/1032

Ver.Rev 8.00

9

Infosys

.Net Coding Standards & Guidelines © Infosys Technologies Limited

5.CODING STYLE •





The style must be followed through out the class and application. void CalculateTotal (...) { //Write code here } The code must be aligned properly. Even if the action statement for if-else statement is only one, it should be enclosed with braces and code formatting followed as below. Example: if(cnt > total) { Console.WriteLine (“count value is: “ + cnt); } Leave one space before and after any operator so as to increase readability. Example: Assignment operator “=” a = b + c;

5.1Line Length Avoid line longer than 70 characters for readability. 5.2Wrapping Lines When an expression will not fit on a single line, break it according to these general principles • Break after a comma • Break before an operator • Align the new line with the beginning of the expression at the same level on the previous line Example: Method1(longExpression1, longExpression2, longExpression3, + longExpression4, longExpression5); Var2 = longName1 + longName2 – longName3 * (longName4 + longName5) 5.3Indentation Establish a standard size for an indent. Set it to 4 spaces, and use it consistently. Align sections of code using the prescribed indentation. 5.4Miscellaneous • • • •

Divide source code logically between physical files. Break large, complex sections of code into smaller, comprehensible modules. When writing SQL statements, use all uppercase for keywords and mixed case for database elements, such as tables, columns, and views. Put each major SQL clause on separate line for better readability. Example: SELECT FirstName, LastName FROM Customers WHERE State = 'WA'

References QSD/REF/1032

Ver.Rev 8.00

10

Infosys

.Net Coding Standards & Guidelines © Infosys Technologies Limited

6.DECLARATIONS 6.1Number Per Line One declaration per line is recommended since it encourages commenting. Also initialize the variable in the same line. Example: string name = “john”; Dataset dsEmployee = new Dataset(); 6.1.1Placement Declare variables as and when they are required. This will also minimize the number of variables, which are declared first and then not used anywhere.

7.PROGRAMMING PRACTICES 7.1Providing Access to Instance and Class Variables Do not make any instance or class variable public without good reason. Often, instance variables do not need to be explicitly set or get. One example of appropriate public instance variables is the case where the class is essentially a data structure, with no behavior. If struct is not being used, then it’s appropriate to make the class’s instance variables public. 7.2Constants Numerical constants (literals) should not be coded directly, except for -1, 0, and 1, which can appear in a for loop as counter values. 7.3Variable Assignments Avoid assigning several variables to the same value in a single statement. It is hard to read. Example: name =id = 'c'; // Avoid! Do not use embedded assignments in an attempt to improve run-time performance. This is the job of the compiler, and besides, it rarely actually helps. Example: D = (a = b + c) + r; // Avoid! should be written as a = b + c; d = a + r; 7.4Variable Scope A variable declared in code could be of any of the following types – static, instance, array, value parameter, reference parameter, output parameter and local variable. When programming with variables be careful about the scope of the variable. A variable should never be referenced outside of its scope. For more details, refer to Chapter 5 on Variables in C# Language Specification in .NET SDK Documentation.

References QSD/REF/1032

Ver.Rev 8.00

11

Infosys

.Net Coding Standards & Guidelines © Infosys Technologies Limited

7.5Implementing Equality Operator • • • • •

Implement the GetHashCode method whenever you implement the Equals method. This keeps Equals and GetHashCode synchronized. Override the Equals method whenever == is overridden, and make them do the same thing. Overload operators in a symmetric manner. For example, if the equality operator (==) is to be overloaded, overload the not equal operator (! =) also. Override the Equals method any time the IComparable Interface is implemented. Do not throw exceptions from the Equals or GetHashCode methods or the equality operator (==).

7.6Exception Handling Use the structured error handling (Try, Catch, Finally and Throw). Do not use On Error Goto, Resume, Resume Next statements anymore. The way to use try… catch…finally would be as below Try Catch

// statements that need to be execute go here

// // // Finally // // //

code to handle the exception go here. You would typically write clean to take corrective action for the exception raised code that needs to execute irrespective of the exception occurrence would go here. You would typically write clean up code here

Do not mix old VB6 style of error handling (On Error Goto) with structured exception handling. Do not raise exception unnecessarily. Decide if a simple return value like “false” would do the job. Example – If a user enters a wrong password, validation logic should return false instead of raising exception. Exception should really be raised in exceptional cases like database not found, network problems etc. Make sure that you put Try around the code that can potentially raise an exception. This would also be valid for all calls to .NET framework classes which can raise exceptions. Add a Catch handler and do the necessary corrective action. It could be a simple conversion to a different error, which would make sense for the next layer and throwing this new exception. For more details, check the following article in MSDN – Introduction to Exception handling in Visual Basic .NET. 7.7Threading Threading support is built into the .NET framework, thus enabling VB.NET developers to also start using threads in their programs. The key benefits of threading comes in performing asynchronous operations and also enhance performance of a program by having more than one thread handle the execution. Always try to use a thread from a thread pool. This gives the same benefits as things like object pooling with COM+ and Connection Pooling with ADO.NET. Threading is a big topic and cannot be really covered in detail here. For details, refer to the following articles in MSDN • Using Threads and Threading in .NET Framework Class Library documentation • Threading objects and features in .NET Framework Class Library documentation

References QSD/REF/1032

Ver.Rev 8.00

12

Infosys

.Net Coding Standards & Guidelines © Infosys Technologies Limited

7.8Data types When programming in .NET always use strong types. .NET supports implicit conversion between types when there is no loss of data and careful scrutiny is not required. However for other cases an explicit conversion is required. All types in .NET can also be converted to the base object type (boxing) and converted back to the actual data type (unboxing). Be careful when doing this and recasting back to a value type of reference type. If the initial type and type the data is being cast back to, is not the same, there could be loss of information. In .NET you can declare a variable as object, which is similar to VARIANT in VB 6.0. However as a coding practice, this should be used only if really required for cases like writing a generic function for which the data types being passed as parameters are not know. Also note that there is cost associated when a value type is converted to object type and back. Additionally note that there are certain types in .NET and the unmanaged world (COM) that have the same memory layout and hence when interoperating between .NET and COM, they don’t require marshalling. Hence it would be good to use these types in the interface as against non-blittable types. The following table shows a list of blittable and non-blittable .NET data types (Tables has been taken from MSDN) Blittable Types System.Byte System.SByte System.Int16 System.UInt16 System.Int32 System.UInt32 System.Int64 System.IntPtr System.UIntPtr

Non-blittable type

System.Array System.Boolean

Description Converts to a C-style array or a SAFEARRAY. Converts to a 1, 2, or 4-byte value with true as 1 or -1. Converts to a Unicode or ANSI character.

System.Char Converts to a class interface. System.Class Converts to a variant or an interface. System.Object System.Mdarray Converts to a C-style array or a SAFEARRAY. Converts to a null-terminated string or to a BSTR. System.String System.Valuetype Converts to a structure with a fixed memory layout. System.Szarray Converts to a C-style array or a SAFEARRAY.

8.GUIDELINES • •

Avoid elusive names that are open to subjective interpretation, such as AnalyzeThis () for a routine, or xxK8 for a variable. Such names contribute to ambiguity more than abstraction. Do not use names that require case sensitivity. Components must be fully usable from both casesensitive and case-insensitive languages. The following examples are incorrect : o void calculate()

References QSD/REF/1032

Ver.Rev 8.00

13

Infosys

.Net Coding Standards & Guidelines © Infosys Technologies Limited void Calculate()

• •



o

void MyFunction(string a, string A)

o

namespace ee.cummings; namespace Ee.Cummings;

Start by making everything private and then make them public on case to case basis. Do not have any field, property, method, class etc as public unless it is really required. Going the other (starting with public and then making private) can result in breaking existing code. Avoid Type Name Confusion o Do not create language-specific argument names. Example: Do not use void Write (double doubleValue) Use void Write (double Value) If it is necessary to create a uniquely named method for each fundamental data type, use a universal type name to maintain cross-language interoperability. Example: Double ReadDouble ();

The following table lists fundamental data type names and their universal substitutions (Table has been taken from MSDN). C# type name Sbyte Byte

Visual Basic type name SByte Byte

JScript type name sByte byte

Short Ushort

Short UInt16

short ushort

Int Uint Long Ulong

Integer UInt32 Long UInt64

int uint long ulong

Float Double Bool Char String Object

Single Double Boolean Char String Object

float double boolean char string object



• • •

Visual C++ type Ilasm.exe name representation char int8 unsigned unsigned int8 char short int16 unsigned unsigned int16 short int int32 unsigned int unsigned int32 __int64 int64 unsigned unsigned int64 __int64 float float32 double float64 bool bool wchar_t char String string Object object

Universal type name SByte Byte Int16 UInt16 Int32 UInt32 Int64 UInt64 Single Double Boolean Char String Object

Threading Design • Static state must be thread safe. • Be aware of method calls in locked sections. Deadlocks can result when a static method in class A calls static methods in class B and vice versa. If A and B both synchronize their static methods, this will cause a deadlock. Use sealed classes if it will not be necessary to create derived classes. A class cannot be derived from a sealed class. Use sealed classes if there are only static methods and properties on a class Add a brief comment against the If/for/while.. do/do..while statement indicating the existence of the statement that too if the comment will make the program more readable.

References QSD/REF/1032

Ver.Rev 8.00

14

Infosys

.Net Coding Standards & Guidelines © Infosys Technologies Limited

• • • • • • • • • • •

• •

• • • •

• • •

Do not hard code anything - use constants. Use local constants if it is applicable to that form only. Use global constants if the value is to be used across files. The size of array should be defined through a constant. To concatenate strings use StringBuilder class instead of ‘+’ to improve performance. Do not declare any variable in a block (like while, for) as then the variable scope has only block scope and would essentially get created and destroyed every time the block is executed. Enumerating into collections sometimes is more expensive than index access in a loop. This is because the CLR can sometimes optimize array indexes and can check bound in loops, but can’t detect them in foreach type of code. Avoid having objects with Finalize methods since this means additional work by garbage collector when performing memory cleanup. When comparing text, use binary compare instead of text compare. At run time, the overhead is much lighter for binary. Use exp += val instead of exp = exp + val. Include return statements. Explicitly using return allows the JIT to perform slightly more optimizations. Without a return statement, each function is given several local variables on stack to transparently support returning values without the keyword. Throwing exceptions can be very expensive, so make sure not to throw a lot of them. Use Perfmon application to see how many exceptions your application is throwing. Do not use exceptions gratuitously as it can affect the performance. For example, avoid using exceptions for normal control flow. For example, a user might enter an invalid user name or password while logging onto an application. While this is not a successful logon, it should be a valid and expected result, and therefore should not throw an exception. However, an exception should be generated if an unexpected condition occurs, such as an unavailable user database. Minimize the number of assemblies you use to keep working set small. Port call-intensive COM components to managed code. The performance impact of COM interoperability is proportional to the number of function calls made, or data marshaled, from unmanaged to managed code. So, try to reach a compromise between porting the unmanaged code to managed code or redesigning the component to require fewer calls, or marshal more data during a single call. Wherever possible, move processing to the database using stored procedures for all data processing to have improved performance, efficient use of network, more resilience to database changes. Each Interop operation executes approximately 20 to 30 CPU instructions. When a method call is made on a class that is hosted in COM+, this overhead is incurred during each call. Make chunky calls as against chatty calls when making calls over the network to reduce the network roundtrips If features (object pooling or transaction support for multiple databases) of COM+ or MTS must be provided, only then host the component in COM+. If component is performing transactions on a single database and will always work against only one database, then implement them with ADO.NET. Set the debug mode to off before deployment or conducting any performance measurements. For the classes you implement, avoid writing Finalize() method since this results in more work for garbage collector (GC). Though garbage collection is available, always destroy objects after you finish using them. Leaving everything for GC is costly and can affect overall application performance

9.ASP.NET GUIDELINES •

Caching is on by default in ASP.NET. Leave it on unless you have a specific reason to turn it off.

References QSD/REF/1032

Ver.Rev 8.00

15

Infosys

.Net Coding Standards & Guidelines © Infosys Technologies Limited

• • •

Do not do your own string buffering – Response.Write will automatically buffer any responses without the need for the user to do it. Use ASP.NET's Trace feature to debug instead of using Response.Write Here is how you can turn tracing on or off in a single ASP.NET page: <%@ Page Language="C#" Trace="True" %> We can also turn tracing on or off for the entire ASP.NET application using syntax similar to the following (in our web.config file): <system.web> Then, in our ASP.NET page, we can use code such as the following to write custom trace (debug) information out to the page: Trace.Write("This is some custom debugging information") or Trace.Write("This is my variable and it's value is:" & myVariable.ToString())







While you can use the web.config file to store your database connection string it is more secure to store the database connection string in the machine.config file. The machine.config file contains machine-wide settings for various parts of the .NET Framework. Most of the setting stored in the machine.config file pertains to ASP.NET. There is also a section of the machine.config file where you (the developer) can add your own elements called Although the DataGrid can be a quick–it also tends to be the most expensive in terms of performance. With simple data, render the data by generating the appropriate HTML, XML or XSL. When dealing with more complex data requirements, the Data Repeater control is more of a “middle of the road” solution – it’s light, efficient, customizable and programmable. ViewState can be disabled for a single control, for an entire page, or for an entire application. Minimize the use of ViewState and scope it only to the level required. You don't need ViewState if: Pages The page doesn't post back to itself.

• •

• • •

Controls You aren't handling the control's events. The control has no dynamic or data bound property values (or they are set in code on every request).

The DataGrid control is a particularly heavy user of ViewState. By default, all of the data displayed in the grid is also stored in ViewState Caching allows us to improve the performance and scalability of our application. We can improve performance by caching the results and serving them statically (versus dynamically on each request) and our scalability increases since we're using fewer resources to service each request. Use ASP.NET cache to store information that doesn’t change frequently (such as the Collaboration Index). Note that caching can be case sensitive, hence pay attention to casing of page names when building hyperlinks Use ‘Server.Transfer’ and ‘Server.Execute’ to redirect between pages in the same application. This avoids the unnecessary client-side redirection. The Internet Explorer cache is case-sensitive. That means that you should author your hyperlinks with case-sensitivity in mind. Rather than using tables to achieve page layout, you should use Cascading Style Sheets (CSS) positioning instead. Internet Explorer offers even better performance to those who use CSS

References QSD/REF/1032

Ver.Rev 8.00

16

Infosys

.Net Coding Standards & Guidelines © Infosys Technologies Limited

• • • • • • •

• • • • •

• • • • • • •

• •

If you don't close tags, Internet Explorer renders your pages just fine. If you do close tags, Internet Explorer will render your pages even faster. Put global page objects that are reused into variables. Referring to the "document", the "body", the "window" objects repeatedly are much more expensive than simply referring to a locally declared variable. Use fixed table layouts (i.e. fixed column widths, etc.) when possible. Element.innerHTML is extremely slow. Avoid using this whenever possible. Take any Cascading Style Sheets (CSS) styles you have defined in <STYLE> elements and move them into a .css file. CSS file can be included in the HTML part with a tag, or an @import Use the same client scripting language on all pages. When you use both VBScript and JavaScript on the same page, both script engines are loaded into memory. Simply rewriting your code to use only one language will make your pages faster. Minimize the use of IFRAMES since each frame represents a browser window with its own object model. If it is necessary to use IFRAMES, use a single IFRAME and change the SRC property on the IFRAME element. In this way, only one preview document is in memory at any time. Also, there is only one IFRAME element. When positioning elements, use posLeft, posTop, posWidth, and posHeight instead of Left, Top, etc. since Left, Top, etc. are strings and need to be converted to numbers for calculations. Use the visibility CSS property to hide and show absolutely positioned elements. Use functions instead of subroutines. This makes error propagation easier through use of return values. Keep routines small enough to fit one screen for easy readability. In ASP.NET, use script delimiters around blocks of script rather than around each line of script or interspersing small HTML fragments with server-side scripting. Using script delimiters around each line or interspersing HTML fragments with server-side scripting increases the frequency of context-switching on the server-side, which hampers performance and degrades code readability. Use COM Interop judiciously since there is a performance overhead when calling COM component from .NET Set ASPCOMPAT to true in page directive when calling STA COM components (components written in VB 6.0). Use validation controls to help get both client side and server side validation without any coding overhead. Use client side logic (mostly validation type code) as much as possible and minimize server round trips. Use early binding as against late binding Use <%@ Page Language=“VB” Strict=“true”%> Always declare all variables before use Use <%@ Page Language=“VB” Explicit=“true”%> Store application initialization information (like connection strings) in Registry, load them at application load time and store in Application object o Storing in web.config has issues with altering web.config file for each deployment box o Storing in Machine.config makes machine.config bulky and could affect load and parse time Mark Session as readonly in pages which don’t modify session data Disable Session in pages that don’t require Session data

10.REFERENCES 1. 2. 3.

Performance Comparison: Data Access Techniques Performance tips and tricks in .NET Simplifying deployment and solving DLL Hell with the .Net Framework

References QSD/REF/1032

Ver.Rev 8.00

17

Infosys

.Net Coding Standards & Guidelines © Infosys Technologies Limited

4. 5.

Design Guidelines for Class Library Developers Blittable and Non-Blittable types

References QSD/REF/1032

Ver.Rev 8.00

18

Related Documents

Dotnet Guide Lines
April 2020 10
Dotnet
November 2019 30
Dotnet
November 2019 23
Dotnet
November 2019 31
Dotnet
October 2019 29

More Documents from ""

046-057.pdf
April 2020 18
Form Med0809
October 2019 22
Vip-kathalu6
April 2020 23
Fmge Information Bulletin
October 2019 35
Asp.net Faq's
April 2020 20