IntelliJ IDEAStatic Code Analysis       Hamlet DArcy     Canoo Engineering AG         @HamletDRChttp://hamletdarcy.blogspo...
Static Code AnalysisCode InspectionsJSR 305 and 308 AnnotationsDuplicate DetectionStack Trace AnalysisDataflow AnalysisDep...
About Mewww.jetbrains.com/idea   3
Static Code AnalysisCode InspectionsJSR 305 and 308 AnnotationsDuplicate DetectionStack Trace AnalysisDataflow AnalysisDep...
class _01Example {      private static long count = 0L;      public synchronized void increment() {        count++;      }...
class _02Example {      private boolean active = false;      public boolean isActive() {        return active;      }     ...
class _03Example {     private final ReentrantLock lock = new ReentrantLock();     private boolean active = false;     pub...
class _04Example {  private static final boolean DEFAULT = true;      void myMethod(Boolean value) {        if (value == n...
class _05Example {      Frame makeFrame(int height, int width) {        Frame frame = new Frame();        frame.setSize(he...
class _06Example {    {        try {            doSomething();        } catch (UnsupportedOperationException e) {         ...
class _07Example {    private def Object lock = new Object()     def method() {         synchronized(lock) {             /...
class _08Example {    var property: String = null     def getProperty() {         println(property)     }}www.jetbrains.co...
CorrectnessMulti-threaded correctnessMalicious code vulnerabilityBad practiceInternationalizationPerformanceCode style vio...
… and moreSuppress False PositivesDefine profiles and scopesRun on demandRun from command lineTeam City integrationFindBug...
Supported FrameworksAndroid                  JSFAnt                      JSPApplication Server       Junit  Inspections   ...
Write Your OwnIntelliJ IDEA Static Analysis:Custom Rules with Structural Search & ReplaceOn http://JetBrains.tvwww.jetbrai...
10 Best Unknown InspectionsIllegal package dependencies           return of collection or arraythis reference escapes     ...
How it WorksSearches AST for Bug Patternswww.jetbrains.com/idea          18
How it Works@Overridepublic void visitMethod(@NotNull final PsiMethod method) {    super.visitMethod(method);    if (metho...
Static Code AnalysisCode InspectionsJSR 305 and 308 AnnotationsDuplicate DetectionStack Trace AnalysisDataflow AnalysisDep...
@Immutable and @GuardedBy@Immutablepublic class GuardedByExample {     private final Object lock = new Object();     @Guar...
@Nullable and @NotNullpublic class NullableExample {  @Nullable Integer getId() {    return 1;  }     @NotNull String getN...
@Patternclass PatternExample {      @Pattern("[a-zA-Z]+")      String getName() {        return "my name";      }}    www....
@Languagepublic class LanguageExample {     @Language("Groovy")     String getScript() {       return "5.times { i -> prin...
@Nls, @NonNls, @PropertyKey   Resource bundle & i18n integration   Extracting hard-coded String literals:    http://goo.gl...
Static Code AnalysisCode InspectionsJSR 305 and 308 AnnotationsDuplicate DetectionStack Trace AnalysisDataflow AnalysisDep...
Duplicate DetectionAnonymizes Local Variables, Fields,  Methods, Types, and LiteralsProvides weighted/scored analysisSuppo...
Static Code AnalysisCode InspectionsJSR 305 and 308 AnnotationsDuplicate DetectionStack Trace AnalysisDataflow AnalysisDep...
Analyze StacktraceCopy and paste log files into IDEAZKM Unscramble support (& others)More Info: http://goo.gl/A8i87www.jet...
Static Code AnalysisCode InspectionsJSR 305 and 308 AnnotationsDuplicate DetectionStack Trace AnalysisDataflow AnalysisDep...
Dataflow AnalysisCode archeologyto here – how a reference gets setfrom here – where a reference goes toMore info: http://g...
Static Code AnalysisCode InspectionsJSR 305 and 308 AnnotationsDuplicate DetectionStack Trace AnalysisDataflow AnalysisDep...
UML GenerationDynamically generates diagramStandard Show/Hide optionsIntegrated with RefactoringsDependency AnalysisShows ...
Dependency Structure MatrixAnalyzes structure of complex projectsShows module, package, class dependenciesShows cyclic & b...
Classes on top depend-on classes belowwww.jetbrains.com/idea                       43
* le click *CalculatorFacade uses:         – Conversions, OperationsFactory & BinaryOperationwww.jetbrains.com/idea       ...
CalculatorFacade is used by         – CalculatorServlet & FPCalculatorServletwww.jetbrains.com/idea                       ...
* le click *BinaryOperation is used 4 times by Facade       – Darker color == more dependenciesGreen shows who BinaryOpera...
Cyclic Dependencies can be highlightedModules can be collapsed/expandedwww.jetbrains.com/idea                   47
Dependency Structure MatrixDemos on JetBrains site & boothFeature Overview: http://goo.gl/0bcz3JetBrains Blog Post: http:/...
Static Code AnalysisCode InspectionsJSR 305 and 308 AnnotationsDuplicate DetectionStack Trace AnalysisDataflow AnalysisDep...
Software LifecycleCode InspectionsJSR 305 and 308 AnnotationsDuplicate DetectionStack Trace AnalysisDataflow AnalysisDepen...
Software LifecycleCode Inspections every secondJSR 305 and 308 Annotations     every secondDuplicate DetectionStack Trace ...
Software LifecycleCode Inspections every debugJSR 305 and 308 Annotations     every debugDuplicate DetectionStack Trace An...
Software LifecycleCode Inspections every buildJSR 305 and 308 AnnotationsDuplicate DetectionStack Trace AnalysisDataflow A...
Software LifecycleCode InspectionsJSR 305 and 308 AnnotationsDuplicate Detection every dayStack Trace AnalysisDataflow Ana...
Software LifecycleCode InspectionsJSR 305 and 308 AnnotationsDuplicate DetectionStack Trace AnalysisDataflow AnalysisDepen...
Learn More – Q & AMy JetBrains.tv Screencasts: http://tv.jetbrains.net/tags/hamletMy IDEA blog: http://hamletdarcy.blogspo...
Static Analysis in IDEA
Static Analysis in IDEA
Static Analysis in IDEA
Static Analysis in IDEA
Static Analysis in IDEA
Static Analysis in IDEA
Static Analysis in IDEA
Static Analysis in IDEA
Upcoming SlideShare
Loading in …5
×

Static Analysis in IDEA

1,797 views
1,613 views

Published on

My presen

Published in: Technology
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,797
On SlideShare
0
From Embeds
0
Number of Embeds
10
Actions
Shares
0
Downloads
2
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide
  • 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
  • Static access on instance lock
  • Field accessed in sync and non-sync context
  • lock acquired & not properly unlocked
  • Suspicious Indentation of Control Statement
  • Suspicious Variable/Parameter Name
  • Suspicious Variable/Parameter Name
  • Suspicious Variable/Parameter Name
  • Suspicious Variable/Parameter Name
  • - Command line & 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
  • - Mention WebStorm for other inspections
  • - @GuardedBy and @Immutable - GuardedByExample.java - Add jcp classes to classpath - non final GuardedBy field, not guarded correctly - non final field in @Immutable class
  • - http://www.jetbrains.com/idea/documentation/howto.html - Add annotations to classpath - Can be associated with other annotations (like Hibernate'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/
  • - Enforces String against a regex
  • - @Language - LanguageExample.java - Syntax checks language snippets - http://www.jetbrains.com/idea/webhelp/using-language-injections.html
  • - 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
  • Static Analysis in IDEA

    1. 1. IntelliJ IDEAStatic Code Analysis Hamlet DArcy Canoo Engineering AG @HamletDRChttp://hamletdarcy.blogspot.com
    2. 2. Static Code AnalysisCode InspectionsJSR 305 and 308 AnnotationsDuplicate DetectionStack Trace AnalysisDataflow AnalysisDependency Analysiswww.jetbrains.com/idea 2
    3. 3. About Mewww.jetbrains.com/idea 3
    4. 4. Static Code AnalysisCode InspectionsJSR 305 and 308 AnnotationsDuplicate DetectionStack Trace AnalysisDataflow AnalysisDependency Analysiswww.jetbrains.com/idea 4
    5. 5. class _01Example { private static long count = 0L; public synchronized void increment() { count++; }} www.jetbrains.com/idea 5
    6. 6. class _02Example { private boolean active = false; public boolean isActive() { return active; } public synchronized void activate() { active = true; }} www.jetbrains.com/idea 6
    7. 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. 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. 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. 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. 11. class _07Example { private def Object lock = new Object() def method() { synchronized(lock) { // do something } }}www.jetbrains.com/idea 11
    12. 12. class _08Example { var property: String = null def getProperty() { println(property) }}www.jetbrains.com/idea 12
    13. 13. CorrectnessMulti-threaded correctnessMalicious code vulnerabilityBad practiceInternationalizationPerformanceCode style violationsDodgy * Bill Pugh, FindBugswww.jetbrains.com/idea 13
    14. 14. … and moreSuppress False PositivesDefine profiles and scopesRun on demandRun from command lineTeam City integrationFindBugs, PMD & CheckStyle pluginsLanguage and framework support...www.jetbrains.com/idea 14
    15. 15. Supported FrameworksAndroid JSFAnt JSPApplication Server Junit Inspections LESSCDI(Contexts and Maven Dependency OSGi Injection) RELAX NGCSS SCSSFaces Model Spring ModelFreeMarkerwww.jetbrains.com/idea 15
    16. 16. Write Your OwnIntelliJ IDEA Static Analysis:Custom Rules with Structural Search & ReplaceOn http://JetBrains.tvwww.jetbrains.com/idea 16
    17. 17. 10 Best Unknown InspectionsIllegal package dependencies return of collection or arraythis 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 parameterSynchronization on this and method may be static synchronized methodhttp://hamletdarcy.blogspot.com/2008/04/10-best-idea-inspections-youre-not.htmlwww.jetbrains.com/idea 17
    18. 18. How it WorksSearches AST for Bug Patternswww.jetbrains.com/idea 18
    19. 19. How it Works@Overridepublic 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. 20. Static Code AnalysisCode InspectionsJSR 305 and 308 AnnotationsDuplicate DetectionStack Trace AnalysisDataflow AnalysisDependency Analysiswww.jetbrains.com/idea 20
    21. 21. @Immutable and @GuardedBy@Immutablepublic 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. 22. @Nullable and @NotNullpublic 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. 23. @Patternclass PatternExample { @Pattern("[a-zA-Z]+") String getName() { return "my name"; }} www.jetbrains.com/idea 23
    24. 24. @Languagepublic 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. 25. @Nls, @NonNls, @PropertyKey Resource bundle & i18n integration Extracting hard-coded String literals: http://goo.gl/VZDln Documentation: http://goo.gl/NWzsvwww.jetbrains.com/idea 25
    26. 26. Static Code AnalysisCode InspectionsJSR 305 and 308 AnnotationsDuplicate DetectionStack Trace AnalysisDataflow AnalysisDependency Analysiswww.jetbrains.com/idea 26
    27. 27. Duplicate DetectionAnonymizes Local Variables, Fields, Methods, Types, and LiteralsProvides weighted/scored analysisSupports several languagesMore info: http://goo.gl/qmhhdwww.jetbrains.com/idea 29
    28. 28. Static Code AnalysisCode InspectionsJSR 305 and 308 AnnotationsDuplicate DetectionStack Trace AnalysisDataflow AnalysisDependency Analysiswww.jetbrains.com/idea 30
    29. 29. Analyze StacktraceCopy and paste log files into IDEAZKM Unscramble support (& others)More Info: http://goo.gl/A8i87www.jetbrains.com/idea 33
    30. 30. Static Code AnalysisCode InspectionsJSR 305 and 308 AnnotationsDuplicate DetectionStack Trace AnalysisDataflow AnalysisDependency Analysiswww.jetbrains.com/idea 34
    31. 31. Dataflow AnalysisCode archeologyto here – how a reference gets setfrom here – where a reference goes toMore info: http://goo.gl/Cp92Qwww.jetbrains.com/idea 37
    32. 32. Static Code AnalysisCode InspectionsJSR 305 and 308 AnnotationsDuplicate DetectionStack Trace AnalysisDataflow AnalysisDependency Analysiswww.jetbrains.com/idea 38
    33. 33. UML GenerationDynamically generates diagramStandard Show/Hide optionsIntegrated with RefactoringsDependency AnalysisShows all classes your code depends onShows specific usages in your classesAllows jump to sourcewww.jetbrains.com/idea 41
    34. 34. Dependency Structure MatrixAnalyzes structure of complex projectsShows module, package, class dependenciesShows cyclic & backwards dependenciesHelps eliminate illegal dependencieswww.jetbrains.com/idea 42
    35. 35. Classes on top depend-on classes belowwww.jetbrains.com/idea 43
    36. 36. * le click *CalculatorFacade uses: – Conversions, OperationsFactory & BinaryOperationwww.jetbrains.com/idea 44
    37. 37. CalculatorFacade is used by – CalculatorServlet & FPCalculatorServletwww.jetbrains.com/idea 45
    38. 38. * le click *BinaryOperation is used 4 times by Facade – Darker color == more dependenciesGreen shows who BinaryOperation is “used by”Yellow shows who BinaryOperation “uses” www.jetbrains.com/idea 46
    39. 39. Cyclic Dependencies can be highlightedModules can be collapsed/expandedwww.jetbrains.com/idea 47
    40. 40. Dependency Structure MatrixDemos on JetBrains site & boothFeature Overview: http://goo.gl/0bcz3JetBrains Blog Post: http://goo.gl/fdj26Canoo Blog Post: http://goo.gl/M1hTYwww.jetbrains.com/idea 48
    41. 41. Static Code AnalysisCode InspectionsJSR 305 and 308 AnnotationsDuplicate DetectionStack Trace AnalysisDataflow AnalysisDependency Analysiswww.jetbrains.com/idea 49
    42. 42. Software LifecycleCode InspectionsJSR 305 and 308 AnnotationsDuplicate DetectionStack Trace AnalysisDataflow AnalysisDependency Analysiswww.jetbrains.com/idea 50
    43. 43. Software LifecycleCode Inspections every secondJSR 305 and 308 Annotations every secondDuplicate DetectionStack Trace AnalysisDataflow AnalysisDependency Analysiswww.jetbrains.com/idea 51
    44. 44. Software LifecycleCode Inspections every debugJSR 305 and 308 Annotations every debugDuplicate DetectionStack Trace AnalysisDataflow Analysis every debugDependency Analysiswww.jetbrains.com/idea 52
    45. 45. Software LifecycleCode Inspections every buildJSR 305 and 308 AnnotationsDuplicate DetectionStack Trace AnalysisDataflow AnalysisDependency Analysiswww.jetbrains.com/idea 53
    46. 46. Software LifecycleCode InspectionsJSR 305 and 308 AnnotationsDuplicate Detection every dayStack Trace AnalysisDataflow AnalysisDependency Analysiswww.jetbrains.com/idea 54
    47. 47. Software LifecycleCode InspectionsJSR 305 and 308 AnnotationsDuplicate DetectionStack Trace AnalysisDataflow AnalysisDependency Analysis every releasewww.jetbrains.com/idea 55
    48. 48. Learn More – Q & AMy JetBrains.tv Screencasts: http://tv.jetbrains.net/tags/hamletMy IDEA blog: http://hamletdarcy.blogspot.com/search/label/IDEAWorks IDEA blog: http://www.canoo.com/blog/tag/idea/Main blog: http://hamletdarcy.blogspot.comYouTube channel: http://www.youtube.com/user/HamletDRCTwitter: http://twitter.com/hamletdrcIDEA RefCard from DZone: http://goo.gl/Fg4AfIDEA Keyboard Stickers: JetBrains BoothShare-a-Canooie – http://people.canoo.com/share/Hackergarten – http://www.hackergarten.net/ www.jetbrains.com/idea 56

    ×