can you review my error handling and detect any unused, redundant or code smells bugs or performance issues in this or detect any OVER-ENGINEERED CODE // Error types
sealed interface WidgetError {
data object NotFound : WidgetError
data object InvalidWidget : WidgetError
data class Storage(val message: String) : WidgetError
data class UpdateFailed(val message: String) : WidgetError
}
// Outcome sealed class
sealed class Outcome {
data class Ok(val value: T) : Outcome()
data class Err(val error: WidgetError) : Outcome()
code
inline fun <R> map(transform: (T) -> R): Outcome<R> = when (this) {
is Ok -> Ok(transform(value))
is Err -> this
}
inline fun <R> flatMap(transform: (T) -> Outcome<R>): Outcome<R> = when (this) {
is Ok -> transform(value)
is Err -> this
}
fun getOrNull(): T? = when (this) {
is Ok -> value
is Err -> null
}
}
// Helper function for widget operations
inline fun widgetOperation(block: () -> T): Outcome = try {
Outcome.Ok(block())
} catch (e: Exception) {
Outcome.Err(
when {
e.message?.contains("not found") == true -> WidgetError.NotFound
e.message?.contains("invalid") == true -> WidgetError.InvalidWidget
e is IOException -> WidgetError.Storage(e.message ?: "Storage error")
else -> WidgetError.UpdateFailed(e.message ?: "Update failed")
}
)
}
fun getErrorMessage(error: WidgetError): String = when (error) {
is WidgetError.NotFound -> "Widget not found"
is WidgetError.InvalidWidget -> "Invalid widget"
is WidgetError.Storage -> "Save failed"
is WidgetError.UpdateFailed -> "Update failed"
}
// Extension functions for easier usage
fun Outcome.onSuccess(action: (T) -> Unit): Outcome {
if (this is Outcome.Ok) action(value)
return this
}
fun Outcome.onError(action: (WidgetError) -> Unit): Outcome {
if (this is Outcome.Err) action(error)
return this
}
fun Outcome.getOrElse(default: () -> T): T = when (this) {
is Outcome.Ok -> value
is Outcome.Err -> default()
}
and override suspend fun doWork(): Result {
return when (val outcome = widgetPreferencesManager.updateAllWidgets { cityId ->
getWeatherDBbyCityIdUseCase(cityId)
}) {
is Outcome.Ok -> Result.success()
is Outcome.Err -> {
// Log the error for debugging
Log.e(
"WidgetUpdateWorker",
"Failed to update widgets: ${getErrorMessage(outcome.error)}"
)
code
// Retry based on error type
when (outcome.error) {
is WidgetError.Storage,
is WidgetError.UpdateFailed -> Result.retry()
is WidgetError.NotFound,
is WidgetError.InvalidWidget -> Result.failure()
}
}
}
} and class WidgetReceiver : GlanceAppWidgetReceiver(), KoinComponent {
override val glanceAppWidget: GlanceAppWidget = WeatherWidget()
private val widgetPreferencesManager: WidgetPreferencesManager by inject()
private val coroutineScope = CoroutineScope(
SupervisorJob() + Dispatchers.IO + CoroutineExceptionHandler { _, throwable ->
// Log error but don't crash
Log.e("WidgetReceiver", "Coroutine error", throwable)
}
)
override fun onUpdate(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetIds: IntArray
) {
super.onUpdate(context, appWidgetManager, appWidgetIds)
// Trigger immediate update for all widgets
coroutineScope.launch {
appWidgetIds.forEach { widgetId ->
when (val result = widgetPreferencesManager.getWidgetState(widgetId)) {
is Outcome.Ok -> {
result.value?.let { state ->
if (state.weather == null && state.config.selectedCityId != 0L) {
// Widget needs weather data
WidgetUpdateWorker.schedule(context)
}
}
}
is Outcome.Err -> {
// Log error but continue with other widgets
Log.w("WidgetReceiver", "Failed to get state for widget $widgetId")
}
}
}
}
}
override fun onDeleted(context: Context, appWidgetIds: IntArray) {
super.onDeleted(context, appWidgetIds)
// Clean up widget data
coroutineScope.launch {
appWidgetIds.forEach { widgetId ->
when (widgetPreferencesManager.removeWidget(widgetId)) {
is Outcome.Ok -> {
// Successfully removed
}
is Outcome.Err -> {
Log.w("WidgetReceiver", "Failed to remove widget $widgetId")
}
}
}
// Cancel worker if no widgets remain
when (val result = widgetPreferencesManager.getAllWidgetIds()) {
is Outcome.Ok -> {
if (result.value.isEmpty()) {
WidgetUpdateWorker.cancelScheduled(context)
}
}
is Outcome.Err -> {
Log.w("WidgetReceiver", "Failed to get widget IDs")
}
}
}
} and // viewmodel private suspend fun loadWidgetConfig(widgetId: Int) {
when (val result = widgetPreferencesManager.getWidgetConfig(widgetId)) {
is Outcome.Ok -> {
val config = result.value ?: WidgetConfig(widgetId = widgetId)
updateState { state ->
state.copy(
config = config,
selectedCity = state.citiesById[config.selectedCityId]
)
}
}
is Outcome.Err -> {
updateState { state ->
state.copy(
error = getErrorMessage(result.error),
config = WidgetConfig(widgetId = widgetId)
)
}
}
}
}
private suspend fun observeWidgetChanges(widgetId: Int) {
widgetPreferencesManager.observeWidgetState(widgetId)
.filterNotNull()
.collect { widgetState ->
updateState { state ->
state.copy(
config = widgetState.config,
selectedCity = state.citiesById[widgetState.config.selectedCityId]
)
}
}
} fun saveConfiguration() {
val currentState = _uiState.value
// Validation
if (currentState.selectedCity == null) {
updateState { it.copy(error = "Please select a city before saving") }
return
}
if (currentState.isSaving) return
viewModelScope.launch {
updateState { it.copy(isSaving = true, error = null) }
// Chain operations - stop on first failure
val saveResult = saveConfigAndWeather(
currentState.config,
currentState.selectedCity
)
updateState { state ->
state.copy(
isSaving = false,
error = when (saveResult) {
is Outcome.Ok -> null
is Outcome.Err -> getErrorMessage(saveResult.error)
}
)
}
}
}
private suspend fun saveConfigAndWeather(
config: WidgetConfig,
city: Weather
): Outcome<Unit> {
// Save config
val configResult = widgetPreferencesManager.saveWidgetConfig(currentWidgetId, config)
if (configResult is Outcome.Err) return configResult
// Update weather
val widgetModel = city.mapToWidgetModel()
return widgetPreferencesManager.updateWidgetWeather(currentWidgetId, widgetModel)
}
Assistant
Your code is generally well-structured and follows good practices for error handling and functional programming. However, there are a few areas where improvements can be made to avoid redundancy, improve performance, and eliminate potential code smells. Here are some suggestions:
1. Redundant Code and Code Smells
getErrorMessage Function
The getErrorMessage function can be simplified by using a when expression with a single is check for each error type.
kotlin
fun getErrorMessage(error: WidgetError): String = when (error) {
WidgetError.NotFound -> "Widget not found"
WidgetError.InvalidWidget -> "Invalid widget"
is WidgetError.Storage -> "Save failed"
is WidgetError.UpdateFailed -> "Update failed"
}
onSuccess and onError Extension Functions
These functions are redundant because they don't modify the Outcome object. They can be replaced with simple if checks.
kotlin
fun <T> Outcome<T>.onSuccess(action: (T) -> Unit) {
if (this is Outcome.Ok) action(value)
}
fun <T> Outcome<T>.onError(action: (WidgetError) -> Unit) {
if (this is Outcome.Err) action(error)
}
2. Performance Improvements
widgetOperation Function
The widgetOperation function can be optimized by avoiding multiple calls to e.message?.contains.
kotlin
inline fun <T> widgetOperation(block: () -> T): Outcome<T> = try {
Outcome.Ok(block())
} catch (e: Exception) {
val message = e.message ?: "Unknown error"
Outcome.Err(
when {
message.contains("not found") -> WidgetError.NotFound
message.contains("invalid") -> WidgetError.InvalidWidget
e is IOException -> WidgetError.Storage(message)
else -> WidgetError.UpdateFailed(message)
}
)
}
3. Over-Engineered Code
doWork Function
The doWork function can be simplified by removing the redundant when expression.
kotlin
override suspend fun doWork(): Result {
return when (val outcome = widgetPreferencesManager.updateAllWidgets { cityId ->
getWeatherDBbyCityIdUseCase(cityId)
}) {
is Outcome.Ok -> Result.success()
is Outcome.Err -> {
// Log the error for debugging
Log.e(
"WidgetUpdateWorker",
"Failed to update widgets: ${getErrorMessage(outcome.error)}"
)
// Retry based on error type
when (outcome.error) {
is WidgetError.Storage,
is WidgetError.UpdateFailed -> Result.retry()
else -> Result.failure()
}
}
}
}
4. Unused Code
getOrElse Extension Function
The getOrElse function is not used anywhere in the provided code. If it's not needed, it can be removed.
5. General Improvements
CoroutineScope Initialization
The CoroutineScope initialization in WidgetReceiver can be improved by using CoroutineScope(Dispatchers.IO + SupervisorJob()) and adding the CoroutineExceptionHandler separately.