Coding Practices. Why do we care? Good code is more than just functionality Other people will read...

Post on 16-Dec-2015

213 views 1 download

Transcript of Coding Practices. Why do we care? Good code is more than just functionality Other people will read...

Coding Practices

Why do we care?

• Good code is more than just functionality

• Other people will read your code

• You will forget what you code does

• Debugging bad code is time consuming and frustrating

Basic Coding Practices

• Use meaningful names

• Don’t duplicate code

• Don’t reinvent the wheel

• Use comments effectively

• Test early and often

• Code maintenance

Names

• Give functions and variables meaningful names

• Bad names include ‘temp’, ‘integer1’, ‘l’

int l = 6;if (1 == 6) { print(“true”);}else { print(“false”);}

What is the output from this piece of code?

Names

• Give functions and variables meaningful names

• Bad names include ‘temp’, ‘integer1’, ‘l’

int l = 6;if (1 == 6) { print(“true”);}else { print(“false”);}

What is the output from this piece of code?

Output is “false”. The variable in line 1 is a lower case L. In some fonts this is confused with the character for the number one, as found on the second line.

Names

int func1(int a, int b)

{

if (a < 24 && b < 60)

return 1;

else

return 0;

}

• Bad names make code hard to read and understand

What does this code do?

Names

int func1(int a, int b)

{

if (a < 24 && b < 60)

return 1;

else

return 0;

}

• Bad names make code hard to read and understand

int validateTime(int hours, int minutes)

{

if (hours < 24 && minutes < 60)

return 1;

else

return 0;

}

What does this code do? How about this code?

Code Duplication

• Duplicated code adds confusion

• Duplicated code leads to more bugs

• Replace duplicated code with functions

Reinventing the Wheel

• The “I can do it better trap”

• Read and understand support code, especially so called “helper” functions

• Explore the standard librariese.g. www.cppreference.com

Comments

• Comments help the reader understand the code

• Bad comments include:– repeating what the code does– lengthy explanations of badly written code

Comments

• Good comments include:– summarizing blocks of code – describing the programmers intent– identifying logical divisions in the code– identifying unconventional methods

Testing

• Test early and often – don’t write everything and the start testing

• Identify separate components that can be tested individually – Code in Blocks

• If necessary write your own test cases, but start small

• Test user inputs (and function inputs)

Code Maintenance

• Periodically backup your work

• Every time you get a particular feature to work, save a copy of your files

• More advanced source control – RCS or CVS