I need some advice for my following code. ``` imp...
# getting-started
t
I need some advice for my following code.
Copy code
import java.time.Duratio

class SimpleObjectCache (val cacheDuration: Duration)  {
    private val cacheManager = if (cacheDuration.getSeconds().toInt() <= 2147483647) SimpleObjectCacheManager(cacheDuration.getSeconds().toInt()) else throw IllegalArgumentException("cacheDuration Int value is out of range")
It is simple, i hope you got what i m doing is.
cacheManger
is too long right? 😁 Is there any better way? 🤔
k
Make
SimpleObjectCacheManager
accept
Duration
in the constructor.
Copy code
class SimpleObjectCache(val cacheDuration: Duration) {
  private val DURATION_THRESHOLD = Duration.ofSeconds(2147483647)

  private val cacheManager: SimpleObjectCacheManager =
    if (cacheDuration <= DURATION_THRESHOLD) SimpleObjectCacheManager(cacheDuration)
    else error("cacheDuration Int value is out of range")
}
👍 1
Or even better make use of
require
on initialization
Copy code
class SimpleObjectCache(cacheDuration: Duration) {
  init {
    require(cacheDuration <= DURATION_THRESHOLD) { "cacheDuration Int value is out of range" }
  }

  private companion object {
    val DURATION_THRESHOLD = Duration.ofSeconds(2147483647)
  }

  private val cacheManager = SimpleObjectCacheManager(cacheDuration)
}
🤔 1
1
t
thanks for you advice @Kirill Zhukov
👍 1