Hi, I need your opinions: We have an extension pr...
# codereview
r
Hi, I need your opinions: We have an extension property for Boolean:
Copy code
val Boolean?.isTrue
    get() = this == true
What is better for
x: Boolean?
?
Copy code
if(x == true) ...
Or
Copy code
if(x.isTrue) ...
We also have extension values
isFalse
,
isTrueOrNull
,
isFalseOrNull
. What do you think about those?
j
Personally I don't like extensions on nullable types in general. They break my pattern recognition of
.
vs
?.
. I kinda assume the left side is non-nullable if I see a
.
. This is why I tend not to use
.orEmpty()
for collections, and prefer
?: emptyList()
. Now I have to admit I find
x == true
a bit confusing too (personally) for nullable booleans, but this is technically the recommended style AFAIR. So overall I wouldn't lean strongly towards either of those choices. Instead, I'd rather favor an approach where we just don't have that many nullable booleans, and this is not needed.
e
there are other standard extensions on nullable types like
.toString()
which is definitely more convenient than
?.toString() ?: "null"
but in this case I really don't think extensions on nullable booleans are worthwhile
j
there are other standard extensions on nullable types like .toString() which is definitely more convenient than ?.toString() ?: "null"
Usually, string interpolation does its job without me having to write
toString()
explicitly. I do write
.toString()
explicitly sometimes, but I don't recall ever doing that on a nullable value. I would add that I don't recall ever needing the
"null"
value outside string interpolation.
e
I would prefer
it.toString()
over
"$it"
when that's the only thing being stringified. but in any case that's not the only such generic function,
.equals()
is too
… I thought, but actually no it's just the
==
operator being magic
.isNullOrEmpty()
.isNullOrBlank()
.orEmpty()
are useful but not really critical imo
r
Oh, man, I don't wanna talk strings... Can you please tell me if you'd create an extension for this thing and if you see any advantages in the extension?
e
I would not. the only advantage I can see is that it's easier to chain
foo.isTrue.somethingElse()
than
(foo == true).somethingElse()
but that's not something you do with Booleans anyway
r
I know what you could chain:
.not()
🤣
e
it turns out it's a common desire to negate the
==
in some way… common enough that there might be a shortcut for it…
r
!=
c
IMO, I would treat this extension as a code smell. It adds a layer of hidden code for no benefits
It doesn't help that I've seen codebases with similar "simple" helpers that did something else than what their name said 😕
1