Skip to content

feat(triangle): add Triangle class and tests#138

Open
MudasirStanikzay wants to merge 1 commit intomainfrom
feat/triangle-clean
Open

feat(triangle): add Triangle class and tests#138
MudasirStanikzay wants to merge 1 commit intomainfrom
feat/triangle-clean

Conversation

@MudasirStanikzay
Copy link
Copy Markdown

@MudasirStanikzay MudasirStanikzay commented Sep 1, 2025

Added Triangle class with basic methods and TriangleTest with all tests passing.

Summary by CodeRabbit

  • New Features

    • Introduced a Triangle shape with validation to prevent non-positive sides and impossible triangles.
    • Provides quick calculations for perimeter and area (using Heron’s formula).
    • Exposes accessors for each side length.
  • Tests

    • Added unit tests covering valid creation, invalid inputs, perimeter, and area computations.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Sep 1, 2025

Walkthrough

Introduces a new Triangle class with validation, perimeter, and area calculations using Heron’s formula, plus getters. Adds corresponding JUnit 5 tests covering valid creation, invalid inputs, perimeter, and area. No other files changed.

Changes

Cohort / File(s) Summary
Geometry model
src/main/java/org/fungover/breeze/geometry/Triangle.java
New public Triangle class with sides a, b, c; constructor validates positive lengths and triangle inequality; methods: getPerimeter(), getArea() (Heron’s formula), getters getA(), getB(), getC().
Unit tests
src/test/java/org/fungover/breeze/geometry/TriangleTest.java
JUnit 5 tests: valid 3-4-5 triangle getters, perimeter=12, area=6; invalid triangle (1,2,10) throws IllegalArgumentException.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Client
  participant Triangle

  rect rgb(238,245,255)
  note over Client,Triangle: Construction and validation
  Client->>Triangle: new Triangle(a,b,c)
  alt any side <= 0
    Triangle-->>Client: throw IllegalArgumentException("Sidornas längd måste vara större än 0.")
  else violates triangle inequality
    Triangle-->>Client: throw IllegalArgumentException("Ogiltig triangel enligt triangelolikheten.")
  else valid
    Triangle-->>Client: instance created
  end
  end

  rect rgb(241,252,241)
  note over Client,Triangle: Computations
  Client->>Triangle: getPerimeter()
  Triangle-->>Client: a + b + c
  Client->>Triangle: getArea()
  Triangle-->>Client: sqrt(s*(s-a)*(s-b)*(s-c))
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

I sketched three sides in morning light,
A triangle born, its angles tight—
Perimeter strolls, area sings,
Heron hums on whispered strings.
I thump with joy, review complete,
Geometry feels extra sweet.
— A happy hare with tidy feet 🐇✏️

✨ 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/triangle-clean

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 or @coderabbit 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
Copy Markdown
Contributor

@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 (6)
src/main/java/org/fungover/breeze/geometry/Triangle.java (5)

4-6: Make fields immutable (final)

These fields are set only in the constructor; mark them final to enforce immutability and improve thread-safety/readability.

-    private double a;
-    private double b;
-    private double c;
+    private final double a;
+    private final double b;
+    private final double c;

8-19: Validate finiteness and standardize exception messages

  • Guard against NaN/Infinity explicitly for clearer failure modes.
  • If the codebase uses English, consider switching messages to English for consistency.
     public Triangle(double a, double b, double c) {
-        if (a <= 0 || b <= 0 || c <= 0) {
-            throw new IllegalArgumentException("Sidornas längd måste vara större än 0.");
-        }
-        if (!isValidTriangle(a, b, c)) {
-            throw new IllegalArgumentException("Ogiltig triangel enligt triangelolikheten.");
-        }
+        if (!Double.isFinite(a) || !Double.isFinite(b) || !Double.isFinite(c)) {
+            throw new IllegalArgumentException("Side lengths must be finite numbers.");
+        }
+        if (a <= 0 || b <= 0 || c <= 0) {
+            throw new IllegalArgumentException("Side lengths must be greater than 0.");
+        }
+        if (!isValidTriangle(a, b, c)) {
+            throw new IllegalArgumentException("Invalid triangle: violates triangle inequality.");
+        }
         this.a = a;
         this.b = b;
         this.c = c;
     }

21-23: Triangle inequality check looks good; consider static

Method is pure and does not rely on instance state. Making it static communicates intent.

-    private boolean isValidTriangle(double a, double b, double c) {
+    private static boolean isValidTriangle(double a, double b, double c) {
         return a + b > c && a + c > b && b + c > a;
     }

30-34: Clamp radicand to avoid NaN from FP roundoff in near-degenerate triangles

For very skinny valid triangles, rounding can make the radicand slightly negative. Clamping prevents spurious NaNs.

     public double getArea() {
-        double s = getPerimeter() / 2;
-        return Math.sqrt(s * (s - a) * (s - b) * (s - c));
+        double s = getPerimeter() / 2.0;
+        double radicand = s * (s - a) * (s - b) * (s - c);
+        return Math.sqrt(Math.max(0.0, radicand));
     }

36-39: Optional naming tweak

If you want a more descriptive API, consider getSideA/B/C. Not required.

src/test/java/org/fungover/breeze/geometry/TriangleTest.java (1)

27-32: Use tolerance for floating-point comparison and add a couple more negative-path tests

  • Prefer a delta for doubles to avoid brittleness.
  • Add tests for zero/negative sides and degenerate equality (a + b == c).
     @Test
     void testArea() {
         Triangle t = new Triangle(3, 4, 5);
-        assertEquals(6, t.getArea());
+        assertEquals(6.0, t.getArea(), 1e-9);
     }
+
+    @Test
+    void testZeroOrNegativeSidesThrow() {
+        assertAll(
+            () -> assertThrows(IllegalArgumentException.class, () -> new Triangle(0, 1, 1)),
+            () -> assertThrows(IllegalArgumentException.class, () -> new Triangle(-1, 1, 1))
+        );
+    }
+
+    @Test
+    void testDegenerateTriangleThrows() {
+        assertThrows(IllegalArgumentException.class, () -> new Triangle(1, 2, 3));
+    }
📜 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 beeafc7 and e55b3db.

📒 Files selected for processing (2)
  • src/main/java/org/fungover/breeze/geometry/Triangle.java (1 hunks)
  • src/test/java/org/fungover/breeze/geometry/TriangleTest.java (1 hunks)
🔇 Additional comments (4)
src/main/java/org/fungover/breeze/geometry/Triangle.java (1)

25-28: LGTM: perimeter

Straightforward and correct.

src/test/java/org/fungover/breeze/geometry/TriangleTest.java (3)

8-14: LGTM: valid creation and getters

Covers the happy path clearly.


16-19: Good: triangle inequality failure

Consistently exercises invalid input.


21-25: LGTM: perimeter test

Simple and correct.

@alistanikzay alistanikzay self-requested a review September 1, 2025 18:18
Copy link
Copy Markdown

@alistanikzay alistanikzay Sep 1, 2025

Choose a reason for hiding this comment

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

Good validation for positive side lengths and triangle inequality.

Correct use of Heron’s formula for area calculation.

Clean and readable implementation with clear method separation.

Copy link
Copy Markdown

@alistanikzay alistanikzay Sep 1, 2025

Choose a reason for hiding this comment

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

Tests are simple, clear, and easy to understand.

Covers both valid and invalid triangle creation.

Checks correctness of both perimeter and area.

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