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

Modernize and optimize serialization #398

Merged
merged 1 commit into from
Oct 30, 2024
Merged

Modernize and optimize serialization #398

merged 1 commit into from
Oct 30, 2024

Conversation

jodastephen
Copy link
Member

@jodastephen jodastephen commented Oct 30, 2024

  • Update to Java 21
  • Adjust code with minor optimizations
  • No externally observable changes

Summary by CodeRabbit

  • New Features

    • Enhanced error handling for binary data processing.
    • Introduced a new method for parsing properties in JodaBeanSimpleMapReader.
  • Improvements

    • Refactored methods for better readability and maintainability across multiple classes.
    • Updated control flow structures to use modern syntax, improving clarity.
    • Streamlined variable declarations using type inference.
  • Documentation

    • Updated method documentation to reflect changes in terminology.

* Update to Java 21
* Adjust code with minor optimizations
* No externally observable changes
Copy link

coderabbitai bot commented Oct 30, 2024

📝 Walkthrough

Walkthrough

The pull request includes extensive refactoring across several classes in the org.joda.beans.ser.bin package, focusing on enhancing code clarity, maintainability, and error handling. Key modifications involve replacing explicit type declarations with the var keyword, restructuring control flows using switch-case statements, and refining method signatures. Notable changes include the introduction of new methods for parsing and error handling, as well as the removal of redundant checks. Overall, these changes aim to streamline the code without altering its core functionality.

Changes

File Path Change Summary
src/main/java/org/joda/beans/ser/bin/AbstractBinReader.java - Replaced explicit type declarations with var for local variables.
- Refactored parseBean to parseObjectAsBean with updated signature.
- Centralised error handling into invalidBinaryData method.
- Streamlined control flow in parseObject.
src/main/java/org/joda/beans/ser/bin/AbstractBinWriter.java - Refactored conditional statements in writeElements and writeSimple to use switch-case structures.
- Streamlined handling of effective types in getAndSerializeEffectiveTypeIfRequired.
src/main/java/org/joda/beans/ser/bin/BeanReferences.java - Added static final variable NON_REFERENCED for primitive types.
- Updated findReferences to use a stream for sorting.
- Replaced conditional checks with a switch statement in findReferencesIterable.
src/main/java/org/joda/beans/ser/bin/JodaBeanReferencingBinReader.java - Updated variable types to var in parseClassInfo and parseBean methods.
- Refactored acceptIntExtension to use a switch expression.
- Simplified iteration over metaBean.metaPropertyIterable().
src/main/java/org/joda/beans/ser/bin/MsgPackInput.java - Updated readObject method to use switch expression syntax.
- Modified handling of UINT_32 to use Integer.toUnsignedLong(val).
src/main/java/org/joda/beans/ser/bin/MsgPackOutput.java - Updated documentation for writeExtensionByte method to reflect semantic changes in terminology.
src/main/java/org/joda/beans/ser/bin/MsgPackVisualizer.java - Refactored handleExtension method to use enhanced switch expression syntax.
src/main/java/org/joda/beans/ser/map/JodaBeanSimpleMapReader.java - Removed throws Exception from parseRoot and other methods.
- Introduced var for local variable declarations.
- Split parseObject into parseProperty and parseObjectAsBean.

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 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: 1

🧹 Outside diff range and nitpick comments (1)
src/main/java/org/joda/beans/ser/bin/BeanReferences.java (1)

Line range hint 147-157: Consider extracting nested logic into separate methods

While the code is functionally correct, the nested conditional logic could be more maintainable if extracted into well-named methods. This would improve readability and make the code easier to test.

Consider refactoring like this:

- for (var prop : bean.metaBean().metaPropertyIterable()) {
-     if (settings.isSerialized(prop)) {
-         var value = prop.get(bean);
-         var type = SerOptional.extractType(prop, base.getClass());
-         if (value != null) {
-             var itemIterator = settings.getIteratorFactory().create(value, prop, bean.getClass());
-             if (itemIterator != null) {
-                 if (itemIterator.metaTypeRequired()) {
-                     objects.compute(itemIterator.metaTypeName(), BeanReferences::incrementOrOne);
-                 }
-                 findReferencesIterable(itemIterator, objects);
-             } else {
-                 findReferencesBean(value, type, objects, null);
-             }
-         }
-     }
- }
+ for (var prop : bean.metaBean().metaPropertyIterable()) {
+     processPropertyIfSerialisable(prop, bean, base, objects);
+ }

+ private void processPropertyIfSerialisable(MetaProperty<?> prop, Bean bean, Object base, Map<Object, Integer> objects) {
+     if (!settings.isSerialized(prop)) {
+         return;
+     }
+     var value = prop.get(bean);
+     if (value == null) {
+         return;
+     }
+     processPropertyValue(value, prop, bean, base, objects);
+ }

+ private void processPropertyValue(Object value, MetaProperty<?> prop, Bean bean, Object base, Map<Object, Integer> objects) {
+     var type = SerOptional.extractType(prop, base.getClass());
+     var itemIterator = settings.getIteratorFactory().create(value, prop, bean.getClass());
+     if (itemIterator == null) {
+         findReferencesBean(value, type, objects, null);
+         return;
+     }
+     processIterator(itemIterator, objects);
+ }

+ private void processIterator(SerIterator itemIterator, Map<Object, Integer> objects) {
+     if (itemIterator.metaTypeRequired()) {
+         objects.compute(itemIterator.metaTypeName(), BeanReferences::incrementOrOne);
+     }
+     findReferencesIterable(itemIterator, objects);
+ }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between fe17436 and b2a1546.

📒 Files selected for processing (8)
  • src/main/java/org/joda/beans/ser/bin/AbstractBinReader.java (10 hunks)
  • src/main/java/org/joda/beans/ser/bin/AbstractBinWriter.java (3 hunks)
  • src/main/java/org/joda/beans/ser/bin/BeanReferences.java (6 hunks)
  • src/main/java/org/joda/beans/ser/bin/JodaBeanReferencingBinReader.java (4 hunks)
  • src/main/java/org/joda/beans/ser/bin/MsgPackInput.java (1 hunks)
  • src/main/java/org/joda/beans/ser/bin/MsgPackOutput.java (1 hunks)
  • src/main/java/org/joda/beans/ser/bin/MsgPackVisualizer.java (1 hunks)
  • src/main/java/org/joda/beans/ser/map/JodaBeanSimpleMapReader.java (3 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/main/java/org/joda/beans/ser/bin/MsgPackOutput.java
🧰 Additional context used
📓 Path-based instructions (7)
src/main/java/org/joda/beans/ser/bin/AbstractBinReader.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.
  • Allow use of var keyword when 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 'Summary by CodeRabbit' 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/main/java/org/joda/beans/ser/bin/AbstractBinWriter.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.
  • Allow use of var keyword when 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 'Summary by CodeRabbit' 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/main/java/org/joda/beans/ser/bin/BeanReferences.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.
  • Allow use of var keyword when 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 'Summary by CodeRabbit' 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/main/java/org/joda/beans/ser/bin/JodaBeanReferencingBinReader.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.
  • Allow use of var keyword when 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 'Summary by CodeRabbit' 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/main/java/org/joda/beans/ser/bin/MsgPackInput.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.
  • Allow use of var keyword when 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 'Summary by CodeRabbit' 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/main/java/org/joda/beans/ser/bin/MsgPackVisualizer.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.
  • Allow use of var keyword when 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 'Summary by CodeRabbit' 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/main/java/org/joda/beans/ser/map/JodaBeanSimpleMapReader.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.
  • Allow use of var keyword when 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 'Summary by CodeRabbit' 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.
🪛 ast-grep
src/main/java/org/joda/beans/ser/bin/BeanReferences.java

[warning] 106-106: Detected a cookie where the Secure flag is either missing or disabled. The Secure cookie flag instructs the browser to forbid sending the cookie over an insecure HTTP request. Set the Secure flag to true so the cookie will only be sent over HTTPS.
Context: (value, new Ref(false, refs.size()))
Note: [CWE-614]: Sensitive Cookie in HTTPS Session Without 'Secure' Attribute [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration


[warning] 106-106: Detected a cookie where the HttpOnly flag is either missing or disabled. The HttpOnly cookie flag instructs the browser to forbid client-side JavaScript to read the cookie. If JavaScript interaction is required, you can ignore this finding. However, set the HttpOnly flag to true` in all other cases.
Context: (value, new Ref(false, refs.size()))
Note: [CWE-1004]: Sensitive Cookie Without 'HttpOnly' Flag [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration

🔇 Additional comments (48)
src/main/java/org/joda/beans/ser/bin/MsgPackVisualizer.java (1)

187-193: Well-structured switch expression modernisation

The switch expression has been properly modernised to use Java 21's arrow syntax whilst maintaining the existing functionality. The implementation is clean, consistent, and follows the project's coding standards.

src/main/java/org/joda/beans/ser/bin/MsgPackInput.java (3)

98-136: Excellent modernisation of switch expression!

The switch expression has been properly modernised to use Java 21's arrow syntax, making the code more concise and less error-prone by eliminating break statements.


Line range hint 1-1: No changes to public API

This PR makes no changes to the public Java API. The modifications are internal refactoring only, focusing on modernising the switch expression syntax for Java 21 compatibility.


111-118: 🛠️ Refactor suggestion

Consider simplifying the UINT_32 case

The nested block in the UINT_32 case could be simplified using a ternary operator for better readability.

-                case UINT_32 -> {
-                    var val = input.readInt();
-                    if (val >= 0) {
-                        handleInt(val);
-                    } else {
-                        handleUnsignedLong(Integer.toUnsignedLong(val));
-                    }
-                }
+                case UINT_32 -> {
+                    var val = input.readInt();
+                    handleInt(val >= 0 ? val : (int) Integer.toUnsignedLong(val));
+                }

Likely invalid or redundant comment.

src/main/java/org/joda/beans/ser/bin/AbstractBinWriter.java (3)

123-128: Excellent use of modern switch expression syntax!

The conversion to a pattern matching switch statement improves readability and maintainability while ensuring exhaustive handling of all categories.


224-242: Well-structured pattern matching implementation

The switch statement effectively utilises Java 21's pattern matching features for primitive type handling. The code is clear and maintainable.


250-268: Good separation of numeric type handling

The implementation correctly handles the distinction between Integer and Long types, with clear comments explaining the separation. The pattern matching approach is consistent with the previous switch statement.

src/main/java/org/joda/beans/ser/bin/BeanReferences.java (6)

41-50: Well-structured constant definition for non-referenced types

Good use of Set.of() to create an immutable set of types that don't require references. This improves code maintainability and readability by centralising these definitions.


98-101: Elegant use of modern Java stream operations

The stream operation with reverseOrder(comparingInt()) provides a clear and concise way to sort the entries. Good use of the var keyword aligns with Java 21 practices.


106-106: Improved type checking using Set membership

Efficient simplification of type checking using NON_REFERENCED.contains(). This approach is more maintainable and less error-prone than multiple individual checks.

🧰 Tools
🪛 ast-grep

[warning] 106-106: Detected a cookie where the Secure flag is either missing or disabled. The Secure cookie flag instructs the browser to forbid sending the cookie over an insecure HTTP request. Set the Secure flag to true so the cookie will only be sent over HTTPS.
Context: (value, new Ref(false, refs.size()))
Note: [CWE-614]: Sensitive Cookie in HTTPS Session Without 'Secure' Attribute [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration


[warning] 106-106: Detected a cookie where the HttpOnly flag is either missing or disabled. The HttpOnly cookie flag instructs the browser to forbid client-side JavaScript to read the cookie. If JavaScript interaction is required, you can ignore this finding. However, set the HttpOnly flag to true` in all other cases.
Context: (value, new Ref(false, refs.size()))
Note: [CWE-1004]: Sensitive Cookie Without 'HttpOnly' Flag [OWASP A05:2021]: Security Misconfiguration [REFERENCES]
- https://owasp.org/Top10/A05_2021-Security_Misconfiguration


179-211: Excellent use of modern switch expressions

The switch expression with arrow syntax provides a clear and structured way to handle different iterator categories. The consistent pattern across all cases makes the code easy to follow and maintain.


218-225: Improved type checking and error handling

Good optimisation of the type checking order and clear error messaging for non-immutable beans. The use of var and the improved conditional structure enhance readability.


Line range hint 1-1: No changes to public Java API

This PR contains only internal implementation changes and optimisations. There are no changes to the public Java API that would affect end users.

src/main/java/org/joda/beans/ser/bin/JodaBeanReferencingBinReader.java (3)

114-114: LGTM: Type inference changes align with Java 21 standards

The use of var for local variables improves code conciseness whilst maintaining readability, as the types are clear from the right-hand side of the assignments.

Also applies to: 143-144, 390-392


417-423: LGTM: Excellent use of Java 21 switch expression

The refactoring to a switch expression improves code clarity and safety by:

  • Ensuring exhaustive handling of all cases
  • Eliminating the need for explicit return statements
  • Providing compile-time verification of completeness

Line range hint 1-453: No changes to public Java API

This PR contains no changes to the public Java API. All modifications are internal refactoring to utilise Java 21 features whilst maintaining backwards compatibility.

src/main/java/org/joda/beans/ser/map/JodaBeanSimpleMapReader.java (21)

84-85: Good use of var for local variable declaration

Using var enhances readability and aligns with Java 21 standards.


91-91: Initialization of propName

Initialising propName to an empty string ensures it has a defined value before use, preventing potential NullPointerException.


93-96: Consistent use of var improves code clarity

Replacing explicit type declarations with var simplifies the code and follows modern Java practices.


99-103: Efficient property handling in parseBean method

Utilising var and streamlining the property extraction enhances maintainability.


107-107: Resetting propName after processing

Clearing propName post-processing aids in accurate exception messages if subsequent errors occur.


115-133: Refactored parseProperty method improves modularity

Breaking down the parsing logic into parseProperty enhances code organisation and readability.


141-153: Optimised parsing in parseObject method

The method effectively distinguishes between beans, collections, and simple types, ensuring correct parsing.


155-162: Robust handling in parseObjectAsBean

The method correctly processes input as a bean or converts it to a simple type when necessary.


177-184: Enhanced readability with switch expressions in parseIterable

Using switch expressions improves control flow and reduces complexity.


188-197: Correct implementation of parseIterableMap

The method accurately parses map inputs, ensuring key-value pairs are handled properly.


213-224: Accurate parsing in parseIterableTable

Processing of table entries is precise, maintaining data integrity in complex structures.


227-243: Improved error checking in parseIterableGrid

Adding input size validations enhances reliability and prevents incorrect data processing.


247-257: Effective parsing in parseIterableCounted

The method successfully handles counted iterables, ensuring accurate representation of counts.


260-265: Simplified array parsing in parseIterableArray

The concise handling of arrays improves code maintainability and readability.


268-282: Efficient type handling in parseSimple using switch expressions

The method cleanly manages various input types, enhancing code clarity.


284-292: Appropriate null value conversions in convertNull

Returning NaN for null inputs in floating-point types ensures consistent handling of special cases.


294-300: Correct utilisation of convertText

The method properly leverages the converter settings to transform text inputs to the desired type.


301-307: Proper delegation in convertLong

Long inputs are correctly handled, with appropriate delegation to integer conversion when necessary.


309-316: Accurate handling of integer inputs in convertInteger

The method ensures that integers are converted safely, respecting type boundaries.


317-325: Robust floating-point conversions in convertDouble and convertFloat

The methods correctly manage type conversions, ensuring precision and preventing data loss.


327-335: Comprehensive value range checks in convertInteger

The method thoroughly validates value ranges to prevent overflow and maintain data integrity.

src/main/java/org/joda/beans/ser/bin/AbstractBinReader.java (11)

89-101: Use of var enhances code readability

The replacement of explicit type declarations with var improves code conciseness and readability. This modernises the code in line with Java 21 standards.


Line range hint 116-150: Refactored parseObject method improves control flow

The restructuring of the parseObject method enhances maintainability by simplifying the control flow and consolidating data type handling. The use of helper methods and updated error handling improves code clarity.


Line range hint 153-167: New parseObjectAsBean method introduced

The introduction of the private method parseObjectAsBean encapsulates bean parsing logic, improving code organisation and reusability without affecting external functionality.


188-218: Enhanced error handling in parseObjectFromInput

The updated method includes comprehensive handling of different data types and conditions, ensuring robustness against invalid input. The structured approach improves readability.


220-229: Switch expression used for iterable parsing

Utilising a switch expression for parsing iterables modernises the code and aligns with Java 21 features, enhancing both performance and readability.


310-324: Improved numeric type handling in parseSimple

The method now provides explicit handling for various numeric types, ensuring accurate parsing and appropriate exception handling for out-of-range values.


354-354: Consistent use of invalidBinaryData method

Centralising error messages through invalidBinaryData standardises exception handling and simplifies future maintenance.


416-421: Optimised binary data acceptance

The switch expression for accepting binary data sizes improves code clarity and efficiency, utilising Java 21 language features effectively.


431-441: Detailed integer parsing with comprehensive type support

The method acceptInteger now includes a switch expression that handles all relevant integer types, providing clear exceptions for unexpected cases.


448-459: Expanded long integer parsing in acceptLong

The method accommodates both signed and unsigned long integers, ensuring correct parsing and type casting, along with precise exception messages for invalid data.


493-495: Standardised exception creation in invalidBinaryData

The helper method invalidBinaryData consolidates the creation of IllegalArgumentException instances, promoting consistency in error messages throughout the class.

@jodastephen jodastephen merged commit 404d68c into main Oct 30, 2024
5 checks passed
@jodastephen jodastephen deleted the ser1 branch October 30, 2024 17:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

Successfully merging this pull request may close these issues.

1 participant