Sunteți pe pagina 1din 19

Introduction

Developers always love to fght about coding standards. But it is very vital to
follow coding standards to achieve consistency throughout the project or
code. All should be of the same mind that conventions are very infuential. I
will show some good practices that I have learned during my professional
years, those are lower level but very important for all levels.
uic! "est
#et us demonstrate a $i%%Bu%% e&ample. "he $i%%Bu%% test is to write a
program that goes through the numbers ' to '((. $or every multiple of ),
the program should output *$i%%* and for every multiple of + it should output
*Bu%%*. If both above conditions are met it should output *$i%%Bu%%*. If none
of the above conditions are met, it should just output the number.
,&ample '-
public void "est./
0
for .int i 1 '2 i 3 '('2 i44/
0
if .i 5 ) 11 ( 66 i 5 + 11 (/
0
7onsole.8rite#ine.*$i%%Bu%%*/2
9
else if .i 5 ) 11 (/
0
7onsole.8rite#ine.*$i%%*/2
9
else if .i 5 + 11 (/
0
7onsole.8rite#ine.*Bu%%*/2
9
else
0
7onsole.8rite#ine.i/2
9
9
9
8hat do you thin!: Do we need to ma!e the code better:
,&ample ;-
public void 7hec!./
0
for .int i 1 '2 i 31 '((2 i44/
0
string output 1 **2
if .i 5 ) 11 (/ 0 output 1 *$i%%*2 9
if .i 5 + 11 (/ 0 output 1 output 4 *Bu%%*2 9
if .output 11 **/ 0 output 1 i."o<tring./2 9
7onsole.8rite#ine.output/2
9
9
8hat do you thin! now : Do we need to ma!e the code even better:
=!, let me help to ma!e it better. >aming thing is one of the hardest job we
have as a software developer. Because we spend a lot of time naming things,
there are so many things to name properties, methods, classes, fles,
projects etc. 8e should spend some energies for naming things because
names can be meanings. Adding meaning to code is readability all about.
public void Do$i%%Bu%%./
0
for .int number 1 '2 number 31 '((2 number44/
0
var output 1 ?et$i%%Bu%%=utput.number/2
7onsole.8rite#ine.output/2
9
9
private static string ?et$i%%Bu%%=utput.int number/
0
string output 1 string.,mpty2
if .number5) 11 (/
0
output 1 *$i%%*2
9
if .number5+ 11 (/
0
output 41 *Bu%%*2
9
if.string.Is>ull=r,mpty.output//
0
output 1 number."o<tring./2
9
return output2
9
8hat do you thin! now: Is this better than previous e&amples : Is it more
readable:
8hat is better 7ode:
8rite code for @eople $irst, 7omputers <econd. Aeadable code doesnBt ta!e
any longer to write than confusing code does, at least not in the long run. ItCs
easier to be sure your code wor!s, if you can easily read what you wrote.
"hat should be a suDcient reason to write readable code. But code is also
read during reviews. 7ode is read when you or someone else f&es an error.
7ode is read when the code is modifed. 7ode is read when someone tries to
use part of your code in a similar project or diEerent project but similar
feature or part of a feature.
What if you just writing code for yourself ? Why should you make it
readable ?
=!, the major reason behind writing readable is , a wee! or two from now
youCre going to be wor!ing on another project. 8hat will happen when any
other FGHA> needs to f& an error on that project: I can guarantee you that
you will also lost within your own horror code.
$rom my point of view a better should carried out the following
characteristics-
7ode that is easy to write , modify and e&tend
7ode that is clean and tal!sIconvey meaning
7ode that has values and cares about Juality
<o, write with the human reader in mind while satisfying the needs of the
machine to the degree necessary.
Fow can you improve the Aeadability:
$irst you have to read other peoples code and fgure out what is good and
what is bad within that code. 8hat ma!es you easy to understand and what
ma!es you feel more complicated. "hen apply those things to your own code.
$inally you need sometime, some e&perience and you need some practice to
improve the readability of your code. It is very hard but obvious to
implement standards in any software company, through methods li!e
"rainings, @eer 7ode Aeviews, Introducing automated code review tools, etc.
"he most popular tools are as follows-
FxCop is a tool that performs static code analysis of .>," code. It
provides hundreds of rules that perform various types of analysis.
StyleCop is an open source project that analy%es 7K source code to
enforce a set of style and consistency rules. It can be run from inside of
Lisual <tudio or integrated into an H<Build project. <tyle7op has also been
integrated into many thirdMparty development tools.
JetBrains ReSharper is a renowned productivity tool that ma!es
Hicrosoft Lisual <tudio a much better ID,. "housands of .>," developers
worldwide wonder how theyCve ever lived without Ae<harperCs code
inspections, automated code refactoring, bla%ing fast navigation, and coding
assistance.
8hat are 7onventions:
According to 8i!ipedia *Coding conventions are a set of guidelines for a
specifc programming language that recommend programming style,
practices and methods for each aspect of a piece program written in this
language !hese conventions usually cover fle organi"ation, indentation,
comments, declarations, statements, white space, naming conventions,
programming practices, programming principles, programming rules of
thumb, architectural best practices, etc !hese are guidelines for software
structural #uality $oftware programmers are highly recommended to follow
these guidelines to help improve the readability of their source code and
make software maintenance easier Coding conventions are only applicable
to the human maintainers and peer reviewers of a software project
Conventions may be formali"ed in a documented set of rules that an entire
team or company follows, or may be as informal as the habitual coding
practices of an individual Coding conventions are not enforced by compilers
%s a result, not following some or all of the rules has no impact on the
e&ecutable programs created from the source code*
Nou should be able to tell the diEerence between a property, local variable,
method name, class name etc. because they use diEerent capitali%ation
conventions. "hese type of conventions has values. Nou will be able to get
lots of guidelines and conventions over internet. <o fnd a convention or build
your own and stic! with it.
"he source of the following .Design ?uidelines for Developing 7lass #ibraries/
was developed by the Hicrosoft special interest group. I just made some
addons.
7apitali%ation 7onventions
Below are some e&amples of our 7K coding standards, naming conventions,
and best practices. Gse these according to your own needs.
Pascal Casing
"he frst letter in the identifer and the frst letter of each subseJuent
concatenated word are capitali%ed. Nou can use @ascal case for identifers of
three or more characters.
Camel Casing
"he frst letter of an identifer is lowercase and the frst letter of each
subseJuent concatenated word is capitali%ed.
Aef. 7apitali%ation Aules for Identifers
,&amples of <ome >aming 7onventions ?uidelines
Nou will fnd enough resources over internet. I am just highlighting some of
my favorites among them
7K 7oding 7onventions
7K 7oding ?uidelines
7K 7oding <tandards and Best @rogramming @ractices
7K 7oding <tandards and >aming 7onventions
I am providing some basic level e&amples below but as I already mentioned,
fnd a good convention that fts for you and stic! with it.
Do use @ascal7asing for class names and method names.
public class @roduct
0
public void ?etActive@roducts./
0
''
9
public void 7alculate@roductAdditinal7ost./
0
''
9
9
Do use camel7asing for method arguments and local variables.
public class @roduct7ategory
0
public void <ave.@roduct7ategory product7ategory/
0
''
9
9
Do not use Abbreviations.
'' Correct
@roduct7ategory product7ategory2

'' %void
@roduct7ategory prod7at2
Do not use Gnderscores in identifers.
'' Correct
@roduct7ategory product7ategory2

'' %void
@roduct7ategory productO7ategory2
Do pref& interfaces with the letter I.
public interface IAddress
0

9
Do declare all member variables at the top of a class, with static variables at
the very top.

public class @roduct
0
public static string Brand>ame2

public string >ame0get2 set29
public Date"ime DateAvailable 0get2 set29

public @roduct./
0
II ...
9
9
Do use singular names for enums. ,&ception- bit feld enums.
public enum Direction
0
>orth,
,ast,
<outh,
8est
9
Do not suD& enum names with ,num.
''%void
public enum Direction,num
0
>orth,
,ast,
<outh,
8est
9
8hy 8e >eed 7onventions:
@rogrammers on large projects sometimes go overboard with conventions.
"hey establish so many standards and guidelines that remembering them
becomes a fullMtime job. "he computer doesnCt care whether your code is
readable. ItCs better at reading binary machine instructions than it is at
reading highMlevelMlanguage statements.
7onventions oEer several specifc benefts. "hey let you ta!e more for
granted. By ma!ing one global decision rather than many local ones, you can
concentrate on the more important characteristics of the code.
"hey help you transfer !nowledge across projects
"hey help you learn code more Juic!ly on a new project.
"hey emphasi%e relationships among related items.
Nou should write readable code because it helps other people to read your
code. >aming thing is one of the hardest job we have as a software
developer. Because we spend a lot of time naming things, there are so many
things to name properties, methods, classes, fles, projects etc. 8e should
spend some energies for naming things because names can be meanings.
Adding meaning to code is readability all about.
<o it will help you better sleep at night.

"op Aules Developers <hould $ollow
Peep 7lass <i%e <mall
I have seen and written some gigantic classes. But unfortunately those were
never turns out well. #ater I found the reason that is, those large classes try
to do too many things. "hat violates the <ingle Aesponsibility
@rinciple. < in<=#ID .=bject =riented Design/.
!he single responsibility principle states that every object should have a
single responsibility, and that responsibility should be entirely encapsulated
by the class %ll its services should be narrowly aligned with that
responsibility
=r
According to HartinCs defnition -*!()*) $(+,-. /)0)* 1) 2+*) !(%/ +/)
*)%$+/ 3+* % C-%$$ !+ C(%/4)*
8hy was it important to separate these two responsibilities into separate
classes: Because each responsibility is an a&is of change. 8hen the
reJuirements change, that change will be manifest through a change in
responsibility amongst the classes. If a class assumes more than one
responsibility, then there will be more than one reason for it to change. If a
class has more then one responsibility, then the responsibilities become
coupled. 7hanges to one responsibility may impair or inhibit the classC ability
to meet the others. "his !ind of coupling leads to fragile designs that brea!
in une&pected ways when changed.
Avoid =bsolete 7omments
#et us start with =bsolete 7omments. According to Aobert 7. Hartin-
*% comment that has gotten old, irrelevant, and incorrect is obsolete
Comments get old #uickly 5t is best not to write a comment that will
become obsolete 5f you fnd an obsolete comment, it is best to update it or
get rid of it as #uickly as possible +bsolete comments tend to migrate away
from the code they once described !hey become 6oating islands of
irrelevance and misdirection in the code*
"his is topic create some interesting conversations among all level of
developers. "ry to avoid comments on individual method or short class.
Because most comments i have ever seen is trying to describe the
purposeIintentions. <ome cases comments are meaningless. Developers
writes comments to increase the readability 6 maintainability . Ha!e sure
your comments are not ma!ing any noise. It will be great if you could name a
method more meaningful instead of comments. I am suggesting because
method names are more aEective than comments. Host of the comments
are meaningless noise. #et us chec! comments below-
''ensure that we are not e&porting
''deleted products
if.product.IsDeleted 66 Qproduct.Is,&ported /
0
,&port@roducts 1 false2
9
'' !his is a for loop that prints the 7 million times
for .int i 1 (2 i 3 '((((((2 i44/
0
7onsole.8rite#ine.i/2
9
If we name the method li!e 7ancel,&port$orDeleted@roducts./ instead of
comments what will happen: <o, method names are more aEective than
comments. Hethods e&ecute and they are real. But comment is good for
some cases li!e, when visual studio will ta!e comments for creating an A@I
documentation and those comments are diEerent, you can use *III* for those
comments so that other developers can get intelligence of A@I or #ibrary.
I am not telling you that avoid comment is a must for all the times.
According to PentBs oral tradition point goes more to largeMscale comments
about how the whole thing wor!s, not to individual method comments. If
comment is trying to describe the purposeIintentions then it is wrong. If you
loo! at thic!ly commented code, you will notice that most of those
comments are there because the code is bad. @lease read the following
boo!s for further detail-
Professional Refactoring in C# and ASP.N! by Danijel Arsenovski
*Refactoring" #mpro$ing the Design of xisting Code* by Martin
Fowler, Kent Beck, John Brant, William Opdyke, don Roberts
Avoid Gnnecessary Aegions in 7lass
Aegions are a feature of L< that allow you to surround bloc!s of code. It
could be a single or multiple methods. "he region e&ists because it is easier
to navigate around the large fle. "he regions are used to hide ugly code or
class that have e&ploded in si%e . If a class does too many things it also
violates the <ingle Aesponsibility @rinciple. <o ne&t time whenever you will
thin! for adding a new region to your fle ta!e step bac! and as! that is it
possible to separate your region into a separate class.
Peep Hethod <hort
"he more lines of code in a method the harder it is to understand. ,veryone
recommends ;(M;+ lines of code is o!. But some gee!s prefer 'M'( lines for
safety, this their personal preference. "here is no hard and fast rule. ,&tract
Hethod is one of the most common refactoring. If you consider a method
that is too long or needs a comment to understand its purpose. Nou can
apply ,&tract Hethod there with little eEort. @eople always !eep as!ing on
the length for a method. But length is not the issue. 8hen you are dealing
with comple& methods, !eeping trac! of all local variables can be
complicated and timeMconsuming. 8here e&tracting a method can be a real
timeMsaver. Nou can use the Lisual <tudio e&tract method which will trac!
which variables are passed to a new method, which are returned by the
methodCs return value as output parameters.
%sing ReSharper
%sing &icrosoft 'is(al St(dio
$or more detail on each step, please navigate the H<D> lin!.
According to Reactorin!" #mprovin! the Desi!n o $%istin! &ode by
Martin Fowler' Kent Beck (&ontrib)tor*' John Brant (&ontrib)tor*'
William Opdyke' don Roberts
*)&tract 2ethod is one of the most common refactoring 5 do 5 look at a
method that is too long or look at code that needs a comment to understand
its purpose 5 then turn that fragment of code into its own method 5 prefer
short, well8named methods for several reasons 3irst, it increases the
chances that other methods can use a method when the method is fnely
grained $econd, it allows the higher8level methods to read more like a series
of comments +verriding also is easier when the methods are fnely grained
5t does take a little getting used to if you are used to seeing larger methods
%nd small methods
really work only when you have good names, so you need to pay attention to
naming 9eople sometimes ask me what length 5 look for in a method !o me
length is not the issue !he key is the semantic distance between the
method name and the method body 5f e&tracting improves clarity, do it,
even if the name is longer than the code you have e&tracted*
Avoid "oo Hany @arameters
Declare a class instead of too many parameters. 7reating a class that puts all
these parameters together. "his is generally a better design and valuable
abstraction.
7ollapse R 7opy 7ode
''avoid
public void 7hec!out.string shipping>ame, string shipping7ity,
string shipping<ate, string shippingSip, string billing>ame,
string billing7ity, string billing<ate, string billingSip/
0
9
7ollapse R 7opy 7ode
''.+
public void 7hec!out.<hippingAddress shippingAddress,BillingAddress
billingAddress/
0
9
8e should introduce class instead of all parameters.
Avoid 7omple& ,&pressions
7ollapse R 7opy 7ode
if.product.@riceT+(( 66 Qproduct.IsDeleted 66
Qproduct.Is$eatured 66 product.Is,&ported/
0
'' do something
9
7omple& e&pression have some meaning behind them it is just hidden by
those multiple e&pressions. 8e can encapsulate the comple& e&pression into
that object by using a property. "hat code will be easier to read.
7onsider 8arnings as ,rrors
If you notice the code you will fnd a variable that was declared but never
used. >ormally if we build the project we will get a warning and we can run
our project without any error. But we should remove warning as much as
possible. <o setup your build to treat warning as ,rrors li!e the following
steps-
Hinimi%e the >umber of Aeturns
Hinimi%e the number of returns in each routine. ItBs harder to understand a
routine if, reading it at the bottom, youBre unaware of the possibility that it
returned somewhere above.
Gse a return when it enhances readability. In certain routines, once you !now
the answer, you want to return it to the calling routine immediately. If the
routine is defned in such a way that it doesnBt reJuire any cleanup, not
returning immediately means that you have to write more code.
''avoid
if.product.@riceT'+/
0
return false2
9
else if.product.IsDeleted/
0
return false2
9
else if.Qproduct.Is$eatured/
0
return false2
9
else if./
0
''
9
return true2
7opy 7ode
''.+
var isLalid 1 true2
if.product.@riceT'+/
0
isLalid1 false2
9
else if.product.IsDeleted/
0
isLalid1 false2
9
else if.Qproduct.Is$eatured/
0
isLalid1 false2
9
return isLalid2
Nou can imagine U e&it points scattered around ;(M )( lines of code. "hat
ma!es you more harder to understand and see what is happening inside the
method and what will e&ecute and when will e&ecute.
I got too many responses, some agreeing but mostly disagreeing that it was
a good *standard* to enforce. "o fnd out the potentiality I did some unit
testing and found that for comple& method that have multiple e&it points
usually have a set of tests for each of those paths.
7ollapse R 7opy 7ode
if. BAD$unction./ 11 true/
0
'' e&pression
if. another$unction./ 11 true /
0
'' e&pression
return true2
9
else
0
''error
9
9
else
0
''error
9
return false2
7ollapse R 7opy 7ode
if. Q?ood$unction.//
0
'' error
return false
9
'' e&pression
if. Q?ood$unction;.//
0
''error
return false2
9
'' more e&pression
return true2
Aef. *Code Complete* by +teve Mc&onnell for further detail clarifcation.
Hove Declaration >ear Aeference
<ome programmers are used to placing temporary variable declarations at
the top of the method. But by placing the variable declaration far away from
the line where it is frst referenced, you are ma!ing code more diDcult to
read, because it is not immediately clear how the variable was initiali%ed. In
addition, declaring variables well ahead of time ma!es the method more
diDcult to refactor. If you try to e&tract a part of the method in which the
variable was referenced, you have to pass the variable as a parameter to a
newly e&tracted method, even though the declaration could possibly have
been placed inside the e&tracted bloc!.
Assertion
An assertion is code thatCs used during developmentVusually a routine or
macroVthat allows to chec! itself as it runs. "rue means everything is
operating as e&pected. $alse means it has detected an une&pected error in
the code. An assertion usually ta!es two arguments- a Boolean e&pression
that describes the assumption thatCs supposed to be true and a message to
display if it isnCt.
Assertions are especially useful in large, complicated and in high reliability
system.
,&ample- If a system assumes that there will be ma&imum '((,((( user
records, the system might contain an assertion that the number of records is
less than or eJual to '((,(((. <o assertion will be silent within that range. If
it encounters more than that records, it will loudly WassertX that there is an
error in the program.
7hec!ing #oop ,ndpoints
A single loop usually has three cases of interest- the frst case, an arbitrarily
selected middle case, and the last case. If you have any special cases that
are diEerent from the frst or last case, chec! those too. If the loop contains
comple& computations, get out your calculator and manually chec! the
calculations.
7onclusion
It is obvious to implement standards in any software company according to
organi%ational behavior, project nature, and domain. <o I would li!e to repeat
*$ind a convention and stic! with it*.
If you thin! I missed any prominent guideline, please leave that in the
comments section. ICll try to include that in the main post. 7oding $or $un.

S-ar putea să vă placă și