SlideShare a Scribd company logo
IntelliJ IDEA
Static Code Analysis

       Hamlet D'Arcy
     Canoo Engineering AG
         @HamletDRC
http://hamletdarcy.blogspot.com
Static Code Analysis
Code Inspections
JSR 305 and 308 Annotations
Duplicate Detection
Stack Trace Analysis
Dataflow Analysis
Dependency Analysis


www.jetbrains.com/idea        2
About Me




www.jetbrains.com/idea   3
Static Code Analysis
Code Inspections
JSR 305 and 308 Annotations
Duplicate Detection
Stack Trace Analysis
Dataflow Analysis
Dependency Analysis


www.jetbrains.com/idea        4
class _01Example {

      private static long count = 0L;

      public synchronized void increment() {
        count++;
      }
}




    www.jetbrains.com/idea                     5
class _02Example {

      private boolean active = false;

      public boolean isActive() {
        return active;
      }

      public synchronized void activate() {
        active = true;
      }
}
    www.jetbrains.com/idea                    6
class _03Example {
     private final ReentrantLock lock = new ReentrantLock();
     private boolean active = false;

     public boolean isActive() throws Exception {
         lock.lock();
         boolean result = active;
         lock.unlock();
         return result;
     }

     public void activate() {
         lock.lock();
         active = true;
         lock.unlock();
     }
}

    www.jetbrains.com/idea                                     7
class _04Example {
  private static final boolean DEFAULT = true;

      void myMethod(Boolean value) {
        if (value == null)
          System.out.println("value: null");
          value = DEFAULT;

          System.out.println("received: " + value);
      }
}



    www.jetbrains.com/idea                        8
class _05Example {

      Frame makeFrame(int height, int width) {
        Frame frame = new Frame();
        frame.setSize(height, width);
        return frame;
      }

      Rectangle makeRectangle() {
        int x = 0;
        int y = 0;
        return new Rectangle(y, x, 20, 20);
      }
}
    www.jetbrains.com/idea                       9
class _06Example {
    {
        try {
            doSomething();
        } catch (UnsupportedOperationException e) {
            handleError(e);
        } catch (IllegalStateException e) {
            handleError(e);
        } catch (IllegalArgumentException e) {
            handleError(e);
        }
    }
    ...
}
www.jetbrains.com/idea                          10
class _07Example {
    private def Object lock = new Object()

     def method() {
         synchronized(lock) {
             // do something
         }
     }
}




www.jetbrains.com/idea                       11
class _08Example {
    var property: String = null

     def getProperty() {
         println(property)
     }
}




www.jetbrains.com/idea            12
Correctness
Multi-threaded correctness
Malicious code vulnerability
Bad practice
Internationalization
Performance
Code style violations
Dodgy
                       * Bill Pugh, FindBugs
www.jetbrains.com/idea                    13
… and more
Suppress False Positives
Define profiles and scopes
Run on demand
Run from command line
Team City integration
FindBugs, PMD & CheckStyle plugins
Language and framework support...


www.jetbrains.com/idea               14
Supported Frameworks
Android                  JSF
Ant                      JSP
Application Server       Junit
  Inspections            LESS
CDI(Contexts and         Maven
  Dependency             OSGi
  Injection)
                         RELAX NG
CSS
                         SCSS
Faces Model
                         Spring Model
FreeMarker
www.jetbrains.com/idea                  15
Write Your Own


IntelliJ IDEA Static Analysis:
Custom Rules with Structural Search & Replace

On http://JetBrains.tv



www.jetbrains.com/idea                     16
10 Best Unknown Inspections
Illegal package dependencies           return of collection or array
'this' reference escapes                  field
    constructor                        call to 'Thread.run()'
Field accessed in both                 expression.equals("literal")
    synched & unsynched                   rather than
    contexts                              "literal".equals(expression)
non private field accessed in          equals method does not check
    synched context                       class of parameter
Synchronization on 'this' and          method may be static
    'synchronized' method


http://hamletdarcy.blogspot.com/2008/04/10-best-idea-inspections-youre-not.html

www.jetbrains.com/idea                                                     17
How it Works
Searches AST for Bug Patterns




www.jetbrains.com/idea          18
How it Works
@Override
public void visitMethod(@NotNull final PsiMethod method) {
    super.visitMethod(method);
    if (method.hasModifierProperty(PsiModifier.ABSTRACT)) {
        return;
    }
    if (!RecursionUtils.methodMayRecurse(method)) {
        return;
    }
    if (!RecursionUtils.methodDefinitelyRecurses(method)) {
        return;
    }
    super.registerMethodError(method);
}
        www.jetbrains.com/idea                                19
Static Code Analysis
Code Inspections
JSR 305 and 308 Annotations
Duplicate Detection
Stack Trace Analysis
Dataflow Analysis
Dependency Analysis


www.jetbrains.com/idea        20
@Immutable and @GuardedBy
@Immutable
public class GuardedByExample {

     private final Object lock = new Object();

     @GuardedBy("lock")
     private final List<Object> myList = new ArrayList<Object>();

     public Object getElement(int index) {
       synchronized (lock) {
         return myList.get(index);
       }
     }

     public void addElement(Object e) {
       synchronized (lock) {
         myList.add(e);
       }
     }
}
    www.jetbrains.com/idea                                     21
@Nullable and @NotNull
public class NullableExample {
  @Nullable Integer getId() {
    return 1;
  }

     @NotNull String getName() {
       return "name";
     }

     @Override public String toString() {
       if (getName() == null) {
         return getId().toString() + "<unknown>";
       } else {
         return getId().toString() + getName();
       }
     }
}
    www.jetbrains.com/idea                          22
@Pattern

class PatternExample {


      @Pattern("[a-zA-Z]+")
      String getName() {
        return "my name";
      }
}


    www.jetbrains.com/idea    23
@Language

public class LanguageExample {

     @Language("Groovy")
     String getScript() {
       return "5.times { i -> println "Hello $i" } ";
     }

     String getMarkup() {
       @Language("XML")
       String markup = "<root><body>Some Text</body></root>";
       return markup;
     }
}


    www.jetbrains.com/idea                                24
@Nls, @NonNls, @PropertyKey
   Resource bundle & i18n integration

   Extracting hard-coded String literals:
    http://goo.gl/VZDln

   Documentation: http://goo.gl/NWzsv



www.jetbrains.com/idea                      25
Static Code Analysis
Code Inspections
JSR 305 and 308 Annotations
Duplicate Detection
Stack Trace Analysis
Dataflow Analysis
Dependency Analysis


www.jetbrains.com/idea        26
Static Analysis in IDEA
Static Analysis in IDEA
Duplicate Detection
Anonymizes Local Variables, Fields,
  Methods, Types, and Literals
Provides weighted/scored analysis
Supports several languages


More info: http://goo.gl/qmhhd


www.jetbrains.com/idea                29
Static Code Analysis
Code Inspections
JSR 305 and 308 Annotations
Duplicate Detection
Stack Trace Analysis
Dataflow Analysis
Dependency Analysis


www.jetbrains.com/idea        30
Static Analysis in IDEA
Static Analysis in IDEA
Analyze Stacktrace
Copy and paste log files into IDEA
ZKM Unscramble support (& others)

More Info: http://goo.gl/A8i87




www.jetbrains.com/idea               33
Static Code Analysis
Code Inspections
JSR 305 and 308 Annotations
Duplicate Detection
Stack Trace Analysis
Dataflow Analysis
Dependency Analysis


www.jetbrains.com/idea        34
Static Analysis in IDEA
Static Analysis in IDEA
Dataflow Analysis
Code archeology

to here – how a reference gets set
from here – where a reference goes to

More info: http://goo.gl/Cp92Q



www.jetbrains.com/idea                  37
Static Code Analysis
Code Inspections
JSR 305 and 308 Annotations
Duplicate Detection
Stack Trace Analysis
Dataflow Analysis
Dependency Analysis


www.jetbrains.com/idea        38
Static Analysis in IDEA
Static Analysis in IDEA
UML Generation
Dynamically generates diagram
Standard Show/Hide options
Integrated with Refactorings

Dependency Analysis
Shows all classes your code depends on
Shows specific usages in your classes
Allows jump to source
www.jetbrains.com/idea                   41
Dependency Structure Matrix
Analyzes structure of complex projects
Shows module, package, class
 dependencies
Shows cyclic & backwards dependencies
Helps eliminate illegal dependencies




www.jetbrains.com/idea                   42
Classes on top depend-on classes below


www.jetbrains.com/idea                       43
* le click *




CalculatorFacade uses:
         – Conversions, OperationsFactory & BinaryOperation

www.jetbrains.com/idea                                   44
CalculatorFacade is used by
         – CalculatorServlet & FPCalculatorServlet

www.jetbrains.com/idea                               45
* le click *
BinaryOperation is used 4 times by Facade
       – Darker color == more dependencies
Green shows who BinaryOperation is “used by”
Yellow shows who BinaryOperation “uses”
 www.jetbrains.com/idea                              46
Cyclic Dependencies can be highlighted
Modules can be collapsed/expanded

www.jetbrains.com/idea                   47
Dependency Structure Matrix
Demos on JetBrains site & booth

Feature Overview: http://goo.gl/0bcz3
JetBrains Blog Post: http://goo.gl/fdj26
Canoo Blog Post: http://goo.gl/M1hTY




www.jetbrains.com/idea                     48
Static Code Analysis
Code Inspections
JSR 305 and 308 Annotations
Duplicate Detection
Stack Trace Analysis
Dataflow Analysis
Dependency Analysis


www.jetbrains.com/idea        49
Software Lifecycle
Code Inspections
JSR 305 and 308 Annotations
Duplicate Detection
Stack Trace Analysis
Dataflow Analysis
Dependency Analysis


www.jetbrains.com/idea        50
Software Lifecycle
Code Inspections every second
JSR 305 and 308 Annotations     every second

Duplicate Detection
Stack Trace Analysis
Dataflow Analysis
Dependency Analysis


www.jetbrains.com/idea                   51
Software Lifecycle
Code Inspections every debug
JSR 305 and 308 Annotations     every debug

Duplicate Detection
Stack Trace Analysis
Dataflow Analysis every debug
Dependency Analysis


www.jetbrains.com/idea                    52
Software Lifecycle
Code Inspections every build
JSR 305 and 308 Annotations
Duplicate Detection
Stack Trace Analysis
Dataflow Analysis
Dependency Analysis


www.jetbrains.com/idea         53
Software Lifecycle
Code Inspections
JSR 305 and 308 Annotations
Duplicate Detection every day
Stack Trace Analysis
Dataflow Analysis
Dependency Analysis


www.jetbrains.com/idea          54
Software Lifecycle
Code Inspections
JSR 305 and 308 Annotations
Duplicate Detection
Stack Trace Analysis
Dataflow Analysis
Dependency Analysis     every release




www.jetbrains.com/idea                  55
Learn More – Q & A
My JetBrains.tv Screencasts: http://tv.jetbrains.net/tags/hamlet
My IDEA blog: http://hamletdarcy.blogspot.com/search/label/IDEA
Work's IDEA blog: http://www.canoo.com/blog/tag/idea/
Main blog: http://hamletdarcy.blogspot.com
YouTube channel: http://www.youtube.com/user/HamletDRC
Twitter: http://twitter.com/hamletdrc
IDEA RefCard from DZone: http://goo.gl/Fg4Af
IDEA Keyboard Stickers: JetBrains Booth

Share-a-Canooie – http://people.canoo.com/share/
Hackergarten – http://www.hackergarten.net/
     www.jetbrains.com/idea                                  56

More Related Content

What's hot (20)

PPTX
Automated Patching for Vulnerable Source Code
Vladimir Kochetkov
 
PDF
PVS-Studio is there to help CERN: analysis of Geant4 project
PVS-Studio
 
PPT
Groovy Update - JavaPolis 2007
Guillaume Laforge
 
PDF
Groovy 2 and beyond
Guillaume Laforge
 
PDF
Lift off with Groovy 2 at JavaOne 2013
Guillaume Laforge
 
PPTX
Дмитрий Нестерук, Паттерны проектирования в XXI веке
Sergey Platonov
 
PPTX
Alexey Sintsov- SDLC - try me to implement
DefconRussia
 
PDF
How to write clean & testable code without losing your mind
Andreas Czakaj
 
PDF
Sandboxie process isolation with kernel hooks
KarlFrank99
 
PDF
Visualizing MVC, and an introduction to Giotto
priestc
 
PPT
Much ado about randomness. What is really a random number?
Aleksandr Yampolskiy
 
PDF
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
Christopher Frohoff
 
PPTX
Solid principles
Hanokh Aloni
 
PPTX
From C++ to Objective-C
corehard_by
 
PPTX
Java Bytecode Fundamentals - JUG.lv
Anton Arhipov
 
PPTX
The operation principles of PVS-Studio static code analyzer
Andrey Karpov
 
PDF
New methods for exploiting ORM injections in Java applications
Mikhail Egorov
 
PDF
Testing untestable code - IPC12
Stephan Hochdörfer
 
PPT
Android JNI
Siva Ramakrishna kv
 
PPTX
OWASP Poland Day 2018 - Pedro Fortuna - Are your Java Script based protection...
OWASP
 
Automated Patching for Vulnerable Source Code
Vladimir Kochetkov
 
PVS-Studio is there to help CERN: analysis of Geant4 project
PVS-Studio
 
Groovy Update - JavaPolis 2007
Guillaume Laforge
 
Groovy 2 and beyond
Guillaume Laforge
 
Lift off with Groovy 2 at JavaOne 2013
Guillaume Laforge
 
Дмитрий Нестерук, Паттерны проектирования в XXI веке
Sergey Platonov
 
Alexey Sintsov- SDLC - try me to implement
DefconRussia
 
How to write clean & testable code without losing your mind
Andreas Czakaj
 
Sandboxie process isolation with kernel hooks
KarlFrank99
 
Visualizing MVC, and an introduction to Giotto
priestc
 
Much ado about randomness. What is really a random number?
Aleksandr Yampolskiy
 
OWASP SD: Deserialize My Shorts: Or How I Learned To Start Worrying and Hate ...
Christopher Frohoff
 
Solid principles
Hanokh Aloni
 
From C++ to Objective-C
corehard_by
 
Java Bytecode Fundamentals - JUG.lv
Anton Arhipov
 
The operation principles of PVS-Studio static code analyzer
Andrey Karpov
 
New methods for exploiting ORM injections in Java applications
Mikhail Egorov
 
Testing untestable code - IPC12
Stephan Hochdörfer
 
Android JNI
Siva Ramakrishna kv
 
OWASP Poland Day 2018 - Pedro Fortuna - Are your Java Script based protection...
OWASP
 

Similar to Static Analysis in IDEA (20)

PPTX
DevNexus 2020: Discover Modern Java
Henri Tremblay
 
PDF
Java Runtime: повседневные обязанности JVM
odnoklassniki.ru
 
PDF
Eclipse Indigo DemoCamp Walldorf 2011
Marcel Bruch
 
PDF
Need 4 Speed FI
Marcel Bruch
 
PDF
How to train the jdt dragon
Ayushman Jain
 
PDF
Simple Pure Java
Anton Keks
 
ODP
Java compilation
Mike Kucera
 
PPT
General introduction to intellij idea
Yusup
 
PDF
10 Ways To Improve Your Code( Neal Ford)
guestebde
 
PPTX
Java and the JVM
Manish Pandit
 
PDF
From Renamer Plugin to Polyglot IDE
intelliyole
 
PDF
findbugs Bernhard Merkle
bmerkle
 
PPTX
Proposals for new function in Java SE 9 and beyond
Barry Feigenbaum
 
PPT
Beyond Static Analysis: Integrating Java Static Analysis with Unit Testing an...
Erika Barron
 
PPTX
2010 06-24 karlsruher entwicklertag
Marcel Bruch
 
PDF
Basics of reflection in java
kim.mens
 
KEY
2 the essentials of effective java
Honnix Liang
 
PPTX
Static analysis: Around Java in 60 minutes
Andrey Karpov
 
PPT
Eclipse
guestb66fe26
 
PDF
Terence Barr - jdk7+8 - 24mai2011
Agora Group
 
DevNexus 2020: Discover Modern Java
Henri Tremblay
 
Java Runtime: повседневные обязанности JVM
odnoklassniki.ru
 
Eclipse Indigo DemoCamp Walldorf 2011
Marcel Bruch
 
Need 4 Speed FI
Marcel Bruch
 
How to train the jdt dragon
Ayushman Jain
 
Simple Pure Java
Anton Keks
 
Java compilation
Mike Kucera
 
General introduction to intellij idea
Yusup
 
10 Ways To Improve Your Code( Neal Ford)
guestebde
 
Java and the JVM
Manish Pandit
 
From Renamer Plugin to Polyglot IDE
intelliyole
 
findbugs Bernhard Merkle
bmerkle
 
Proposals for new function in Java SE 9 and beyond
Barry Feigenbaum
 
Beyond Static Analysis: Integrating Java Static Analysis with Unit Testing an...
Erika Barron
 
2010 06-24 karlsruher entwicklertag
Marcel Bruch
 
Basics of reflection in java
kim.mens
 
2 the essentials of effective java
Honnix Liang
 
Static analysis: Around Java in 60 minutes
Andrey Karpov
 
Eclipse
guestb66fe26
 
Terence Barr - jdk7+8 - 24mai2011
Agora Group
 
Ad

More from HamletDRC (8)

ODP
AST Transformations at JFokus
HamletDRC
 
ODP
10 Years of Groovy
HamletDRC
 
ODP
Java Boilerplate Busters
HamletDRC
 
ODP
New Ideas for Old Code - Greach
HamletDRC
 
ODP
Groovy Ast Transformations (greach)
HamletDRC
 
ODP
AST Transformations
HamletDRC
 
ODP
Java Boilerplate Busters
HamletDRC
 
ODP
Ast transformations
HamletDRC
 
AST Transformations at JFokus
HamletDRC
 
10 Years of Groovy
HamletDRC
 
Java Boilerplate Busters
HamletDRC
 
New Ideas for Old Code - Greach
HamletDRC
 
Groovy Ast Transformations (greach)
HamletDRC
 
AST Transformations
HamletDRC
 
Java Boilerplate Busters
HamletDRC
 
Ast transformations
HamletDRC
 
Ad

Recently uploaded (20)

PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PPT
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PPTX
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
PDF
July Patch Tuesday
Ivanti
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PDF
Predicting the unpredictable: re-engineering recommendation algorithms for fr...
Speck&Tech
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Interview paper part 3, It is based on Interview Prep
SoumyadeepGhosh39
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
SWEBOK Guide and Software Services Engineering Education
Hironori Washizaki
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
✨Unleashing Collaboration: Salesforce Channels & Community Power in Patna!✨
SanjeetMishra29
 
July Patch Tuesday
Ivanti
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Smart Air Quality Monitoring with Serrax AQM190 LITE
SERRAX TECHNOLOGIES LLP
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Why Orbit Edge Tech is a Top Next JS Development Company in 2025
mahendraalaska08
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
Predicting the unpredictable: re-engineering recommendation algorithms for fr...
Speck&Tech
 

Static Analysis in IDEA

  • 1. IntelliJ IDEA Static Code Analysis Hamlet D'Arcy Canoo Engineering AG @HamletDRC http://hamletdarcy.blogspot.com
  • 2. Static Code Analysis Code Inspections JSR 305 and 308 Annotations Duplicate Detection Stack Trace Analysis Dataflow Analysis Dependency Analysis www.jetbrains.com/idea 2
  • 4. Static Code Analysis Code Inspections JSR 305 and 308 Annotations Duplicate Detection Stack Trace Analysis Dataflow Analysis Dependency Analysis www.jetbrains.com/idea 4
  • 5. class _01Example { private static long count = 0L; public synchronized void increment() { count++; } } www.jetbrains.com/idea 5
  • 6. class _02Example { private boolean active = false; public boolean isActive() { return active; } public synchronized void activate() { active = true; } } www.jetbrains.com/idea 6
  • 7. class _03Example { private final ReentrantLock lock = new ReentrantLock(); private boolean active = false; public boolean isActive() throws Exception { lock.lock(); boolean result = active; lock.unlock(); return result; } public void activate() { lock.lock(); active = true; lock.unlock(); } } www.jetbrains.com/idea 7
  • 8. class _04Example { private static final boolean DEFAULT = true; void myMethod(Boolean value) { if (value == null) System.out.println("value: null"); value = DEFAULT; System.out.println("received: " + value); } } www.jetbrains.com/idea 8
  • 9. class _05Example { Frame makeFrame(int height, int width) { Frame frame = new Frame(); frame.setSize(height, width); return frame; } Rectangle makeRectangle() { int x = 0; int y = 0; return new Rectangle(y, x, 20, 20); } } www.jetbrains.com/idea 9
  • 10. class _06Example { { try { doSomething(); } catch (UnsupportedOperationException e) { handleError(e); } catch (IllegalStateException e) { handleError(e); } catch (IllegalArgumentException e) { handleError(e); } } ... } www.jetbrains.com/idea 10
  • 11. class _07Example { private def Object lock = new Object() def method() { synchronized(lock) { // do something } } } www.jetbrains.com/idea 11
  • 12. class _08Example { var property: String = null def getProperty() { println(property) } } www.jetbrains.com/idea 12
  • 13. Correctness Multi-threaded correctness Malicious code vulnerability Bad practice Internationalization Performance Code style violations Dodgy * Bill Pugh, FindBugs www.jetbrains.com/idea 13
  • 14. … and more Suppress False Positives Define profiles and scopes Run on demand Run from command line Team City integration FindBugs, PMD & CheckStyle plugins Language and framework support... www.jetbrains.com/idea 14
  • 15. Supported Frameworks Android JSF Ant JSP Application Server Junit Inspections LESS CDI(Contexts and Maven Dependency OSGi Injection) RELAX NG CSS SCSS Faces Model Spring Model FreeMarker www.jetbrains.com/idea 15
  • 16. Write Your Own IntelliJ IDEA Static Analysis: Custom Rules with Structural Search & Replace On http://JetBrains.tv www.jetbrains.com/idea 16
  • 17. 10 Best Unknown Inspections Illegal package dependencies return of collection or array 'this' reference escapes field constructor call to 'Thread.run()' Field accessed in both expression.equals("literal") synched & unsynched rather than contexts "literal".equals(expression) non private field accessed in equals method does not check synched context class of parameter Synchronization on 'this' and method may be static 'synchronized' method http://hamletdarcy.blogspot.com/2008/04/10-best-idea-inspections-youre-not.html www.jetbrains.com/idea 17
  • 18. How it Works Searches AST for Bug Patterns www.jetbrains.com/idea 18
  • 19. How it Works @Override public void visitMethod(@NotNull final PsiMethod method) { super.visitMethod(method); if (method.hasModifierProperty(PsiModifier.ABSTRACT)) { return; } if (!RecursionUtils.methodMayRecurse(method)) { return; } if (!RecursionUtils.methodDefinitelyRecurses(method)) { return; } super.registerMethodError(method); } www.jetbrains.com/idea 19
  • 20. Static Code Analysis Code Inspections JSR 305 and 308 Annotations Duplicate Detection Stack Trace Analysis Dataflow Analysis Dependency Analysis www.jetbrains.com/idea 20
  • 21. @Immutable and @GuardedBy @Immutable public class GuardedByExample { private final Object lock = new Object(); @GuardedBy("lock") private final List<Object> myList = new ArrayList<Object>(); public Object getElement(int index) { synchronized (lock) { return myList.get(index); } } public void addElement(Object e) { synchronized (lock) { myList.add(e); } } } www.jetbrains.com/idea 21
  • 22. @Nullable and @NotNull public class NullableExample { @Nullable Integer getId() { return 1; } @NotNull String getName() { return "name"; } @Override public String toString() { if (getName() == null) { return getId().toString() + "<unknown>"; } else { return getId().toString() + getName(); } } } www.jetbrains.com/idea 22
  • 23. @Pattern class PatternExample { @Pattern("[a-zA-Z]+") String getName() { return "my name"; } } www.jetbrains.com/idea 23
  • 24. @Language public class LanguageExample { @Language("Groovy") String getScript() { return "5.times { i -> println "Hello $i" } "; } String getMarkup() { @Language("XML") String markup = "<root><body>Some Text</body></root>"; return markup; } } www.jetbrains.com/idea 24
  • 25. @Nls, @NonNls, @PropertyKey Resource bundle & i18n integration Extracting hard-coded String literals: http://goo.gl/VZDln Documentation: http://goo.gl/NWzsv www.jetbrains.com/idea 25
  • 26. Static Code Analysis Code Inspections JSR 305 and 308 Annotations Duplicate Detection Stack Trace Analysis Dataflow Analysis Dependency Analysis www.jetbrains.com/idea 26
  • 29. Duplicate Detection Anonymizes Local Variables, Fields, Methods, Types, and Literals Provides weighted/scored analysis Supports several languages More info: http://goo.gl/qmhhd www.jetbrains.com/idea 29
  • 30. Static Code Analysis Code Inspections JSR 305 and 308 Annotations Duplicate Detection Stack Trace Analysis Dataflow Analysis Dependency Analysis www.jetbrains.com/idea 30
  • 33. Analyze Stacktrace Copy and paste log files into IDEA ZKM Unscramble support (& others) More Info: http://goo.gl/A8i87 www.jetbrains.com/idea 33
  • 34. Static Code Analysis Code Inspections JSR 305 and 308 Annotations Duplicate Detection Stack Trace Analysis Dataflow Analysis Dependency Analysis www.jetbrains.com/idea 34
  • 37. Dataflow Analysis Code archeology to here – how a reference gets set from here – where a reference goes to More info: http://goo.gl/Cp92Q www.jetbrains.com/idea 37
  • 38. Static Code Analysis Code Inspections JSR 305 and 308 Annotations Duplicate Detection Stack Trace Analysis Dataflow Analysis Dependency Analysis www.jetbrains.com/idea 38
  • 41. UML Generation Dynamically generates diagram Standard Show/Hide options Integrated with Refactorings Dependency Analysis Shows all classes your code depends on Shows specific usages in your classes Allows jump to source www.jetbrains.com/idea 41
  • 42. Dependency Structure Matrix Analyzes structure of complex projects Shows module, package, class dependencies Shows cyclic & backwards dependencies Helps eliminate illegal dependencies www.jetbrains.com/idea 42
  • 43. Classes on top depend-on classes below www.jetbrains.com/idea 43
  • 44. * le click * CalculatorFacade uses: – Conversions, OperationsFactory & BinaryOperation www.jetbrains.com/idea 44
  • 45. CalculatorFacade is used by – CalculatorServlet & FPCalculatorServlet www.jetbrains.com/idea 45
  • 46. * le click * BinaryOperation is used 4 times by Facade – Darker color == more dependencies Green shows who BinaryOperation is “used by” Yellow shows who BinaryOperation “uses” www.jetbrains.com/idea 46
  • 47. Cyclic Dependencies can be highlighted Modules can be collapsed/expanded www.jetbrains.com/idea 47
  • 48. Dependency Structure Matrix Demos on JetBrains site & booth Feature Overview: http://goo.gl/0bcz3 JetBrains Blog Post: http://goo.gl/fdj26 Canoo Blog Post: http://goo.gl/M1hTY www.jetbrains.com/idea 48
  • 49. Static Code Analysis Code Inspections JSR 305 and 308 Annotations Duplicate Detection Stack Trace Analysis Dataflow Analysis Dependency Analysis www.jetbrains.com/idea 49
  • 50. Software Lifecycle Code Inspections JSR 305 and 308 Annotations Duplicate Detection Stack Trace Analysis Dataflow Analysis Dependency Analysis www.jetbrains.com/idea 50
  • 51. Software Lifecycle Code Inspections every second JSR 305 and 308 Annotations every second Duplicate Detection Stack Trace Analysis Dataflow Analysis Dependency Analysis www.jetbrains.com/idea 51
  • 52. Software Lifecycle Code Inspections every debug JSR 305 and 308 Annotations every debug Duplicate Detection Stack Trace Analysis Dataflow Analysis every debug Dependency Analysis www.jetbrains.com/idea 52
  • 53. Software Lifecycle Code Inspections every build JSR 305 and 308 Annotations Duplicate Detection Stack Trace Analysis Dataflow Analysis Dependency Analysis www.jetbrains.com/idea 53
  • 54. Software Lifecycle Code Inspections JSR 305 and 308 Annotations Duplicate Detection every day Stack Trace Analysis Dataflow Analysis Dependency Analysis www.jetbrains.com/idea 54
  • 55. Software Lifecycle Code Inspections JSR 305 and 308 Annotations Duplicate Detection Stack Trace Analysis Dataflow Analysis Dependency Analysis every release www.jetbrains.com/idea 55
  • 56. Learn More – Q & A My JetBrains.tv Screencasts: http://tv.jetbrains.net/tags/hamlet My IDEA blog: http://hamletdarcy.blogspot.com/search/label/IDEA Work's IDEA blog: http://www.canoo.com/blog/tag/idea/ Main blog: http://hamletdarcy.blogspot.com YouTube channel: http://www.youtube.com/user/HamletDRC Twitter: http://twitter.com/hamletdrc IDEA RefCard from DZone: http://goo.gl/Fg4Af IDEA Keyboard Stickers: JetBrains Booth Share-a-Canooie – http://people.canoo.com/share/ Hackergarten – http://www.hackergarten.net/ www.jetbrains.com/idea 56

Editor's Notes

  • #4: About Me http://www.manning.com/koenig2/ http://hamletdarcy.blogspot.com Twitter: @HamletDRC Groovy, CodeNarc, JConch Committer GPars, Griffon, Gradle, etc. Contributor GroovyMag, NFJS magazine author JetBrains Academy Member
  • #6: Static access on instance lock
  • #7: Field accessed in sync and non-sync context
  • #8: lock acquired &amp; not properly unlocked
  • #9: Suspicious Indentation of Control Statement
  • #10: Suspicious Variable/Parameter Name
  • #11: Suspicious Variable/Parameter Name
  • #12: Suspicious Variable/Parameter Name
  • #13: Suspicious Variable/Parameter Name
  • #15: - Command line &amp; CI integration - command line: need a valid .idea / .ipr file - http://www.jetbrains.com/idea/webhelp/running-inspections-offline.html - inspect.bat or inspect.sh in idea/bin - CI Integration: TeamCity has inspections built in
  • #16: - Mention WebStorm for other inspections
  • #22: - @GuardedBy and @Immutable - GuardedByExample.java - Add jcp classes to classpath - non final GuardedBy field, not guarded correctly - non final field in @Immutable class
  • #23: - http://www.jetbrains.com/idea/documentation/howto.html - Add annotations to classpath - Can be associated with other annotations (like Hibernate&apos;s) - Infer Nullity - http://www.jetbrains.com/idea/webhelp/inferring-nullity.html - http://blogs.jetbrains.com/idea/2011/03/more-flexible-and-configurable-nullublenotnull-annotations/
  • #24: - Enforces String against a regex
  • #25: - @Language - LanguageExample.java - Syntax checks language snippets - http://www.jetbrains.com/idea/webhelp/using-language-injections.html
  • #38: - http://www.jetbrains.com/idea/webhelp/dataflow-analysis.html - code archeology - better understand the inherited project code, interpret complicated parts of the code, find bottlenecks in the source, and more. - Dataflow to here - Shows how a reference gets set. ie Divide by zero example - Dataflow from here - Shows where a reference goes to. ie new Divide() example