CodingStandard
CodingStandard
o Is easy to understand.
o Can be tested.
Testing alone cannot ensure good code quality as testing will never find every error in the
code.
Need to measure the quality and then take steps to improve it.
Coding Standards
The earlier the defects are detected, the easier and faster it is to resolve them.
CODE REVIEWS
Code Review is a phase of the software development process in which the authors of the
code use a system of review to examine the source code.
The code is usually reviewed by another programmer who inspects the code for mistakes,
irregular formatting, or inconsistencies with the system requirements that may create larger
issues during the integration process.
Code review is the most commonly used procedure for validating the design and
implementation of features.
It creates consistent code and enables better QA testing and seamless software integration.
By diminishing mistakes and fixing errors earlier at the review stage, programmers become
more efficient in designing customized solutions in line with the specifications to the client.
Code issues
Quality of documentation
Peer review
Feature Completion
Consistency
Performance
Exception Handling
Simplicity
External review
Focuses on how to enhance code quality, promote best practices, and remove “code
smells.”
Coding Style
Code Smells
It limits risks
It is important to understand that asking for a code review is not a sign of weakness or
something negative and one should always be open and positive feedback.
Static code analysis is a set of algorithms and techniques used to analyze source code in
order to automatically find potential errors or poor coding practices.
Static code analysis, also commonly known as “white-box” testing, tests applications in non-
runtime environments. It is a proven technique which covers entire codebase and identifies
all the vulnerabilities.
Static analysis tools Checkstyle, PMD, and Sonarqube are well-known and commonly used in
the projects.
SonarQube
It is implemented in Java language and can analyze the code of about 20 different
programming languages, including c/c++, PL/SQL, Cobol etc through plugins. More than 50
plugins are available which extend the functionality of SonarQube.
SonarQube can inspect and evaluate anything that affects code base, from minor styling
details to critical design errors. Hence, it is a great aid to software application developers in
identifying the issues and their impact.
SonarQube is in no way competing with any of the above static analysis tools, but rather it
complements and works very well with these tools. In fact, it ceases to work if these static
analysis tools (Checkstyle, PMD, and FindBugs) do not exist.
SonarQube’s offerings span what its creators call the Seven Axes of Quality:
Unit tests
Duplicated code
Potential bugs
Complex code
Coding standards
Comments
Code Smell:
It is basically an indicator of something fishy in the code – “a hint that something has gone
wrong somewhere in your code. Use the smell to track down the problem.”
Technical Debt:
It describes the estimated effort to fix to fix all the maintainability Issues / code smells. It is a
programming concept that reflects the extra development work, which has to be done if
long-term and best solutions are not sought, and things are implemented keeping the ease
in mind, for short term.
Code coverage:
It is a measure which describes the degree of which the source code of the program has
been tested. It is one form of white box testing which finds the areas of the program not
exercised by a set of test cases.
Test coverage:
Code Bugs:
A problem or an issue that shows that something is wrong in the code. It might not break
the code right away, but surely will, and may be at the moment when its impact is huge. It
has to be fixed.
Vulnerabilities:
It is a cyber-security term that refers to a flaw or loophole in the system that makes it
vulnerable to attack. A vulnerability may also refer to any type of weakness in a set of
procedures, or in anything that leaves information security exposed to a threat.
SONARQUBE
SonarQube Integration is an open source static code analysis tool that has become quite
popular in recent times. It can integrate with your existing workflow to enable continuous
code inspection across your project branches and pull requests.
Everything right from minor styling details to critical design errors, is inspected and
evaluated by SonarQube, thereby enabling developers to access and track code analysis data
continuously, ranging from styling errors, potential bugs, and code defects to design
inefficiencies, code duplication, lack of test coverage, and excess complexity.
The Sonar platform analyzes source code from different aspects and drills down to your code
layer by layer, moving from the module level down to the class level, giving metric values
and statistics, revealing issues in the source code at each level, that need to be addressed.
Your project home page tells you where you stand in terms of quality in a glimpse of an eye.
It you an immediate sense of what you have achieved till now and the project status.
Features:
Overall Health – Discovered issues can either be Unreachable source code, a Bug,
Vulnerability, Code Smell, Coverage or Duplication. Each category has a corresponding
number of issues. Dashboard page shows where you stand in terms of quality in a glimpse of
an eye.
Enforce Quality gate – To fully enforce a code quality practice across all teams, you need to
set up a Quality Gate which is a set of standard conditions the project must meet before it
can be released to production.
Issue Resolution – There are five different severity levels of Issues like blocker, critical,
major, minor and info. Also, the issues tab has different filter criteria like category, severity
level, tag(s), and the calculated time required for the issue rectification.
SonarQube automatically detects the project language and run corresponding code analyzer
for each language.
Shared rulesets
SonarQube provides the facility to create your own quality profiles and define Sonar Rules
shareable across different projects.
A blocker might be an issue or bug which you have come across during development or
testing and which is not allowing you to develop or test further. Blockers are also known as
impediments in Scrum, and issues in more traditional project management approaches.
Quality Gates
A quality gate is the best way to enforce a quality policy in your company.
They are basically a set of conditions that the project must meet before it can be delivered
to production.
You can define as many quality gates as you wish to, depending on the project need.
All projects may not be verified against the same quality gate, as it’s not practical that the
threshold measures would be the same for all projects.
The encapsulation is compromised here as anyone can change these values like this,
Using private access modifier with class members keeps the fields hidden preventing a user
to change the data except for setter methods.
Here is another example using private access modifier:
Generally, it won’t make any difference to use either of them but in some cases, the counter
variable used could be very error-prone.
The counter variable can incidentally get altered, it may get used later in the code or you may
start the index from 1 instead of 0 which will result in disturbing the code at multiple points.
Consider the following code snippet:
Here variable “I” is used as a counter for a loop as well as the index for the array names. It
can get problematic later in the code so We can avoid the potential problems by using an
enhanced for loop like shown below:
This line is free of any error, but if either the object “office” or method” listEmployees()” is Null
then the code will throw a null pointer exception.
Null pointer exceptions are inevitable but for its better handling, there are some java coding
best practices to follow.
First, it is important to check Nulls prior execution so that they can be eliminated and alter your
code to handle it well.
A corrected version of code is show below,
Proper Commenting
As your code will be read by various people with varying knowledge of Java,
Proper comments should be used to give overviews of your code and provide additional
information that cannot be perceived from the code itself.
Comments are supposed to describe the working of your code to be read by Quality
assurance engineer, tester or maintenance staff who might not have Java skills
Neglecting NullPointerException
Bypassing Exceptions
Solution#1
We can collect all objects which are candidate for removal in a
separate collection. Then remove them from another loop. But this
method requires one additional collection for collecting the items.
List<Invoice> invoicesForRemoval = new LinkedList<>();
for (Invoice invoice : invoices) {
if (invoice.getInvoiceAmount() >= 100.0) {
invoicesForRemoval.add(invoice);
}
}
for (Invoice invoice : invoicesForRemoval) {
invoices.remove(invoice);
}
Solution#2
We can use iterator() method of the collection to make it more
concise as below:
int index = 0;
switch (index) {
case 0:
System.out.println("Sunday");
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
default:
System.out.println("Not a Day Of Week");
}
Common Standards/Conventions
Below are some common conventions that are important to discuss
under the topic ‘Java Coding Best Practices and Standards’:
/*
* Author
* Version info
*/
@FunctionalInterface
interface MyInterface {
void m1();
}
Class (static) Variables
The standard order of static variables is : first the public class
variables, then the protected, and then the private.
Instance Variables
The standard order of instance variables is : first the public, then
protected, and then private.
Constructors
In case of parameterized constructors, the constructors with lesser
number of fields should come first.
Methods
The methods should be grouped by functionality rather than by
scope or accessibility. For example, a private class method can be in
between two public instance methods. The goal is to make reading
and understanding the code easier.
Comments
We should use Comments to give overviews of code and provide
additional information that is not readily available in the code itself.
Moreover, Comments should contain only information that is
relevant to reading and understanding the program.
=========================================
======
https://www.sonarqube.org/downloads/
E:\Program Files\sonor\sonarqube-9.3.0.51899\bin\windows-x86-64
StartSonar.bat
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId>
<version>3.4.0.905</version>
</plugin>
</plugins>
</pluginManagement>
</build>