corretto / corretto-17

Amazon Corretto 17 is a no-cost, multi-platform, production-ready distribution of OpenJDK 17
GNU General Public License v2.0
214 stars 50 forks source link

Improving the readabilty of the repeat() method in the String object #153

Closed PgmJun closed 11 months ago

PgmJun commented 11 months ago

Description

Improving the readabilty of the repeat() method in the String object

Related issues

152

Motivation and context

public String repeat(int count) {
        // ...omission
        if (Integer.MAX_VALUE / count < len) {
            throw new OutOfMemoryError("Required length exceeds implementation limit");
        }
        // ...omission

I found a point that could improve readability in the repeat() method of the String object.

I think you will get better readability if you change the condition order of the condition statement a little in the repeat method.

public String repeat(int count) {
        // ...omission
        if (len * count > Integer.MAX_VALUE) {
            throw new OutOfMemoryError("Required length exceeds implementation limit");
        }
        // ...omission

I think changing the internal order of conditional statements like this will make it a little more readable code.

How has this been tested?

It was found to work normally because only the order of the values used in the condition was changed. When I actually implemented the same logic and ran it, I confirmed that the logic worked normally.

alvdavi commented 11 months ago

Hi, there is a reason why the comparison is done that way. Integer.MAX_VALUE is, as its name indicates, the largest number that can be stored as an integer. Should the result of len * count be a number higher than Integer.MAX_VALUE, the multiplication would cause an overflow. By using Integer.MAX_VALUE / count < len we can check if the result is within bounds without actually triggering an overflow.

PgmJun commented 11 months ago

@alvdavi Oh, I understood why it was designed like this. Thank you for your detailed reply.