I have static function which is limited to some context eg only for docs. There are 2 alternative ways to define it as top-level function or function in an object.
1.
package com.armsoft.mtrade.data.pref
import com.armsoft.mtrade.App
import com.armsoft.mtrade.domain.model.DocSaveType
object DocPrefManager {
private const val DOC_PREF = "DOC_PREF"
private const val KEY_ORDER_SAVE_TYPE = "KEY_ORDER_SAVE_TYPE"
@JvmStatic
fun setOrderSaveType(orderSaveType: DocSaveType) {
val context = App.getContext()
val sharedPreferences = context.getSharedPreferences(DOC_PREF, 0)
val editor = sharedPreferences.edit()
editor.putString(KEY_ORDER_SAVE_TYPE, orderSaveType.getCode())
editor.commit()
}
}
2.
package com.armsoft.mtrade.data.pref
import com.armsoft.mtrade.App
import com.armsoft.mtrade.domain.model.DocSaveType
fun setOrderSaveType(orderSaveType: DocSaveType) {
val context = App.getContext()
val sharedPreferences = context.getSharedPreferences(DocPrefManager.DOC_PREF, 0)
val editor = sharedPreferences.edit()
editor.putString(DocPrefManager.KEY_ORDER_SAVE_TYPE, orderSaveType.getCode())
editor.commit()
}
The advantage of top-level function that it is not wrapped in an object and disadvantage that it can be accessed from everywhere without class name prefix. Are there advantages or disadvantages or best practice for such cases?
KotlinConf 2017 - You Can, but Should You? by Mike Gouline recommends we should use the top-level function carefully because it may cause "autocomplete pollution".
But, BTW, Andrey Breslav regarded the top-level function as his the most favorite language feature in KotlinConf 2018 - Closing Panel.
The recommended practice is to never use object for creating namespaces, and to always use top-level declarations when possible. We haven’t found name conflicts to be an issue, and if you do get a conflict, you can resolve it using an import with alias.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With