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

A new method to format only with provided formats. #269

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

ptahchiev
Copy link

@ptahchiev ptahchiev commented Jun 14, 2023

I'm having two instances of LocalDateTime and I want to get the time it has passed between them, but I only need days, hours and minutes.

For this reason I have created a new method that allows users to specify which formats they want included in the final result.

Summary by CodeRabbit

  • New Features

    • Enhanced visibility of several constants related to word-based formatting for easier access.
    • Introduced a new method for localized word-based formatting of periods and durations.
  • Bug Fixes

    • Improved testing capabilities for the AmountFormats class to ensure accurate functionality across various formats and locales.

Copy link

coderabbitai bot commented Oct 8, 2024

Walkthrough

The changes involve modifications to the AmountFormats class in the org.threeten.extra package, where several static string constants have been made public and a new public method wordBasedWithFormats has been introduced for formatting periods and durations. Additionally, the TestAmountFormats class has been updated with new test methods and data sources to enhance testing for the AmountFormats functionalities.

Changes

File Path Change Summary
src/main/java/org/threeten/extra/AmountFormats.java - Changed visibility of constants WORDBASED_YEAR, WORDBASED_MONTH, WORDBASED_WEEK, WORDBASED_DAY, WORDBASED_HOUR, WORDBASED_MINUTE, WORDBASED_SECOND, WORDBASED_MILLISECOND from private to public.
- Added method public static String wordBasedWithFormats(Period period, Duration duration, List<String> formats, Locale locale).
src/test/java/org/threeten/extra/TestAmountFormats.java - Added method public static Object[][] period_duration_wordBasedWithFormats() for test data.
- Added method public void test_wordBasedWithFormats(Period period, Duration duration, List<String> formats, Locale locale, String expected) for parameterized testing.
- Refactored existing tests and updated import statements.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant AmountFormats
    participant TestAmountFormats

    User->>AmountFormats: call wordBasedWithFormats(period, duration, formats, locale)
    AmountFormats-->>User: returns formatted string
    User->>TestAmountFormats: run test_wordBasedWithFormats()
    TestAmountFormats->>AmountFormats: call wordBasedWithFormats() with test data
    AmountFormats-->>TestAmountFormats: returns expected results
    TestAmountFormats-->>User: test results
Loading

Poem

In the land of formats, bright and clear,
Constants now public, oh what cheer!
With methods for words, our tasks align,
Testing with joy, our code will shine.
Hopping through changes, we dance with glee,
For every duration, there's magic, you'll see! 🐇✨


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.

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

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.

@ptahchiev
Copy link
Author

Any update on this one?

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

🧹 Outside diff range and nitpick comments (1)
src/test/java/org/threeten/extra/TestAmountFormats.java (1)

162-180: LGTM: New data provider added for wordBasedWithFormats tests.

The period_duration_wordBasedWithFormats() method provides comprehensive test data for the new wordBasedWithFormats functionality. It covers various scenarios with different periods, durations, format lists, locales, and expected outputs.

Consider adding a test case with an empty format list to ensure the method handles this edge case correctly.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4e01634 and 2888040.

📒 Files selected for processing (2)
  • src/main/java/org/threeten/extra/AmountFormats.java (3 hunks)
  • src/test/java/org/threeten/extra/TestAmountFormats.java (2 hunks)
🧰 Additional context used
🔇 Additional comments (6)
src/main/java/org/threeten/extra/AmountFormats.java (3)

Line range hint 1-863: Overall assessment of changes to AmountFormats.java

The changes to this file enhance the flexibility and customization options of the AmountFormats class. The new wordBasedWithFormats method and the increased visibility of constants provide users with more control over formatting options. The implementation is consistent with the existing codebase and follows good coding practices.

Some minor improvements have been suggested, such as additional validation for the new method. It's also important to consider the long-term implications of making the constants public.

Please ensure that these changes are well-documented in the class and module level documentation, and that any public API changes are reflected in the project's changelog or release notes.


302-363: New method provides flexible word-based formatting

The new wordBasedWithFormats method enhances the class's functionality by allowing custom formatting of time units. This addition aligns well with the class's purpose and provides users with more control over the output format.

Some observations and suggestions:

  1. Null checks and validation:
    The method properly checks for null parameters, which is good practice. Consider adding validation for the formats list to ensure it's not empty.

  2. Time unit calculations:
    The logic for calculating weeks and days is consistent with other methods in the class, which maintains coherence in the codebase.

  3. Use of streams:
    The method uses streams and functional programming concepts, which is modern and concise. However, for very large lists of formats, this might have a slight performance impact. Consider benchmarking with large format lists to ensure performance meets expectations.

  4. Consistency:
    The method follows the pattern of other wordBased methods in the class, which is good for maintainability and understanding.

  5. Reusability:
    The method reuses the WordBased class, promoting code reuse and consistency.

Consider adding a check for an empty formats list:

 public static String wordBasedWithFormats(Period period, Duration duration, List<String> formats, Locale locale) {
     Objects.requireNonNull(period, "period must not be null");
     Objects.requireNonNull(duration, "duration must not be null");
     Objects.requireNonNull(formats, "formats must not be null");
+    if (formats.isEmpty()) {
+        throw new IllegalArgumentException("formats list must not be empty");
+    }
     Objects.requireNonNull(locale, "locale must not be null");
     // ... rest of the method
 }

To ensure the new method is properly integrated and doesn't introduce any regressions, run the following script:

#!/bin/bash
# Check for usage of the new method and potential test coverage
rg --type java "wordBasedWithFormats" -g '!AmountFormats.java'

95-123: Consider the implications of changing constant visibility.

The visibility of several constants (WORDBASED_YEAR, WORDBASED_MONTH, etc.) has been changed from private to public. While this allows for external use and customization, it may impact encapsulation and make future modifications more challenging. Ensure that this change aligns with the library's design principles and future maintainability goals.

To verify the usage of these constants, run the following script:

src/test/java/org/threeten/extra/TestAmountFormats.java (3)

40-41: LGTM: New imports added for Arrays and List.

These imports are necessary for the new test methods that use lists of format strings in the wordBasedWithFormats functionality.


188-192: LGTM: New test method added for wordBasedWithFormats functionality.

The test_wordBasedWithFormats method is a well-structured parameterized test that uses the new data provider to test the AmountFormats.wordBasedWithFormats method with various inputs. This ensures comprehensive testing of the new functionality.


Line range hint 40-193: Overall assessment: Comprehensive test coverage for new functionality.

The changes in this file significantly enhance the test suite for the AmountFormats class by adding support for the new wordBasedWithFormats functionality. The additions include:

  1. New imports for Arrays and List.
  2. A new data provider method period_duration_wordBasedWithFormats() with various test cases.
  3. A new parameterized test method test_wordBasedWithFormats.

These changes ensure thorough testing of the new feature across different scenarios, time units, and locales. The code style and structure are consistent with the existing codebase, maintaining good readability and maintainability.

To ensure that the new wordBasedWithFormats method is properly implemented in the AmountFormats class, please run the following command:

@perceptron8
Copy link
Contributor

perceptron8 commented Oct 8, 2024

I'm having two instances of LocalDateTime and I want to get the time it has passed between them, but I only need days, hours and minutes.

You don't need to change AmountFormats to achieve this.

LocalDateTime ld1 = ...;
LocalDateTime ld2 = ...;
Duration d = Duration.between(ld1, ld2);
PeriodDuration pd = PeriodDuration.of(d);
String format = AmountFormats.wordBased(pd.getPeriod(), pd.getDuration().truncatedTo(ChronoUnit.MINUTES), Locale.ENGLISH);

It's impossible to fulfill your need for any Period and Duration as there may be years and months involved (how many days are there in a year? how many in a month?). What I mean is that if you "only need days", then you won't be able to format "P1Y" or "P1M".

As you can see above, it is sufficient to compute duration between 2 temporals, normalize it using PeriodDuration (24 hours = standard day), then truncate to whatever unit you are interested in, and then - finally - format.

However, to make it simpler, it would be worth considering adding these methods:

  • PeriodDuration.truncatedTo(TemporalUnit),
  • AmountFormats.wordBased(PeriodDuration).

Edit: On second thought, I'm not sure about PeriodDuration.truncatedTo(TemporalUnit) as there is no Period.truncatedTo(TemporalUnit) present already. The reason may be that it's not well defined. It's not clear for instance what it means to truncate "P1Y18M" to years: is it "P1Y" or "P2Y"? Same for months: would it be "P18M" or "P6M"? As for AmountFormats.wordBased(PeriodDuration), it should be fine to add.

@perceptron8
Copy link
Contributor

perceptron8 commented Oct 8, 2024

With those 2 new methods one could write something like:

LocalDateTime ld1 = ...;
LocalDateTime ld2 = ...;
Duration d = Duration.between(ld1, ld2);
PeriodDuration pd = PeriodDuration.of(d);
String format = AmountFormats.wordBased(pd.truncatedTo(ChronoUnit.MINUTES), Locale.ENGLISH);

But... see edit in previous comment.

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.

2 participants