36
Coding Best Practices Coding Best Practices Architecture & Design Team R.Rajesh Kannan [email protected]

Coding Best Practices

Embed Size (px)

DESCRIPTION

this will explain about some coding practices and references

Citation preview

Page 1: Coding Best Practices

Coding Best PracticesCoding Best Practices

Architecture & Design Team

R.Rajesh Kannan

[email protected]

Page 2: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

2

APT – A&D

Route MapRoute Map

• Coding

• Good Code

• Common Coding Conventions

• Best Practices – What and Why?

• List Of Best Practices

• Where To Take-off?

• References

Page 3: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

3

APT – A&D

CodingCoding

• 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.

Page 4: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

4

APT – A&D

Good CodeGood Code

• 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.

• Standards(!) – Example: for loop instead of while loop for iterations.

Code is read much more often than it is written

Rajesh Kannan
Small violations on standard practices disturb the normal flow. Real example: Following traffic patterns (Keep Left) even while walking inside the buildings.
Rajesh Kannan
Aesthetic Beauty
Page 5: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

5

APT – A&D

Common Coding ConventionCommon Coding Convention

• 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

Page 6: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

6

APT – A&D

Best PracticesBest Practices

• 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.

Page 7: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

7

APT – A&D

Why Best Practices?Why Best Practices?

• 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.

Page 8: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

8

APT – A&D

1. Clarity1. Clarity

• “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: ( n << 4 – n ) – it is same as .

• 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.

( n * 15 )

Rajesh Kannan
If something is not white, it is not necessarily black. It could be green or yellow also.Structured Programming supports the law of the excluded middle. – Alan Perlis.
Page 9: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

9

APT – A&D

2. Proper Variable Usage2. Proper Variable Usage

• 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.

Page 10: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

10

APT – A&D

3. Extra Care On Variables And 3. Extra Care On Variables And MethodsMethods

• 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: Increases understanding by increasing readability.

Page 11: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

11

APT – A&D

4. Arrays And Collections4. Arrays And Collections

• 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.

Page 12: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

12

APT – A&D

5. Single Purpose Method5. Single Purpose Method

• 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.

Page 13: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

13

APT – A&D

6. Arguments…6. Arguments…

• 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”.

Page 14: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

14

APT – A&D

……ArgumentsArguments

• 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.

Page 15: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

15

APT – A&D

7. Validate Arguments7. Validate Arguments

• 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 from inside the class itself.

Page 16: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

16

APT – A&D

8. Constructors8. Constructors

• 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.

Page 17: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

17

APT – A&D

9. Proper Overloading9. Proper Overloading

• 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 as mentioned in the previous item.

• Rationale: Use overloads judiciously.

Page 18: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

18

APT – A&D

10. Proper Overriding10. Proper Overriding

• 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.

Page 19: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

19

APT – A&D

11. Minimize Statics11. Minimize Statics

• 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.

Page 20: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

20

APT – A&D

12. Garbage And Memory Leak12. Garbage And Memory Leak

• 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; otherwise, it may lead to memory leak.

Page 21: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

21

APT – A&D

13. Multicast Delegates (.NET)13. Multicast Delegates (.NET)

• 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

Page 22: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

22

APT – A&D

14. Error Handling14. Error Handling

• 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.

Page 23: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

23

APT – A&D

15. Minimize Repetition15. Minimize Repetition

• 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 require him to write a DestroyCity procedure, to which Baghdad could be given as a parameter. - [Uttered after the Gulf War but long before 9/11/01] - Nathaniel S. Borenstein.

Page 24: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

24

APT – A&D

16. Optimization16. Optimization

You're bound to be unhappy if you optimize everything – Donald Knuth.

• 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):

– Rule 1: Don't do it.

– Rule 2 (for experts only): Don't do it yet.

Rajesh Kannan
Brian W.Kernighan: Do the simplest thing that works. Choose the simplest algorithm that is likely to be fast enough, and the simplest data structure that will do the job; combine them with clean, clear code. Don't complicate them unless performance measurements show that more engineering is necessary.
Page 25: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

25

APT – A&D

17. It’s Not A Greenfield17. It’s Not A Greenfield

• 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 document it to make it even clearer.

Good code is its own best documentation.

Page 26: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

26

APT – A&D

18. What To Comment?18. What To Comment?

• 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 expected to understand this. - A comment from the source of UNIX 6th Ed, unix/slp.c, line 438”.

Page 27: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

27

APT – A&D

Where To Take-off?Where To Take-off?

• 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.

Page 28: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

28

APT – A&D

Where To Take-off?Where To Take-off?

• 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 obviously no deficiencies and the other way is to make it so complicated that there are no obvious deficiencies”.

Simplicity carried to the extreme becomes elegance – Jon Franklin

Page 29: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

29

APT – A&D

Where To Take-off?Where To Take-off?

• 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

Page 30: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

30

APT – A&D

Where To Take-off?Where To Take-off?

• 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 the scope of your logic.

Page 31: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

31

APT – A&D

Where To Take-off?Where To Take-off?

• Use standard algorithms

• Unit testing

• Refactoring

• Use Design Patterns and Idioms

Page 32: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

32

APT – A&D

ReferencesReferences

• 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

Page 33: Coding Best Practices

18th, 20th February 2008

ARCHITECTURE & DESIGN TEAM

33

APT – A&D

Some Interesting QuotesSome Interesting Quotes

• 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.

Rajesh Kannan
Excellence is an art won by training and habituation. We do not act rightly because we have virtue or excellence, but we rather have those because we have acted rightly. We are what we repeatedly do. Excellence, then, is not an act but a habit.
Page 34: Coding Best Practices

QUESTIONQUESTIONSS

COMMENTCOMMENTSS

Page 35: Coding Best Practices

TEAM TEAM WORKWORK

Page 36: Coding Best Practices

THANK THANK YOUYOU