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

Use ClassValue to simplify JSON #453

Merged
merged 1 commit into from
Dec 29, 2024
Merged

Use ClassValue to simplify JSON #453

merged 1 commit into from
Dec 29, 2024

Conversation

jodastephen
Copy link
Member

@jodastephen jodastephen commented Dec 29, 2024

  • As per recent commits, use ClassValue to speed up JSON serialization
  • Code is structured to allow simple JSON logic to be unified

Summary by CodeRabbit

  • New Features

    • Updated JSON serialisation formats for primitive arrays
    • Enhanced support for Iterable and map key serialisation
    • Improved handling of method placement for nested classes
  • Bug Fixes

    • Reduced requirements for @meta and @type annotations
    • Streamlined JSON serialisation process
  • Documentation

    • Clarified changes related to version 3.0.0-RC1
    • Specified new serialisation behaviour for various data types

* As per recent commits, use ClassValue to speed up JSON serialization
* Code is structured to allow simple JSON logic to be unified
Copy link

coderabbitai bot commented Dec 29, 2024

📝 Walkthrough

Walkthrough

The pull request introduces significant changes to the Joda-Beans library, focusing on JSON serialization and method placement rules. Key modifications include updates to the JSON serialization format for primitive arrays, improvements in handling collections and map serialization, and new guidelines for positioning manually defined methods. The changes impact how beans are written to JSON, with optimizations in type resolution, error handling, and support for various optional types. Test resources have been updated to reflect these new serialization approaches.

Changes

File Change Summary
src/changes/changes.xml Added action for version 3.0.0-RC1, specifying new rules for method placement and JSON serialization format changes
src/main/java/org/joda/beans/ser/json/JodaBeanJsonWriter.java - Updated method signatures for writing beans
- Added ClassValue<JsonHandler<Object>> for optimized serialization
- Introduced new methods for writing objects and beans
- Added handlers for Java and Guava Optional types
src/test/java/org/joda/beans/ser/json/TestSerializeJson.java - Added test methods for array serialization
- Updated assertions for new JSON file references
- Added tests for various array and collection types
src/test/resources/org/joda/beans/ser/*.json - Added new JSON files: Collections2.json, ImmAddress2.json, ImmArrays2.json
- Updated serialization structures for different bean types
- Expanded test coverage for complex data structures

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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.

Documentation and Community

  • 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

🧹 Nitpick comments (18)
src/main/java/org/joda/beans/ser/json/JodaBeanJsonWriter.java (9)

98-100: Expand the comment for clarity on ClassValue usage
The explanatory comment at lines 98-99 is slightly cryptic. Consider elaborating on how ClassValue achieves O(1) lookups and why it is preferred over if/else or switch statements in this context.


225-233: Suggest early exit for null check
When value is null at line 227, consider returning early, instead of using the else block. This can improve readability and reduce nesting.

    private void writeObject(ResolvedType declaredType, String propertyName, Object value) throws IOException {
        if (value == null) {
+           output.writeNull();
+           return;
        }
        var handler = LOOKUP.get(value.getClass());
        handler.handle(this, declaredType, propertyName, value);
    }

230-232: Use var for local variable
On line 230, consider using var for the variable type.

-    JsonHandler<Object> handler = LOOKUP.get(value.getClass());
+    var handler = LOOKUP.get(value.getClass());

355-356: Consider documenting fallback
When the effective type is Object.class, the fallback logic at lines 355-356 might merit a short comment clarifying that we rely on the real type or the typed converter.


389-402: Clarify exception message
At line 399, the exception message is good but might benefit from specifying the original cause (i.e., detail which converter was used, if known). This can help debugging.


449-466: Check performance of deeply nested arrays
The map-special handling is sound. If the system might handle deeply nested or large arrays, consider the performance implications and whether streaming or chunk-based approaches are beneficial.


495-495: Encourage usage of sealed interfaces
Since Java 21 is used, the MetaTypeHandler interface might take advantage of sealed or record references if it’s logically beneficial. This is optional and depends on the design constraints.


555-555: Potential consideration for sealed class
Likewise, this interface JsonHandler could be sealed if all implementations are within this file. Only do so if it aligns with your architectural constraints.


854-862: Consider removing reflection for Grid
If Grid usage is frequent and reflective calls are expensive, investigate potential direct handling. This is a micro-optimisation and may not be critical unless performance is proven to be a bottleneck.

src/test/java/org/joda/beans/ser/json/TestSerializeJson.java (3)

65-65: Test name alignment
Using the same naming convention (e.g. test_writeImmAddress2) might help clarify that it outputs ImmAddress2.json.


225-234: Check for empty arrays
For string arrays, also consider an empty array test. While likely safe, it can reveal corner-case issues.


Line range hint 180-180: Spelling check
Line 180: “implcit” → “implicit.” Please fix this minor typo if it still exists in the actual code or documentation.

src/test/resources/org/joda/beans/ser/Collections2.json (1)

13-16: Clarify the meaning of nested arrays
If users are not deeply familiar with multi-map JSON representation, consider adding comments or documentation clarifying that [["A", "B"], ...] denotes key-value pairs.

src/test/resources/org/joda/beans/ser/ImmAddress2.json (2)

10-10: Consider consistency in naming
array2d might be more consistent if named consistently with other 2D array fields (like matrix). Minor detail, but can help avoid confusion.


146-150: Validate larger grid sizes
If your code eventually handles large or deeply nested grids, confirm memory usage is acceptable.

src/changes/changes.xml (3)

17-24: Incompatibility note
The note about manual equals, hashCode and toString is crucial. Updating older code must be done carefully to avoid overshadowing.


41-47: Provide migration guide
The updated JSON format for primitive arrays might impact downstream consumers. Consider adding a short “migration from older array format” section in your docs.


51-54: Typo: 'implcit'
At line 53, ensure to fix the “implcit” → “implicit” if it remains in final docs.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 52693f5 and ef459ad.

📒 Files selected for processing (6)
  • src/changes/changes.xml (2 hunks)
  • src/main/java/org/joda/beans/ser/json/JodaBeanJsonWriter.java (5 hunks)
  • src/test/java/org/joda/beans/ser/json/TestSerializeJson.java (6 hunks)
  • src/test/resources/org/joda/beans/ser/Collections2.json (1 hunks)
  • src/test/resources/org/joda/beans/ser/ImmAddress2.json (1 hunks)
  • src/test/resources/org/joda/beans/ser/ImmArrays2.json (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/test/resources/org/joda/beans/ser/ImmArrays2.json
🧰 Additional context used
📓 Path-based instructions (2)
src/main/java/org/joda/beans/ser/json/JodaBeanJsonWriter.java (2)

Pattern **/*.java: - Review code using Java 21 standards, taking into account the rules defined by src/main/checkstyle/checkstyle.xml.

  • Validate that code indentation uses spaces, not tabs, with an indent of multiple of 4.
  • Validate that immutable local variables are not annotated with final unless the variable is required for use in an inner class.
  • Favour use of var keyword for type declarations. var may also be used when the value is a cast null.
  • Use a coding standard where multi-line expressions have operators and tenary separators at the end of line.
  • Propose changes that only use the Java 21 API, not the API of Guava.
  • The pattern matching instanceof expression safely handles null, returning false.

Pattern **/main/java/**/*.java: - This project is mature and must provide a stable backwards-compatible public Java API.

  • In the 'Walkthrough' section, you must always provide a list of up to 25 changes to the public Java API that will affect end users.
    If there are no changes, you must explicitly state that there are no changes to the public Java API in this PR.
    The public Java API is defined as public and protected methods on public classes, plus the file module-info.java.
    Provide the list by deeply analysing code flow, which incudes analysing code flow through private methods and calls to Guava and Java 21.
    Changes to be reported on include:
    • New or removed methods in the public Java API
    • Changes to method return types or parameter types in the public Java API
    • Changes to method behaviour in the public Java API that might affect consumers
  • This project uses System.out.println instead of logging
  • This project tends to prefer for loops to streams for performance reasons, however either form is acceptable.
    Do not make suggestions to change between streams and for loops or vice versa.
src/test/java/org/joda/beans/ser/json/TestSerializeJson.java (2)

Pattern **/*.java: - Review code using Java 21 standards, taking into account the rules defined by src/main/checkstyle/checkstyle.xml.

  • Validate that code indentation uses spaces, not tabs, with an indent of multiple of 4.
  • Validate that immutable local variables are not annotated with final unless the variable is required for use in an inner class.
  • Favour use of var keyword for type declarations. var may also be used when the value is a cast null.
  • Use a coding standard where multi-line expressions have operators and tenary separators at the end of line.
  • Propose changes that only use the Java 21 API, not the API of Guava.
  • The pattern matching instanceof expression safely handles null, returning false.

Pattern **/test/java/**/*.java: For test code, focus on:

  • Correctness of test assertions
  • Test coverage of edge cases
  • Clear test naming and documentation
  • Encourage test methods to be package-scoped where possible
  • Be more lenient with code style and minor optimisations
🔇 Additional comments (9)
src/main/java/org/joda/beans/ser/json/JodaBeanJsonWriter.java (2)

183-185: Parameter rename does not break binary compatibility
Renaming the parameter from rootType to includeRootType does not affect the public API signature. However, ensure internal references and documentation are updated consistently across all usage paths to avoid confusion.


280-290: Highlight potential issues with numeric edge cases
The logic here correctly distinguishes between a primitive long and Long. Ensure all edge cases are tested, including minimum/maximum long values and negative numbers, to confirm correct JSON output.

src/test/java/org/joda/beans/ser/json/TestSerializeJson.java (5)

107-107: Keep file naming consistent
Verify that ImmArrays2.json is the correct naming convention for your JSON test resource. Uniformity across different resource files fosters maintainability.


112-113: Backwards compatibility
You are ensuring backward compatibility by parsing the old JSON. Great job!


212-223: Ensure coverage of all object array edge cases
The test checks a mixture of strings and numbers. Consider adding coverage for large numeric boundary values, nulls in the array, or nested arrays to confirm the writer handles them gracefully.


247-256: Add coverage for negative large long values
This test covers a long[], but you may want to verify behaviour for negative or boundary values.


269-269: Sufficient coverage
The existing approach for int[] is clear and likely covers typical scenarios.

src/test/resources/org/joda/beans/ser/Collections2.json (1)

1-1: File name alignment
The new file is named Collections2.json. Ensure it aligns with your naming scheme for resources like ImmArrays2.json and ImmAddress2.json.

src/changes/changes.xml (1)

39-39: Confirm coverage of Iterable
This indicates that standard binary and simple JSON formats now treat Iterable as a collection type. Ensure your test suite includes an Iterable scenario if not already included.

@jodastephen jodastephen merged commit ed76064 into main Dec 29, 2024
5 checks passed
@jodastephen jodastephen deleted the standard-json-writer branch December 29, 2024 11:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

1 participant