Beruflich Dokumente
Kultur Dokumente
By
http://www.dotnetspider.com
http://www.dotnetspider.com/tutorials/BestPractices.aspx
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
Author
License,CopyrightsandDisclaimer
RevisionHistory
Introduction
Purposeofcodingstandardsandbestpractices
Howtofollowthestandardsacrosstheteam
NamingConventionsandStandards
IndentationandSpacing
GoodProgrammingpractices
Architecture
ASP.NET
Comments
ExceptionHandling
http://www.dotnetspider.com/tutorials/BestPractices.aspx
1.
Author
Thisdocumentispreparedbythe
dotnetspider
team.Latestversionofthisdocumentcanbe
downloadedfrom
http://www.dotnetspider.com/tutorials/BestPractices.aspx
.Pleasepostyour
commentsandfeedbackaboutthisdocumentintheaboveurl.
Mostoftheinformationinthisdocumentiscompiledfromthecodingstandardsandbestpractices
publishedinvariousarticlesindotnetspider.com.Also,wereferredtothe
guidelinespublishedby
Microsoft
andvariousothersources.
2.
License,CopyrightsandDisclaimer
Youarepermittedtouseanddistributethisdocumentforanynoncommercialpurposeaslongas
youretainthislicense©rightsinformation.
ThisdocumentisprovidedonAsIsbasis.Theauthorofthisdocumentwillnotberesponsiblefor
anykindoflossforyouduetoanyinaccurateinformationprovidedinthisdocument.
3.
RevisionHistory
Ifyouareeditingthisdocument,youarerequiredtofilltherevisionhistorywithyournameandtime
stampsothatanybodycaneasilydistinguishyourupdatesfromtheoriginalauthor.
Sl#
Date
ChangedBy
Description
1
4. Introduction
Anybodycanwritecode.Withafewmonthsofprogrammingexperience,youcanwrite'working
applications'.Makingitworkiseasy,butdoingittherightwayrequiresmorework,thanjustmaking
itwork.
Believeit,majorityoftheprogrammerswrite'workingcode',butnotgoodcode'.Writing'goodcode'
isanartandyoumustlearnandpracticeit.
Everyonemayhavedifferentdefinitionsforthetermgoodcode.Inmydefinition,thefollowingare
thecharacteristicsofgoodcode.
Reliable
Maintainable
Efficient
Mostofthedevelopersareinclinedtowardswritingcodeforhigherperformance,compromising
reliabilityandmaintainability.ButconsideringthelongtermROI(ReturnOnInvestment),efficiency
andperformancecomesbelowreliabilityandmaintainability.Ifyourcodeisnotreliableand
maintainable,you(andyourcompany)willbespendinglotoftimetoidentifyissues,tryingto
understandcodeetcthroughoutthelifeofyourapplication.
5.
Purposeofcodingstandardsandbestpractices
http://www.dotnetspider.com/tutorials/BestPractices.aspx
Todevelopreliableandmaintainableapplications,youmustfollowcodingstandardsandbestpractices.
Thenamingconventions,codingstandardsandbestpracticesdescribedinthisdocumentarecompiledfrom
ourownexperienceandbyreferringtovariousMicrosoftandnonMicrosoftguidelines.
Thereareseveralstandardsexistsintheprogrammingindustry.Noneofthemarewrongorbadandyou
mayfollowanyofthem.Whatismoreimportantis,selectingonestandardapproachandensuringthat
everyoneisfollowingit.
6.
Howtofollowthestandardsacrosstheteam
Ifyouhaveateamofdifferentskillsandtastes,youaregoingtohaveatoughtimeconvincing
everyonetofollowthesamestandards.Thebestapproachistohaveateammeetingand
developingyourownstandardsdocument.Youmayusethisdocumentasatemplatetoprepare
yourowndocument.
Distributeacopyofthisdocument(oryourowncodingstandarddocument)wellaheadofthe
codingstandardsmeeting.Allmembersshouldcometothemeetingpreparedtodiscussprosand
consofthevariouspointsinthedocument.Makesureyouhaveamanagerpresentinthemeeting
toresolveconflicts.
Discussallpointsinthedocument.Everyonemayhaveadifferentopinionabouteachpoint,butat
theendofthediscussion,allmembersmustagreeuponthestandardyouaregoingtofollow.
Prepareanewstandardsdocumentwithappropriatechangesbasedonthesuggestionsfromallof
theteammembers.Printcopiesofitandpostitinallworkstations.
Afteryoustartthedevelopment,youmustschedulecodereviewmeetingstoensurethateveryone
isfollowingtherules.3typesofcodereviewsarerecommended:
1. Peerreviewanotherteammemberreviewthecodetoensurethatthecodefollowsthe
codingstandardsandmeetsrequirements.Thislevelofreviewcanincludesomeunit
testingalso.Everyfileintheprojectmustgothroughthisprocess.
2. Architectreviewthearchitectoftheteammustreviewthecoremodulesoftheprojectto
ensurethattheyadheretothedesignandthereisnobigmistakesthatcanaffectthe
projectinthelongrun.
3. Groupreviewrandomlyselectoneormorefilesandconductagroupreviewonceina
week.Distributeaprintedcopyofthefilestoallteammembers30minutesbeforethe
meeting.Letthemreadandcomeupwithpointsfordiscussion.Inthegroupreview
meeting,useaprojectortodisplaythefilecontentinthescreen.Gothrougheverysections
ofthecodeandleteverymembergivetheirsuggestionsonhowcouldthatpieceofcode
canbewritteninabetterway.(Dontforgettoappreciatethedeveloperforthegoodwork
andalsomakesurehedoesnotgetoffendedbythegroupattack!)
7.
NamingConventionsandStandards
Note:
Theterms
PascalCasing
and
CamelCasing
areusedthroughoutthisdocument.
PascalCasing
FirstcharacterofallwordsareUpperCaseandothercharactersarelowercase.
http://www.dotnetspider.com/tutorials/BestPractices.aspx
Example:
B
ack
C
olor
CamelCasing
Firstcharacterofallwords,
exceptthefirstword
areUpperCaseandothercharactersare
lowercase.
Example:
b
ack
C
olor
1.
UsePascalcasingforClassnames
publicclass
HelloWorld
{
...
}
2.
UsePascalcasingforMethodnames
void
SayHello
(stringname)
{
...
}
3.
UseCamelcasingforvariablesandmethodparameters
int
totalCount
=0
voidSayHello(stringname)
{
string
fullMessage
="Hello"+name
...
}
4.
5.
UsetheprefixIwithCamelCasingforinterfaces(Example:
IEntity
)
DonotuseHungariannotationtonamevariables
.
Inearlierdaysmostoftheprogrammerslikedithavingthedatatypeasaprefixforthevariable
nameandusingm_asprefixformembervariables.Eg:
stringm_sName
intnAge
However,in.NETcodingstandards,thisisnotrecommended.Usageofdatatypeandm_torepresent
membervariablesshouldnotbeused.Allvariablesshouldusecamelcasing.
Someprogrammersstillprefertousetheprefix
m_
torepresentmembervariables,sincethereisnoother
easywaytoidentifyamembervariable.
6.
UseMeaningful,descriptivewordstonamevariables.
Donotuseabbreviations.
Good:
stringaddress
intsalary
http://www.dotnetspider.com/tutorials/BestPractices.aspx
NotGood:
stringnam
stringaddr
intsal
7.
Donotusesinglecharactervariablenameslike
i,n,s
etc.Usenameslike
index,temp
Oneexceptioninthiscasewouldbevariablesusedforiterationsinloops:
for(inti=0i<counti++)
{
...
}
Ifthevariableisusedonlyasacounterforiterationandisnotusedanywhereelseintheloop,manypeople
stillliketouseasinglecharvariable(i)insteadofinventingadifferentsuitablename.
8.
9.
Donotuseunderscores(_)forlocalvariablenames.
Allmembervariablesmustbeprefixedwithunderscore(_)sothattheycanbeidentifiedfrom
otherlocalvariables.
10. Donotusevariablenamesthatresemblekeywords.
11. Prefix
boolean
variables,propertiesandmethodswith
is
orsimilarprefixes.
Ex:p
rivatebool_isFinished
12. Namespacenamesshouldfollowthestandardpattern
<companyname>.<productname>.<toplevelmodule>.<bottomlevelmodule>
13. UseappropriateprefixfortheUIelementssothatyoucanidentifythemfromtherestofthevariables.
Thereare2differentapproachesrecommendedhere.
a. Useacommonprefix(ui_)forallUIelements.ThiswillhelpyougroupalloftheUIelements
togetherandeasytoaccessallofthemfromtheintellisense.
b. Useappropriateprefixforeachoftheuielement.Abrieflistisgivenbelow.Since.NEThas
givenseveralcontrols,youmayhavetoarriveatacompletelistofstandardprefixesforeach
ofthecontrols(includingthirdpartycontrols)youareusing.
Control
Prefix
Label
lbl
TextBox
txt
DataGrid
dtg
Button
btn
http://www.dotnetspider.com/tutorials/BestPractices.aspx
ImageButton
imb
Hyperlink
hlk
DropDownList
ddl
ListBox
lst
DataList
dtl
Repeater
rep
Checkbox
chk
CheckBoxList
cbl
RadioButton
rdo
RadioButtonList
rbl
Image
img
Panel
pnl
PlaceHolder
phd
Table
tbl
Validators
val
14. Filenameshouldmatchwithclassname.
Forexample,fortheclassHelloWorld,thefilenameshouldbehelloworld.cs(or,helloworld.vb)
15. UsePascalCaseforfilenames.
8.
IndentationandSpacing
1. UseTABforindentation.DonotuseSPACES.DefinetheTabsizeas4.
2. Commentsshouldbeinthesamelevelasthecode(usethesamelevelofindentation).
Good:
//Formatamessageanddisplay
http://www.dotnetspider.com/tutorials/BestPractices.aspx
stringfullMessage="Hello"+name
DateTimecurrentTime=DateTime.Now
stringmessage=fullMessage+",thetimeis:"+
currentTime.ToShortTimeString()
MessageBox.Show(message)
NotGood:
//Formatamessageanddisplay
stringfullMessage="Hello"+name
DateTimecurrentTime=DateTime.Now
stringmessage=fullMessage+",thetimeis:"+
currentTime.ToShortTimeString()
MessageBox.Show(message)
3.
4.
Curlybraces(
{}
)shouldbeinthesamelevelasthecodeoutsidethebraces.
Useoneblanklinetoseparatelogicalgroupsofcode.
Good:
boolSayHello(stringname)
{
stringfullMessage="Hello"+name
DateTimecurrentTime=DateTime.Now
stringmessage=fullMessage+",thetimeis:"+
currentTime.ToShortTimeString()
MessageBox.Show(message)
if(...)
{
//Dosomething
//...
returnfalse
}
returntrue
}
NotGood:
boolSayHello(stringname)
{
stringfullMessage="Hello"+name
DateTimecurrentTime=DateTime.Now
stringmessage=fullMessage+",thetimeis:"+
currentTime.ToShortTimeString()
MessageBox.Show(message)
if(...)
{
http://www.dotnetspider.com/tutorials/BestPractices.aspx
//Dosomething
//...
returnfalse
}
returntrue
}
5.
6.
Thereshouldbeoneandonlyonesingleblanklinebetweeneachmethodinsidetheclass.
Thecurlybracesshouldbeonaseparatelineandnotinthesamelineas
if,for
etc.
Good:
if(...)
{
//Dosomething
}
NotGood:
if(...)
{
//Dosomething
}
7.
Useasinglespacebeforeandaftereachoperatorandbrackets.
Good:
if(showResult==true)
{
for(inti=0i<10i++)
{
//
}
}
NotGood:
if(showResult==true)
{
for(int
i=0i<10i++)
{
//
}
}
8.
Use
#region
togrouprelatedpiecesofcodetogether.Ifyouusepropergroupingusing
#region
,thepageshouldlikethiswhenalldefinitionsarecollapsed.
http://www.dotnetspider.com/tutorials/BestPractices.aspx
9.
Keepprivatemembervariables,propertiesandmethodsinthetopofthefileandpublic
membersinthebottom.
9.
GoodProgrammingpractices
1.
2.
Avoidwritingverylongmethods.Amethodshouldtypicallyhave1~25linesofcode.Ifamethod
hasmorethan25linesofcode,youmustconsiderrefactoringintoseparatemethods.
Methodnameshouldtellwhatitdoes.Donotusemisleadingnames.Ifthemethodnameis
obvious,thereisnoneedofdocumentationexplainingwhatthemethoddoes.
Good:
voidSavePhoneNumber(stringphoneNumber)
{
//Savethephonenumber.
}
NotGood:
//Thismethodwillsavethephonenumber.
voidSaveDetails(stringphoneNumber)
{
//Savethephonenumber.
}
3.
Amethodshoulddoonly'onejob'.Donotcombinemorethanonejobinasinglemethod,even
ifthosejobsareverysmall.
Good:
//Savetheaddress.
SaveAddress(address)
//Sendanemailtothesupervisortoinformthattheaddressisupdated.
http://www.dotnetspider.com/tutorials/BestPractices.aspx
SendEmail(address,email)
voidSaveAddress(stringaddress)
{
//Savetheaddress.
//...
}
voidSendEmail(stringaddress,stringemail)
{
//Sendanemailtoinformthesupervisorthattheaddressis
changed.
//...
}
NotGood:
//Saveaddressandsendanemailtothesupervisortoinformthat
//theaddressisupdated.
SaveAddress(address,email)
voidSaveAddress(stringaddress,stringemail)
{
//Job1.
//Savetheaddress.
//...
//Job2.
//Sendanemailtoinformthesupervisorthattheaddressischanged.
//...
}
4.
Usethec#orVB.NETspecifictypes(aliases),ratherthanthetypesdefinedinSystem
namespace.
intage(not
I
nt
16
)
stringname(not
S
tring)
objectcontactInfo(not
O
bject)
SomedevelopersprefertousetypesinCommonTypeSystemthanlanguagespecificaliases.
5.
Alwayswatchforunexpectedvalues.Forexample,ifyouareusingaparameterwith2possiblevalues,
neverassumethatifoneisnotmatchingthentheonlypossibilityistheothervalue.
Good:
If(memberType==eMemberTypes.Registered)
{
//Registereduserdosomething
}
elseif(memberType==eMemberTypes.Guest)
{
//Guestuser...dosomething
}
else
{
//Unexpectedusertype.Throwanexception
http://www.dotnetspider.com/tutorials/BestPractices.aspx
thrownewException(Unexpectedvalue+memberType.ToString()
+.)
//Ifweintroduceanewusertypeinfuture,wecaneasilyfind
//theproblemhere.
}
NotGood:
If(memberType==eMemberTypes.Registered)
{
//Registereduserdosomething
}
else
{
//Guestuser...dosomething
//Ifweintroduceanotherusertypeinfuture,thiscodewill
//failandwillnotbenoticed.
}
6. Donothardcodenumbers.Useconstantsinstead.
Declareconstantinthetopofthefileanduseit
inyourcode.
However,usingconstantsarealsonotrecommended.Youshouldusetheconstantsintheconfigfileor
databasesothatyoucanchangeitlater.Declarethemasconstantsonlyifyouaresurethisvaluewill
neverneedtobechanged.
7.
8.
Donothardcodestrings.Useresourcefiles.
Convertstringstolowercaseoruppercasebeforecomparing.Thiswillensurethestringwill
matchevenifthestringbeingcomparedhasadifferentcase.
if(name.ToLower()==john)
{
//
}
9. UseString.Emptyinsteadof
Good:
If(name==String.Empty)
{
//dosomething
}
NotGood:
If(name==)
{
//dosomething
}
10. Avoidusingmembervariables.Declarelocalvariableswherevernecessaryandpassittoother
methodsinsteadofsharingamembervariablebetweenmethods.Ifyoushareamember
variablebetweenmethods,itwillbedifficulttotrackwhichmethodchangedthevalueandwhen.
http://www.dotnetspider.com/tutorials/BestPractices.aspx
11. Use
enum
whereverrequired.Donotusenumbersorstringstoindicatediscretevalues.
Good:
enumMailType
{
Html,
PlainText,
Attachment
}
voidSendMail(stringmessage,MailTypemailType)
{
switch(mailType)
{
caseMailType.Html:
//Dosomething
break
caseMailType.PlainText:
//Dosomething
break
caseMailType.Attachment:
//Dosomething
break
default:
//Dosomething
break
}
}
NotGood:
voidSendMail(stringmessage,stringmailType)
{
switch(mailType)
{
case"Html":
//Dosomething
break
case"PlainText":
//Dosomething
break
case"Attachment":
//Dosomething
break
default:
//Dosomething
break
}
}
12. Donotmakethemembervariablespublicorprotected.Keepthemprivateandexpose
public/protectedProperties.
13. Theeventhandlershouldnotcontainthecodetoperformtherequiredaction.Rathercall
anothermethodfromtheeventhandler.
14. Donotprogrammaticallyclickabuttontoexecutethesameactionyouhavewritteninthebutton
clickevent.Rather,callthesamemethodwhichiscalledbythebuttonclickeventhandler.
http://www.dotnetspider.com/tutorials/BestPractices.aspx
15. Neverhardcodeapathordrivenameincode.Gettheapplicationpathprogrammaticallyand
userelativepath.
16. Neverassumethatyourcodewillrunfromdrive"C:".Youmayneverknow,someusersmay
runitfromnetworkorfroma"Z:".
17. Intheapplicationstartup,dosomekindof"selfcheck"andensureallrequiredfilesand
dependanciesareavailableintheexpectedlocations.Checkfordatabaseconnectioninstart
up,ifrequired.Giveafriendlymessagetotheuserincaseofanyproblems.
18. Iftherequiredconfigurationfileisnotfound,applicationshouldbeabletocreateonewith
defaultvalues.
19. Ifawrongvaluefoundintheconfigurationfile,applicationshouldthrowanerrororgivea
messageandalsoshouldtelltheuserwhatarethecorrectvalues.
20. Errormessagesshouldhelptheusertosolvetheproblem.Nevergiveerrormessageslike
"ErrorinApplication","Thereisanerror"etc.Insteadgivespecificmessageslike"Failedto
updatedatabase.Pleasemakesuretheloginidandpasswordarecorrect."
21. Whendisplayingerrormessages,inadditiontotellingwhatiswrong,themessageshouldalso
tellwhatshouldtheuserdotosolvetheproblem.Insteadofmessagelike"Failedtoupdate
database.",suggestwhatshouldtheuserdo:"Failedtoupdatedatabase.Pleasemakesurethe
loginidandpasswordarecorrect."
22. Showshortandfriendlymessagetotheuser.Butlogtheactualerrorwithallpossible
information.Thiswillhelpalotindiagnosingproblems.
23. Donothavemorethanoneclassinasinglefile.
24. HaveyourowntemplatesforeachofthefiletypesinVisualStudio.Youcanincludeyour
companyname,copyrightinformationetcinthetemplate.YoucanvieworedittheVisual
Studiofiletemplatesinthefolder
C:\ProgramFiles\MicrosoftVisualStudio
8\Common7\IDE\ItemTemplatesCache\CSharp\1033
.(ThisfolderhasthetemplatesforC#,
butyoucaneasilyfindthecorrespondingfoldersoranyotherlanguage)
25. Avoidhavingverylargefiles.Ifasinglefilehasmorethan1000linesofcode,itisagood
candidateforrefactoring.Splitthemlogicallyintotwoormoreclasses.
26. Avoidpublicmethodsandproperties,unlesstheyreallyneedtobeaccessedfromoutsidethe
class.Useinternaliftheyareaccessedonlywithinthesameassembly.
27. Avoidpassingtoomanyparameterstoamethod.Ifyouhavemorethan4~5parameters,itisa
goodcandidatetodefineaclassorstructure.
28. Ifyouhaveamethodreturningacollection,returnanemptycollectioninsteadofnull,ifyou
havenodatatoreturn.Forexample,ifyouhaveamethodreturninganArrayList,alwaysreturn
avalidArrayList.Ifyouhavenoitemstoreturn,thenreturnavalidArrayListwith0items.This
willmakeiteasyforthecallingapplicationtojustcheckforthecountratherthandoingan
additionalcheckfornull.
29. UsetheAssemblyInfofiletofillinformationlikeversionnumber,description,companyname,
copyrightnoticeetc.
http://www.dotnetspider.com/tutorials/BestPractices.aspx
30. Logicallyorganizeallyourfileswithinappropriatefolders.Use2levelfolderhierarchies.You
canhaveupto10foldersintherootfolderandeachfoldercanhaveupto5subfolders.Ifyou
havetoomanyfoldersthancannotbeaccommodatedwiththeabovementioned2level
hierarchy,youmayneedrefactoringintomultipleassemblies.
16. Makesureyouhaveagoodloggingclasswhichcanbeconfiguredtologerrors,warningor
traces.Ifyouconfiguretologerrors,itshouldonlylogerrors.Butifyouconfiguretologtraces,it
shouldrecordall(errors,warningsandtrace).Yourlogclassshouldbewrittensuchawaythat
infutureyoucanchangeiteasilytologtoWindowsEventLog,SQLServer,orEmailto
administratorortoaFileetcwithoutanychangeinanyotherpartoftheapplication.Usethelog
classextensivelythroughoutthecodetorecorderrors,warningandeventracemessagesthat
canhelpyoutroubleshootaproblem.
17. Ifyouareopeningdatabaseconnections,sockets,filestreametc,alwaysclosetheminthe
finally
block.Thiswillensurethatevenifanexceptionoccursafteropeningtheconnection,it
willbesafelyclosedinthef
inally
block.
18. Declarevariablesascloseaspossibletowhereitisfirstused.Useonevariabledeclarationper
line.
19. UseStringBuilderclassinsteadofStringwhenyouhavetomanipulatestringobjectsinaloop.
TheStringobjectworksinweirdwayin.NET.Eachtimeyouappendastring,itisactually
discardingtheoldstringobjectandrecreatinganewobject,whichisarelativelyexpensive
operations.
Considerthefollowingexample:
publicstringComposeMessage(string[]lines)
{
stringmessage=String.Empty
for(inti=0i<lines.Lengthi++)
{
message+=lines[i]
}
returnmessage
}
Intheaboveexample,itmaylooklikewearejustappendingtothestringobjectmessage.But
whatishappeninginrealityis,thestringobjectisdiscardedineachiterationandrecreatedand
appendingthelinetoit.
Ifyourloophasseveraliterations,thenitisagoodideatouseStringBuilderclassinsteadof
Stringobject.
SeetheexamplewheretheStringobjectisreplacedwithStringBuilder.
publicstringComposeMessage(string[]lines)
{
StringBuildermessage=newStringBuilder()
for(inti=0i<lines.Lengthi++)
{
message.Append(lines[i])
}
http://www.dotnetspider.com/tutorials/BestPractices.aspx
returnmessage.ToString()
}
10.
Architecture
1.
2.
3.
4.
Alwaysusemultilayer(NTier)architecture.
NeveraccessdatabasefromtheUIpages.Alwayshaveadatalayerclasswhichperformsall
thedatabaserelatedtasks.Thiswillhelpyousupportormigratetoanotherdatabasebackend
easily.
Usetrycatchinyourdatalayertocatchalldatabaseexceptions.Thisexceptionhandlershould
recordallexceptionsfromthedatabase.Thedetailsrecordedshouldincludethenameofthe
commandbeingexecuted,storedprocname,parameters,connectionstringusedetc.After
recordingtheexception,itcouldberethrownsothatanotherlayerintheapplicationcancatch
itandtakeappropriateaction.
Separateyourapplicationintomultipleassemblies.Groupallindependentutilityclassesintoa
separateclasslibrary.Allyourdatabaserelatedfilescanbeinanotherclasslibrary.
11.
ASP.NET
1.
2.
3.
Donotusesessionvariablesthroughoutthecode.Usesessionvariablesonlywithintheclasses
andexposemethodstoaccessthevaluestoredinthesessionvariables.Aclasscanaccess
thesessionusing
System.Web.HttpCOntext.Current.Session
Donotstorelargeobjectsinsession.Storinglargeobjectsinsessionmayconsumelotofserver
memorydependingonthenumberofusers.
Alwaysusestylesheettocontrolthelookandfeelofthepages.Neverspecifyfontnameand
fontsizeinanyofthepages.Useappropriatestyleclass.ThiswillhelpyoutochangetheUIof
yourapplicationeasilyinfuture.Also,ifyouliketosupportcustomizingtheUIforeach
customer,itisjustamatterofdevelopinganotherstylesheetforthem
12.
Comments
Goodandmeaningfulcommentsmakecodemoremaintainable.However,
1.
2.
3.
4.
Donotwritecommentsforeverylineofcodeandeveryvariabledeclared.
Use
//
or
///
forcomments.Avoidusing
/**/
Writecommentswhereverrequired.Butgoodreadablecodewillrequireverylesscomments.If
allvariablesandmethodnamesaremeaningful,thatwouldmakethecodeveryreadableand
willnotneedmanycomments.
Donotwritecommentsifthecodeiseasilyunderstandablewithoutcomment.Thedrawbackof
havinglotofcommentsis,ifyouchangethecodeandforgettochangethecomment,itwilllead
tomoreconfusion.
http://www.dotnetspider.com/tutorials/BestPractices.aspx
5.
6.
7.
8.
9.
Fewerlinesofcommentswillmakethecodemoreelegant.Butifthecodeisnotclean/readable
andtherearelesscomments,thatisworse.
Ifyouhavetousesomecomplexorweirdlogicforanyreason,documentitverywellwith
sufficientcomments.
Ifyouinitializeanumericvariabletoaspecialnumberotherthan0,1etc,documentthereason
forchoosingthatvalue.
Thebottomlineis,writeclean,readablecodesuchawaythatitdoesn'tneedanycommentsto
understand.
Perform
spellingcheckoncommentsandalsomakesurepropergrammarandpunctuationis
used.
13.
ExceptionHandling
1.
2.
3.
Neverdoa'catchexceptionanddonothing'.Ifyouhideanexception,youwillneverknowifthe
exceptionhappenedornot.Lotofdevelopersusesthishandymethodtoignorenonsignificant
errors.Youshouldalwaystrytoavoidexceptionsbycheckingalltheerrorconditions
programmatically.Inanycase,catchinganexceptionanddoingnothingisnotallowed.Inthe
worstcase,youshouldlogtheexceptionandproceed.
Incaseofexceptions,giveafriendlymessagetotheuser,butlogtheactualerrorwithall
possibledetailsabouttheerror,includingthetimeitoccurred,methodandclassnameetc.
Alwayscatchonlythespecificexception,notgenericexception.
Good:
voidReadFromFile(stringfileName)
{
try
{
//readfromfile.
}
catch(FileIOExceptionex)
{
//logerror.
//rethrowexceptiondependingonyourcase.
throw
}
}
NotGood:
voidReadFromFile(stringfileName)
{
try
{
//readfromfile.
}
catch(Exceptionex)
{
//Catchinggeneralexceptionisbad...wewillneverknowwhether
http://www.dotnetspider.com/tutorials/BestPractices.aspx
//itwasafileerrororsomeothererror.
//Hereyouarehidinganexception.
//Inthiscasenoonewilleverknowthatanexceptionhappened.
return""
}
}
4.
Noneedtocatchthegeneralexceptioninallyourmethods.Leaveitopenandlettheapplicationcrash.
Thiswillhelpyoufindmostoftheerrorsduringdevelopmentcycle.Youcanhaveanapplicationlevel
(threadlevel)errorhandlerwhereyoucanhandleallgeneralexceptions.Incaseofan'unexpected
generalerror',thiserrorhandlershouldcatchtheexceptionandshouldlogtheerrorinadditiontogiving
afriendlymessagetotheuserbeforeclosingtheapplication,orallowingtheuserto'ignoreand
proceed'.
5.
Whenyourethrowanexception,usethe
throw
statementwithoutspecifyingtheoriginalexception.
Thisway,theoriginalcallstackispreserved.
Good:
catch
{
//dowhateveryouwanttohandletheexception
throw
}
NotGood:
catch(Exceptionex)
{
//dowhateveryouwanttohandletheexception
throwex
}
6.
Donotwritetrycatchinallyourmethods.Useitonlyifthereisapossibilitythataspecificexception
mayoccuranditcannotbepreventedbyanyothermeans.Forexample,ifyouwanttoinsertarecordif
itdoesnotalreadyexistsindatabase,youshouldtrytoselectrecordusingthekey.Somedevelopers
trytoinsertarecordwithoutcheckingifitalreadyexists.Ifanexceptionoccurs,theywillassumethat
therecordalreadyexists.Thisisstrictlynotallowed.Youshouldalwaysexplicitlycheckforerrorsrather
thanwaitingforexceptionstooccur.Ontheotherhand,youshouldalwaysuseexceptionhandlers
whileyoucommunicatewithexternalsystemslikenetwork,hardwaredevicesetc.Suchsystemsare
subjecttofailureanytimeanderrorcheckingisnotusuallyreliable.Inthosecases,youshoulduse
exceptionhandlersandtrytorecoverfromerror.
7.
Donotwriteverylargetrycatchblocks.Ifrequired,writeseparatetrycatchforeachtaskyouperform
andencloseonlythespecificpieceofcodeinsidethetrycatch.Thiswillhelpyoufindwhichpieceof
codegeneratedtheexceptionandyoucangivespecificerrormessagetotheuser.
8.
Writeyourowncustomexceptionclassesifrequiredinyourapplication.Donotderiveyourcustom
exceptionsfromthebaseclassSystemException.Instead,inheritfromApplicationException.
http://www.dotnetspider.com/tutorials/BestPractices.aspx