You are on page 1of 36

Coding Best Practices

Architecture & Design Team

R.Rajesh Kannan
Rajesh.Kannan@siemens.com
Route Map
APT –
A&D
• Coding
• Good Code
• Common Coding Conventions
• Best Practices – What and Why?
• List Of Best Practices
• Where To Take-off?
• References

18th, 20th February 2008 ARCHITECTURE & DESIGN TEAM 2


Coding
APT –
A&D • Coding includes three activities:
– Finding the right algorithms that satisfy and fit the
design
– Implementation of algorithms
– Unit Testing
• The coding phase involves a group of people, so-called
programmers.
• What is the job of a good programmer? – Of course,
writing good code.

18th, 20th February 2008 ARCHITECTURE & DESIGN TEAM 3


Good Code
APT –
A&D • Good code is the one that helps in reducing mistakes
and also ensures ease of maintenance.
• Can a good programmer write good code always? – Yes
and No. Yes can often write a hundred lines of code
without making a single mistake, but not consistently,
every time, week after week, month after month.
• How often do we see that our code is not up to the
mark? Can’t we improve? Yes.
• As a first step towards achieving good code consistently,
a good programmer writes more-readable code by
following some consistent conventions. These
conventions include styles and standards.
• Style(!) – Example: break statements between different
cases of switch, placing curly braces ({ and }) at the
new line and etc. Attached Example.
Code is read much more often than it is written
• Standards(!) – Example: for loop instead of while loop for
18th, 20th February 2008
ARCHITECTURE & DESIGN TEAM 4
Common Coding Convention
APT –
A&D • Two potential problems in each individual following own
conventions:
– may lose consistency over a period of time
– may differ from that of other programmers
• Thus, a set of common conventions is required across
diversified programmers to achieve and enforce
consistency in writing code.
• How it helps: Once a consistent coding convention is
established across the entire team, it is easier for
everyone in that team to understand and maintain the
code.

Writing a maintainable code is not hard, it just takes discipline


18th, 20th February 2008 ARCHITECTURE & DESIGN TEAM 5
Best Practices
APT –
A&D
• The industry experts conducted intensive study on how
bugs were generated when code was written and
correlated these bugs to specific coding practices. They
took these correlations between bugs and coding
practices and came up with a set of rules that when used
prevented coding errors from occurring.
• These standard practices close the feedback loop
between a bug and what must be done to prevent that
bug from reoccurring.
• Best coding practices can be broken into many levels
based on the coding language, the platform, the target
environment and so forth.

Writing best code comes through learning and practice.

18th, 20th February 2008 ARCHITECTURE & DESIGN TEAM 6


Why Best Practices?
APT –
A&D
• A code moves between multiple hands during
development as well as maintenance.
• In a team environment, best coding practices ensure the
use of standards and uniform coding, reducing oversight
errors and the time spent in code review.
• There is no need to write our own rules to get the benefit
of these practices – the experts have already done most
of them for us.
• Best practices form a subset of the common coding
conventions.

Using best practices for a given situation greatly reduces the


probability of introducing errors into the applications.
18th, 20th February 2008 ARCHITECTURE & DESIGN TEAM 7
1. Clarity
APT –
A&D • “There are 10 kinds of people in this world...Those who
understand binary and those who don't.” – Anon.
• Inappropriately clever code: It is very difficult to understand
the following code: ( (nn<< 4 )– n ) – it is same as
* 15 .
• Use Natural Form For Expressions: Write expressions as you
might speak them.
– Conditional expressions that include negations are always
hard to understand: if ( !(index < minimum) && !(index >=
minimum + totalElements) ) – Each test is stated negatively
though there is no need for either to be. Let us state the
tests positively by turning the relations around: if ( (index
>= minimum) && (index < minimum + totalElements) ).
– NOT(!) logic is not always correct – It is incorrect that if a
point is not inside a rectangle, it is outside the rectangle 
it might be on the boundaries or corners of the rectangle. –
Reverse NOT logic to state conditions positively.
• “Debugging is twice as hard as writing the code in the first
place. Therefore, if you write the code as cleverly as possible,
you are, by definition, not smart enough to debug it.” – Brian
W. Kernighan.
18th, 20th February 2008 ARCHITECTURE & DESIGN TEAM 8
2. Proper Variable Usage
APT –
A&D
• Declare and initialize a new local variable rather than
reusing (reassigning) an existing one whose value
happens to no longer be used at that program point. For
example, it is very difficult to follow the code when
reusing the variable named, amount, that was holding
the amount represented in rupees to hold the amount
represented in dollars.
• Declare a local variable only at the point in the code
where its initial value is known.
• Rationale: Minimizes bad assumptions about values of
variables.
• First, declare a variable as local, then if needed, follow
this order: promote it to private member variable, then
to internal member, then to protected member, then on
to public member.
18th, 20th February 2008 ARCHITECTURE & DESIGN TEAM 9
3. Extra Care On Variables And
Methods
APT –
A&D • Avoid excessive locals – Normally, the runtime tries to keep the
local variables in the processor registers as they are the ones
used heavily and often in the local context. The variables that
cannot be kept in registers have to be kept in memory.
• Remove unused locals – Some local variables are not used at
present but left there expecting to be used later. Such unused
local variables may tempt some other programmer to use it for
unintended purposes.
• Review unused arguments – The client spends much time
unnecessarily in understanding such arguments.
• Remove unused private member variables – They waste the
precious memory space allotted for an object.
• Remove unused methods – The unused methods waste the
precious time of the reader of the code, if not the processor
and compiler time.
• No unnecessary mutators (set) and accessors (get) that expose
the inner details.
• Rationale:
18th, 20th February Increases
2008 understanding
ARCHITECTURE & DESIGNby increasing
TEAM readability. 10
4. Arrays And Collections
APT –
A&D
• Avoid using multi-dimensional arrays – Multi-dimensional
arrays indicate that our OO design is wrong – instead use
single-dimensional array of instances of a collection
class that packs the columns. For example, how about
this three-dimensional array: int chessPosition [ player ]
[ row ] [column ]. It can be replaced as Players [ player ].
Rows [ row ].Columns [ column ] where Players, Rows
and Columns represent the collections.
• Especially replace the jagged arrays with the collection
classes. Attached Example.
• Prefer arrays over array lists and array lists over hash
tables if possible and appropriate.
• Use generic collections as much as possible.

18th, 20th February 2008 ARCHITECTURE & DESIGN TEAM 11


5. Single Purpose Method
APT –
A&D
• Write methods that do only “one thing”. In particular,
separate out methods that change object state from
those that just rely upon it. For example in the Stack
class, prefer having two methods, Object Top ( ) and
void RemoveTop ( ), versus the single method, Object
Pop( ), that does both.
• Keep the methods short – because
– they are easier to understand – A complex algorithm
can be easily understood if it is broken into small
pieces with descriptive names.
– the clients can use our method in beautiful ways than
expected in combination with other methods.
• Multiple exit points – Try to return from a method as
soon as possible.
18th, 20th February 2008 ARCHITECTURE & DESIGN TEAM 12
6. Arguments…
APT –
A&D
• Avoid side-effects: Try to pass value type arguments to
avoid changing the value of the reference type
arguments inside the called method.
• Order of arguments: Align with standard conventions like
– DrawRectangle ( int x1, int y1, int x2, int y2 ) instead
of
– DrawRectangle ( int y1, int x1, int y2, int x2 )
• Avoid long method signature: Avoid declaring methods
with more number of (for example, more than 7)
arguments. Instead consider passing a struct or class
comprising few of the related arguments.
– Alan Perlis: “If you have a procedure with ten
parameters, you probably missed some”.

18th, 20th February 2008 ARCHITECTURE & DESIGN TEAM 13


…Arguments
APT –
A&D
• Normally, boolean arguments indicate two different
control paths to represent two entirely different
scenarios or behaviors.
• Different scenarios: Try having two different methods
one for assertive and another for negative value. For
example, instead of having a single method named
Compare that accepts a boolean argument named
isCaseSensitive, try having two methods as: Compare
and CompareCaseInsensitive.
• Different behaviors: Try having two different subclasses.
Prefer polymorphism over if or switch…case to
encapsulate and delegate complex operations. But, don’t
overuse this idea as subclasses increase coupling.

It is the user who should parameterize procedures, not their


creators – Alan Perlis.
18th, 20th February 2008 ARCHITECTURE & DESIGN TEAM 14
7. Validate Arguments
APT –
A&D
• The first lines of a public method are usually devoted to
checking the validity of the arguments – Throw an
exception if the validation fails.
• The idea is to fail as quickly as possible in the event of
an error – the public methods are the entry points into
the system. Once the data is validated at its entry point
itself, then it can safely roam inside the system.
• Moreover, if some fault occurs inside our system at a
later stage, it is guaranteed that the data is corrupted
inside our system only.
• This validation is particularly important for constructors –
The constructor validates its arguments before doing
anything else.
• Validating arguments of private methods is not
mandatory – Reason: private methods can only be called
18th, 20th February 2008 ARCHITECTURE & DESIGN TEAM 15
8. Constructors
APT –
A&D
• Use constructor parameters as shortcuts for setting main
properties.
• Do minimal work in the constructor. Constructors should
not do much work other than to capture the constructor
parameters. The cost of any other processing should be
delayed until required.
• Throw exceptions from instance constructors only if
appropriate.
• Do not call overridable methods in constructors – Calling
a virtual method causes the most-derived override to be
called regardless of whether the constructor for the type
that defines the most-derived override has been called.
Attached Example.

18th, 20th February 2008 ARCHITECTURE & DESIGN TEAM 16


9. Proper Overloading
APT –
A&D • Better overload methods on the number of arguments
than on their type.
• Keep the order of the arguments same. For example,
two overloads:
– void DrawRectangle (int x1, int y1, int x2, int y2)
– void DrawRectangle (int x1, int y1, int width, int
height)
• C++ Sweetener: Is there any problem between the
following two?
– void Display ( )
– void Display ( int number = 0 )
• A long list of overloads of a method irritates a client –
Change method names to meet the parameter list like
we can avoid boolean arguments without any confusion
18th,as mentioned
20th February 2008 inARCHITECTURE
the previous item.
& DESIGN TEAM 17
10. Proper Overriding
APT –
A&D
• The names of the arguments in the derived class overridden
declaration should match that of the base class declaration.
• On overriding a method in derived class, it is important to
check whether the overridden base class version should be
called:
– Normally, derived class version provides entirely a different
behavior for the same responsibility – do not call the base
class version in such cases.
– Call the base class version if the base class mandates it – if
the derived class version does not call the base class
version in this case, it results in undefined behavior.
• Scott Meyers: “A non-virtual function says, you have to do this
and you must do it this way. A virtual function says you have to
do this, but you don't have to do it this way. That's their
fundamental difference”.
• Rationale: Avoids inconsistent behaviors.
18th, 20th February 2008 ARCHITECTURE & DESIGN TEAM 18
11. Minimize Statics
APT –
A&D
• Static variables play the equivalent role like global
variables in non-OO languages.
• Static methods remind the past glory of procedural-
oriented programming and they are not for object-
oriented programming. Except in Singletons, avoid static
methods.
• Neither static variables nor methods are overridable in
subclasses.
• Avoid static arrays – as they live long.
• Rationale: Static variables make methods more context-
dependent (they are not extensible to other contexts as
they are not overriddable), hide possible side-effects,
sometimes present synchronized access problems and
are the source of fragile, non-extensible constructions.
18th, 20th February 2008 ARCHITECTURE & DESIGN TEAM 19
12. Garbage And Memory Leak
APT –
A&D • Surprising to hear about garbage and memory leak in
Automatic Garbage Collection environments. Let us see.
• Garbage – objects that no longer needed that hold
memory.
• Garbage collection – an activity for recycling garbage.
• Memory leak – unwanted collection of references to
objects that prevents them from garbage collection. It
causes the program to gradually increase its memory
demands over time.
• Even with automatic garbage collection, we can fill up all
memory with garbage – A classic mistake is to use a
hash table as a cache and forget to remove the
references in the hash table. Since the reference
remains, the referent is non-collectible but useless. This
is called a logical memory leak.
• Take extra care on using arrays and collections;
18th, 20th February 2008
ARCHITECTURE & DESIGN TEAM 20
13. Multicast Delegates (.NET)
APT –
A&D
• A multicast delegate is derived from
System.MulticastDelegate.
• A multicast delegate can wrap up more than one method
– It internally uses an linked list, known as invocation
list, to store references to all these methods.
• Invoking these delegates result in all encapsulated
methods being invoked.
• For this reason, the return type should be void –
Otherwise, only the return value of the last method will
be used.
• The clients might not be determined about which return
value should be used at the time of invocation as the
returned value of the last method only is returned.
Attached Example
18th, 20th February 2008 ARCHITECTURE & DESIGN TEAM 21
14. Error Handling
APT –
A&D
• We should check for everything possible, of course
except:
– if (null == this).
• Throw exceptions instead of returning error values from
a method – it’s the opposite of “Don’t use exception for
control flow”.
• When an exception occurs, it is important to pass all the
relevant data to the constructor of the exception. This
data is often critical to understand and solve the
problem.
• We should not throw an exception from a method if the
end-user directly uses it. We should throw the exception
in all other cases.
• Avoid empty catch blocks.
18th, 20th February 2008 ARCHITECTURE & DESIGN TEAM 22
15. Minimize Repetition
APT –
A&D • A principle that helps to keep consequences local –
Changing one copy of the code brings a dilemma on
whether or not to change all the other copies when we
have the same code in several places. The change is no
more local – The more copies of the code, the more a
change will cost.
• Example forms of repetition and how to avoid them:
– Copied code – break programs up into many small
pieces (small statements, small methods, small
objects, small modules) – large pieces of logic tend to
duplicate parts of other large pieces of logic.
– Parallel class hierarchies – Restructure class
hierarchies.
• It should be noted that no ethically-trained software
engineer would ever consent to write a DestroyBaghdad
procedure. Basic professional ethics would instead
18th,require him
20th February 2008 to ARCHITECTURE
write a DestroyCity
& DESIGN TEAMprocedure, to which
23
16. Optimization
APT –
A&D • Profile the application first to identify the bottlenecks
and optimize only these bottlenecks. Bottleneck – a
constriction that limits performance.
• Inside loops – Avoid concatenating strings, Avoid
creating or cloning objects, Avoid casting data types, try
to fold constants.
• Minimize number of access to data.
• Avoid introducing complexity in the name of
optimization. For example, complex search algorithms
for searching less than 10 items. (!)
• Premature optimization is the root of all evil – Donald
Knuth.
• Rules of Optimization (by M.A. Jackson):
You're bound to be unhappy if you optimize everything – Donald
– Rule 1: Don't do it. Knuth.
18th, 20th February 2008 ARCHITECTURE & DESIGN TEAM 24
17. It’s Not A Greenfield
APT –
A&D • Avoid excessive comments. Surprising! Reason: On
effecting changes to a section of code, it is necessary to
make adjustments to the associated comments as well.
– “If the code and the comments disagree, then both
are probably wrong” – Norm Schryer.
– “Incorrect documentation is often worse than no
documentation” – Bertrand Meyer.
• Comment out a section of code only if there was a
specific purpose and add comments indicating the
reason why it is commented out. If the code has to be
removed for good, then remove it don't just comment it
out. Attached Example.
• Steve McConnell: As you're about to add a comment, ask
yourself, 'How can I improve the code so that this
comment isn't needed?' Improve the code and then
Good code is its own best documentation.
document it to make it even clearer.
18th, 20th February 2008 ARCHITECTURE & DESIGN TEAM 25
18. What To Comment?
APT –
A&D
• Add comments to clarify non-obvious code, don't bother
commenting obvious code – Remember that the thing
seems to be obvious to us mayn’t be so to others.
• Write the logic or pseudo-code of complex or
nonstandard algorithms.
• Place comments on a variable declaration explaining its
bounds (or legal values), its units of measure, how it is
used and etc.
• Place comments at the top of each function and class
describing the purpose, parameters and internals.
• Document the reason if the return value of a called
method is ignored.
• Comments should clearly state the intention of the
things. Example for a bad comment: “You are not
18th,expected to understand
20th February 2008 this.
ARCHITECTURE & DESIGN- TEAM
A comment from the
26
Where To Take-off?
APT –
A&D
• We can write readable and thus less error-prone code by
spending some little extra care while coding.
• Ask yourself “Am I making it take longer for someone to
understand my code, or am I making it just take longer
to deliver the code?”
• Avoid shortcuts – A good thumb-rule is that if it saves
time to write it at the first time, it is going to take longer
to maintain.
– The shortcut assumes several details (like “well,
everything I need this for fits within those
parameters”). So we go ahead and use the shortcut.
Then the client wants one small feature added.
Suddenly that shortcut no longer works and we have
to rewrite that whole section without the shortcut.

18th, 20th February 2008 ARCHITECTURE & DESIGN TEAM 27


Where To Take-off?
APT –
A&D
• Be a minimalist – Write compact, elegant code.
• Simplicity – means that we don’t do in ten lines what we
can do in five. It means that we make extra effort to be
concise or compact, but not to the point of obfuscation.
Attached Example.
• Simplicity does not precede complexity, but follows it –
Alan Perlis.
• The best programmers simply do not use a solution that
is not elegant. For example, using recursion if possible
instead of using subroutine that includes a while loop.
Recursion increases readability.
• C.A.R. Hoare: “There are two ways of constructing a
software design: one way is to make it so simple that
there are
Simplicity obviously
carried no deficiencies
to the extreme becomes and the other
elegance way is
– Jon Franklin
to make it so complicated that there are no obvious
18th, 20th February 2008 ARCHITECTURE & DESIGN TEAM 28
Where To Take-off?
APT –
A&D
• Source Code Formatting – clear and consistent – uniform
indentation, surrounding operators with blank-spaces,
using // instead of /*…*/ for comments and etc.
– Main reason to format the code is to make the code
easier to read at a glance.
• Habit Of Good Style:
– If we think about style as we write the code originally
and if we take the time to revise and improve it, we
will develop good habits.
– Once they become automatic, our subconscious will
take care of many of the details for us, and even the
code we produce under pressure will be better.

Style distinguishes excellence from accomplishment – James Coplien


18th, 20th February 2008 ARCHITECTURE & DESIGN TEAM 29
Where To Take-off?
APT –
A&D • Discuss programming techniques and let other
programmers see your code.
– Nothing but good only will come out from
programmers getting together to resolve an issue or
develop a solution.
– The more code you see from other people, the better
programmer you become.
– The more times your code is reviewed by other
programmers, the better you will become.
– Even if the other programmer is some fresher who
wants to tell you what he/she thinks of your code,
listen to him/her and you will learn.
– The basic thing is that you don't have to agree with
everything anyone says and you won't necessarily
change your code, but listening to others opinions will
help you broaden
18th, 20th February 2008
the scope of your logic.
ARCHITECTURE & DESIGN TEAM 30
Where To Take-off?
APT –
A&D
• Use standard algorithms
• Unit testing
• Refactoring
• Use Design Patterns and Idioms

18th, 20th February 2008 ARCHITECTURE & DESIGN TEAM 31


References
APT –
A&D
• Code Complete – Steve McConnell
• Writing Solid Code – Steve Maguire
• The Practice of Programming – Brian W. Kernighan and
Rob Pike
• The Pragmatic Programmer: From Journeyman To Master
– Andrew Hunt and David Thomas
• Effective series books
• Refactoring – Martin Fowler
• The Design and Evolution of C++ – Bjourne Stroustrup
• Of course, Design Patterns by GoF

18th, 20th February 2008 ARCHITECTURE & DESIGN TEAM 32


Some Interesting Quotes
APT –
A&D • The skill of writing is to create a context in which other
people can think – Edwin Schlossberg
• Inspiration comes from the act of writing – Steven Dunn.
• Someone who does something bad requires education,
not punishment – Plato.
• Never discourage anyone...who continually makes
progress, no matter how slow – Plato.
• Pleasure in the job puts perfection in the work. –
Aristotle.
• (!)We are what we repeatedly do – Aristotle.
• If you give someone a program, you will frustrate them
for a day; if you teach them how to program, you will
frustrate them for a lifetime – Anonymous.

18th, 20th February 2008 ARCHITECTURE & DESIGN TEAM 33


QUESTIONS
COMMENTS
TEAM
WORK
THANK
YOU

You might also like