1

I'm using Lombok S1F4j to log my data and In order to avoid logging empty data , I check if the object is null or not . I want avoid this guys so my code is more robuste and so easy to test .

This is an example :

if (object != null)
 {
log.info("lalalalal", object)
object1.set(object)  }

Is there anyway to avoid checking null and not logging if object is null ?

Anas Hadhri
  • 159
  • 1
  • 2
  • 9
  • You should look into Google guava or Apache commons. They have a bunch of utility classes that'll fit this use case. You could also try locking into Optionals. – HaseebR7 Dec 17 '19 at 09:28
  • you can write your own static factory method and have the check there instead of using Lombok – Richard Elite Dec 17 '19 at 09:37
  • 1
    You could use an optional `Optional.ofNullable(object).ifPresent(it -> log.info("lalalalal", it));` But that isn't really any better. IMHO there is nothing wrong with the if statement. – M. Deinum Dec 17 '19 at 09:45
  • I think , it's better with OptionalOfNullable , because it is more simple to write your Unit tests after if you want that UT covers all the dev . – Anas Hadhri Dec 17 '19 at 10:29

2 Answers2

0

you can add a question mark before calling any functions or data fields of an object. That will only call the function if the object is not null

object?.function()
  • That will work for some JVM languages like Groovy, but there's nothing in the question to indicate that the OP is not using Java, for which your anwer will not work. – NickJ Dec 18 '19 at 11:31
0

You can create a wrapper function something like:


    public static void log_info(Logger logger, Object obj) {
        if (obj != null) {
            logger.info(obj);
        }
    }

And, use this wrapper method in place of logging methods.

Gorav Singal
  • 508
  • 3
  • 11