Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature Request] Modeling Error results using type hierarchy #7

Open
alibagherifam opened this issue Sep 25, 2024 · 1 comment
Open

Comments

@alibagherifam
Copy link

alibagherifam commented Sep 25, 2024

Generally, it is a good idea to model Application-Specific Errors using Type Hierarchies (ADTs) and leaving exceptions for Programming Errors. Creating an exception for a simple error can be inefficient, as it includes a full stack trace, and exceptions are meant to remain uncaught to cause a crash and highlight critical programming mistakes.

Roman Elizarov has written a great article about Kotlin and Exceptions that is worth reading.

Additionally, using type hierarchies makes APIs more discoverable. For instance, you would check for BazaarIsNotInstalledException only if you know it exists. However, with type hierarchies, you can't easily miss that cause the compiler will scream at you :)

Since exception messages cannot be used directly without localization, you might end up treating all errors the same and miss the opportunity of already knowing root cause of the error, such as BazaarIsNotInstalled.

// Exceptions
BazaarUpdater.getLastUpdateState(context) { result ->
   when (result) {
      /* ... */

      is Error -> {
          // Can't use non-localized `result.message`
          showMessage("خطا در بروزرسانی از بازار") 
      }
   }
}

// Type Hierarchy
BazaarUpdater.getLastUpdateState(context) { result ->
   when (result) {
      /* ... */

      // Compiler added this branch
      is Error.BazaarIsNotInstalled -> { 
           showMessage("اپلیکیشن بازار روی دستگاه شما یافت نشد") 
      }

      is Error.Unknown -> {
           showMessage("خطا در بروزرسانی از بازار") 
      }
   }
}
@alibagherifam alibagherifam changed the title Modeling Error results with type hierarchy [Feature Request] Modeling Error results using type hierarchy Sep 25, 2024
@hamid97m
Copy link
Collaborator

hamid97m commented Nov 7, 2024

Thank you for bringing this issue to our attention. We appreciate your insight and agree that your suggestion could be quite beneficial. If you'd like, please feel free to submit a pull request with your proposed fix. We'd be happy to review it and work towards improving the project together. Thank you once again for your valuable contribution!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants