Перейти к содержанию
Skillpedia
Код в целом25k · #10062

nullaway

Что он делает

Этот скилл ведёт ИИ через исправление ошибок NullAway, инструмента, который находит возможные null-значения в Java-коде. Он нужен разработчикам, которые добавляют или обновляют null-аннотации.

Когда использовать

  • ✓Когда NullAway сообщает об ошибке про значение, которое может быть null.
  • ✓Когда вы добавляете @NullMarked в Java-файл и нужно исправить новые предупреждения.
  • ✓Когда нужно передать nullable-поставщика или наблюдаемое значение, не сломав код.

Ссылка на скилл

https://github.com/chromium/chromium/blob/main/agents/skills/nullaway/SKILL.md

Скопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.

Как использовать

Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.

Готовое сообщение для вставки

Используй этот скилл, чтобы помочь мне: https://github.com/chromium/chromium/blob/main/agents/skills/nullaway/SKILL.md Прочитай файл SKILL.md по этой ссылке и следуй его инструкциям в моей задаче.
Хотите, чтобы ваш ИИ сам находил такие скиллы?Установите бесплатный MCP Skillpedia: одна строка, и перед каждой задачей он ищет среди 15 000+ скиллов.Установить за 1 минуту →

Пример запроса к вашему ИИ

“NullAway показывает ошибку в моём Java-файле. Можешь исправить её, не меняя работу приложения?”

5 новых скиллов в неделю. 1 минута чтения.

Как это работает

ИИ смотрит, как используется каждое значение, которое может быть null. Затем он добавляет безопасную проверку или утверждение, выбирая самый лёгкий вариант, который устраивает проверяющего.

Технический текст (оригинальный SKILL.md)

Оригинальный текст автора на английском, прямо с GitHub.

Core Principles

1. Migration to @NullMarked vs New Code

The approach differs significantly depending on whether you are migrating existing code to @NullMarked or writing new code in an already @NullMarked context:

  • Migration to @NullMarked:
    • Goal: Satisfy the static analyzer while minimizing functional changes to avoid regressions.
    • Practice: Use NullUtil.assumeNonNull() when dereferencing immediately to satisfy the analyzer without runtime overhead. Use assert when storing or returning values. Use if guards occasionally if it helps avoid assertions, but avoid changing the logic.
  • New Code (and modifying already @NullMarked code):
    • Goal: Build robust, null-safe components from the ground up.
    • Practice: Be more liberal with asserts to enforce contracts. Rely on correct annotations (or their absence for implicit @NonNull) and only use null guards for @Nullable values. assumeNonNull() should generally not be used for new code.

2. No Functional Changes (For Migration)

  • Rule: When migrating existing code, avoid adding new throwing runtime checks where they did not exist before, unless guided by the rules below.

3. assumeNonNull vs assert != null

The choice between assumeNonNull and Java assert depends on how the value is used:

  • Dereferencing @Nullable values immediately: Use NullUtil.assumeNonNull(x).
    • Example:
      var value = mSupplier.get();
      assumeNonNull(value);
      value.doSomething();
      
    • Why: If it is null, it will NPE on the dereference anyway. assumeNonNull is a no-op that satisfies the analyzer without adding redundant runtime checks.
    • Style Rule: assumeNonNull() should be on a separate line, almost always, rather than used inline.
    • Note: This rule is primarily for migrations to avoid functional changes. For new code, rely on correct annotations and avoid assumeNonNull().
  • Passing @Nullable values to non-null parameters: First, look into the call tree of the receiver class and see if that parameter should be annotated as @Nullable or not. If it can natively handle null, update the method signature instead of adding an assertion. If it strictly requires a non-null value, THEN you MUST use a Java assert x != null; on a preceding line before passing or storing it.

    [!CAUTION] NEVER use assumeNonNull(x) to pass a @Nullable value to a non-null parameter or to return it from a non-nullable method. This is STRICTLY FORBIDDEN. You MUST use a Java assert on a preceding line to add a runtime check.

    • Bad Example:
      mReceiver.setSomething(assumeNonNull(nullableValue));
      
    • Good Example:
      assert nullableValue != null;
      mReceiver.setSomething(nullableValue);
      
  • Returning @Nullable values from non-nullable methods: First, consider if the method's return type can be safely updated to @Nullable. If it cannot (e.g., because it implements an interface or strictly enforces a non-null contract), you MUST use a Java assert x != null; on a preceding line before returning the value. Using assumeNonNull(x) inline within a return statement is strictly forbidden.
    • Bad Example:
      return assumeNonNull(nullableValue);
      
    • Good Example:
      assert nullableValue != null;
      return nullableValue;
      
  • Why: Asserts add a runtime check (active in tests/debug) which is an acceptable functional change. We rely on instrumentation tests to validate these changes.
    • Deep Investigation Rule: Before asserting or assuming non-null for a passed value, investigate the call tree. If the method being called can be updated to consider the parameter @Nullable, prefer updating the method signature over adding an assertion.
    • Warning: Be careful with assert value != null on Supplier.get() during initialization. If the supplier value is set LATER (as is common with UI wiring), the assert might fail immediately during construction. In such cases, the getter should return @Nullable and callers should handle it, rather than asserting non-null immediately.

4. Handling Suppliers and Generics

  • Problem: Passing a Supplier<@Nullable T> to a constructor that expects Supplier<T> (non-nullable), or vice
Частые вопросы

Что такое NullAway?

NullAway — проверяющий инструмент, который ищет в Java-коде места, где значение может быть пустым, а это может привести к падению.

Изменит ли исправление поведение приложения?

Скилл старается не менять поведение при миграции старого кода. Он предпочитает небольшие утверждения новой логике.

Только ли для нового кода?

Нет. Он охватывает и миграцию старого кода на код с null-маркировкой, и написание нового кода в файлах, которые уже её используют.

Подробности

Оригинальное описание автора

Guide for resolving NullAway static analysis errors. Best practices for: - Passing ObservableSupplier/Supplier<@Nullable T> - Dereferencing potentially @Nullable values - Adding @NullMarked to Java code

repo: chromium/chromium

Популярность

Звёзды на GitHub
25k
Место в рейтинге
#10062
Лицензия
BSD-3-Clause
Обновлён
02.11.2026

Полезен ли этот скилл?

0

Войдите , чтобы голосовать.

Комментарии

  • …

Другие скиллы из этого репозитория

Похожие скиллы