Home > database >  How can I simplify this if else statement to reduce code repetition?
How can I simplify this if else statement to reduce code repetition?

Time:12-22

How can i simplify this if else statement to reduce code repetition? As you can see, the variable uri is assigned with just 1 parameter changing.

    var uri: String?

    if (otfText.isNullOrEmpty()) {
        uri = StickerFileManager.checkIfStickerCreated(
            sticker,
            head,
            sticker.translatedOTFText
        )
        if (uri.isNullOrEmpty()) {
            ResourceDownloadManager.downloadResource(sticker)
            uri = StickerCreator().createStickerWith(
                sticker,
                head,
                sticker.translatedOTFText
            )
        }
    } else {
        uri = StickerFileManager.checkIfStickerCreated(
            sticker,
            head,
            otfText
        )
        if (uri.isNullOrEmpty()) {
            ResourceDownloadManager.downloadResource(sticker)
            uri = StickerCreator().createStickerWith(
                sticker,
                head,
                otfText
            )
        }
    }

CodePudding user response:

This is one way to do it. If it is simply null than you should use otfText ?: sticker.translatedOTFText If it is nullOrEmpty then below method can be used

     uri = StickerFileManager.checkIfStickerCreated(
          sticker,
          head,
          if (otfText.isNullOrEmpty()) sticker.translatedOTFText else otfText)
            if (uri.isNullOrEmpty()) {
                ResourceDownloadManager.downloadResource(sticker)
                uri = StickerCreator().createStickerWith(
                    sticker,
                    head,
                    if (otfText.isNullOrEmpty()) sticker.translatedOTFText else otfText
                )
            }

CodePudding user response:

I would do it like this

var text = if (otfText.isNullOrEmpty()) sticker.translatedOTFText else otfText
var uri = StickerFileManager.checkIfStickerCreated(
    sticker,
    head,
    text
)
if (uri.isNullOrEmpty()) {
    ResourceDownloadManager.downloadResource(sticker)
    uri = StickerCreator().createStickerWith(
        sticker,
        head,
        text
    )
}

It's very similar to Shahnawaz's answer but I think it's better to avoid having to do the same check twice so I save the result in the text variable and use that one instead at the two spots.

CodePudding user response:

Try like this

var uri = StickerFileManager.checkIfStickerCreated(
    sticker,
    head,
    if (otfText.isNullOrEmpty()) sticker.translatedOTFText else otfText
)


if (uri.isNullOrEmpty()) {
    ResourceDownloadManager.downloadResource(sticker)
    uri = StickerCreator().createStickerWith(
        sticker,
        head,
         if (otfText.isNullOrEmpty()) sticker.translatedOTFText else otfText
    )
}
  • Related