Return null or create Null object

i got a trait name Connection,
and it has multiple implementation.
my Factory Object return me an implementation base on configuration,
and the Connection can be null either(if the user doesnt want use database at all).
what is best practice in this case?
1.that my Factory object will return null and i will check if the connection variable is null before using his functions.
2.create NullConnection that will extend my Connection trait, and the Implementation of it function will do nothing.and than i can return in my Factory object the NullConnection and not check if it is a null.?

The canonical way is to use Option

val connection = Factory.connection
val connectionOpt = Option(connection)

If connection is null, connectionOpt will be None, otherwise it will be

Then, each of the following

connectionOpt.foreach(connection => doSomethingWith(connection))

will apply doSomthingWith to the connection, if it is Some(connection)
and do nothing, if it is None.

 Best, Oliver
1 Like