0

There are many != null s and != null && !s.isEmpty()

Like this:

if(sidebar.getModel() != null && !sidebar.getModel().isEmpty()) { ... }

In our code. Too many that it looks not really good. Is there a short hand for this null check. Which Java library provides extensive support for such shorthand functions while does not need that much dependency on other java artifacts?

Like if(notNull(s)) or if(notEmpty(s)) which checks for not null and not empty altogether. Something like this.

Emil Laine
  • 41,598
  • 9
  • 101
  • 157
quarks
  • 33,478
  • 73
  • 290
  • 513

3 Answers3

1

For String class there is StringUtils.isEmpty(String value) in apache-commons-lang3. For other types you can create your own static method and use it via static import.

Andremoniy
  • 34,031
  • 20
  • 135
  • 241
1

Apache commons-lang

Checks if a String is not empty (""), not null and not whitespace only.

StringUtils.isNotBlank(null)      = false
StringUtils.isNotBlank("")        = false
StringUtils.isNotBlank(" ")       = false
StringUtils.isNotBlank("bob")     = true
StringUtils.isNotBlank("  bob  ") = true

Parameters: str - the String to check, may be null

Returns: true if the String is not empty and not null and not whitespace

LittlePanda
  • 2,496
  • 1
  • 21
  • 33
0

From Java 1.7 you can use utility class Objects:

Checks that the specified object reference is not null. This method is designed primarily for doing parameter validation in methods and constructors, as demonstrated below:

 public Foo(Bar bar) {
     this.bar = Objects.requireNonNull(bar);
 }

Useful links:

UPDATE:

For avoiding NullPointerException Java 1.8 has some special class Optional.

Working with this class will be smt as follows:

    String contents = new String(Files.readAllBytes(Paths.get(Test.ALICE_PATH)), StandardCharsets.UTF_8);
    List<String> wordList = Arrays.asList(contents.split("[\\P{L}]+"));

    Optional<String> optionalValue = wordList.stream().filter(s -> s.contains("red")).findFirst();
    optionalValue.ifPresent(s -> System.out.println(s + " contains red"));

    Set<String> results = new HashSet<>();
    optionalValue.ifPresent(results::add);
    Optional<Boolean> added = optionalValue.map(results::add);

    System.out.println(added);
    //
    Optional<String> optionalString = Optional.empty();
    String result = optionalString.orElse("N/A");
    System.out.println("result: " + result);

    result = optionalString.orElseGet(() -> System.getProperty("user.dir"));
    System.out.println("result: " + result);
catch23
  • 17,519
  • 42
  • 144
  • 217
  • 1
    It is very bad decision: it will throw `NullPointerException` if value is null. Not what really QA wants – Andremoniy Apr 03 '15 at 08:45
  • 1
    This will throw an exception if the object is null. That's not what the questioner wants. It seems that these methods should be used for validation of parameters. – Mehul Lalan Apr 03 '15 at 08:46