Skip to content

Add nullability annotations and simplify time zone logic#17

Merged
arika0093 merged 3 commits intomainfrom
feat/add-membernotnull-attr
Aug 27, 2025
Merged

Add nullability annotations and simplify time zone logic#17
arika0093 merged 3 commits intomainfrom
feat/add-membernotnull-attr

Conversation

@arika0093
Copy link
Owner

@arika0093 arika0093 commented Aug 26, 2025

Introduce nullability annotations for IsTimeZoneInfoAvailable and streamline the logic in GetBrowserTimeZone to enhance code clarity and safety.

Summary by CodeRabbit

  • Refactor

    • Simplified internal time zone availability checks to streamline error handling.
  • Chores

    • Added null-safety annotations to improve reliability and static analysis.
  • Bug Fixes / UX

    • Clarified error text to reference BlazorLocalTimeProvider and suggest registering the provider on a root component, making setup issues easier to diagnose.

@coderabbitai
Copy link

coderabbitai bot commented Aug 26, 2025

Walkthrough

Adds member-nullability attributes to ILocalTimeService.IsTimeZoneInfoAvailable, imports System.Diagnostics.CodeAnalysis, simplifies the guard in GetBrowserTimeZone, and updates an error message; changes touch src/BlazorLocalTime/LocalTimeService.cs and approval output files.

Changes

Cohort / File(s) Summary
Local time service implementation
src/BlazorLocalTime/LocalTimeService.cs
Added using System.Diagnostics.CodeAnalysis; applied [MemberNotNullWhen(true, nameof(TimeZoneInfo))] to ILocalTimeService.IsTimeZoneInfoAvailable (and to its getter), simplified GetBrowserTimeZone guard to check only IsTimeZoneInfoAvailable, and updated an error message to reference BlazorLocalTimeProvider and suggesting adding it to a root component.
Public API approvals
tests/BlazorLocalTimeTest/Approvals/PublicApiCheckTest.Run.net8.approved.txt, tests/BlazorLocalTimeTest/Approvals/PublicApiCheckTest.Run.net9.approved.txt
Approval outputs updated to include the new MemberNotNullWhen attributes on IsTimeZoneInfoAvailable (property and getter); minor formatting/BOM note in net9 file.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Consumer
  participant S as ILocalTimeService

  C->>S: IsTimeZoneInfoAvailable()
  alt true
    Note over S,C #DFF2E1: MemberNotNullWhen(true) -> TimeZoneInfo non-null
    C->>S: GetBrowserTimeZone()
    S-->>C: return TimeZoneInfo
  else false
    C->>S: GetBrowserTimeZone()
    S-->>C: throw (unavailable)
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

I twitch my whiskers, tidy and spry,
An attribute hops in—nulls waved goodbye.
Guards trimmed to truth, messages clear,
Time zones align, the code does cheer. 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/add-membernotnull-attr

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/BlazorLocalTime/LocalTimeService.cs (1)

104-111: Typo/mismatch in the exception message: component is BlazorLocalTimeProvider, not BrowserLocalTimeProvider.

This is user-facing and can mislead consumers following the guidance.

-                1) The `<BrowserLocalTimeProvider />` component has not been added.
-                    In this case, please add `<BrowserLocalTimeProvider />` to a root component such as `Routes.razor`.
+                1) The `<BlazorLocalTimeProvider />` component has not been added.
+                    In this case, please add `<BlazorLocalTimeProvider />` to a root component such as `Routes.razor`.
🧹 Nitpick comments (2)
src/BlazorLocalTime/LocalTimeService.cs (2)

38-39: Good use of MemberNotNullWhen to establish the nullability contract.

Minor style nit: prefer pattern matching for readability.

-    public bool IsTimeZoneInfoAvailable => TimeZoneInfo != null;
+    public bool IsTimeZoneInfoAvailable => TimeZoneInfo is not null;

100-115: Guard simplification is sound; optionally capture the value to avoid double-evaluation/race window.

Today you compute TimeZoneInfo twice (in the property and again when returning). Capturing once is a tiny optimization and closes a theoretical race between check and use if the value changes mid-call.

-        if (!IsTimeZoneInfoAvailable)
+        var tz = TimeZoneInfo;
+        if (tz is null)
         {
             throw new InvalidOperationException(
                 """
                 Failed to obtain the browser's time zone information.
                 Possible causes:
-                1) The `<BrowserLocalTimeProvider />` component has not been added.
+                1) The `<BlazorLocalTimeProvider />` component has not been added.
                     In this case, please add `<BrowserLocalTimeProvider />` to a root component such as `Routes.razor`.
                 2) You are trying to use `ILocalTimeService` in `OnInitialized(Async)`.
                     In this case, you need to subscribe to the `ILocalTimeService.OnLocalTimeZoneChanged` event
                     and perform processing after the time zone information has been set.
                 """
             );
         }
-        return TimeZoneInfo;
+        return tz;
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between d03cc09 and 961d1e6.

📒 Files selected for processing (1)
  • src/BlazorLocalTime/LocalTimeService.cs (3 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
src/BlazorLocalTime/LocalTimeService.cs (4)
src/BlazorLocalTime/Components/LocalTimeText.razor.cs (1)
  • LocalTimeText (8-59)
tests/BlazorLocalTimeTest/LocalTimeServiceTest.cs (2)
  • LocalTimeServiceTest (6-42)
  • Fact (8-15)
src/BlazorLocalTime/Components/LocalTime.razor.cs (1)
  • LocalTime (8-55)
tests/BlazorLocalTimeTest/BlazorLocalTimeProviderCodeTest.cs (1)
  • BlazorLocalTimeProviderCodeTest (10-66)
🔇 Additional comments (1)
src/BlazorLocalTime/LocalTimeService.cs (1)

1-1: Supported TFMs and LangVersion Confirmed – No Action Needed

All projects target .NET 6.0 and above with LangVersion set to latest, which include the built-in MemberNotNullWhenAttribute. No polyfill or additional package is required.

src/BlazorLocalTime/BlazorLocalTime.csproj: net6.0;net7.0;net8.0;net9.0
tests/BlazorLocalTimeTest/BlazorLocalTimeTest.csproj: net8.0;net9.0
example/BlazorLocalTimeSample/BlazorLocalTimeSample.csproj: net9.0
• Central Directory.Build.props: <LangVersion>latest</LangVersion>

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
tests/BlazorLocalTimeTest/Approvals/PublicApiCheckTest.Run.net9.approved.txt (1)

15-16: Is duplicating the attribute on both property and getter required?

Some analyzers/consumers only honor the accessor-level attribute, but others pick up the property-level one. If you don’t have a concrete need for both, consider simplifying to just the getter target to reduce API noise. If you’ve observed analyzer gaps, keep both as-is.

Proposed change in src/BlazorLocalTime/LocalTimeService.cs:

-        [MemberNotNullWhen(true, nameof(TimeZoneInfo))]
-        [get: MemberNotNullWhen(true, nameof(TimeZoneInfo))]
+        [get: MemberNotNullWhen(true, nameof(TimeZoneInfo))]
         bool IsTimeZoneInfoAvailable { get; }
tests/BlazorLocalTimeTest/Approvals/PublicApiCheckTest.Run.net8.approved.txt (1)

15-16: Consider trimming to only the accessor attribute unless both are needed

If analyzer/tooling coverage is satisfied with just the getter attribute, you can remove the property-level attribute to minimize public API churn. Keep both if you rely on property-level consumption in any downstream tooling.

Suggested change in src/BlazorLocalTime/LocalTimeService.cs:

-        [MemberNotNullWhen(true, nameof(TimeZoneInfo))]
-        [get: MemberNotNullWhen(true, nameof(TimeZoneInfo))]
+        [get: MemberNotNullWhen(true, nameof(TimeZoneInfo))]
         bool IsTimeZoneInfoAvailable { get; }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 961d1e6 and 1f724bb.

📒 Files selected for processing (3)
  • src/BlazorLocalTime/LocalTimeService.cs (3 hunks)
  • tests/BlazorLocalTimeTest/Approvals/PublicApiCheckTest.Run.net8.approved.txt (1 hunks)
  • tests/BlazorLocalTimeTest/Approvals/PublicApiCheckTest.Run.net9.approved.txt (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/BlazorLocalTime/LocalTimeService.cs
🧰 Additional context used
🧬 Code graph analysis (2)
tests/BlazorLocalTimeTest/Approvals/PublicApiCheckTest.Run.net8.approved.txt (3)
tests/BlazorLocalTimeTest/PublicApiCheckTest.cs (2)
  • PublicApiCheckTest (8-30)
  • Fact (10-22)
tests/BlazorLocalTimeTest/LocalTimeServiceTest.cs (1)
  • Fact (8-15)
tests/BlazorLocalTimeTest/BlazorLocalTimeProviderCodeTest.cs (1)
  • Fact (57-65)
tests/BlazorLocalTimeTest/Approvals/PublicApiCheckTest.Run.net9.approved.txt (2)
tests/BlazorLocalTimeTest/PublicApiCheckTest.cs (2)
  • PublicApiCheckTest (8-30)
  • Fact (10-22)
tests/BlazorLocalTimeTest/LocalTimeServiceTest.cs (1)
  • Fact (8-15)
🪛 LanguageTool
tests/BlazorLocalTimeTest/Approvals/PublicApiCheckTest.Run.net9.approved.txt

[grammar] ~1-~1: There might be a mistake here.
Context: .../github.com/arika0093/BlazorLocalTime")] [assembly: System.Runtime.CompilerServic...

(QB_NEW_EN)

🔇 Additional comments (4)
tests/BlazorLocalTimeTest/Approvals/PublicApiCheckTest.Run.net9.approved.txt (2)

15-16: Good addition: precise nullability contract on IsTimeZoneInfoAvailable

Annotating IsTimeZoneInfoAvailable with MemberNotNullWhen(true, "TimeZoneInfo") (and mirroring it on the getter) clearly communicates the flow contract to the compiler and consumers. This is a source- and binary-compatible public API enhancement.


15-16: Don’t extend MemberNotNullWhen to BrowserTimeZoneInfo

The current implementation of IsTimeZoneInfoAvailable guarantees that TimeZoneInfo is non-null when true, but does not guarantee the same for BrowserTimeZoneInfo. In particular:

  • TimeZoneInfo returns OverrideTimeZoneInfo if set, or else BrowserTimeZoneInfo.
  • When a user override is applied (OverrideTimeZoneInfo != null), IsTimeZoneInfoAvailable becomes true even though BrowserTimeZoneInfo may still be null.
  • Applying [MemberNotNullWhen(true, nameof(BrowserTimeZoneInfo))] would be incorrect and could lead to false assumptions.

Consumers should continue to rely on the non-nullable TimeZoneInfo property when IsTimeZoneInfoAvailable is true.

Likely an incorrect or invalid review comment.

tests/BlazorLocalTimeTest/Approvals/PublicApiCheckTest.Run.net8.approved.txt (2)

15-16: Nullability attribute on IsTimeZoneInfoAvailable looks correct and is compat-safe

Carrying the MemberNotNullWhen(true, "TimeZoneInfo") contract into the net8 public API is consistent with the implementation intent and remains a non-breaking, compiler-aided improvement for consumers on .NET 8.


15-16: Ignore BrowserTimeZoneInfo nullability suggestion

The contract of IsTimeZoneInfoAvailable only guarantees that TimeZoneInfo (defined as OverrideTimeZoneInfo ?? BrowserTimeZoneInfo) is non-null. When an override is set, IsTimeZoneInfoAvailable can be true while BrowserTimeZoneInfo remains null, so adding MemberNotNullWhen(true, nameof(BrowserTimeZoneInfo)) would be incorrect.

Likely an incorrect or invalid review comment.

@arika0093 arika0093 merged commit e9667e3 into main Aug 27, 2025
2 checks passed
@arika0093 arika0093 deleted the feat/add-membernotnull-attr branch August 27, 2025 00:36
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

Successfully merging this pull request may close these issues.

1 participant