21
BEST CODING PRACTICES JAVA & C++ By: Nitin Aggarwal

Best Coding Practices in Java and C++

Embed Size (px)

DESCRIPTION

Best Coding practices followed in Java and C++

Citation preview

Page 1: Best Coding Practices in Java and C++

BEST CODING PRACTICESJAVA & C++

By: Nitin Aggarwal

Page 2: Best Coding Practices in Java and C++

AGENDA OF TRAINING• Guidelines regarding naming conventions:

• Standards for naming variables.• Standards for naming member functions.• Standards for local variables.• Standards for naming method arguments.• Standards for classes, interfaces and packages.

• Guidelines related to code documentation, comments and indentation.

• Common coding errors (C++) and how to avoid them.

• General security loopholes in code and tips to avoid them.

• Some best coding practices to follow in java.

Page 3: Best Coding Practices in Java and C++

Guidelines regarding naming conventionsStandards for naming variables:• Use full English descriptors that accurately describe

the variable/field/class/interface, for example:• use names like firstName, grandTotal, or CorporateCustomer.

• Use terminology applicable to the domain like If the users of the system refer to their clients as Customer, then use the term Customer for the class, not client.

• Use mixed case to make names readable.• Use abbreviations sparingly, but if you do so then

use then intelligently and document it, for example:• to use a short form for the word “number”, choose one of nbr,

no or num.

• Avoid long names (<15 characters is a good tradeoff).

• Avoid names that are similar or differ only in case.

Page 4: Best Coding Practices in Java and C++

Guidelines regarding naming conventionsStandards for naming member function:• Member functions should be named using a full

English description, using mixed case with the first letter of any non-initial word capitalized. The first word of the member function should be a verb, for example:• openAccount(), printMailingList(), save() etc.

• Naming accessor member functions:• Getters: member functions that return the value of a

field / attribute / property of an object.• Use prefix “get” to the name of the field / attribute /

property if the field in not boolean, for example getFirstName().

• Use prefix “is” to the name of the field / attribute / property if the field is Boolean, for example isAvailable().

• A viable alternative is to use the prefix ‘has’ or ‘can’ instead of ‘is’ for boolean getters, for example canConsume().

Page 5: Best Coding Practices in Java and C++

Guidelines regarding naming conventionsStandards for naming member function (contd..):• Naming accessor member functions:

• Setters: member functions that modify the values of a field.• Use prefix ‘set’ to the name of the field, for example:

setFirstName()setLongCode()setMACAddr()

Page 6: Best Coding Practices in Java and C++

Guidelines regarding naming conventionsStandards for naming local variables:• Naming local variables: Use full English descriptors

with the first letter of any non-initial word in uppercase, for example tempCounter.

• Naming streams: When there is a single input and/or output stream being opened, used, and then closed within a member function the convention is to use in and out for the names of these streams, respectively. For example:

FileInputStream fileIn = new FileInputStream();FileOutputStream fileOut = new FileOutputStream();

• Naming loop counter: A common way is to use words like loopCounters or simply counter because it helps facilitate the search for the counters in the program. i, j, k can also be used as loop counters but the disadvantage is that search for i ,j and k in the code will result in many hits.

• Naming exception objects: Use letter ‘e’ for generic exception, for example Catch (Exception e).

Page 7: Best Coding Practices in Java and C++

Guidelines regarding naming conventionsStandards for naming method arguements:• Naming parameters: Parameters should be

named following the exact same conventions as for local variable. Name parameters the same as their corresponding fields (if any).

• Example: If Account has an attribute called balance and you needed to pass a parameter representing a new value for it the parameter would be called balance. The field would be referred to as this.balance in the code and the parameter would be referred as balance.

Page 8: Best Coding Practices in Java and C++

Guidelines regarding naming conventionsStandards for classes, interfaces and packages:• Naming classes: Use full English descriptor starting with the

first letter capitalized using mixed case for the rest of the name, for example class InterestCalculator.

• Ordering member functions and fields: The order should as:

• Constructors.• Private fields.• Public member functions.• Protected member functions.• Private member functions.• finalize().

• Naming interfaces: Name interfaces using mixed case with the first letter of each word capitalized. Prefix the letter “I” or “Ifc” to the interface name, for example interface IThirdPartyReqHandler.

• Naming packages: Packages names should begin with an identifier that is not all upper case, for example safeword.jdbc.sql. Package name must be defined logically depending on the type of class it holds.

Page 9: Best Coding Practices in Java and C++

Code documentation, comments and indentation• Comment should add to clarity of code. Avoid

decoration like comments.• Document why something is being done not just

what.Comment Type Usage Example

Documentation Starts with /** and ends with */

Used before declarations of interfaces, classes, member functions, and fields to document them.

/** * Customer – a person or * organization */

C style Starts with /* and ends with */

Used to document out lines of code that are no longer applicable. It is helpful in debugging. 

/* This code was commented out by Ashish Sarin*/ 

Single line Starts with // and go until the end of the line

Used internally within member functions to document business logic, sections of code, and declarations of temporary variables.

// If the amount is greater // than 10 multiply by 100

Page 10: Best Coding Practices in Java and C++

Code documentation, comments and indentation• Documentation related to member functions:

• What and why the member function does than just what it does.

• What member function must be passed as parameters.• What a member function returns.• Known bugs.• Any exception that a member function throws.• Visibility decisions (if questionable by other developers).• Applicable pre conditions and post conditions under which

the function will work properly. These are the assumptions made during writing of the function.

• Explanation of why keeping a function synchronized must be documented.

• Use C style comments to document out lines of unneeded code (within member function).

• Use single-line comments for business logic (within member function).

Page 11: Best Coding Practices in Java and C++

Code documentation, comments and indentation• Indentation:

• Four spaces should be used as the unit of indentation or in eclipse IDE, use shortcut ctrl+I to indent complete code in one go.

• When an expression will not fit on a single line, break it according to these general principles:• Break after a comma.• Break before an operator.• Prefer higher-level breaks to lower-level breaks.• Example:

longName1 = longName2 * (longName3 + longName4 - longName5) + 4 * longname6; // PREFER

 longName1 = longName2 * (longName3 + longName4 - longName5) + 4 * longname6; // AVOID

• One declaration per line is recommended since it encourages commenting. In other words,int level;int size; Is preferred over int level, size;

Page 12: Best Coding Practices in Java and C++

Common coding error (C++) & their remedial• Memory leak: Memory that is not freed when no longer needed.

• Example:{

Char *output;If(s>0)

Output=(char*) malloc (size)If(s==1)

Return NULL /* if s==1 then mem leaked */Return (output);

}• Trying to free memory that no longer exists.

• Example:main(){

char *str;Str=(char *)malloc(10);If(global==0)

free(str);Free(str); /* str is already freed */

}

Page 13: Best Coding Practices in Java and C++

Common coding error (C++) & their remedial• NULL dereferencing: Trying to access an object

which is pointing to NULL.• Example:

if (x>0){

ch=‘c’;}printf(“\%c”. *ch); /* ch may be NULL */*ch=malloc(size)ch=‘c’; /* ch will be NULL if malloc returns NULL */

• Lack of unique addresses: Aliasing creates many problems among them is violation of unique addresses when we expect different addresses.• e.g in the string concatenation function, we expect source

and destination addresses to be different.• strcat (src , destn ); if src and destn are same then runtime

exeception will be thrown.

Page 14: Best Coding Practices in Java and C++

Common coding error (C++) & their remedial• Synchronization error: When multiple threads tries

to acccess some common resources then deadlock may happen:• Example:

Thread 1:synchronized (A){synchronized (B){ }}Thread 2:synchronized (B){synchronized (C){ }}Thread 3:synchronized (C){synchronized (A){ }}

Page 15: Best Coding Practices in Java and C++

Security loopholes in code and way to avoid them• SQL injection attack:

Page 16: Best Coding Practices in Java and C++

Security loopholes in code and way to avoid them• SQL injection attack:

Page 17: Best Coding Practices in Java and C++

Security loopholes in code and way to avoid them• SQL injection attack: Use parameterized sql queries

to avoid SQL injection attack.

• Expose of confidential information: Never print fileNotFoundException messages to console or log file or user prompt because these exceptions may show the exact path where file is present/what’s the file name and attacker may use this information for some malicious activities.

Page 18: Best Coding Practices in Java and C++

Security loopholes in code and way to avoid them• Cross site scripting: Attacks involving embedding

some malicious information and special characters in URLs and getting unauthorized information. To avoid this, always use url.encode method to encode the url and decode method to decode url and then use it.

• Disable HTML rendering in swing components: Sometimes any adversar may inject some false information in html tag and display it on swing components. To avoid this always disable html in swing by calling html.disable client property. For example, label.putClientProperty("html.disable", true)

• Always validate user input at server side and not on client side, as some malicious programs may bypass client and directly call server side application.

Page 19: Best Coding Practices in Java and C++

Best Java coding practices to use• Always use finally block with try-catch clause to ensure code

execution.• Example:

try{}catch(Exception e){}finally{}

• Replace Hashtable and Vector with Hashmap, ArrayList and LinkedList.

• Use stringbuffer instead of stringbuilder and string concatenation.

• Use lazy initialization to defer creation of objects until they are required.

Page 20: Best Coding Practices in Java and C++

Best Java coding practices to use• Always close DB resources in finally block in following

order to avoid connection leak:• Connection open• Statement open• Resultset open (if required)• Resultset closed (if opened)• Statement closed• Connection closed

• Always set session timeouts to kill idle sessions and avoid any security breach.

• Always do session.invalidate() before calling session.close() to avoid security breach.

• Always use string.length()==0 instead of string.equals(Null) to check null string.

Page 21: Best Coding Practices in Java and C++

ThanksAny Questions?