this is a subjective design question, but:
say you've got
Copy code
interface Foo {
/* ... */
}
interface Bar {
val thing: Thing
/* ... */
}
fun getFooByName(s: String): Foo? = /* ... */
// no getBarByName
// ... and a bunch of classes that implement some combination of Foo and Bar
would you add a
fun asBar(): Bar?
or even
fun getThing(): Thing?
for
Foo
, or is that silly from a coupling/API design point of view?
m
Michael de Kaste
04/15/2024, 6:24 AM
I've personally only ever exposed a
Copy code
val thing: Thing?
on a sealed interface where only 1 or 2 implementations have a thing and the others do not. (where translating it to an API object was easier to do with nullable fields)
I don't see the need for asBar() func as
Copy code
as Bar?
functionally does the same.
In most cases I would advice against such pattern, but it depends on the usage and situation, like everything
thank you color 1
y
y
04/15/2024, 6:28 AM
for some more context,
Foo
and
Bar
used to be a single interface that (for no good reason, imho) was later split into
Bar
which contains
val Thing
and nothing else
🔥 1
j
Joffrey
04/15/2024, 8:59 AM
> for no good reason, imho
Splitting an interface like this makes the code more type-safe. You can use
Bar
instead of
Foo
in areas of the code where you know the objects have a
thing
. It's usually better to do this than to have a nullable property and never know at compile time whether it's there or not.
y
y
04/15/2024, 12:00 PM
@Joffrey that's almost certainly why this was done. thanks for this