SlideShare a Scribd company logo
By: Nitin Aggarwal
• 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.
Standards 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.
Standards 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().
Standards 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()
Standards 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).
Standards 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.
Standards 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.
• 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
• 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).
• 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;
• 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 */
}
• 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.
• 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){ }
}
• SQL injection attack:
• SQL injection attack:
• 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.
• 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.
• 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.
• 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.
Best Coding Practices in Java and C++

More Related Content

PPTX
Coding standards
PPS
Coding Best Practices
PDF
How to Get My Paper Accepted at Top Software Engineering Conferences
PPT
Coding Standards & Best Practices for iOS/C#
PPTX
Qt test framework
 
PDF
Best Practices in Qt Quick/QML - Part IV
 
PPTX
Coding standards and guidelines
PPTX
Best Practices in Qt Quick/QML - Part I
 
Coding standards
Coding Best Practices
How to Get My Paper Accepted at Top Software Engineering Conferences
Coding Standards & Best Practices for iOS/C#
Qt test framework
 
Best Practices in Qt Quick/QML - Part IV
 
Coding standards and guidelines
Best Practices in Qt Quick/QML - Part I
 

What's hot (20)

PDF
C# conventions & good practices
PPTX
Clean Code Principles
PDF
Javascript 교육자료 pdf
PPT
Clean Code summary
PPTX
structures in C and Union in C, enumerated datatype
PDF
7 rules of simple and maintainable code
PPT
C# basics
KEY
Clean code and Code Smells
PPTX
Kotlin Collections
PDF
Best Practices in Qt Quick/QML - Part II
 
PDF
Writing Parsers and Compilers with PLY
PDF
Java conditional statements
PDF
Writing clean code
PPTX
IELTS Listening- Table Completion - Introduction - Useful Tips
PDF
Hot C++: Rvalue References And Move Semantics
PDF
ODP
Unit testing with Qt test
PDF
Puntatori e Riferimenti
DOCX
Code review guidelines
PDF
Kata Your Way to SW Craftsmanship
C# conventions & good practices
Clean Code Principles
Javascript 교육자료 pdf
Clean Code summary
structures in C and Union in C, enumerated datatype
7 rules of simple and maintainable code
C# basics
Clean code and Code Smells
Kotlin Collections
Best Practices in Qt Quick/QML - Part II
 
Writing Parsers and Compilers with PLY
Java conditional statements
Writing clean code
IELTS Listening- Table Completion - Introduction - Useful Tips
Hot C++: Rvalue References And Move Semantics
Unit testing with Qt test
Puntatori e Riferimenti
Code review guidelines
Kata Your Way to SW Craftsmanship
Ad

Viewers also liked (20)

PPTX
Coding standards for java
PDF
Standards For Java Coding
PPT
12 multi-threading
 
PPTX
Alternate concurrency models
PPTX
Developer Friendly API Design
PPTX
Multi threading
PDF
null Bachaav Session | Secure Coding in Java
PDF
Standards For Java Coding
PDF
(Ebook resume) job interview - 101 dynamite answers to interview questions ...
PPTX
Java best practices
PDF
Concurrency and Multithreading Demistified - Reversim Summit 2014
PPTX
Inner Classes & Multi Threading in JAVA
PPT
Data Structures- Part7 linked lists
PPTX
Advanced Introduction to Java Multi-Threading - Full (chok)
PPT
Java Performance, Threading and Concurrent Data Structures
PPT
Data Structures- Part5 recursion
PPT
Best Practices of Software Development
PDF
Top 10 Java Interview Questions and Answers 2014
PDF
Standard java coding convention
PPTX
Software development best practices & coding guidelines
Coding standards for java
Standards For Java Coding
12 multi-threading
 
Alternate concurrency models
Developer Friendly API Design
Multi threading
null Bachaav Session | Secure Coding in Java
Standards For Java Coding
(Ebook resume) job interview - 101 dynamite answers to interview questions ...
Java best practices
Concurrency and Multithreading Demistified - Reversim Summit 2014
Inner Classes & Multi Threading in JAVA
Data Structures- Part7 linked lists
Advanced Introduction to Java Multi-Threading - Full (chok)
Java Performance, Threading and Concurrent Data Structures
Data Structures- Part5 recursion
Best Practices of Software Development
Top 10 Java Interview Questions and Answers 2014
Standard java coding convention
Software development best practices & coding guidelines
Ad

Similar to Best Coding Practices in Java and C++ (20)

PDF
UNIT I cloud computing ppt cloud ccd all about the cloud computing
PDF
1. Coding Conventions [Part 1]
PPTX
Introduction to C#
PPTX
gdscWorkShopJavascriptintroductions.pptx
PPT
GTU Guidelines for Project on JAVA
PPT
c-coding-standards-and-best-programming-practices.ppt
PPTX
C programming language:- Introduction to C Programming - Overview and Importa...
PPTX
Presentation 2nd
PDF
76829060 java-coding-conventions
DOCX
CodingStandardsDoc
PPTX
CLEAN CODING AND DEVOPS Final.pptx
PPT
Introduction to C
PPTX
Web technologies-course 07.pptx
PDF
C Programming - Refresher - Part IV
PDF
C programming language
PPTX
Presentation 5th
PPTX
C language updated
PPTX
C_plus_plus
PPTX
C++ Intro C++ Intro C++ Intro C++ Intro C++ Intro
UNIT I cloud computing ppt cloud ccd all about the cloud computing
1. Coding Conventions [Part 1]
Introduction to C#
gdscWorkShopJavascriptintroductions.pptx
GTU Guidelines for Project on JAVA
c-coding-standards-and-best-programming-practices.ppt
C programming language:- Introduction to C Programming - Overview and Importa...
Presentation 2nd
76829060 java-coding-conventions
CodingStandardsDoc
CLEAN CODING AND DEVOPS Final.pptx
Introduction to C
Web technologies-course 07.pptx
C Programming - Refresher - Part IV
C programming language
Presentation 5th
C language updated
C_plus_plus
C++ Intro C++ Intro C++ Intro C++ Intro C++ Intro

Recently uploaded (20)

PPT
Teaching material agriculture food technology
PDF
Unlocking AI with Model Context Protocol (MCP)
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
KodekX | Application Modernization Development
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Machine learning based COVID-19 study performance prediction
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Teaching material agriculture food technology
Unlocking AI with Model Context Protocol (MCP)
“AI and Expert System Decision Support & Business Intelligence Systems”
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Understanding_Digital_Forensics_Presentation.pptx
KodekX | Application Modernization Development
Diabetes mellitus diagnosis method based random forest with bat algorithm
Advanced methodologies resolving dimensionality complications for autism neur...
Machine learning based COVID-19 study performance prediction
The AUB Centre for AI in Media Proposal.docx
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Reach Out and Touch Someone: Haptics and Empathic Computing
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Spectral efficient network and resource selection model in 5G networks
The Rise and Fall of 3GPP – Time for a Sabbatical?
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
sap open course for s4hana steps from ECC to s4
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Programs and apps: productivity, graphics, security and other tools
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf

Best Coding Practices in Java and C++

  • 2. • 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.
  • 3. Standards 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.
  • 4. Standards 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().
  • 5. Standards 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()
  • 6. Standards 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).
  • 7. Standards 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.
  • 8. Standards 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.
  • 9. • 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
  • 10. • 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).
  • 11. • 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;
  • 12. • 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 */ }
  • 13. • 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.
  • 14. • 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){ } }
  • 15. • SQL injection attack:
  • 16. • SQL injection attack:
  • 17. • 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.
  • 18. • 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.
  • 19. • 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.
  • 20. • 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.