J
J
Jake Taylor2020-08-22 02:08:39
Java
Jake Taylor, 2020-08-22 02:08:39

What is the best way to shorten return code in Java?

A question.
There is a method that takes a quadrilateral as an argument (inside it contains four objects of type Point . Point contains the X and Y coordinates). The method determines if the quadrilateral is a trapezoid.

For reference: A
trapezoid is a quadrilateral in which two sides are parallel and the other two are not parallel.

The boolean isSidesParallel(side1, side2) method determines if the sides are parallel.

Actually, the code itself, which performs its task. But I don't like how return looks. How to bring it to a more readable form and reduce it?

Code (click)

@Override
    public boolean isTrapezoid(Quadrangle quadrangle) {
        // создаем точки
        Point p1 = quadrangle.getP1();
        Point p2 = quadrangle.getP2();
        Point p3 = quadrangle.getP3();
        Point p4 = quadrangle.getP4();

        // создаем стороны АB, BC, CD, DA
        Line sideAb = new Line(p1, p2);
        Line sideBc = new Line(p2, p3);
        Line sideCd = new Line(p3, p4);
        Line sideDa = new Line(p1, p4);

        // проверка, чтобы две противоположыне стороны были параллельны, а другие - не параллельны
        return (isSidesParallel(sideAb, sideCd) && !isSidesParallel(sideBc, sideDa)) || (!isSidesParallel(sideAb, sideCd) && isSidesParallel(sideBc, sideDa));
    }

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
koperagen, 2020-08-22
@n199a

The condition "two sides are parallel, the other two are not" is similar to the xor operator.
For it, the truth table is
1 1 -> 0
1 0 -> 1
0 1 -> 1
0 0 -> 0
. can be written as
isSidesParallel(sideAb, sideCd) ^ isSidesParallel(sideBc, sideDa)
(^ is xor in java)

A
Alex Wells, 2020-08-22
@Alex_Wells

return (isSidesParallel(sideAb, sideCd) && !isSidesParallel(sideBc, sideDa)) || 
    (!isSidesParallel(sideAb, sideCd) && isSidesParallel(sideBc, sideDa));

and are sides parallel, not is

T
Therapyx, 2020-08-22
@Therapyx

Write it in a human way, with comments and so that another person can read it. And then return true or false.
my best advice to you. Don't... Practice writing good code. And good code is not beautiful in your opinion, but understandable both to you and to other people.
For believe me, if something more complicated in this vein and you return to this code in a year, then you will break your eyes and your head))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question