Is there a safe "no id" @StringRes or @DrawableRes value for a null object pattern?

968 views Asked by At

Suppose I wanted to implement a null object pattern of a model so as to guarantee an object that will do nothing, without requiring null checks on nullable fields.

interface Model(
    val textId: Int,
    val imageId: Int,
    ...
)

data class ModelImpl(
    @StringRes val textId: Int,
    @DrawableRes val imageId: Int,
    ...
) : Model

data class NullModel(
    @StringRes val textId: Int = StringRes.None, // some value representing no value ?
    @DrawableRes val imageId: Int = DrawableRes.None,
    ...
) : Model

Is there any resource id number for strings or drawables, that could be passed to stringResource(id = model.textId) or painterResource(id = model.imageId) which would result in an empty string or a 'placeholder no image' without trigging an error?

Alternatively I could, of course, make an empty string resource and blank image resource to refer to myself but I would also question if, in the world of clean architecture and/or idiomatic Kotlin code, this is even a good practise in the first place?

Edit: I noticed that in the Android Docs, the parameter type of compose's resource function's id is Int?, but contrary to this documentation, in the Compose version I am using, 1.2.0-alpha04, these id parameters are not nullable types. I also ask this question for the Resources.getString() etc. equivalents which are also not nullable. https://developer.android.com/reference/kotlin/androidx/compose/ui/res/package-summary

2

There are 2 answers

0
Kostya  Mistery On

Add <string name="empty"/> to String resources and just use it as R.string.empty Follow the "KISS" principle.

0
nilsi On

I couldn't find any elegant solution to this either. What I ended up doing is the following:

state.emailError?.let { stringResource(it) }.orEmpty()