Ich will heute ein Java-Tool für statische Code-Analyse vorstellen.
Der Java-Compiler findet neben Syntaxfehlern auch teilweise offensichtliche Laufzeitfehler im Voraus. Beispiel:
String str; str.isEmpty(); // Compile-Error
Klar, der String ist nicht initialisiert und würde zu einer NullPointerException führen.
Es gibt Code-Konstrukte, die der Compiler nicht anmeckert, weil der Code selbst legal und auf den ersten Blick auch zur Laufzeit keinen Fehler verursachen würde. Schauen wir uns mal ein konstruiertes Beispiel an:
public class MyClass { public boolean equals(Object e) { if(e.toString() == "") new IllegalArgumentException(); return true; } }
Solcher Code wird kompiliert. Aber wenn ein Fehler passiert, wird man ihn schlecht nachvollziehen können, weil er sich nur in bestimmten Programmzuständen auswirkt.
Deshalb ist statische Code-Analyse, eine Art maschineller Code-Review, eine Hilfe. Ich benutze aktuell das Java-Tool FindBugs. Wenn ich FindBugs über den obigen Code laufen lasse, liefert es folgende vier Fehler:
MyClass.java:4 new IllegalArgumentException() not thrown in MyClass.equals(Object)
In Zeile 4 will ich eigentlich eine Exception werfen, habe aber das throw vergessen.
MyClass.java:3 Comparison of String objects using == or != in MyClass.equals(Object)
In Zeile 3 mache ich einen String-Vergleich mit dem ==-Operator. Völlig legaler Code, aber ob es gewollt ist? Normalerweise benutzt man die equals-Methode.
MyClass.java:3 MyClass defines equals and uses Object.hashCode()
Stimmt, ich habe das Protokoll nicht eingehalten. Laut Javadoc soll man auch hashCode() implementieren, wenn man eine equals-Methode bereit stellt. Denn für HashMaps ist das wichtig. Wird einem aber so lange nicht zum Verhängnis, wie die Objekte nicht in HashMaps gepackt werden.
MyClass.java:3 MyClass.equals(Object) does not check for null argument
In Zeile 3 habe ich den Parameter einfach benutzt, ohne zu prüfen ob er Null ist. Sollte es Null sein, muss equals ein False zurück liefern. Es ist selten das der Parameter in equals Null ist, weil diese Methode selten Null-Referenzen bekommt. Durch Such- oder Sortier-Algorithmen in Collections sind Objekte meistens gültig. Aber das equals-Protokoll sagt, das bei Null ein False zurück muss.
FindBugs hat dann geholfen folgenden Code zu schreiben:
public class MyClass { public boolean equals(Object b) { if (b == null) return false; if("".equals(b.toString())) throw new IllegalArgumentException(); return true; } public int hashCode() { assert false : "hashCode not designed"; return 42; } }
Das sieht doch gleich viel sauberer aus. 🙂
Bug-Patterns und Bug-Levels
FindBugs benutzt zur Suche sogenannte Bug-Patterns. Diese werden je nach Schwere in Bug-Levels kategorisiert: Scariest, Scary, Troubling und Normal Confidence.
Dabei kann ein Bug-Pattern aber auch einen negativen Fehler melden. Man kann dem Tool somit nicht voll vertrauen, und sollte auch selbst mit denken.
Einige Bug-Patterns liefern auch gleich eine Lösung mit, wie z.B. die obige hashCode-Implementierung.
Es gibt für die Eclipse IDE und NetBeans IDE Plugins, damit man sich nicht mit der Commandozeile rum schlagen muss.
Fazit
Die statische Code-Analyse braucht man nicht bei jedem Compile-Vorgang ausführen. Denn der Compiler und Unittests decken schon viel auf. Ich orientiere mich danach, wie oft ich Code-Reviews von Menschen machen lassen würde… zu jedem Milestone. Wer zu Projektanfang sehr viel Code produziert, kann das auch vor jedem VCS-Check-in tun.
Ich kann FindBugs bzw. Statische Code-Analyse jedem empfehlen. Wer Erfahrung mit anderen Tools hat, die besser sind, kann gerne einen Kommentar hinterlassen.
Keep on working, great job!
Thanks a bunch for sharing this with all people you actually understand what you’re speaking approximately!
Bookmarked. Please also seek advice from my
site =). We can have a link trade agreement
among us
Woah! I’m really digging the template/theme of this website.
It’s simple, yet effective. A lot of times it’s very difficult to get that „perfect balance“ between usability and visual appeal.
I must say you have done a great job with this. Also,
the blog loads extremely fast for me on Chrome. Outstanding Blog!
Pharmacy https://cialedrx.com/
viagra fast
Cialis coupon https://mycialedst.com generic
cialis
Cheap tadalafil 21cialismen.com generic
cialis online
Cialis online buy viagra canadian pharmacy
cialis
Small personal loans online personal4usloans.com personal loans bank of america
Generic viagra cost buy real viagra online cost of viagra
Best place to buy viagra online viagra for women viagra online
Viagra cost http://genericrxxx.com sildenafil vs viagra
Thank you, I have just been searching for info approximately this subject for a long time and yours is
the best I have discovered till now. But, what in regards to the conclusion? Are
you positive about the supply?
Diabetes is a serious condition with far-reaching consequences.
http://bestviagrx.com/ Diabetes is a serious condition with far-reaching consequences.
I have not yet seen a doctor about it. generic viagra online for sale I have not yet seen a doctor about
it.
Other than that, there is no such thing as a male or female genital herpes virus, the infection is caused
by the same virus in both sexes. viagra without a doctor prescription usa Other than that, there is no such thing as a male or female genital herpes virus, the infection is caused by the same virus in both sexes.
Embryos have three layers, which will ultimately make up
specialized organs and body parts. https://wowviaprice.com viagraviagria over the counter viagra
Chemotherapy can cause infertility and early menopause by destroying the eggs
in the ovaries. viagra generic (buybuyviamen.com) otc viagra
The FDA says it’s the ninth medicine to be approved to help men with drug becomes the
ninth approved by FDA to help men with BPH. http://genqpviag.com generic soft tab viagra
state in which the Internet pharmacy resides. http://siviagmen.com best generic viagra
The CDC Center for Disease Control estimates 1 in 10 pre-menopausal women are anemic,
and recommends anemia testing for women of childbearing age
at least every 5 to 10 years. best online pharmacy to buy viagra viagra online cheap
Generic viagra canada paypal lightvigra.com buy generic viagra soft tabs
Generic sildenafil buy https://miraclevigra.com/
viagra prescription nz
Brand viagra online https://mygoviagar.com/ buy generic viagra online pharmacy
Women viagra pills in india https://hopeviagrin.com viegra
Buy pre written essays https://buyessayhelpbtg.com buy essay writing online
Essay helpers https://essayhelpbgs.com/ help with college essays
Doctoral thesis https://thesiswritinghelpsjj.com thesis services
Can you write my paper for me writemypaperbuyhrd.com write my paper for cheap
Cialis without a doctor prescription https://vipmenciall.com cialis reviews
How long does cialis take to work https://cialmenon.com/ viagra vs cialis vs levitra
Viagra price viagstorerx.com pills like viagra over the counter
Cialis dosage gocialirx.com canadian pharmacy cialis
20mg
Pingback: cialis pills
Pingback: no prescription generic cialis
Pingback: female viagra prank
Pingback: foods that act like viagra
Pingback: cheap cialis pills
Pingback: interaction viagra metoprolol
Pingback: can cialis cause anxiety
Pingback: viagra prescriptions
Why people still use to read news papers when in this technological world
the whole thing is available on net?