티스토리 뷰

Remove this "BigDecimal" constructor

수정 전

    public void serialize(Double value, JsonGenerator jgen, SerializerProvider provider) throws IOException {

        if (null == value) {

            jgen.writeNull();

        } else {

            jgen.writeNumber(new BigDecimal(value).setScale(2, BigDecimal.ROUND_DOWN));

        }

    }

수정 후

    public void serialize(Double value, JsonGenerator jgen, SerializerProvider provider) throws IOException {

        if (null == value) {

            jgen.writeNull();

        } else {

            jgen.writeNumber(BigDecimal.valueOf(value).setScale(2, BigDecimal.ROUND_DOWN));

        }

    }




Constructors should not be used to instantiate "String", "BigInteger", "BigDecimal" and primitive-wrapper classes (squid:S2129)

CODE_SMELL Code smell MAJOR Major

Constructors for Strings, BigInteger, BigDecimal and the objects used to wrap primitives should never be used. Doing so is less clear and uses more memory than simply using the desired value in the case of strings, and using valueOf for everything else.

Further, these constructors are deprecated in Java 9, which is an indication that they will eventually be removed from the language altogether.

Noncompliant Code Example

String empty = new String(); // Noncompliant; yields essentially "", so just use that.
String nonempty = new String("Hello world"); // Noncompliant
Double myDouble = new Double(1.1); // Noncompliant; use valueOf
Integer integer = new Integer(1); // Noncompliant
Boolean bool = new Boolean(true); // Noncompliant
BigInteger bigInteger1 = new BigInteger("3"); // Noncompliant
BigInteger bigInteger2 = new BigInteger("9223372036854775807"); // Noncompliant
BigInteger bigInteger3 = new BigInteger("111222333444555666777888999"); // Compliant, greater than Long.MAX_VALUE
BigDecimal bigDecimal = new BigDecimal(1.1); // Noncompliant

Compliant Solution

String empty = "";
String nonempty = "Hello world";
Double myDouble = Double.valueOf(1.1);
Integer integer = Integer.valueOf(1);
Boolean bool = Boolean.valueOf(true);
BigInteger bigInteger1 = BigInteger.valueOf(3);
BigInteger bigInteger2 = BigInteger.valueOf(9223372036854775807L);
BigInteger bigInteger3 = new BigInteger("111222333444555666777888999");
BigDecimal bigDecimal = BigDecimal.valueOf(1.1);


댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함