SlideShare a Scribd company logo
EVERYTHING
ABOUT STATIC CODE ANALYSIS
FOR A JAVA PROGRAMMER
Maxim Stefanov
PVS-Studio, C++/Java developer, Tula
1
About the speaker
• Maxim Stefanov (stefanov@viva64.com)
• C++/Java developer in the PVS-Studio company
• Activities:
• Taking part in developing the C++ analyser core
• Taking part in developing the Java analyzer
2
We’re going to talk about...
• Theory
• Code quality (bugs, vulnerabilities)
• Methodologies of code protection against defects
• Code Review
• Static analysis and everything related to it
• Tools
• Existing tools of static analysis
• SonarQube
• PVS-Studio for Java what is it?
• Several detected examples of code with defects
• More about static analysis
• Conclusions
3
Why we need to concern about code quality
• Don’t let technical debt accrue, if a project is green
• Don’t lose users, if a project already has a history
4
Cost of fixing a defect
From the book by C. McConnell "Code Complete"
5
Methods to provide the code of high quality
6
Static code analysis
Pros Cons
Detects defects before code reviewing You cannot detect high level
errors
The analyser doesn’t get tired and is ready to work
anytime
False positives
You can find some errors not knowing about such patterns
You can detect errors that are difficult to notice when
reviewing code
7
Technologies used in static analysis
•Pattern-based analysis
•Type inference
•Data-flow analysis
•Symbolic execution
•Method annotations
8
Pattern-based analysis
@Override
public boolean equals(Object obj) {
....
return index.equals(other.index)
&& type.equals(other.type)
&& version == other.version
&& found == other.found
&& tookInMillis == tookInMillis
&& Objects.equals(terms, other.terms);
}
9
Type inference
interface Human { ... }
class Parent implements Human{ ... }
class Child extends Parent { ... }
...
class Animal { ... }
...
boolean someMethod(List<Child> list, Animal animal)
{
if (list.remove(animal))
return false;
...
}
10
Method annotations
Class("java.lang.Math")
- Function("max", Type::Int32, Type::Int32)
.Pure()
.Set(FunctionClassification::NoDiscard)
.Requires(NotEquals(Arg1, Arg2))
.Returns(Arg1, Arg2, [](const Int &v1, const Int &v2)
{
return v1.Max(v2);
}
)
11
Method annotations
int test(int a, int b) {
Math.max(a, b); //1
if (a > 5 && b < 2) {
// a = [6..INT_MAX]
// b = [INT_MIN..1]
if (Math.max(a, b) > 0) //2
{...}
}
return Math.max(a, a); //3
}
12
Data-flow analysis
void func(int x) // x: [-2147483648..2147483647] //1
{
if (x > 3)
{
// x: [4..2147483647] //2
if (x < 10)
{
// x: [4..9] //3
}
}
else
{
// x: [-2147483648..3] //4
}
}
13
Symbolic execution
int someMethod(int A, int B)
{
if (A == B)
return 10 / (A - B);
return 1;
}
14
Existing tools
15
SonarQube: who, what and why
• Platform with open source code for continuous analysis and
estimating the code quality
• Contains a number of analyzers for various languages
• Allows to integrate third-party analyzers
• Clearly demonstrates quality of your project
16
SonarQube: data representation
17
SonarQube: data representation
18
SonarQube: data representation
19
SonarQube: data representation
20
Story of creating PVS-Studio for Java
• Java is a popular language
• Wide implementation area of the language
• We could use mechanisms from the C++ analyzer
(data-flow analysis, method annotations)
21
Analyzer internals
22
Spoon for getting a syntax tree and semantic
model
Spoon transforms the code in the metamodel:
class TestClass
{
void test(int a, int b)
{
int x = (a + b) * 4;
System.out.println(x);
}
}
23
Analyzer internals
Data-flow analysis, method annotations - usage of mechanisms from
the C++ analyzer using SWIG
24
Analyzer internals
Diagnostic rule is a visitor with overloaded methods.
Inside the methods the items that are of interest for us are traversed
along the tree.
25
Analyzer internals
Several examples of errors, found using
PVS-Studio
26
Integer division
private static boolean checkSentenceCapitalization(@NotNull String value) {
List<String> words = StringUtil.split(value, " ");
....
int capitalized = 1;
....
return capitalized / words.size() < 0.2; // allow reasonable amount of
// capitalized words
}
V6011 [CWE-682] The '0.2' literal of the 'double' type is compared to a value of the 'int' type.
TitleCapitalizationInspection.java 169
IntelliJ IDEA
27
Always false
PVS-Studio: V6007 [CWE-570] Expression '"0".equals(text)' is always false. ConvertIntegerToDecimalPredicate.java 46
IntelliJ IDEA
public boolean satisfiedBy(@NotNull PsiElement element) {
....
@NonNls final String text = expression.getText().replaceAll("_", "");
if (text == null || text.length() < 2) {
return false;
}
if ("0".equals(text) || "0L".equals(text) || "0l".equals(text)) {
return false;
}
return text.charAt(0) == '0';
}
28
Unexpected number of iterations
public static String getXMLType(@WillNotClose InputStream in) throws
IOException
{
....
String s;
int count = 0;
while (count < 4) {
s = r.readLine();
if (s == null) {
break;
}
Matcher m = tag.matcher(s);
if (m.find()) {
return m.group(1);
}
}
....
}
29
SpotBugs
V6007 [CWE-571] Expression 'count < 4' is always true. Util.java 394
We can’t go on without Copy-Paste
public class RuleDto {
....
private final RuleDefinitionDto definition;
private final RuleMetadataDto metadata;
....
private void setUpdatedAtFromDefinition(@Nullable Long updatedAt) {
if (updatedAt != null && updatedAt > definition.getUpdatedAt()) {
setUpdatedAt(updatedAt);
}
}
private void setUpdatedAtFromMetadata(@Nullable Long updatedAt) {
if (updatedAt != null && updatedAt > definition.getUpdatedAt()) {
setUpdatedAt(updatedAt);
}
}
....
}
30
SonarQube
V6032 It is odd that the body of method 'setUpdatedAtFromDefinition' is fully equivalent to the body of another method
'setUpdatedAtFromMetadata'. Check lines: 396, 405. RuleDto.java 396
Duplicates
V6033 [CWE-462] An item with the same key 'JavaPunctuator.PLUSEQU' has already been added. Check lines: 104, 100.
KindMaps.java 104
SonarJava
private final Map<JavaPunctuator, Tree.Kind> assignmentOperators =
Maps.newEnumMap(JavaPunctuator.class);
public KindMaps() {
....
assignmentOperators.put(JavaPunctuator.PLUSEQU, Tree.Kind.PLUS_ASSIGNMENT);
....
assignmentOperators.put(JavaPunctuator.PLUSEQU, Tree.Kind.PLUS_ASSIGNMENT);
....
}
31
How to integrate static analysis in the process
of software development
• Each developer has a static analysis tool on his machine
• Analysis of the entire code base during the night builds.
When suspicious code is found - all guilty ones get
mails.
32
How to start using static analysis tools on large
projects and not to lose heart
1. Check the project
2. Specify that all issued warnings are not interesting for us yet.
Place the warnings in a special suppression file
3. Upload the file with markup in the version control system
4. Run the analyser and get warnings only for the newly written or
modified code
5. PROFIT!
33
Conclusions
• Static analysis – additional methodology, not a «silver bullet»
• Static analysis has to be used regularly
• You can immediately start using the analysis and postpone fixing of
old errors
• Competition is a key to progress
34

More Related Content

What's hot (20)

PDF
Core java pract_sem iii
Niraj Bharambe
 
PPTX
Pragmatic unittestingwithj unit
liminescence
 
PDF
JUnit Kung Fu: Getting More Out of Your Unit Tests
John Ferguson Smart Limited
 
PDF
Magic methods
Matthew Barlocker
 
PDF
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source Code
Nicolas Bettenburg
 
PDF
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 
PDF
13 advanced-swing
Nataraj Dg
 
PDF
Google Guava & EMF @ GTUG Nantes
mikaelbarbero
 
PPT
Using xUnit as a Swiss-Aarmy Testing Toolkit
Chris Oldwood
 
DOCX
Junit With Eclipse
Sunil kumar Mohanty
 
PPTX
The secret unit testing tools no one has ever told you about
Dror Helper
 
PPTX
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac
Anna Brzezińska
 
PPT
2012 JDays Bad Tests Good Tests
Tomek Kaczanowski
 
PDF
GeeCON 2017 - TestContainers. Integration testing without the hassle
Anton Arhipov
 
PPTX
Use of Apache Commons and Utilities
Pramod Kumar
 
PDF
Second Level Cache in JPA Explained
Patrycja Wegrzynowicz
 
PPTX
PHP 5 Magic Methods
David Stockton
 
PDF
Ruslan Shevchenko - Property based testing
Ievgenii Katsan
 
DOCX
Java Programs Lab File
Kandarp Tiwari
 
PPTX
.NET Database Toolkit
wlscaudill
 
Core java pract_sem iii
Niraj Bharambe
 
Pragmatic unittestingwithj unit
liminescence
 
JUnit Kung Fu: Getting More Out of Your Unit Tests
John Ferguson Smart Limited
 
Magic methods
Matthew Barlocker
 
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source Code
Nicolas Bettenburg
 
33rd Degree 2013, Bad Tests, Good Tests
Tomek Kaczanowski
 
13 advanced-swing
Nataraj Dg
 
Google Guava & EMF @ GTUG Nantes
mikaelbarbero
 
Using xUnit as a Swiss-Aarmy Testing Toolkit
Chris Oldwood
 
Junit With Eclipse
Sunil kumar Mohanty
 
The secret unit testing tools no one has ever told you about
Dror Helper
 
Jug trojmiasto 2014.04.24 tricky stuff in java grammar and javac
Anna Brzezińska
 
2012 JDays Bad Tests Good Tests
Tomek Kaczanowski
 
GeeCON 2017 - TestContainers. Integration testing without the hassle
Anton Arhipov
 
Use of Apache Commons and Utilities
Pramod Kumar
 
Second Level Cache in JPA Explained
Patrycja Wegrzynowicz
 
PHP 5 Magic Methods
David Stockton
 
Ruslan Shevchenko - Property based testing
Ievgenii Katsan
 
Java Programs Lab File
Kandarp Tiwari
 
.NET Database Toolkit
wlscaudill
 

Similar to EVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMER (20)

PPTX
Static code analysis: what? how? why?
Andrey Karpov
 
PPTX
Does static analysis need machine learning?
Andrey Karpov
 
PDF
Achieving quality with tools case study
EosSoftware
 
PPTX
Expanding the idea of static analysis from code check to other development pr...
Andrey Karpov
 
PPTX
Java Code Quality Tools
Сергей Гоменюк
 
PPT
Verifcation &amp;validation
ssusere50573
 
PPTX
Static Code Analysis: Keeping the Cost of Bug Fixing Down
Andrey Karpov
 
PDF
Presentations Unusual Java Bugs And Detecting Them Using Foss Tools
Ganesh Samarthyam
 
PPTX
How to create a high quality static code analyzer
Andrey Karpov
 
PPTX
verification and validation
Dinesh Pasi
 
PPTX
Testing Technique
Ajeng Savitri
 
PDF
Know Your Analysis: How Instrumentation Aids Static Analysis
Ben Hermann
 
PDF
Why Don't Software Developers Use Static Analysis Tools to Find Bugs?
PVS-Studio
 
PDF
Développer un moteur d'exécution symbolique en partant de rien
JUG Lausanne
 
PPTX
Software engineering
GuruAbirami2
 
PPT
Ch22
phanleson
 
PDF
Jdj Foss Java Tools
Ganesh Samarthyam
 
PPT
Dr.Jonathan Software verification validation.ppt
Phial
 
PPT
Sech1920 1200112979886874-3
Mateti Anilraja
 
PPT
S_22.ppt verification and validation in software testing
namrataparopate
 
Static code analysis: what? how? why?
Andrey Karpov
 
Does static analysis need machine learning?
Andrey Karpov
 
Achieving quality with tools case study
EosSoftware
 
Expanding the idea of static analysis from code check to other development pr...
Andrey Karpov
 
Java Code Quality Tools
Сергей Гоменюк
 
Verifcation &amp;validation
ssusere50573
 
Static Code Analysis: Keeping the Cost of Bug Fixing Down
Andrey Karpov
 
Presentations Unusual Java Bugs And Detecting Them Using Foss Tools
Ganesh Samarthyam
 
How to create a high quality static code analyzer
Andrey Karpov
 
verification and validation
Dinesh Pasi
 
Testing Technique
Ajeng Savitri
 
Know Your Analysis: How Instrumentation Aids Static Analysis
Ben Hermann
 
Why Don't Software Developers Use Static Analysis Tools to Find Bugs?
PVS-Studio
 
Développer un moteur d'exécution symbolique en partant de rien
JUG Lausanne
 
Software engineering
GuruAbirami2
 
Ch22
phanleson
 
Jdj Foss Java Tools
Ganesh Samarthyam
 
Dr.Jonathan Software verification validation.ppt
Phial
 
Sech1920 1200112979886874-3
Mateti Anilraja
 
S_22.ppt verification and validation in software testing
namrataparopate
 
Ad

More from Andrey Karpov (20)

PDF
60 антипаттернов для С++ программиста
Andrey Karpov
 
PDF
60 terrible tips for a C++ developer
Andrey Karpov
 
PPTX
Ошибки, которые сложно заметить на code review, но которые находятся статичес...
Andrey Karpov
 
PDF
PVS-Studio in 2021 - Error Examples
Andrey Karpov
 
PDF
PVS-Studio in 2021 - Feature Overview
Andrey Karpov
 
PDF
PVS-Studio в 2021 - Примеры ошибок
Andrey Karpov
 
PDF
PVS-Studio в 2021
Andrey Karpov
 
PPTX
Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...
Andrey Karpov
 
PPTX
Best Bugs from Games: Fellow Programmers' Mistakes
Andrey Karpov
 
PPTX
Typical errors in code on the example of C++, C#, and Java
Andrey Karpov
 
PPTX
How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)
Andrey Karpov
 
PPTX
Game Engine Code Quality: Is Everything Really That Bad?
Andrey Karpov
 
PPTX
C++ Code as Seen by a Hypercritical Reviewer
Andrey Karpov
 
PPTX
The Use of Static Code Analysis When Teaching or Developing Open-Source Software
Andrey Karpov
 
PPTX
Static Code Analysis for Projects, Built on Unreal Engine
Andrey Karpov
 
PPTX
Safety on the Max: How to Write Reliable C/C++ Code for Embedded Systems
Andrey Karpov
 
PPTX
The Great and Mighty C++
Andrey Karpov
 
PDF
Zero, one, two, Freddy's coming for you
Andrey Karpov
 
PDF
PVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOps
Andrey Karpov
 
PDF
PVS-Studio Static Analyzer as a Tool for Protection against Zero-Day Vulnerab...
Andrey Karpov
 
60 антипаттернов для С++ программиста
Andrey Karpov
 
60 terrible tips for a C++ developer
Andrey Karpov
 
Ошибки, которые сложно заметить на code review, но которые находятся статичес...
Andrey Karpov
 
PVS-Studio in 2021 - Error Examples
Andrey Karpov
 
PVS-Studio in 2021 - Feature Overview
Andrey Karpov
 
PVS-Studio в 2021 - Примеры ошибок
Andrey Karpov
 
PVS-Studio в 2021
Andrey Karpov
 
Make Your and Other Programmer’s Life Easier with Static Analysis (Unreal Eng...
Andrey Karpov
 
Best Bugs from Games: Fellow Programmers' Mistakes
Andrey Karpov
 
Typical errors in code on the example of C++, C#, and Java
Andrey Karpov
 
How to Fix Hundreds of Bugs in Legacy Code and Not Die (Unreal Engine 4)
Andrey Karpov
 
Game Engine Code Quality: Is Everything Really That Bad?
Andrey Karpov
 
C++ Code as Seen by a Hypercritical Reviewer
Andrey Karpov
 
The Use of Static Code Analysis When Teaching or Developing Open-Source Software
Andrey Karpov
 
Static Code Analysis for Projects, Built on Unreal Engine
Andrey Karpov
 
Safety on the Max: How to Write Reliable C/C++ Code for Embedded Systems
Andrey Karpov
 
The Great and Mighty C++
Andrey Karpov
 
Zero, one, two, Freddy's coming for you
Andrey Karpov
 
PVS-Studio Is Now in Chocolatey: Checking Chocolatey under Azure DevOps
Andrey Karpov
 
PVS-Studio Static Analyzer as a Tool for Protection against Zero-Day Vulnerab...
Andrey Karpov
 
Ad

Recently uploaded (20)

PPTX
arctitecture application system design os dsa
za241967
 
PPTX
Agentforce – TDX 2025 Hackathon Achievement
GetOnCRM Solutions
 
PPTX
IObit Driver Booster Pro 12.4-12.5 license keys 2025-2026
chaudhryakashoo065
 
PPTX
Avast Premium Security crack 25.5.6162 + License Key 2025
HyperPc soft
 
DOCX
Zoho Creator Solution for EI by Elsner Technologies.docx
Elsner Technologies Pvt. Ltd.
 
PDF
IObit Uninstaller Pro 14.3.1.8 Crack for Windows Latest
utfefguu
 
PPTX
CV-Project_2024 version 01222222222.pptx
MohammadSiddiqui70
 
PDF
AWS Consulting Services: Empowering Digital Transformation with Nlineaxis
Nlineaxis IT Solutions Pvt Ltd
 
PPTX
IObit Driver Booster Pro Crack Download Latest Version
chaudhryakashoo065
 
PPTX
For my supp to finally picking supp that work
necas19388
 
PDF
The Rise of Sustainable Mobile App Solutions by New York Development Firms
ostechnologies16
 
PDF
Designing Accessible Content Blocks (1).pdf
jaclynmennie1
 
PDF
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
DOCX
Best AI-Powered Wearable Tech for Remote Health Monitoring in 2025
SEOLIFT - SEO Company London
 
PDF
Writing Maintainable Playwright Tests with Ease
Shubham Joshi
 
PPTX
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
BradBedford3
 
PDF
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
PDF
Building scalbale cloud native apps with .NET 8
GillesMathieu10
 
PPTX
Iobit Driver Booster Pro 12 Crack Free Download
chaudhryakashoo065
 
PDF
Telemedicine App Development_ Key Factors to Consider for Your Healthcare Ven...
Mobilityinfotech
 
arctitecture application system design os dsa
za241967
 
Agentforce – TDX 2025 Hackathon Achievement
GetOnCRM Solutions
 
IObit Driver Booster Pro 12.4-12.5 license keys 2025-2026
chaudhryakashoo065
 
Avast Premium Security crack 25.5.6162 + License Key 2025
HyperPc soft
 
Zoho Creator Solution for EI by Elsner Technologies.docx
Elsner Technologies Pvt. Ltd.
 
IObit Uninstaller Pro 14.3.1.8 Crack for Windows Latest
utfefguu
 
CV-Project_2024 version 01222222222.pptx
MohammadSiddiqui70
 
AWS Consulting Services: Empowering Digital Transformation with Nlineaxis
Nlineaxis IT Solutions Pvt Ltd
 
IObit Driver Booster Pro Crack Download Latest Version
chaudhryakashoo065
 
For my supp to finally picking supp that work
necas19388
 
The Rise of Sustainable Mobile App Solutions by New York Development Firms
ostechnologies16
 
Designing Accessible Content Blocks (1).pdf
jaclynmennie1
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Best AI-Powered Wearable Tech for Remote Health Monitoring in 2025
SEOLIFT - SEO Company London
 
Writing Maintainable Playwright Tests with Ease
Shubham Joshi
 
Foundations of Marketo Engage - Programs, Campaigns & Beyond - June 2025
BradBedford3
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Building scalbale cloud native apps with .NET 8
GillesMathieu10
 
Iobit Driver Booster Pro 12 Crack Free Download
chaudhryakashoo065
 
Telemedicine App Development_ Key Factors to Consider for Your Healthcare Ven...
Mobilityinfotech
 

EVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMER

  • 1. EVERYTHING ABOUT STATIC CODE ANALYSIS FOR A JAVA PROGRAMMER Maxim Stefanov PVS-Studio, C++/Java developer, Tula 1
  • 2. About the speaker • Maxim Stefanov ([email protected]) • C++/Java developer in the PVS-Studio company • Activities: • Taking part in developing the C++ analyser core • Taking part in developing the Java analyzer 2
  • 3. We’re going to talk about... • Theory • Code quality (bugs, vulnerabilities) • Methodologies of code protection against defects • Code Review • Static analysis and everything related to it • Tools • Existing tools of static analysis • SonarQube • PVS-Studio for Java what is it? • Several detected examples of code with defects • More about static analysis • Conclusions 3
  • 4. Why we need to concern about code quality • Don’t let technical debt accrue, if a project is green • Don’t lose users, if a project already has a history 4
  • 5. Cost of fixing a defect From the book by C. McConnell "Code Complete" 5
  • 6. Methods to provide the code of high quality 6
  • 7. Static code analysis Pros Cons Detects defects before code reviewing You cannot detect high level errors The analyser doesn’t get tired and is ready to work anytime False positives You can find some errors not knowing about such patterns You can detect errors that are difficult to notice when reviewing code 7
  • 8. Technologies used in static analysis •Pattern-based analysis •Type inference •Data-flow analysis •Symbolic execution •Method annotations 8
  • 9. Pattern-based analysis @Override public boolean equals(Object obj) { .... return index.equals(other.index) && type.equals(other.type) && version == other.version && found == other.found && tookInMillis == tookInMillis && Objects.equals(terms, other.terms); } 9
  • 10. Type inference interface Human { ... } class Parent implements Human{ ... } class Child extends Parent { ... } ... class Animal { ... } ... boolean someMethod(List<Child> list, Animal animal) { if (list.remove(animal)) return false; ... } 10
  • 11. Method annotations Class("java.lang.Math") - Function("max", Type::Int32, Type::Int32) .Pure() .Set(FunctionClassification::NoDiscard) .Requires(NotEquals(Arg1, Arg2)) .Returns(Arg1, Arg2, [](const Int &v1, const Int &v2) { return v1.Max(v2); } ) 11
  • 12. Method annotations int test(int a, int b) { Math.max(a, b); //1 if (a > 5 && b < 2) { // a = [6..INT_MAX] // b = [INT_MIN..1] if (Math.max(a, b) > 0) //2 {...} } return Math.max(a, a); //3 } 12
  • 13. Data-flow analysis void func(int x) // x: [-2147483648..2147483647] //1 { if (x > 3) { // x: [4..2147483647] //2 if (x < 10) { // x: [4..9] //3 } } else { // x: [-2147483648..3] //4 } } 13
  • 14. Symbolic execution int someMethod(int A, int B) { if (A == B) return 10 / (A - B); return 1; } 14
  • 16. SonarQube: who, what and why • Platform with open source code for continuous analysis and estimating the code quality • Contains a number of analyzers for various languages • Allows to integrate third-party analyzers • Clearly demonstrates quality of your project 16
  • 21. Story of creating PVS-Studio for Java • Java is a popular language • Wide implementation area of the language • We could use mechanisms from the C++ analyzer (data-flow analysis, method annotations) 21
  • 23. Spoon for getting a syntax tree and semantic model Spoon transforms the code in the metamodel: class TestClass { void test(int a, int b) { int x = (a + b) * 4; System.out.println(x); } } 23 Analyzer internals
  • 24. Data-flow analysis, method annotations - usage of mechanisms from the C++ analyzer using SWIG 24 Analyzer internals
  • 25. Diagnostic rule is a visitor with overloaded methods. Inside the methods the items that are of interest for us are traversed along the tree. 25 Analyzer internals
  • 26. Several examples of errors, found using PVS-Studio 26
  • 27. Integer division private static boolean checkSentenceCapitalization(@NotNull String value) { List<String> words = StringUtil.split(value, " "); .... int capitalized = 1; .... return capitalized / words.size() < 0.2; // allow reasonable amount of // capitalized words } V6011 [CWE-682] The '0.2' literal of the 'double' type is compared to a value of the 'int' type. TitleCapitalizationInspection.java 169 IntelliJ IDEA 27
  • 28. Always false PVS-Studio: V6007 [CWE-570] Expression '"0".equals(text)' is always false. ConvertIntegerToDecimalPredicate.java 46 IntelliJ IDEA public boolean satisfiedBy(@NotNull PsiElement element) { .... @NonNls final String text = expression.getText().replaceAll("_", ""); if (text == null || text.length() < 2) { return false; } if ("0".equals(text) || "0L".equals(text) || "0l".equals(text)) { return false; } return text.charAt(0) == '0'; } 28
  • 29. Unexpected number of iterations public static String getXMLType(@WillNotClose InputStream in) throws IOException { .... String s; int count = 0; while (count < 4) { s = r.readLine(); if (s == null) { break; } Matcher m = tag.matcher(s); if (m.find()) { return m.group(1); } } .... } 29 SpotBugs V6007 [CWE-571] Expression 'count < 4' is always true. Util.java 394
  • 30. We can’t go on without Copy-Paste public class RuleDto { .... private final RuleDefinitionDto definition; private final RuleMetadataDto metadata; .... private void setUpdatedAtFromDefinition(@Nullable Long updatedAt) { if (updatedAt != null && updatedAt > definition.getUpdatedAt()) { setUpdatedAt(updatedAt); } } private void setUpdatedAtFromMetadata(@Nullable Long updatedAt) { if (updatedAt != null && updatedAt > definition.getUpdatedAt()) { setUpdatedAt(updatedAt); } } .... } 30 SonarQube V6032 It is odd that the body of method 'setUpdatedAtFromDefinition' is fully equivalent to the body of another method 'setUpdatedAtFromMetadata'. Check lines: 396, 405. RuleDto.java 396
  • 31. Duplicates V6033 [CWE-462] An item with the same key 'JavaPunctuator.PLUSEQU' has already been added. Check lines: 104, 100. KindMaps.java 104 SonarJava private final Map<JavaPunctuator, Tree.Kind> assignmentOperators = Maps.newEnumMap(JavaPunctuator.class); public KindMaps() { .... assignmentOperators.put(JavaPunctuator.PLUSEQU, Tree.Kind.PLUS_ASSIGNMENT); .... assignmentOperators.put(JavaPunctuator.PLUSEQU, Tree.Kind.PLUS_ASSIGNMENT); .... } 31
  • 32. How to integrate static analysis in the process of software development • Each developer has a static analysis tool on his machine • Analysis of the entire code base during the night builds. When suspicious code is found - all guilty ones get mails. 32
  • 33. How to start using static analysis tools on large projects and not to lose heart 1. Check the project 2. Specify that all issued warnings are not interesting for us yet. Place the warnings in a special suppression file 3. Upload the file with markup in the version control system 4. Run the analyser and get warnings only for the newly written or modified code 5. PROFIT! 33
  • 34. Conclusions • Static analysis – additional methodology, not a «silver bullet» • Static analysis has to be used regularly • You can immediately start using the analysis and postpone fixing of old errors • Competition is a key to progress 34

Editor's Notes

  • #3: Добрый день. Меня зовут Максим. Я разработчик в компании PVS-Studio, которая занимается разработкой статического анализатора для языков программирования C/C++/C#/Java. Сегодня я хочу вам рассказать, что статический анализ кода является такой же неотъемлемой частью разработки как, например, Code Review, тестирование.