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

Improve Tag<T>.values() method #15

Open
Hiiragi283 opened this issue Jun 28, 2024 · 8 comments
Open

Improve Tag<T>.values() method #15

Hiiragi283 opened this issue Jun 28, 2024 · 8 comments
Labels
enhancement New feature or request

Comments

@Hiiragi283
Copy link
Contributor

実装次第ではTag<T>.values()を呼ぶと例外を吐かれる
現状らぎマテで使ってるのはこれ

fun <T : Any> Tag<T>.safeValues(): List<T> = try {
    values()
} catch (e: Exception) {
    listOf()
}

これを改善して

fun <T: Any> Tag<T>.valueResult: Result<List<T>>
  get() = runCatching { values() }

的なのをつくれないだろうか

@Hiiragi283 Hiiragi283 added the enhancement New feature or request label Jun 28, 2024
@Hiiragi283
Copy link
Contributor Author

これTag.Identified<T>にも使えるんじゃね?

fun <T: Any> Tag<T>.idResult: Result<Identifier>
  get() = runCatching { (this as Tag.Identified<T>).id }

@Hiiragi283
Copy link
Contributor Author

ただなんでもかんでもResult<T>で包んじゃっていいのだろうか

@turtton
Copy link
Contributor

turtton commented Jun 28, 2024

失敗する可能性を型で表現するためにResultを使うのは良いことだと思いますよ
ただ命名はtryGetId()みたいにしたほうが良いかも?

@Hiiragi283

This comment was marked as resolved.

@toliner
Copy link
Collaborator

toliner commented Jun 28, 2024

Resultを使うか使わないか、全体を通して方針を統一しないと無秩序になるので、何かしらの統一はしたい
そんでぱっと思いついた指針

  • 基本は普通の返り値
  • 「値が存在しない」事に起因する例外はnullで値を返す
  • 利用者側がハンドリングすべきエラーが発生する場合はResult型等を使う

Tag<T>.values()は、「値が存在しない」事に起因すると思うので、nullを返す(か空のリストを返す)のが良いと思う

@Hiiragi283
Copy link
Contributor Author

List<T>?は気持ち悪いからemptyList()すかね

@turtton
Copy link
Contributor

turtton commented Jun 28, 2024

Tag.values()は、「値が存在しない」事に起因すると思うので、nullを返す(か空のリストを返す)のが良いと思う

これちゃんと確認したんですけど、吐かれる可能性あるのは IllegalStateException みたいですね。例外潰してemptyList返すなら一応warnで例外をログに流すとかはした方が良いかもしれません

@Hiiragi283
Copy link
Contributor Author

こんな感じかな

fun <T : Any> Tag<T>.safeValues(): List<T> = runCatching { values() }
    .onFailure { e: Throwable -> HTLogger.log { logger: Logger -> logger.throwing(e) } }
    .getOrDefault(emptyList())

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

No branches or pull requests

3 participants