0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AIコードのnullable処理はちゃんと見た方がいい話

0
Posted at

はじめに

このエントリは、初挑戦カレンダー Advent Calendar 2025 の 20日目記事です。
https://qiita.com/advent-calendar/2025/silvia

今年、Twitterで何か主張したかったことを拾いながら記事を書いていきます。

本文

AIにコードを書いてもらうとよくあるのが、以下のようなNullableの代入である。

int intval = xxx.data ?? 0;

intvalはint、xxx.dataはint?型に定義されているとき、このようなコードがよく作られる。
これは型を合わすために処理で、一件問題ないように見えるのだが、これが運用の時に悪さをする場合がある。

何故なら、xxx.dataに整数データが入っていない時に0を代入するのが、果たして設計通りなのかが考慮されていないからである。

例えばxxx.dataは必ず整数が入るはず、という設計でこのコードを書いた時、xxx.dataにnullが入っていた場合は想定外としてエラーにするのが正しい。
本当に想定外であれば
if(xxx.data == null) throw new Exception();
のように明示的エラーにする必要はなく、
int intval = xxx.data.Value;
とすることで、nullだった場合に例外がエスカレーションされる。

しかし、AIが提示したコード
int intval = xxx.data ?? 0;
はエラーが発生せず、intvalに0が代入される。
そして正常終了してしまうので、エラーが追えない。

さらに、いつかどこかでこの0が画面や計算処理に出て来て、えっどうしてここで0が?!
となってしまうのである。

AIにコードを書いてもらう場合は、この処理には十分注意したい。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?