boas praticas codificação c#

Upload: pep

Post on 04-Feb-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/21/2019 Boas Praticas Codificao c#

    1/20

    C# Coding Standards and Best Programming Practices

    By

    http://www.dotnetspider.com

    http://www.dotnetspider.com/tutorials/BestPractices.aspx

    http://www.dotnetspider.com/http://www.dotnetspider.com/
  • 7/21/2019 Boas Praticas Codificao c#

    2/20

    1. Author..........................................................................................................................32. License, Copyrihts and !isclaimer............................................................................3

    3. "e#ision $istory..........................................................................................................3

    %. &ntroduction..................................................................................................................3'. Purpose o( codin standards and )est practices...........................................................3*. $ow to (ollow the standards across the team..............................................................%

    +. amin Con#entions and -tandards............................................................................%

    . &ndentation and -pacin..............................................................................................+. 0ood Prorammin practices....................................................................................1

    1. Architecture...............................................................................................................1'

    11. A-P.....................................................................................................................1*12. Comments..................................................................................................................1*

    13. xception $andlin...................................................................................................1+

    http://www.dotnetspider.com/tutorials/BestPractices.aspx

  • 7/21/2019 Boas Praticas Codificao c#

    3/20

    1. Author

    This document is prepared by the dotnetspiderteam. Latest version of this document can bedownloaded fromhttp://www.dotnetspider.com/tutorials/BestPractices.aspx . Please post yourcomments and feedback about this document in the above url.

    Most of the information in this document is compiled from the codin standards and bestpractices published in various articles in dotnetspider.com. !lso" we referred to the uidelinespublished by Microsoftand various other sources.

    2. License, Copyrights and Disclaimer

    #ou are permitted to use and distribute this document for any non commercial purpose as lon asyou retain this license $ copyrihts information.

    This document is provided on %!s&'s( basis. The author of this document will not be responsiblefor any kind of loss for you due to any inaccurate information provided in this document.

    3. Revision History

    'f you are editin this document" you are re)uired to fill the revision history with your name andtime stamp so that anybody can easily distinuish your updates from the oriinal author.

    *l+ ,ate -haned By ,escription

    4. ntroduction

    !nybody can write code. ith a few months of prorammin experience" you can write 0workinapplications0. Makin it work is easy" but doin it the riht way re)uires more work" than 1ustmakin it work.

    Believe it" ma1ority of the prorammers write 0workin code0" but not 2ood code0. ritin 0oodcode0 is an art and you must learn and practice it.

    3veryone may have different definitions for the term 2ood code4. 'n my definition" the followinare the characteristics of ood code.

    5eliable

    Maintainable

    3fficient

    Most of the developers are inclined towards writin code for hiher performance" compromisinreliability and maintainability. But considerin the lon term 56' 75eturn 6n 'nvestment8"efficiency and performance comes below reliability and maintainability. 'f your code is not reliableand maintainable" you 7and your company8 will be spendin lot of time to identify issues" tryin tounderstand code etc throuhout the life of your application.

    !. "urpose o# coding standards and $est practices

    http://www.dotnetspider.com/tutorials/BestPractices.aspx

    http://www.dotnetspider.com/http://www.dotnetspider.com/http://www.dotnetspider.com/tutorials/BestPractices.aspxhttp://www.dotnetspider.com/tutorials/BestPractices.aspxhttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconNETFrameworkDesignGuidelines.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconNETFrameworkDesignGuidelines.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconNETFrameworkDesignGuidelines.asphttp://www.dotnetspider.com/http://www.dotnetspider.com/tutorials/BestPractices.aspxhttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconNETFrameworkDesignGuidelines.asphttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconNETFrameworkDesignGuidelines.asp
  • 7/21/2019 Boas Praticas Codificao c#

    4/20

    To develop reliable and maintainable applications" you must follow codin standards and best practices.

    The namin conventions" codin standards and best practices described in this document are compiled fromour own experience and by referrin to various Microsoft and non Microsoft uidelines.

    There are several standards exists in the prorammin industry. 9one of them are wron or bad and you

    may follow any of them. hat is more important is" selectin one standard approach and ensurin thateveryone is followin it.

    %. Ho& to #ollo& the standards across the team

    'f you have a team of different skills and tastes" you are oin to have a touh time convincineveryone to follow the same standards. The best approach is to have a team meetin anddevelopin your own standards document. #ou may use this document as a template to prepareyour own document.

    ,istribute a copy of this document 7or your own codin standard document8 well ahead of thecodin standards meetin. !ll members should come to the meetin prepared to discuss prosand cons of the various points in the document. Make sure you have a manaer present in the

    meetin to resolve conflicts.

    ,iscuss all points in the document. 3veryone may have a different opinion about each point" butat the end of the discussion" all members must aree upon the standard you are oin to follow.Prepare a new standards document with appropriate chanes based on the suestions from allof the team members. Print copies of it and post it in all workstations.

    !fter you start the development" you must schedule code review meetins to ensure thateveryone is followin the rules. types of code reviews are recommended:

    . Peer review ; another team member review the code to ensure that the code follows thecodin standards and meets re)uirements. This level of review can include some unittestin also. 3very file in the pro1ect must o throuh this process.

    minutes before themeetin. Let them read and come up with points for discussion. 'n the roup reviewmeetin" use a pro1ector to display the file content in the screen. =o throuh everysections of the code and let every member ive their suestions on how could that pieceof code can be written in a better way. 7,on4t foret to appreciate the developer for theood work and also make sure he does not et offended by the %roup attack(?8

    '. (aming Conventions and )tandards

    9ote :9ote :

    The termsThe terms Pascal -asinPascal -asinandand -amel -asin-amel -asinare used throuhout this document.are used throuhout this document."ascal Casing"ascal Casing & @irst character of all words are Apper -ase and other characters are lower case.& @irst character of all words are Apper -ase and other characters are lower case.

    3xample:3xample: BBackack--olorolor

    Camel Casing *Camel Casing * @irst character of all words"@irst character of all words" except the first wordexcept the first wordare Apper -ase and other characters areare Apper -ase and other characters are

    lower case.lower case.

    3xample:3xample: bbackack--olorolor

    . Ase Pascal casin for -lass names

    http://www.dotnetspider.com/tutorials/BestPractices.aspx

  • 7/21/2019 Boas Praticas Codificao c#

    5/20

    public class HelloWorld{

    ...}

  • 7/21/2019 Boas Praticas Codificao c#

    6/20

    6ne exception in this case would be variables used for iterations in loops:

    or ( int i = 0; i # count; i++ ){

    ...}

    'f the variable is used only as a counter for iteration and is not used anywhere else in the loop" many peoplestill like to use a sinle char variable 7i8 instead of inventin a different suitable name.

    H. ,o not use underscores 7E8 for local variable names.

    I. !ll member variables must be prefixed with underscore 7E8 so that they can be identified fromother local variables.

    >. ,o not use variable names that resemble keywords.

    . Prefix booleanvariables" properties and methods with %is( or similar prefixes.

    3x: private bool $is%inis&ed

  • 7/21/2019 Boas Praticas Codificao c#

    7/20

    PlaceDolderPlaceDolder phdphd

    TableTable tbltbl

    JalidatorsJalidators valval

    . @ile name should match with class name.

    @or example" for the class Delloorld" the file name should be helloworld.cs 7or" helloworld.vb8

    C. Ase Pascal -ase for file names.

    -. ndentation and )pacing

    . Ase T!B for indentation. ,o not use *P!-3*. ,efine the Tab siKe as .

  • 7/21/2019 Boas Praticas Codificao c#

    8/20

    =ood:bool SayHello ( string name ){

    string ullessage = "Hello " + name;*ateime currentime = *ateime.,o-;

    string message = ullessage + " t&e time is " +

    currentime.oS&ortimeString();

    essage/o!.S&o- ( message );

    i ( ... ){

    *o somet&ing ...

    return alse;}

    return true;}

    9ot =ood:

    )ool -ay$ello ;strin name

    G. Ase a sinle space before and after each operator and brackets.

    =ood:i ( s&o-esult == true ){

    or ( int i = 0; i # 10; i++ ){

    }

    }

    9ot =ood:

    i(;show"esult88true

    H. Ase 2regionto roup related pieces of code toether. 'f you use proper roupin usin

    2region" the pae should like this when all definitions are collapsed.

    http://www.dotnetspider.com/tutorials/BestPractices.aspx

  • 7/21/2019 Boas Praticas Codificao c#

    10/20

    I. Neep private member variables" properties and methods in the top of the file and publicmembers in the bottom.

    . /ood "rogramming practices

    . !void writin very lon methods. ! method should typically have O

  • 7/21/2019 Boas Praticas Codificao c#

    11/20

    . ! method should do only 0one 1ob0. ,o not combine more than one 1ob in a sinle method"even if those 1obs are very small.

    =ood: Save t&e address.Save4ddress ( address );

    Send an email to t&e supervisor to inorm t&at t&e address is updated.Send5mail ( address email );

    void Save4ddress ( string address ){

    Save t&e address. ...

    }

    void Send5mail ( string address string email ){

    Send an email to inorm t&e supervisor t&at t&e address isc&anged.

    ...}

    9ot =ood:

    // -a#e address and send an email to the super#isor to in(orm that

    // the address is updated.

    -a#eAddress ; address, email

    . Ase the c+ or JB.93T specific types 7aliases8" rather than the types defined in *ystemnamespace.

    int age; (not Int16)string name; (not String)ob6ect contact7no; (not Ob6ect)

    http://www.dotnetspider.com/tutorials/BestPractices.aspx

  • 7/21/2019 Boas Praticas Codificao c#

    12/20

    *ome developers prefer to use types in -ommon Type *ystem than lanuae specific aliases.*ome developers prefer to use types in -ommon Type *ystem than lanuae specific aliases.

    C. !lways watch for unexpected values. @or example" if you are usin a parameter with < possible values"never assume that if one is not matchin then the only possibility is the other value.

    =ood:

    7 ( memberype == eemberypes.egistered ){ egistered user8 do somet&ing8}else i ( memberype == eemberypes.9uest ){ 9uest user... do somet&ing8}else{

    // Un expected user type !"ro# an exceptiont"ro# ne# Exception $%Un expected &alue % ' (e()er!ype!oString$*

    ' %+,*

    // If #e introduce a ne# user type in future- #e can easily find// t"e pro)le( "ere

    .

    9ot =ood:

    &( ; mem)erype 88 e7em)erypes."eistered . !void usin member variables. ,eclare local variables wherever necessary and pass it toother methods instead of sharin a member variable between methods. 'f you share amember variable between methods" it will be difficult to track which method chaned thevalue and when.

    . Ase enumwherever re)uired. ,o not use numbers or strins to indicate discrete values.

    =ood:enum ailype{

    Html3laine!t4ttac&ment

    }

    void Sendail (string message ailype mailype){

    s-itc& ( mailype ){

    case ailype.Html *o somet&ingbrea;

    case ailype.3laine!t *o somet&ingbrea;

    case ailype.4ttac&ment *o somet&ingbrea;

    deault *o somet&ingbrea;

    http://www.dotnetspider.com/tutorials/BestPractices.aspx

  • 7/21/2019 Boas Praticas Codificao c#

    14/20

    }}

    9ot =ood:

    #oid -end7ail ;strin messae, strin mailype

  • 7/21/2019 Boas Praticas Codificao c#

    15/20

    G. 'n the application start up" do some kind of self check and ensure all re)uired files anddependancies are available in the expected locations. -heck for database connection in startup" if re)uired. =ive a friendly messae to the user in case of any problems.

    H. 'f the re)uired confiuration file is not found" application should be able to create one withdefault values.

    I. 'f a wron value found in the confiuration file" application should throw an error or ive amessae and also should tell the user what are the correct values.

    . 3rror messaes should help the user to solve the problem. 9ever ive error messaes like3rror in !pplication" There is an error etc. 'nstead ive specific messaes like @ailed toupdate database. Please make sure the loin id and password are correct.

    >> lines of code" it is a oodcandidate for refactorin. *plit them loically into two or more classes.

    . Loically oraniKe all your files within appropriate folders. Ase < level folder hierarchies. #oucan have up to > folders in the root folder and each folder can have up to C sub folders. 'fyou have too many folders than cannot be accommodated with the above mentioned < levelhierarchy" you may need re factorin into multiple assemblies.

    F. Make sure you have a ood loin class which can be confiured to lo errors" warnin ortraces. 'f you confiure to lo errors" it should only lo errors. But if you confiure to lotraces" it should record all 7errors" warnins and trace8. #our lo class should be written sucha way that in future you can chane it easily to lo to indows 3vent Lo" *RL *erver" or

    http://www.dotnetspider.com/tutorials/BestPractices.aspx

  • 7/21/2019 Boas Praticas Codificao c#

    16/20

    3mail to administrator or to a @ile etc without any chane in any other part of the application.Ase the lo class extensively throuhout the code to record errors" warnin and even tracemessaes that can help you trouble shoot a problem.

    G. 'f you are openin database connections" sockets" file stream etc" always close them in theinallyblock. This will ensure that even if an exception occurs after openin the connection"

    it will be safely closed in the inallyblock.

    H. ,eclare variables as close as possible to where it is first used. Ase one variable declarationper line.

    I. Ase *trinBuilder class instead of *trin when you have to manipulate strin ob1ects in aloop. The *trin ob1ect works in weird way in .93T. 3ach time you append a strin" it isactually discardin the old strin ob1ect and recreatin a new ob1ect" which is a relativelyexpensive operations.

    -onsider the followin example:

    pu)lic strin Compose7essae ;strinEF lines

    'n the above example" it may look like we are 1ust appendin to the strin ob1ect 2messae4.But what is happenin in reality is" the strin ob1ect is discarded in each iteration andrecreated and appendin the line to it.

    'f your loop has several iterations" then it is a ood idea to use *trinBuilder class instead of*trin ob1ect.

    *ee the example where the *trin ob1ect is replaced with *trinBuilder.

    public string >omposeessage (stringDE lines){ String/uilder message = ne- String/uilder();

    or (int i = 0; i # lines.:engt&; i++) { message.4ppend( linesDiE );

    }

    http://www.dotnetspider.com/tutorials/BestPractices.aspx

  • 7/21/2019 Boas Praticas Codificao c#

    17/20

    return message.oString();}

    10.Architecture

    . !lways use multi layer 79&Tier8 architecture.

  • 7/21/2019 Boas Praticas Codificao c#

    18/20

    F. 'f you have to use some complex or weird loic for any reason" document it very well withsufficient comments.

    G. 'f you initialiKe a numeric variable to a special number other than >" & etc" document thereason for choosin that value.

    H. The bottom line is" write clean" readable code such a way that it doesn0t need any comments

    to understand.

    I. Perform spellin check on comments and also make sure proper rammar and punctuation isused.

    13.ception Handling

    . 9ever do a 0catch exception and do nothin0. 'f you hide an exception" you will never know ifthe exception happened or not. Lot of developers uses this handy method to inore nonsinificant errors. #ou should always try to avoid exceptions by checkin all the errorconditions prorammatically. 'n any case" catchin an exception and doin nothin is notallowed. 'n the worst case" you should lo the exception and proceed.

  • 7/21/2019 Boas Praticas Codificao c#

    19/20

    =

    // Catchin eneral exception is )ad... we will ne#er Dnow whether

    // it was a (ile error or some other error.

    // $ere you are hidin an exception.

    // &n this case no one will e#er Dnow that an exception happened.

    return 995

    >

    >

    . 9o need to catch the eneral exception in all your methods. Leave it open and let the application crash.

    This will help you find most of the errors durin development cycle. #ou can have an application level7thread level8 error handler where you can handle all eneral exceptions. 'n case of an 0unexpectedeneral error0" this error handler should catch the exception and should lo the error in addition to ivina friendly messae to the user before closin the application" or allowin the user to 0inore andproceed0.

    C. hen you re throw an exception" use the t&ro-statement without specifyin the oriinal exception.

    This way" the oriinal call stack is preserved.

    =ood:

    catc&{

    do -&atever you -ant to &andle t&e e!ception

    t&ro-;}

    9ot =ood:

    catch ;xception ex

    F. ,o not write try&catch in all your methods. Ase it only if there is a possibility that a specific exceptionmay occur and it cannot be prevented by any other means. @or example" if you want to insert a record ifit does not already exists in database" you should try to select record usin the key. *ome developerstry to insert a record without checkin if it already exists. 'f an exception occurs" they will assume thatthe record already exists. This is strictly not allowed. #ou should always explicitly check for errors ratherthan waitin for exceptions to occur. 6n the other hand" you should always use exception handlers

    http://www.dotnetspider.com/tutorials/BestPractices.aspx

  • 7/21/2019 Boas Praticas Codificao c#

    20/20

    while you communicate with external systems like network" hardware devices etc. *uch systems aresub1ect to failure anytime and error checkin is not usually reliable. 'n those cases" you should useexception handlers and try to recover from error.

    G. ,o not write very lare try&catch blocks. 'f re)uired" write separate try&catch for each task you performand enclose only the specific piece of code inside the try&catch. This will help you find which piece ofcode enerated the exception and you can ive specific error messae to the user.

    . rite your own custom exception classes if re)uired in your application. ,o not derive your customexceptions from the base class *ystem3xception. 'nstead" inherit from !pplication3xception.

    h // d id / i l /B P i