Return to site

☕ JAVA TRICK: Compact Record Constructors

· java

You know how to use records to model data carriers and 

how to verify incoming data during construction,

but did you know💡 that you don't have to list the parameters of all record constructors?

A record's 𝒄𝒂𝒏𝒐𝒏𝒊𝒄𝒂𝒍 constructor has one argument per component

but in its 𝒄𝒐𝒎𝒑𝒂𝒄𝒕 form, you don't have to list them.

You can't assign fields, that happens in compiler-generated code after yours,

but you can reassign the parameters, which leads to the same result.

𝐖𝐈𝐓𝐇 𝐭𝐡𝐞 𝐂𝐨𝐦𝐩𝐚𝐜𝐭 𝐂𝐨𝐧𝐬𝐭𝐫𝐮𝐜𝐭𝐨𝐫

public record Range(int start, int end) {

    public Range {
        if (end <= start) {
            throw new IllegalArgumentException("End cannot be lesser than start");
        }
        // set start and end
         // by reassigning the compact constructor's
         // implicit parameters
        if (start < 0)
            start = 0;
        if (end > 100)
            end = 10;
    }
}

𝐖𝐈𝐓𝐇𝐎𝐔𝐓 𝐭𝐡𝐞 𝐂𝐨𝐦𝐩𝐚𝐜𝐭 𝐂𝐨𝐧𝐬𝐭𝐫𝐮𝐜𝐭𝐨𝐫

public Range(int start, int end) {
        if (end <= start) {
            throw new IllegalArgumentException("End cannot be lesser than start");
        }
        if (start < 0) {
            this.start = 0;
        } else {
            this.start = start;
        }
        if (end > 100) {
            this.end = 10;
        } else {
            this.end = end;
        }
    }
}