Skip to content

Add new examples and refactor response aggregator#33

Merged
warunalakshitha merged 3 commits intoballerina-platform:mainfrom
snelusha:chore/update-examples
Apr 7, 2026
Merged

Add new examples and refactor response aggregator#33
warunalakshitha merged 3 commits intoballerina-platform:mainfrom
snelusha:chore/update-examples

Conversation

@snelusha
Copy link
Copy Markdown
Contributor

@snelusha snelusha commented Apr 6, 2026

Purpose

$subject

Summary

This pull request refactors the response aggregator example into a modular package and adds several new Ballerina example programs and related configuration updates.

Key changes

  • Refactored response aggregator into a multi-file module (01-response-aggregator/):

    • Added modules/types/types.bal with a shared ApiResponse record.
    • Added modules/handler/handler.bal with response flag constants and a processResponse function to encapsulate processing logic.
    • Added main.bal as the example entrypoint that imports and exercises the new modules.
    • Added Ballerina.toml for the new package.
    • Removed the previous single-file 02-response-aggregator.bal in favor of the modular layout.
  • Added new example programs:

    • 04-temperature-converter.bal — layered call flow with explicit error handling and panic trapping.
    • 05-student-grades.bal — record usage, queries, aggregation, and union-type result handling.
    • 06-library-checkout.bal — object/interface patterns with stateful class behavior and method implementations.
  • UI/config updates:

    • Updated apps/web/src/assets/examples.json to reflect the new example structure and added entries for the new examples.
    • Changed the default fallback file in apps/web/src/components/file-route-sync.tsx to point to the new 01-response-aggregator/main.bal.

Impact

Improves code organization and separation of concerns by modularizing the response aggregator, expands the playground with additional educational examples demonstrating error handling, data manipulation, and object-oriented patterns, and updates web configuration to surface the new examples.

@snelusha snelusha requested a review from warunalakshitha April 6, 2026 20:04
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 6, 2026

📝 Walkthrough

Walkthrough

Rehomes the response-aggregator example into a multi-file Ballerina package (types, handler, main), updates the web app's default example path, removes the old single-file aggregator, and adds three new standalone examples: temperature converter, student grades, and library checkout.

Changes

Cohort / File(s) Summary
Response Aggregator Module
apps/web/src/assets/examples.json, apps/web/src/components/file-route-sync.tsx, examples/01-response-aggregator/Ballerina.toml, examples/01-response-aggregator/main.bal, examples/01-response-aggregator/modules/types/types.bal, examples/01-response-aggregator/modules/handler/handler.bal, examples/02-response-aggregator.bal
Replaced single-file aggregator with 01-response-aggregator/ package: added types:ApiResponse, added handler constants and processResponse(), moved main to main.bal, removed examples/02-response-aggregator.bal, and updated web app default file path to 01-response-aggregator/main.bal.
New Example Programs
examples/04-temperature-converter.bal, examples/05-student-grades.bal, examples/06-library-checkout.bal
Added three new top-level Ballerina examples demonstrating error/panic/trap flows (temperature converter), query/filter/aggregation and union handling (student grades), and object/interface implementation with stateful behavior (library checkout).

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant Main as "Main (examples/01-response-aggregator/main.bal)"
    participant Types as "Types Module\n(modules/types/types.bal)\nApiResponse"
    participant Handler as "Handler Module\n(modules/handler/handler.bal)\nprocessResponse"

    Main->>Types: construct ApiResponse[] (data)
    Main->>Handler: call processResponse(res) for each ApiResponse
    Handler->>Handler: evaluate flags (CACHED/PARTIAL/PAGINATED)
    Handler->>Handler: inspect res.result (type-check int|string)
    Handler-->>Main: print status/flags/result output
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested reviewers

  • warunalakshitha

Poem

🐰 I hopped through modules, neat and spry,
Split the aggregator so types could fly,
Handlers flag responses with a cheer,
New examples joined the playground here,
Hooray — more demos for us to try! ✨

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is incomplete, containing only a placeholder '$subject' instead of meaningful content following the required template with sections for Purpose, Goals, Approach, and other required information. Replace the placeholder with actual content addressing Purpose (problems/issues driving the changes), Goals (solutions being introduced), Approach (how the refactoring and new examples are implemented), and other relevant template sections.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Add new examples and refactor response aggregator' accurately summarizes the main changes: adding three new example files (temperature converter, student grades, library checkout) and refactoring the response aggregator from a single file into a modular structure.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@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: 6

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@examples/01-response-aggregator/modules/handler/handler.bal`:
- Around line 14-20: The code treats res.flags as a scalar status; change the
logic to test each bit independently using bitwise checks on res.flags (e.g.,
(res.flags & PAGINATED) != 0 and (res.flags & CACHED) != 0) instead of using >=
and mutually exclusive else-if, and print each applicable label (PAGINATED,
CACHED, etc.) separately; apply the same change to the mirrored copy in
apps/web/src/assets/examples.json so the playground shows both flags when both
bits are set.

In `@examples/04-temperature-converter.bal`:
- Around line 10-19: The toCelsius and averageCelsius functions currently use
int arithmetic which truncates fractional values; change toCelsius to return
decimal and perform arithmetic with decimal operands by casting the input int to
decimal (e.g., fd = <decimal>f) and using decimal literals (32.0d, 5.0d, 9.0d);
update averageCelsius to return decimal, call toCelsius and cast its result to
decimal if necessary (e.g., check <decimal>(toCelsius(f1))), and compute the
mean using decimal literals (2.0d); ensure validateFahrenheit is still invoked
where needed but adjust any checks to match the new decimal return types in
toCelsius and averageCelsius.

In `@examples/05-student-grades.bal`:
- Around line 21-29: The function maxGrade currently dereferences students[0]
and will panic on an empty array; update the maxGrade(Student[] students)
function to guard against empty input by checking students.length (or
equivalent) at the start and returning a safe value or error (e.g., return 0 or
propagate an error) when students is empty, then proceed with the existing loop
to compute the max only for non-empty arrays.
- Around line 31-37: The averageGrade function can divide by zero when
students.length() == 0; add a guard at the top of averageGrade (similar to the
guard used in maxGrade) to handle an empty array (e.g., return 0 or another
sentinel) before computing sum / students.length(), so the division never occurs
on a zero-length array.

In `@examples/06-library-checkout.bal`:
- Around line 10-13: Add an internal boolean field to the Book class (e.g.,
boolean borrowed = false) to track whether the book is checked out, then update
the Book methods borrowMessage and returnMessage to read and mutate this field
(set borrowed = true on successful borrow, set borrowed = false on return) so
callers no longer maintain external borrowed state—adjust any call sites that
currently pass or check external flags to rely on
Book.borrowMessage/returnMessage behavior instead.
- Around line 28-40: The current borrowMessage and returnMessage functions only
generate strings and accept isBorrowed as a parameter; refactor them into
stateful methods that update the book's borrowed state and return a message
(e.g., change borrowMessage(isBorrowed) -> borrow() and
returnMessage(isBorrowed) -> returnBook() or keep names but remove the parameter
and operate on self.isBorrowed), update the Book interface/type to reflect the
new method signatures, and simplify all call sites in main (where the caller
currently manages isBorrowed) to call the new methods so state is encapsulated
inside the book object and callers no longer track or mutate borrowed state
manually.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 408e0c2f-aae9-420a-a0a6-5d7d94ee8b88

📥 Commits

Reviewing files that changed from the base of the PR and between 803be93 and f3e9b69.

📒 Files selected for processing (11)
  • apps/web/src/assets/examples.json
  • apps/web/src/components/file-route-sync.tsx
  • examples/01-response-aggregator/Ballerina.toml
  • examples/01-response-aggregator/main.bal
  • examples/01-response-aggregator/modules/handler/handler.bal
  • examples/01-response-aggregator/modules/types/types.bal
  • examples/02-orders.bal
  • examples/02-response-aggregator.bal
  • examples/04-temperature-converter.bal
  • examples/05-student-grades.bal
  • examples/06-library-checkout.bal
💤 Files with no reviewable changes (1)
  • examples/02-response-aggregator.bal

Comment thread examples/01-response-aggregator/modules/handler/handler.bal
Comment thread examples/04-temperature-converter.bal
Comment thread examples/05-student-grades.bal
Comment thread examples/05-student-grades.bal
Comment thread examples/06-library-checkout.bal
Comment thread examples/06-library-checkout.bal Outdated
@warunalakshitha
Copy link
Copy Markdown
Contributor

shall we fix the coderabbit comments.

Copy link
Copy Markdown
Contributor

@warunalakshitha warunalakshitha left a comment

Choose a reason for hiding this comment

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

LGTM

Copy link
Copy Markdown

@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.

🧹 Nitpick comments (1)
apps/web/src/assets/examples.json (1)

22-26: Flag checking logic uses arithmetic comparison instead of bitwise operations.

The embedded handler.bal uses res.flags >= PAGINATED and res.flags == CACHED to check flags, but these are defined as bitwise constants (1 << 0, 1 << 1, 1 << 2). This approach:

  1. Works for the provided test cases but breaks with other flag combinations
  2. Cannot detect multiple flags set simultaneously (e.g., CACHED + PAGINATED only prints "[Paginated]", missing that CACHED is also set)

For an educational example demonstrating bitflags, consider using bitwise AND:

♻️ Suggested fix using proper bitwise flag checking
-    if res.flags >= PAGINATED {
+    if (res.flags & PAGINATED) != 0 {
         io:println("  [Paginated]");
-    } else if res.flags == CACHED {
+    }
+    if (res.flags & CACHED) != 0 {
         io:println("  [Cached]");
-    } else {
+    }
+    if (res.flags & PARTIAL) != 0 {
         io:println("  [Partial]");
     }

This allows detecting all set flags independently, which is the standard pattern for bitflag handling.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/web/src/assets/examples.json` around lines 22 - 26, The flag checks in
handler.bal are using arithmetic comparisons (res.flags >= PAGINATED, res.flags
== CACHED) which fail for combined bitflags; update processResponse to test
flags with bitwise AND against the constants (CACHED, PARTIAL, PAGINATED) so
each flag is detected independently (e.g., if (res.flags & PAGINATED) { ... });
ensure you check each flag separately rather than using else/else-if so multiple
flags like CACHED + PAGINATED will both be printed.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@apps/web/src/assets/examples.json`:
- Around line 22-26: The flag checks in handler.bal are using arithmetic
comparisons (res.flags >= PAGINATED, res.flags == CACHED) which fail for
combined bitflags; update processResponse to test flags with bitwise AND against
the constants (CACHED, PARTIAL, PAGINATED) so each flag is detected
independently (e.g., if (res.flags & PAGINATED) { ... }); ensure you check each
flag separately rather than using else/else-if so multiple flags like CACHED +
PAGINATED will both be printed.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 86d5558c-8559-40a0-b719-69dd58e0ec53

📥 Commits

Reviewing files that changed from the base of the PR and between f3e9b69 and ce6bb9f.

📒 Files selected for processing (2)
  • apps/web/src/assets/examples.json
  • examples/06-library-checkout.bal

@warunalakshitha warunalakshitha merged commit 313e30f into ballerina-platform:main Apr 7, 2026
3 checks passed
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.

2 participants