SlideShare a Scribd company logo
1 of 52
1 FindBugs™ - Find Bugs in Java Programs Defective Java Code Learning from mistakes Carol McDonald
2 What is FindBugs? ,[object Object]
Looks for defects based on bug patterns
Bug patterns come from real bugs
bug patterns are grouped into categories:
correctness, bad practice, performance…
assigned a priority: high, medium or low.
High-Medium priority have low false positive rates
http://findbugs.sourceforge.net/,[object Object]
a read or write on a null pointer
typos
Methods whose return value should not be ignored
Also specific bug patterns:
Every Programming Puzzler
Eclipse documented bug fixes
Every chapter in Effective Java
Many postings to http://thedailywtf.com/3
© Availity, LLC | All rights reserved.	 4 BugPatterns: http://thedailywtf.com/ 4
© Availity, LLC | All rights reserved.	 5 Some bug Patterns:
© Availity, LLC | All rights reserved.	 6 Some bug Patterns:
7 Misconceptions about Bugs ,[object Object]
Smart people don’t make dumb mistakes
WRONG!
Smart people make dumb mistakes
Common errors:
wrong boolean operator, forgetting parentheses, etc.
Misunderstood class or method  !,[object Object]
9 Who uses FindBugs?  ,[object Object]
Google, Ebay, Sun, Wells Fargo…
Bill Pugh spent a year sabbatical at Google  working Findbugs  into their development process
Google runs FindBugs over all Java code
1800s issues identified, > 600 fixed.
Ebay found 2 developers reviewing  Findbugs  was 10 times more effective than 2 testers,[object Object]
Concurrency
Performance• Security defect
11 Can you find the Bug?  public String sendMessage (User user, String body, Date time) {     return sendMessage(user, body, null);   } public String sendMessage (User user, String body, Date time, List attachments) {    String xml = buildXML (body, attachments);    String response = sendMessage(user, xml);    return response;   }
12 Infinite recursive loopHigh priority correctness public String sendMessage (User user, String body, Date time) {     return sendMessage(user, body, null);   } public String sendMessage (User user, String body, Date time, List attachments) {    String xml = buildXML (body, attachments);    String response = sendMessage(user, xml);    return response;   }
13 Can you find the Bug?  public String foundType() {    return this.foundType(); }
14 Infinite recursive loop public String foundType() {    return this.foundType(); } // should be  public String foundType() {    return this.foundType; } • Findbugs found 5 infinite recursive loops in  JDK1.6.0-b13 • Including this one written by Joshua Bloch • Smart people make dumb mistakes • 27 across all versions of JDK, 31 in Google’s Java code • Embrace and fix your dumb mistakes
15 Can you find the Bug?  if (name != null || name.length > 0)
16 Can you find the Bug?  if (name != null || name.length > 0) if (name != null &&name.length > 0) Found in //com.sun.corba.se.impl.naming.cosnaming.NamingContextImpl
17 Can you find the Bug?  if (part == null | part.equals(""))
18 Can you find the Bug?  if (part == null | part.equals("")) if (part == null ||part.equals("")) Found in  //com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser
19 Null Pointer Bugs found in com.sun…. if (name != null || name.length > 0) if (part == null | part.equals("")) // sun.awt.x11.ScrollPanePeer if (g != null) paintScrollBars(g,colors); g.dispose();
© Availity, LLC | All rights reserved.	 20 Can you find the Bug?  //BoundedThreadPool private final String _lock = "LOCK";...synchronized(_lock){...}
© Availity, LLC | All rights reserved.	 21 found in Jetty…. //BoundedThreadPoolprivate final String _lock = "LOCK";...synchronized(_lock){...} Constant Strings are shared across all other classes loaded by the JVM. Could lead to unexpected deadlocks in conjunction with other code
22 Problem? public final WritableRaster filter( Raster src, 	WritableRasterdst) { intdstLength = dst.getNumBands();  // Create a new destination Raster,if needed  if (dst == null) dst = createCompatibleDestRaster(src);
23 Redundant Check for Null Is it a bug or a redundant check? public final WritableRaster filter( Raster src, 	WritableRasterdst) { intdstLength = dst.getNumBands();  // Create a new destination Raster,if needed  if (dst == null) dst = createCompatibleDestRaster(src); can't be null because there would have been a NPE if it were null
24 Can you find the Bug?  if (adapters == null && adapters.length == 0) 	return; Eclipse, 3.5RC3 • in Eclipse since  3.2 •in this case adapters is probably never null • Impact: ,[object Object]
Won’t return if length is 0, error harder to find,[object Object]
26 Bad Method Call // com.sun.xml.internal.txw2.output.XMLWriter try { ... } catch (IOException e) {   new SAXException("Server side Exception:" + e); } Exception created and dropped rather than thrown  try { ... } catch (IOException e) { throw new SAXException("Server side Exception:" + e); }
27 Problem? public static String getNameById(String userId) {     String str = userId;     ... str.replace(' ', '_');     return str;   }

More Related Content

What's hot

What's hot (20)

Asynchronous javascript
 Asynchronous javascript Asynchronous javascript
Asynchronous javascript
 
JVM Memory Management Details
JVM Memory Management DetailsJVM Memory Management Details
JVM Memory Management Details
 
9. ES6 | Let And Const | TypeScript | JavaScript
9. ES6 | Let And Const | TypeScript | JavaScript9. ES6 | Let And Const | TypeScript | JavaScript
9. ES6 | Let And Const | TypeScript | JavaScript
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) Language
 
Coding with golang
Coding with golangCoding with golang
Coding with golang
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
 
Regular Expression
Regular ExpressionRegular Expression
Regular Expression
 
Learn react-js
Learn react-jsLearn react-js
Learn react-js
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Javascript - Array - Creating Array
Javascript - Array - Creating ArrayJavascript - Array - Creating Array
Javascript - Array - Creating Array
 
Features of JAVA Programming Language.
Features of JAVA Programming Language.Features of JAVA Programming Language.
Features of JAVA Programming Language.
 
java Features
java Featuresjava Features
java Features
 
Asynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & PromisesAsynchronous JavaScript Programming with Callbacks & Promises
Asynchronous JavaScript Programming with Callbacks & Promises
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Complete C++ programming Language Course
Complete C++ programming Language CourseComplete C++ programming Language Course
Complete C++ programming Language Course
 
Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in java
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCJava/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBC
 

Viewers also liked (8)

Preemptive Error Detection with FindBugs
Preemptive Error Detection with FindBugsPreemptive Error Detection with FindBugs
Preemptive Error Detection with FindBugs
 
Ensuring code quality
Ensuring code qualityEnsuring code quality
Ensuring code quality
 
Story behind PF 2016
Story behind PF 2016Story behind PF 2016
Story behind PF 2016
 
C language in our world 2016
C language in our world 2016C language in our world 2016
C language in our world 2016
 
Java Code Quality Tools
Java Code Quality ToolsJava Code Quality Tools
Java Code Quality Tools
 
Code Coverage
Code CoverageCode Coverage
Code Coverage
 
Development of Mobile Applications
Development of Mobile ApplicationsDevelopment of Mobile Applications
Development of Mobile Applications
 
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
 

Similar to Finding bugs that matter with Findbugs

Similar to Finding bugs that matter with Findbugs (20)

Java best practices
Java best practicesJava best practices
Java best practices
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Java tut1
Java tut1Java tut1
Java tut1
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Clean code
Clean codeClean code
Clean code
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
 
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
Do I need tests when I have the compiler - Andrzej Jóźwiak - TomTom Dev Day 2020
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
00_Introduction to Java.ppt
00_Introduction to Java.ppt00_Introduction to Java.ppt
00_Introduction to Java.ppt
 
Need 4 Speed FI
Need 4 Speed FINeed 4 Speed FI
Need 4 Speed FI
 
Microsoft opened the source code of Xamarin.Forms. We couldn't miss a chance ...
Microsoft opened the source code of Xamarin.Forms. We couldn't miss a chance ...Microsoft opened the source code of Xamarin.Forms. We couldn't miss a chance ...
Microsoft opened the source code of Xamarin.Forms. We couldn't miss a chance ...
 
Clean Code
Clean CodeClean Code
Clean Code
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
Clean Code 2
Clean Code 2Clean Code 2
Clean Code 2
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 

More from Carol McDonald

More from Carol McDonald (20)

Introduction to machine learning with GPUs
Introduction to machine learning with GPUsIntroduction to machine learning with GPUs
Introduction to machine learning with GPUs
 
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...
 
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DB
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DBAnalyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DB
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DB
 
Analysis of Popular Uber Locations using Apache APIs: Spark Machine Learning...
Analysis of Popular Uber Locations using Apache APIs:  Spark Machine Learning...Analysis of Popular Uber Locations using Apache APIs:  Spark Machine Learning...
Analysis of Popular Uber Locations using Apache APIs: Spark Machine Learning...
 
Predicting Flight Delays with Spark Machine Learning
Predicting Flight Delays with Spark Machine LearningPredicting Flight Delays with Spark Machine Learning
Predicting Flight Delays with Spark Machine Learning
 
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DB
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DBStructured Streaming Data Pipeline Using Kafka, Spark, and MapR-DB
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DB
 
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
 
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
 
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
 
How Big Data is Reducing Costs and Improving Outcomes in Health Care
How Big Data is Reducing Costs and Improving Outcomes in Health CareHow Big Data is Reducing Costs and Improving Outcomes in Health Care
How Big Data is Reducing Costs and Improving Outcomes in Health Care
 
Demystifying AI, Machine Learning and Deep Learning
Demystifying AI, Machine Learning and Deep LearningDemystifying AI, Machine Learning and Deep Learning
Demystifying AI, Machine Learning and Deep Learning
 
Spark graphx
Spark graphxSpark graphx
Spark graphx
 
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
 
Streaming patterns revolutionary architectures
Streaming patterns revolutionary architectures Streaming patterns revolutionary architectures
Streaming patterns revolutionary architectures
 
Spark machine learning predicting customer churn
Spark machine learning predicting customer churnSpark machine learning predicting customer churn
Spark machine learning predicting customer churn
 
Fast Cars, Big Data How Streaming can help Formula 1
Fast Cars, Big Data How Streaming can help Formula 1Fast Cars, Big Data How Streaming can help Formula 1
Fast Cars, Big Data How Streaming can help Formula 1
 
Applying Machine Learning to Live Patient Data
Applying Machine Learning to  Live Patient DataApplying Machine Learning to  Live Patient Data
Applying Machine Learning to Live Patient Data
 
Streaming Patterns Revolutionary Architectures with the Kafka API
Streaming Patterns Revolutionary Architectures with the Kafka APIStreaming Patterns Revolutionary Architectures with the Kafka API
Streaming Patterns Revolutionary Architectures with the Kafka API
 
Apache Spark Machine Learning Decision Trees
Apache Spark Machine Learning Decision TreesApache Spark Machine Learning Decision Trees
Apache Spark Machine Learning Decision Trees
 
Advanced Threat Detection on Streaming Data
Advanced Threat Detection on Streaming DataAdvanced Threat Detection on Streaming Data
Advanced Threat Detection on Streaming Data
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Recently uploaded (20)

Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 

Finding bugs that matter with Findbugs

  • 1. 1 FindBugs™ - Find Bugs in Java Programs Defective Java Code Learning from mistakes Carol McDonald
  • 2.
  • 3. Looks for defects based on bug patterns
  • 4. Bug patterns come from real bugs
  • 5. bug patterns are grouped into categories:
  • 7. assigned a priority: high, medium or low.
  • 8. High-Medium priority have low false positive rates
  • 9.
  • 10. a read or write on a null pointer
  • 11. typos
  • 12. Methods whose return value should not be ignored
  • 13. Also specific bug patterns:
  • 16. Every chapter in Effective Java
  • 17. Many postings to http://thedailywtf.com/3
  • 18. © Availity, LLC | All rights reserved. 4 BugPatterns: http://thedailywtf.com/ 4
  • 19. © Availity, LLC | All rights reserved. 5 Some bug Patterns:
  • 20. © Availity, LLC | All rights reserved. 6 Some bug Patterns:
  • 21.
  • 22. Smart people don’t make dumb mistakes
  • 24. Smart people make dumb mistakes
  • 26. wrong boolean operator, forgetting parentheses, etc.
  • 27.
  • 28.
  • 29. Google, Ebay, Sun, Wells Fargo…
  • 30. Bill Pugh spent a year sabbatical at Google working Findbugs into their development process
  • 31. Google runs FindBugs over all Java code
  • 33.
  • 36. 11 Can you find the Bug? public String sendMessage (User user, String body, Date time) { return sendMessage(user, body, null); } public String sendMessage (User user, String body, Date time, List attachments) { String xml = buildXML (body, attachments); String response = sendMessage(user, xml); return response; }
  • 37. 12 Infinite recursive loopHigh priority correctness public String sendMessage (User user, String body, Date time) { return sendMessage(user, body, null); } public String sendMessage (User user, String body, Date time, List attachments) { String xml = buildXML (body, attachments); String response = sendMessage(user, xml); return response; }
  • 38. 13 Can you find the Bug? public String foundType() { return this.foundType(); }
  • 39. 14 Infinite recursive loop public String foundType() { return this.foundType(); } // should be public String foundType() { return this.foundType; } • Findbugs found 5 infinite recursive loops in JDK1.6.0-b13 • Including this one written by Joshua Bloch • Smart people make dumb mistakes • 27 across all versions of JDK, 31 in Google’s Java code • Embrace and fix your dumb mistakes
  • 40. 15 Can you find the Bug? if (name != null || name.length > 0)
  • 41. 16 Can you find the Bug? if (name != null || name.length > 0) if (name != null &&name.length > 0) Found in //com.sun.corba.se.impl.naming.cosnaming.NamingContextImpl
  • 42. 17 Can you find the Bug? if (part == null | part.equals(""))
  • 43. 18 Can you find the Bug? if (part == null | part.equals("")) if (part == null ||part.equals("")) Found in //com.sun.xml.internal.ws.wsdl.parser.RuntimeWSDLParser
  • 44. 19 Null Pointer Bugs found in com.sun…. if (name != null || name.length > 0) if (part == null | part.equals("")) // sun.awt.x11.ScrollPanePeer if (g != null) paintScrollBars(g,colors); g.dispose();
  • 45. © Availity, LLC | All rights reserved. 20 Can you find the Bug? //BoundedThreadPool private final String _lock = "LOCK";...synchronized(_lock){...}
  • 46. © Availity, LLC | All rights reserved. 21 found in Jetty…. //BoundedThreadPoolprivate final String _lock = "LOCK";...synchronized(_lock){...} Constant Strings are shared across all other classes loaded by the JVM. Could lead to unexpected deadlocks in conjunction with other code
  • 47. 22 Problem? public final WritableRaster filter( Raster src, WritableRasterdst) { intdstLength = dst.getNumBands(); // Create a new destination Raster,if needed if (dst == null) dst = createCompatibleDestRaster(src);
  • 48. 23 Redundant Check for Null Is it a bug or a redundant check? public final WritableRaster filter( Raster src, WritableRasterdst) { intdstLength = dst.getNumBands(); // Create a new destination Raster,if needed if (dst == null) dst = createCompatibleDestRaster(src); can't be null because there would have been a NPE if it were null
  • 49.
  • 50.
  • 51. 26 Bad Method Call // com.sun.xml.internal.txw2.output.XMLWriter try { ... } catch (IOException e) { new SAXException("Server side Exception:" + e); } Exception created and dropped rather than thrown try { ... } catch (IOException e) { throw new SAXException("Server side Exception:" + e); }
  • 52. 27 Problem? public static String getNameById(String userId) { String str = userId; ... str.replace(' ', '_'); return str; }
  • 53. 28 Method Ignores return valueCorrectness public static String getNameById(String userId) { String str = userId; ... str= str.replace(' ', '_'); return str; } Methods whose return value shouldn't be ignored • Strings are immutable, so functions like trim() and replace() return new String
  • 54. 29 What does it Print? Integer one = 1; Long addressTypeCode = 1L; if (addressTypeCode.equals(one)) { System.out.println("equals"); } else { System.out.println("not equals"); }
  • 55. 30 Comparing Different Types Integer one = 1; Long addressTypeCode = 1L; if (addressTypeCode.equals(one)) { System.out.println("equals"); } else { System.out.println("not equals"); } According to the contract of equals(), objects of different classes should always compare as unequal;
  • 56.
  • 57. Using .equals to compare arrays
  • 58. only checks if the same array
  • 59. Checking to see if a Set<Long> contains an Integer
  • 60. never found, even if the same integral value is contained in the map
  • 61. Calling get(String) on a Map<Integer,String>
  • 62.
  • 63. May be introduced by refactoring
  • 64. Google refactoring that changed a method to return byte[ ] rather than String© Availity, LLC | All rights reserved. 31
  • 65. 32 Best Way to use Findbugs •Want to find an effective/profitable way to use static analysis to improve software quality Mistakes That Don’t Mistakes That Matter Testing Deployment Static Analysis
  • 66.
  • 67. While code is fresh in developers heads
  • 68. Don’t be too eager to fix old issuesMistakes That Matter Mistakes That Don’t Static Analysis Testing Deployment
  • 69. Runtime exceptions can be your friend… Errors which cause a runtime exception are more easily found Throwing a runtime exception is often a reasonable way to fail safely and report a failure. runtime exceptions represent conditions that reflect errors in your program's logic and cannot be reasonably recovered from IllegalArgumentException, NullPointerException, or IllegalStateException © Availity, LLC | All rights reserved. 34
  • 70.
  • 71. silently cause the wrong answer to be computed
  • 72. Mistakes that cause loss of money when they occur
  • 73. Mistakes that are hard to fix© Availity, LLC | All rights reserved. 35
  • 74. 36 Can you find the (Google) bug ? // calculate DR amount by aggregating CR amounts BigDecimaldrAmount = new BigDecimal(0); for (JournalEntry je: journalEntries) drAmount.add(je.getCrAmount()); // persist to db getTrxnService().saveJournalEntry(id, drAmount, // aggregated amount true, // Debit "USD", "Revenue");
  • 75. 37 A Google Bug //Ignored return value of BigDecimal.add for (JournalEntry je: journalEntries) drAmount.add(je.getCrAmount()); // should be drAmount= drAmount.add(je.getCrAmount()); Fixed within 30 minutes of being reported
  • 76. 38 Bug ? int value2; Public boolean equals(Integer value1){ return value1== intValue() ; } public Integer intValue() { return value2; }
  • 77. 39 Using reference equality rather than .equals int value2; Public boolean equals(Integer value1){ return value1.equals(intValue() ); } public Integer intValue() { return value2; } For boxed primitives, == and != are computed using pointer equality, but <, <=, >, >= are computed by comparing unboxed primitive values This can bite you on other classes (e.g., String) • but boxed primitives is where people get bit
  • 78. 40 Bug ? ConcurrentMap<Long,XmitTimeStat> xmit_time_stats = ...; ..... stat = new XmitTimeStat(); xmit_time_stats.putIfAbsent(key, stat); stat.xmit_rsps_sent.addAndGet(sent);
  • 79. 41 misusing putIfAbsentorg.jgroups.protocols.pbcast.NAKACK ConcurrentMap<Long,XmitTimeStat> xmit_time_stats = ...; ..... stat = new XmitTimeStat(); XmitTimeStat stat2 = xmit_time_stats.putIfAbsent(key, stat); if (stat2 != null) stat = stat2; stat.xmit_rsps_sent.addAndGet(sent); ConcurrentMap provides putIfAbsent • atomically add key -> value mapping • but only if the key isnʼt already in the map • if non-null value is returned, put failed and value returned is the value already associated with the key
  • 80.
  • 81. They don’t cause as many problems as they should
  • 82. Problems will probably increase with bigger core systems
  • 83. Early reports from 768 core systems are that they have more severe problems© Availity, LLC | All rights reserved. 42
  • 84.
  • 85. a lock is held sometimes when field accessed
  • 87. e.g., call to wait() not in loop
  • 88. unsafe lazy initialization of static field© Availity, LLC | All rights reserved. 43
  • 89. 44 Bug ? synchronized (object) {   if (<condition does not hold>) {     object.wait();   }   // Proceed when condition holds }
  • 90. 45 call to wait() not in loop synchronized (object) {   while (<condition does not hold>) {     object.wait();   }   // Proceed when condition holds }
  • 91.
  • 92. In Joshua Blochʼs said: don’t lock on ConcurrentMaps• Bill Pugh wrote a detector for FindBugs © Availity, LLC | All rights reserved. 46
  • 93.
  • 94. 9 synchronizations on CopyOnWriteArrayList
  • 95. 3 synchronizations on AtomicBoolean© Availity, LLC | All rights reserved. 47
  • 96.
  • 97. Need:
  • 98. Risk analysis, careful design, static analysis, dynamic testing and analysis
  • 99. Findbugsdoes simple analysis for network security vulnerabilities© Availity, LLC | All rights reserved. 48
  • 100.
  • 102. Methods that don’t defensively copy mutable arguments before storing them into fields
  • 103. Methods that don’t defensively copy mutable values stored in fields before returning them
  • 106. included in HTTP response
  • 107. Forming a file path © Availity, LLC | All rights reserved. 49
  • 108.
  • 110. Run with Hudson build © Availity, LLC | All rights reserved. 50
  • 112.