-
Notifications
You must be signed in to change notification settings - Fork 698
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
What about Null Object pattern? #20
Comments
Hi |
Just because there's null safety doesn't mean the null object pattern is obsolete. I think one of the main ideas behind the null object pattern is to have a default object in the case that you are required to have an object, but really have nothing to pass to it. |
I agree with @shekibobo, Null Safety and Null Object are orthogonal concepts. Here is a good description of it https://sourcemaking.com/design_patterns/null_object On the other hand it is much less used in Kotlin as we have better null handling with I will think about example where it fits in Kotlin. I am also happy to accept PR. |
This is exactly how I ended up here asking this question :) |
Hi Below, a small snippet (from the Sourcemaking Java example): import java.io.OutputStream
import java.io.PrintStream
object NullOutputStream : OutputStream() {
override fun write(b: Int) {
// do nothing
}
}
object NullPrintStream : PrintStream(NullOutputStream)
fun doSomething(debugOut: PrintStream) {
var sum = 0
for (i in 0..9) {
sum += i
debugOut.println("i = $i")
}
println("sum = $sum")
}
fun main(args: Array<String>) {
doSomething(NullPrintStream) // without debug output
doSomething(System.out) // with debug output
} With elvis operator: import java.io.PrintStream
fun doSomething2(debugOut: PrintStream? = null) {
var sum = 0
for (i in 0..9) {
sum += i
debugOut?.println("i = $i")
}
println("sum = $sum")
}
fun main(args: Array<String>) {
doSomething2() // without debug output
doSomething2(System.out) // with debug output
} |
Will you create a sample for Null Object pattern?
The text was updated successfully, but these errors were encountered: