Scala avoid using null

前端 未结 5 1958
情深已故
情深已故 2021-01-18 04:07

I hava a project on github that is analysed by codacy . The analysis suggest to \"Avoid using null\" for the following line of code:

def doS         


        
5条回答
  •  被撕碎了的回忆
    2021-01-18 04:18

    Problem

    The interdiction not to use null is a best practice. This article explains why and Guava: Ad-hoc Error Handling, Ambiguous Semantic, Slow Failing and so on.

    Writing a require comes from the need to fail fast and clean when the preconditions for calling the method are not met. The problem is that it only replaces a NPE with another exception (nevertheless more descriptive) as @puhlen explained.

    Ideal Solution

    In an ideal world path:Path will be identical to number:Int and a test for the existence of the object will not be needed. The problem is that scala (as plethora of other languages) allows null breaking the pure object oriented approach.

    Intermediate Solution

    A java/scala compiler should force the Optional type as the only code that manages null and force the existence of null in the typing system. In such cases any use of null could be considered a compilation error. I don't know if this is completely feasible.

    Using @NotNull/@Nullable annotations

    Since there is no language/compiler level default behavior you will have impedance mismatch between libraries.

    Practical Solution

    Define my own class with Predef2 with minimal boilerplate logic. I will still get only one "Avoid using null" or use guava Preconditions.checkNotNull

    object Predef2{
        def requireNotNull(object:AnyRef) = 
           require(path != null, "Some object should not be null")
    }
    def doSomethingWithPath(path:Path) = {
        requireNotNull(path)
        ...
    }
    

提交回复
热议问题