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++
Ad

Recommended

Pt permissão de trabalho
Pt permissão de trabalho
fabricioalvesalmeida85
 
Epi para trabalho em altura NR 35
Epi para trabalho em altura NR 35
DiegoAugusto86
 
Permissão de Trabalho - PT 0001
Permissão de Trabalho - PT 0001
IZAIAS DE SOUZA AGUIAR
 
Questionário de Consulta aosTrabalhadores Grupo Consulgal 2009
Questionário de Consulta aosTrabalhadores Grupo Consulgal 2009
Marta Silva
 
DDS ENEVA.ppt
DDS ENEVA.ppt
DavidWill25
 
Check list espaço-confinado
Check list espaço-confinado
Tst Eliana Gil
 
Trabalho a quente modulo II
Trabalho a quente modulo II
emanueltstegeon
 
0051 travamento seguran%e7a-92sld
0051 travamento seguran%e7a-92sld
Sávio Gomes
 
Nbr 12962 inspecao manut. recarga de extintores (2)
Nbr 12962 inspecao manut. recarga de extintores (2)
cristiano Santos
 
11 proteção e combate a incêndio 05102005
11 proteção e combate a incêndio 05102005
Shirlene Maciel Rafino
 
Guia para analise de risco - NR 35
Guia para analise de risco - NR 35
Fabiano Micaella
 
NR 35 - Capacitação no trabalho em altura.pptx
NR 35 - Capacitação no trabalho em altura.pptx
MelquiadesAlmeida2
 
TRABALHO EM ALTURA - Treinamento (SENAI).ppt
TRABALHO EM ALTURA - Treinamento (SENAI).ppt
PalomaRibeirodeOlive
 
Atestado brigada
Atestado brigada
condmarenmaral
 
NR34 - TRABALHO A QUENTE.pptx
NR34 - TRABALHO A QUENTE.pptx
DaniloMartinsdossant2
 
APOSTILA TRABALHO ALTURA NR 35.pdf
APOSTILA TRABALHO ALTURA NR 35.pdf
ssuser22319e
 
01 c ce-–-andaime-fachadeiro-–-manual-de-montagem
01 c ce-–-andaime-fachadeiro-–-manual-de-montagem
Janaina Xavier
 
Laminacao powerpoint 3 d3b
Laminacao powerpoint 3 d3b
Mateushis
 
Uso e Conservação EPIs NR6_2023.pptx
Uso e Conservação EPIs NR6_2023.pptx
HailtonJose1
 
NR12
NR12
Rafael Rocha
 
Capacitação Brigada de Emergência
Capacitação Brigada de Emergência
José Valfrido
 
MODELO DE TREINAMENTO NR12 VOLTADO A FRENTES DE SERVIÇO EM OBRAS
MODELO DE TREINAMENTO NR12 VOLTADO A FRENTES DE SERVIÇO EM OBRAS
Mateus Borges
 
Apresentação nr 26 sinalização de segurança
Apresentação nr 26 sinalização de segurança
João Vitor Rocha
 
Trabalho em altura FI ENGENHARIA
Trabalho em altura FI ENGENHARIA
Renan Biscaglia
 
Treinamento NR12 - Maquinas e Equipamentos Roçadeira Costal
Treinamento NR12 - Maquinas e Equipamentos Roçadeira Costal
leonardocasoconsulto
 
TREINAMENTO NR-33 ESPACO CONFINADO.pptx
TREINAMENTO NR-33 ESPACO CONFINADO.pptx
JoyceMarina2
 
Nr 12 (anexo i)
Nr 12 (anexo i)
JAIME NOVOA
 
PT - Permissão de Trabalho - Trabalho em Altura
PT - Permissão de Trabalho - Trabalho em Altura
proftstsergioetm
 
Coding standards for java
Coding standards for java
maheshm1206
 
Coding standards and guidelines
Coding standards and guidelines
brijraj_singh
 

More Related Content

What's hot (20)

Nbr 12962 inspecao manut. recarga de extintores (2)
Nbr 12962 inspecao manut. recarga de extintores (2)
cristiano Santos
 
11 proteção e combate a incêndio 05102005
11 proteção e combate a incêndio 05102005
Shirlene Maciel Rafino
 
Guia para analise de risco - NR 35
Guia para analise de risco - NR 35
Fabiano Micaella
 
NR 35 - Capacitação no trabalho em altura.pptx
NR 35 - Capacitação no trabalho em altura.pptx
MelquiadesAlmeida2
 
TRABALHO EM ALTURA - Treinamento (SENAI).ppt
TRABALHO EM ALTURA - Treinamento (SENAI).ppt
PalomaRibeirodeOlive
 
Atestado brigada
Atestado brigada
condmarenmaral
 
NR34 - TRABALHO A QUENTE.pptx
NR34 - TRABALHO A QUENTE.pptx
DaniloMartinsdossant2
 
APOSTILA TRABALHO ALTURA NR 35.pdf
APOSTILA TRABALHO ALTURA NR 35.pdf
ssuser22319e
 
01 c ce-–-andaime-fachadeiro-–-manual-de-montagem
01 c ce-–-andaime-fachadeiro-–-manual-de-montagem
Janaina Xavier
 
Laminacao powerpoint 3 d3b
Laminacao powerpoint 3 d3b
Mateushis
 
Uso e Conservação EPIs NR6_2023.pptx
Uso e Conservação EPIs NR6_2023.pptx
HailtonJose1
 
NR12
NR12
Rafael Rocha
 
Capacitação Brigada de Emergência
Capacitação Brigada de Emergência
José Valfrido
 
MODELO DE TREINAMENTO NR12 VOLTADO A FRENTES DE SERVIÇO EM OBRAS
MODELO DE TREINAMENTO NR12 VOLTADO A FRENTES DE SERVIÇO EM OBRAS
Mateus Borges
 
Apresentação nr 26 sinalização de segurança
Apresentação nr 26 sinalização de segurança
João Vitor Rocha
 
Trabalho em altura FI ENGENHARIA
Trabalho em altura FI ENGENHARIA
Renan Biscaglia
 
Treinamento NR12 - Maquinas e Equipamentos Roçadeira Costal
Treinamento NR12 - Maquinas e Equipamentos Roçadeira Costal
leonardocasoconsulto
 
TREINAMENTO NR-33 ESPACO CONFINADO.pptx
TREINAMENTO NR-33 ESPACO CONFINADO.pptx
JoyceMarina2
 
Nr 12 (anexo i)
Nr 12 (anexo i)
JAIME NOVOA
 
PT - Permissão de Trabalho - Trabalho em Altura
PT - Permissão de Trabalho - Trabalho em Altura
proftstsergioetm
 
Nbr 12962 inspecao manut. recarga de extintores (2)
Nbr 12962 inspecao manut. recarga de extintores (2)
cristiano Santos
 
11 proteção e combate a incêndio 05102005
11 proteção e combate a incêndio 05102005
Shirlene Maciel Rafino
 
Guia para analise de risco - NR 35
Guia para analise de risco - NR 35
Fabiano Micaella
 
NR 35 - Capacitação no trabalho em altura.pptx
NR 35 - Capacitação no trabalho em altura.pptx
MelquiadesAlmeida2
 
TRABALHO EM ALTURA - Treinamento (SENAI).ppt
TRABALHO EM ALTURA - Treinamento (SENAI).ppt
PalomaRibeirodeOlive
 
APOSTILA TRABALHO ALTURA NR 35.pdf
APOSTILA TRABALHO ALTURA NR 35.pdf
ssuser22319e
 
01 c ce-–-andaime-fachadeiro-–-manual-de-montagem
01 c ce-–-andaime-fachadeiro-–-manual-de-montagem
Janaina Xavier
 
Laminacao powerpoint 3 d3b
Laminacao powerpoint 3 d3b
Mateushis
 
Uso e Conservação EPIs NR6_2023.pptx
Uso e Conservação EPIs NR6_2023.pptx
HailtonJose1
 
Capacitação Brigada de Emergência
Capacitação Brigada de Emergência
José Valfrido
 
MODELO DE TREINAMENTO NR12 VOLTADO A FRENTES DE SERVIÇO EM OBRAS
MODELO DE TREINAMENTO NR12 VOLTADO A FRENTES DE SERVIÇO EM OBRAS
Mateus Borges
 
Apresentação nr 26 sinalização de segurança
Apresentação nr 26 sinalização de segurança
João Vitor Rocha
 
Trabalho em altura FI ENGENHARIA
Trabalho em altura FI ENGENHARIA
Renan Biscaglia
 
Treinamento NR12 - Maquinas e Equipamentos Roçadeira Costal
Treinamento NR12 - Maquinas e Equipamentos Roçadeira Costal
leonardocasoconsulto
 
TREINAMENTO NR-33 ESPACO CONFINADO.pptx
TREINAMENTO NR-33 ESPACO CONFINADO.pptx
JoyceMarina2
 
PT - Permissão de Trabalho - Trabalho em Altura
PT - Permissão de Trabalho - Trabalho em Altura
proftstsergioetm
 

Viewers also liked (20)

Coding standards for java
Coding standards for java
maheshm1206
 
Coding standards and guidelines
Coding standards and guidelines
brijraj_singh
 
Standards For Java Coding
Standards For Java Coding
Rahul Bhutkar
 
12 multi-threading
12 multi-threading
APU
 
Alternate concurrency models
Alternate concurrency models
Abid Khan
 
Developer Friendly API Design
Developer Friendly API Design
theamiableapi
 
Multi threading
Multi threading
Mavoori Soshmitha
 
null Bachaav Session | Secure Coding in Java
null Bachaav Session | Secure Coding in Java
n|u - The Open Security Community
 
Standards For Java Coding
Standards For Java Coding
Rahul Bhutkar
 
(Ebook resume) job interview - 101 dynamite answers to interview questions ...
(Ebook resume) job interview - 101 dynamite answers to interview questions ...
Farahaa
 
Java best practices
Java best practices
Ray Toal
 
Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014
Haim Yadid
 
Inner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVA
Tech_MX
 
Data Structures- Part7 linked lists
Data Structures- Part7 linked lists
Abdullah Al-hazmy
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)
choksheak
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data Structures
Hitendra Kumar
 
Data Structures- Part5 recursion
Data Structures- Part5 recursion
Abdullah Al-hazmy
 
Best Practices of Software Development
Best Practices of Software Development
Folio3 Software
 
Top 10 Java Interview Questions and Answers 2014
Top 10 Java Interview Questions and Answers 2014
iimjobs and hirist
 
Standard java coding convention
Standard java coding convention
Tam Thanh
 
Coding standards for java
Coding standards for java
maheshm1206
 
Coding standards and guidelines
Coding standards and guidelines
brijraj_singh
 
Standards For Java Coding
Standards For Java Coding
Rahul Bhutkar
 
12 multi-threading
12 multi-threading
APU
 
Alternate concurrency models
Alternate concurrency models
Abid Khan
 
Developer Friendly API Design
Developer Friendly API Design
theamiableapi
 
Standards For Java Coding
Standards For Java Coding
Rahul Bhutkar
 
(Ebook resume) job interview - 101 dynamite answers to interview questions ...
(Ebook resume) job interview - 101 dynamite answers to interview questions ...
Farahaa
 
Java best practices
Java best practices
Ray Toal
 
Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014
Haim Yadid
 
Inner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVA
Tech_MX
 
Data Structures- Part7 linked lists
Data Structures- Part7 linked lists
Abdullah Al-hazmy
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)
choksheak
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data Structures
Hitendra Kumar
 
Data Structures- Part5 recursion
Data Structures- Part5 recursion
Abdullah Al-hazmy
 
Best Practices of Software Development
Best Practices of Software Development
Folio3 Software
 
Top 10 Java Interview Questions and Answers 2014
Top 10 Java Interview Questions and Answers 2014
iimjobs and hirist
 
Standard java coding convention
Standard java coding convention
Tam Thanh
 
Ad

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

76829060 java-coding-conventions
76829060 java-coding-conventions
slavicp
 
Clean code
Clean code
Alvaro García Loaisa
 
What's in a name
What's in a name
Koby Fruchtnis
 
Writing Good Code
Writing Good Code
Leo Liang
 
Coding standards
Coding standards
Mimoh Ojha
 
Clean Code
Clean Code
Chris Farrell
 
UNIT I cloud computing ppt cloud ccd all about the cloud computing
UNIT I cloud computing ppt cloud ccd all about the cloud computing
vishnubala78900
 
Clean code
Clean code
Uday Pratap Singh
 
Crafting high quality code
Crafting high quality code
Allan Mangune
 
Clean code
Clean code
Henrique Smoco
 
Naming guidelines for professional programmers
Naming guidelines for professional programmers
Peter Hilton
 
Perfect Code
Perfect Code
Artem Tabalin
 
Variables
Variables
Maha Saad
 
Android course session 3 ( OOP ) part 1
Android course session 3 ( OOP ) part 1
Keroles M.Yakoub
 
Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#
Asim Rais Siddiqui
 
clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English version
saber tabatabaee
 
Lecture No 13.ppt
Lecture No 13.ppt
AhmadNaeem59
 
Clean code - DSC DYPCOE
Clean code - DSC DYPCOE
Patil Shreyas
 
Writing High Quality Code in C#
Writing High Quality Code in C#
Svetlin Nakov
 
R. herves. clean code (theme)2
R. herves. clean code (theme)2
saber tabatabaee
 
76829060 java-coding-conventions
76829060 java-coding-conventions
slavicp
 
Writing Good Code
Writing Good Code
Leo Liang
 
Coding standards
Coding standards
Mimoh Ojha
 
UNIT I cloud computing ppt cloud ccd all about the cloud computing
UNIT I cloud computing ppt cloud ccd all about the cloud computing
vishnubala78900
 
Crafting high quality code
Crafting high quality code
Allan Mangune
 
Naming guidelines for professional programmers
Naming guidelines for professional programmers
Peter Hilton
 
Android course session 3 ( OOP ) part 1
Android course session 3 ( OOP ) part 1
Keroles M.Yakoub
 
Coding Standards & Best Practices for iOS/C#
Coding Standards & Best Practices for iOS/C#
Asim Rais Siddiqui
 
clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English version
saber tabatabaee
 
Clean code - DSC DYPCOE
Clean code - DSC DYPCOE
Patil Shreyas
 
Writing High Quality Code in C#
Writing High Quality Code in C#
Svetlin Nakov
 
R. herves. clean code (theme)2
R. herves. clean code (theme)2
saber tabatabaee
 
Ad

Recently uploaded (20)

Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
 
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
Edge AI and Vision Alliance
 
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
Fwdays
 
Agentic AI for Developers and Data Scientists Build an AI Agent in 10 Lines o...
Agentic AI for Developers and Data Scientists Build an AI Agent in 10 Lines o...
All Things Open
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 
Database Benchmarking for Performance Masterclass: Session 2 - Data Modeling ...
Database Benchmarking for Performance Masterclass: Session 2 - Data Modeling ...
ScyllaDB
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
10 Key Challenges for AI within the EU Data Protection Framework.pdf
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Priyanka Aash
 
The Future of Product Management in AI ERA.pdf
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
Curietech AI in action - Accelerate MuleSoft development
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
 
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 
Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
 
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
Edge AI and Vision Alliance
 
From Manual to Auto Searching- FME in the Driver's Seat
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
Fwdays
 
Agentic AI for Developers and Data Scientists Build an AI Agent in 10 Lines o...
Agentic AI for Developers and Data Scientists Build an AI Agent in 10 Lines o...
All Things Open
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 
Database Benchmarking for Performance Masterclass: Session 2 - Data Modeling ...
Database Benchmarking for Performance Masterclass: Session 2 - Data Modeling ...
ScyllaDB
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
10 Key Challenges for AI within the EU Data Protection Framework.pdf
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Priyanka Aash
 
The Future of Product Management in AI ERA.pdf
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
Curietech AI in action - Accelerate MuleSoft development
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
 
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 

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.