mercredi 17 mars 2010

PMD - vérifier si une variable est null

Au cours d'un projet, j'ai eu pour tâche de vérifier le code avec PMD afin de l'améliorer et ainsi de diminuer les bugs (grossiers pour la plupart).

Et là je me suis rendu compte qu'il n'existait aucune règle PMD qui permettait de vérifier si avant d'appeler une méthode d'un objet, un test de nullité de cet objet avait été fait.

En gros est-ce que j'avais des blocs de code comme ca :

Objet obj=getObjectFromAnotherMethod();//potentially null !
obj.doSomething();

Alors qu'il faudrait mieux avoir :

Objet obj=getObjectFromAnotherMethod();//potentially null !
if(obj!=null)
obj.doSomething();

J'ai donc remonté mes manches et suis assez fier de vous présenter la règle PMD XPath qui permet de vérifier cette bonne pratique !


//MethodDeclaration/Block/BlockStatement/Statement//StatementExpression/PrimaryExpression
/PrimaryPrefix/Name
[substring-before(@Image,".")=
./ancestor::Block/BlockStatement/LocalVariableDeclaration//VariableDeclaratorId
[not (../VariableInitializer/Expression/PrimaryExpression/PrimaryPrefix/Literal)
and not(../..//PrimitiveType)
and not (../VariableInitializer/Expression/PrimaryExpression/PrimaryPrefix/AllocationExpression)]
/@Image

and

not( substring-before(@Image,".")=
./ancestor::BlockStatement/Statement/IfStatement/Expression//EqualityExpression
[../../..//NullLiteral]
/PrimaryExpression/PrimaryPrefix/Name/@Image )

]

N'hésitez pas à me faire des commentaires si la règle n'est pas satisfaisante, si vous avez des cas où elle marche pas !

Aucun commentaire: