[Java] Evitando! = Declaraciones nulas



Answers

Si usa (o planea usar) un IDE de Java como JetBrains IntelliJ IDEA , Eclipse o Netbeans o una herramienta como findbugs, entonces puede usar anotaciones para resolver este problema.

Básicamente, tienes @Nullable y @NotNull .

Puede usar en método y parámetros, como este:

@NotNull public static String helloWorld() {
    return "Hello World";
}

o

@Nullable public static String helloWorld() {
    return "Hello World";
}

El segundo ejemplo no se compilará (en IntelliJ IDEA).

Cuando usa la primera función helloWorld() en otro fragmento de código:

public static void main(String[] args)
{
    String result = helloWorld();
    if(result != null) {
        System.out.println(result);
    }
}

Ahora el compilador IntelliJ IDEA le dirá que la verificación es inútil, ya que la función helloWorld() no devolverá null , nunca.

Usando el parámetro

void someMethod(@NotNull someParameter) { }

si escribes algo como:

someMethod(null);

Esto no compilará

Último ejemplo usando @Nullable

@Nullable iWantToDestroyEverything() { return null; }

Haciendo esto

iWantToDestroyEverything().something();

Y puedes estar seguro de que esto no sucederá. :)

Es una buena manera de dejar que el compilador verifique algo más de lo normal y hacer cumplir sus contratos para que sea más fuerte. Desafortunadamente, no es compatible con todos los compiladores.

En IntelliJ IDEA 10.5 y en adelante, agregaron soporte para cualquier otra implementación @Nullable @NotNull .

Ver publicación en el blog Anotaciones más flexibles y configurables @ Nullable / @ NotNull .

Question

Uso object != null para evitar NullPointerException .

¿Hay una buena alternativa a esto?

Por ejemplo:

if (someobject != null) {
    someobject.doCalc();
}

Esto evita una NullPointerException , cuando se desconoce si el objeto es null o no.

Tenga en cuenta que la respuesta aceptada puede estar desactualizada, consulte https://.com/a/2386013/12943 para obtener un enfoque más reciente.




El marco de colecciones de Google ofrece una forma buena y elegante de lograr la verificación nula.

Hay un método en una clase de biblioteca como esta:

static <T> T checkNotNull(T e) {
   if (e == null) {
      throw new NullPointerException();
   }
   return e;
}

Y el uso es (con import static ):

...
void foo(int a, Person p) {
   if (checkNotNull(p).getAge() > a) {
      ...
   }
   else {
      ...
   }
}
...

O en tu ejemplo:

checkNotNull(someobject).doCalc();



Asking that question points out that you may be interested in error handling strategies. Your team's architect should decide how to work errors. There are several ways to do this:

  1. allow the Exceptions to ripple through - catch them at the 'main loop' or in some other managing routine.

    • check for error conditions and handle them appropriately

Sure do have a look at Aspect Oriented Programming, too - they have neat ways to insert if( o == null ) handleNull() into your bytecode.




Vaya, casi odio agregar otra respuesta cuando tenemos 57 formas diferentes de recomendar el NullObject pattern , pero creo que a algunas personas interesadas en esta pregunta les gustaría saber que hay una propuesta sobre la mesa para que Java 7 agregue "null". "manejo seguro": una sintaxis simplificada para la lógica if-not-equal-null.

El ejemplo dado por Alex Miller se ve así:

public String getPostcode(Person person) {  
  return person?.getAddress()?.getPostcode();  
}  

El ?. significa solo desreferenciar el identificador izquierdo si no es nulo; de lo contrario, evalúe el resto de la expresión como null . Algunas personas, como Dick Wall, miembro de Java Posse, y los votantes de Devoxx realmente aman esta propuesta, pero también hay oposición, con el argumento de que realmente alentará un mayor uso del null como valor centinela.

Actualización: proposed una proposed para un operador de seguridad nula en Java 7 bajo Project Coin. La sintaxis es un poco diferente al ejemplo anterior, pero es la misma noción.

Actualización: la propuesta del operador de seguridad nula no se convirtió en Project Coin. Por lo tanto, no verá esta sintaxis en Java 7.




I've tried the NullObjectPattern but for me is not always the best way to go. There are sometimes when a "no action" is not appropiate.

NullPointerException is a Runtime exception that means it's developers fault and with enough experience it tells you exactly where is the error.

Now to the answer:

Try to make all your attributes and its accessors as private as possible or avoid to expose them to the clients at all. You can have the argument values in the constructor of course, but by reducing the scope you don't let the client class pass an invalid value. If you need to modify the values, you can always create a new object . You check the values in the constructor only once and in the rest of the methods you can be almost sure that the values are not null.

Of course, experience is the better way to understand and apply this suggestion.

Byte!




Dependiendo del tipo de objetos que esté verificando, puede usar algunas de las clases en los recursos comunes de apache tales como: Apache commons lang y Apache commons collections

Ejemplo:

String foo;
...
if( StringUtils.isBlank( foo ) ) {
   ///do something
}

o (dependiendo de lo que necesite comprobar):

String foo;
...
if( StringUtils.isEmpty( foo ) ) {
   ///do something
}

La clase StringUtils es solo una de muchas; hay bastantes buenas clases en los comunes que anulan la manipulación segura.

A continuación se incluye un ejemplo de cómo puede usar la vallidación nula en JAVA cuando incluye la biblioteca apache (commons-lang-2.4.jar)

public DOCUMENT read(String xml, ValidationEventHandler validationEventHandler) {
    Validate.notNull(validationEventHandler,"ValidationHandler not Injected");
    return read(new StringReader(xml), true, validationEventHandler);
}

Y si está utilizando Spring, Spring también tiene la misma funcionalidad en su paquete, consulte la biblioteca (spring-2.4.6.jar)

Ejemplo sobre cómo usar este classf estático de spring (org.springframework.util.Assert)

Assert.notNull(validationEventHandler,"ValidationHandler not Injected");



  1. Never initialise variables to null.
  2. If (1) is not possible, initialise all collections and arrays to empty collections/arrays.

Doing this in your own code and you can avoid != null checks.

Most of the time null checks seem to guard loops over collections or arrays, so just initialise them empty, you won't need any null checks.

// Bad
ArrayList<String> lemmings;
String[] names;

void checkLemmings() {
    if (lemmings != null) for(lemming: lemmings) {
        // do something
    }
}



// Good
ArrayList<String> lemmings = new ArrayList<String>();
String[] names = {};

void checkLemmings() {
    for(lemming: lemmings) {
        // do something
    }
}

There is a tiny overhead in this, but it's worth it for cleaner code and less NullPointerExceptions.




Solo para esta situación: evitar la comprobación de nulos antes de una comparación de cadenas:

if ( foo.equals("bar") ) {
 // ...
}

dará como resultado una NullPointerException si foo no existe.

Puedes evitar eso si comparas tus String esta manera:

if ( "bar".equals(foo) ) {
 // ...
}



I highly disregard answers that suggest using the null objects in every situation. This pattern may break the contract and bury problems deeper and deeper instead of solving them, not mentioning that used inappropriately will create another pile of boilerplate code that will require future maintenance.

In reality if something returned from a method can be null and the calling code has to make decision upon that, there should an earlier call that ensures the state.

Also keep in mind, that null object pattern will be memory hungry if used without care. For this - the instance of a NullObject should be shared between owners, and not be an unigue instance for each of these.

Also I would not recommend using this pattern where the type is meant to be a primitive type representation - like mathematical entities, that are not scalars: vectors, matrices, complex numbers and POD(Plain Old Data) objects, which are meant to hold state in form of Java built-in types. In the latter case you would end up calling getter methods with arbitrary results. For example what should a NullPerson.getName() method return?

It's worth considering such cases in order to avoid absurd results.




public static <T> T ifNull(T toCheck, T ifNull) {
    if (toCheck == null) {
           return ifNull;
    }
    return toCheck;
}



Java 7 tiene una nueva clase de utilidad java.util.Objects en la que hay un método requireNonNull() . Todo lo que hace es lanzar una NullPointerException si su argumento es nulo, pero limpia un poco el código. Ejemplo:

Objects.requireNonNull(someObject);
someObject.doCalc();

El método es más útil para checking justo antes de una asignación en un constructor, donde cada uso del mismo puede guardar tres líneas de código:

Parent(Child child) {
   if (child == null) {
      throw new NullPointerException("child");
   }
   this.child = child;
}

se convierte

Parent(Child child) {
   this.child = Objects.requireNonNull(child, "child");
}



Soy un fan del código "fail fast". Pregúntese: ¿está haciendo algo útil en el caso en que el parámetro sea nulo? Si no tiene una respuesta clara para lo que su código debería hacer en ese caso ... Es decir, nunca debería ser nulo en primer lugar, luego ignórelo y permita que se emita una NullPointerException. El código de llamada tendrá tanto sentido de un NPE como lo sería una IllegalArgumentException, pero será más fácil para el desarrollador depurar y comprender qué salió mal si se lanza un NPE en lugar de su código intentando ejecutar alguna otra contingencia inesperada lógica, que finalmente da como resultado que la aplicación falle de todos modos.




Ultimately, the only way to completely solve this problem is by using a different programming language:

  • In Objective-C, you can do the equivalent of invoking a method on nil , and absolutely nothing will happen. This makes most null checks unnecessary, but it can make errors much harder to diagnose.
  • In Nice , a Java-derived language, there are two versions of all types: a potentially-null version and a not-null version. You can only invoke methods on not-null types. Potentially-null types can be converted to not-null types through explicit checking for null. This makes it much easier to know where null checks are necessary and where they aren't.



Just don't ever use null. Don't allow it.

In my classes, most fields and local variables have non-null default values, and I add contract statements (always-on asserts) everywhere in the code to make sure this is being enforced (since it's more succinct, and more expressive than letting it come up as an NPE and then having to resolve the line number, etc.).

Once I adopted this practice, I noticed that the problems seemed to fix themselves. You'd catch things much earlier in the development process just by accident and realize you had a weak spot.. and more importantly.. it helps encapsulate different modules' concerns, different modules can 'trust' each other, and no more littering the code with if = null else constructs!

This is defensive programming and results in much cleaner code in the long run. Always sanitize the data, eg here by enforcing rigid standards, and the problems go away.

class C {
    private final MyType mustBeSet;
    public C(MyType mything) {
       mustBeSet=Contract.notNull(mything);
    }
   private String name = "<unknown>";
   public void setName(String s) {
      name = Contract.notNull(s);
   }
}


class Contract {
    public static <T> T notNull(T t) { if (t == null) { throw new ContractException("argument must be non-null"); return t; }
}

The contracts are like mini-unit tests which are always running, even in production, and when things fail, you know why, rather than a random NPE you have to somehow figure out.




This is a very common problem for every Java developer. So there is official support in Java 8 to address these issues without cluttered code.

Java 8 has introduced java.util.Optional<T> . It is a container that may or may not hold a non-null value. Java 8 has given a safer way to handle an object whose value may be null in some of the cases. It is inspired from the ideas of Haskell and Scala .

In a nutshell, the Optional class includes methods to explicitly deal with the cases where a value is present or absent. However, the advantage compared to null references is that the Optional<T> class forces you to think about the case when the value is not present. As a consequence, you can prevent unintended null pointer exceptions.

In above example we have a home service factory that returns a handle to multiple appliances available in the home. But these services may or may not be available/functional; it means it may result in a NullPointerException. Instead of adding a null if condition before using any service, let's wrap it in to Optional<Service>.

WRAPPING TO OPTION<T>

Let's consider a method to get a reference of a service from a factory. Instead of returning the service reference, wrap it with Optional. It lets the API user know that the returned service may or may not available/functional, use defensively

public Optional<Service> getRefrigertorControl() {
      Service s = new  RefrigeratorService();
       //...
      return Optional.ofNullable(s);
   }

As you see Optional.ofNullable() provides an easy way to get the reference wrapped. There are another ways to get the reference of Optional, either Optional.empty() & Optional.of() . One for returning an empty object instead of retuning null and the other to wrap a non-nullable object, respectively.

SO HOW EXACTLY IT HELPS TO AVOID A NULL CHECK?

Once you have wrapped a reference object, Optional provides many useful methods to invoke methods on a wrapped reference without NPE.

Optional ref = homeServices.getRefrigertorControl();
ref.ifPresent(HomeServices::switchItOn);

Optional.ifPresent invokes the given Consumer with a reference if it is a non-null value. Otherwise, it does nothing.

@FunctionalInterface
public interface Consumer<T>

Represents an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces, Consumer is expected to operate via side-effects. It is so clean and easy to understand. In the above code example, HomeService.switchOn(Service) gets invoked if the Optional holding reference is non-null.

We use the ternary operator very often for checking null condition and return an alternative value or default value. Optional provides another way to handle the same condition without checking null. Optional.orElse(defaultObj) returns defaultObj if the Optional has a null value. Let's use this in our sample code:

public static Optional<HomeServices> get() {
    service = Optional.of(service.orElse(new HomeServices()));
    return service;
}

Now HomeServices.get() does same thing, but in a better way. It checks whether the service is already initialized of not. If it is then return the same or create a new New service. Optional<T>.orElse(T) helps to return a default value.

Finally, here is our NPE as well as null check-free code:

import java.util.Optional;
public class HomeServices {
    private static final int NOW = 0;
    private static Optional<HomeServices> service;

public static Optional<HomeServices> get() {
    service = Optional.of(service.orElse(new HomeServices()));
    return service;
}

public Optional<Service> getRefrigertorControl() {
    Service s = new  RefrigeratorService();
    //...
    return Optional.ofNullable(s);
}

public static void main(String[] args) {
    /* Get Home Services handle */
    Optional<HomeServices> homeServices = HomeServices.get();
    if(homeServices != null) {
        Optional<Service> refrigertorControl = homeServices.get().getRefrigertorControl();
        refrigertorControl.ifPresent(HomeServices::switchItOn);
    }
}

public static void switchItOn(Service s){
         //...
    }
}

The complete post is NPE as well as Null check-free code … Really? .




Links