https://kotlinlang.org logo
Title
j

jcechace

11/05/2018, 12:41 PM
Any idea how to write this piece of code nicer?
override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {
        try {
            customTm?.checkServerTrusted(chain, authType) ?: defaultTm.checkServerTrusted(chain, authType)
        } catch (e : CertificateException) {
            defaultTm.checkServerTrusted(chain, authType)
        }
    }
m

maxmello

11/05/2018, 12:52 PM
You could throw an Exception on the right side of the elvis operator
j

jcechace

11/05/2018, 12:54 PM
Yea…probably would be more readable but it has this “Using exception to control execution flow” anti-pattern feeling to it
m

maxmello

11/05/2018, 1:05 PM
Only alternative I can think of:
override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {
        fun checkCustomTm() = return try {
				customTm?.checkServerTrusted(chain, authType)
			} catch (e : CertificateException) {
				null
			}
		}
		checkCustomTm() ?: defaultTm.checkServerTrusted(chain, authType)
    }
c

camkadev

11/05/2018, 9:07 PM
my 5 cents override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) { try { when(val tm = customTm){ null -> defaultTm.checkServerTrusted(chain, authType) else -> tm.checkServerTrusted(chain, authType) } } catch (e : CertificateException) { defaultTm.checkServerTrusted(chain, authType) } }