Why you should care
Whenever null seems like a good idea, use Option instead. As far as types are concerned,null is a bit of a lie:
val s: String = null
The compiler believes s to be a String and will accept it wherever one is required. The compiler is, obviously, wrong:
s.toLowerCase
// java.lang.NullPointerException
// at repl.Session$App$$anonfun$2.apply(avoid_null.md:15)
// at repl.Session$App$$anonfun$2.apply(avoid_null.md:15)
null, you’re hindering the compiler’s ability to prove your code incorrect.
How we detect
This Code Insight counts one occurrence each time null is used (strings are not concerned): Non-compliant Code Exampleobject HelloWorld {
def concat(a: String, b: String): String = {
if(a == null) b // +1
else if(b == null) a // +1
else s"$a$b"
}
}
object HelloWorld {
def concat(a: Option[String], b: Option[String]): String =
s"${a.getOrElse("")}${b.getOrElse("")}"
}
References
https://nrinaudo.github.io/scala-best-practices/unsafe/avoid_null.htmlAbout CAST and Highlight’s Code Insights
Over the last 25 years, CAST has leveraged unique knowledge on software quality measurement by analyzing thousands of applications and billions of lines of code. Based on this experience and community standards on programming best practices, Highlight implements hundreds of code insights across 15+ technologies to calculate health factors of a software.
For reference only. For the complete details please refer the original article
https://doc.casthighlight.com/alt_comparetonull/
https://doc.casthighlight.com/alt_comparetonull/
Comments