mardi 19 mai 2020

Magic number constant name convention for tests ONE, TWO,.. ONE_HUNDRED vs _1 , _2, _100

so I'm doing some code refactoring/sonar fixes, and there are some tests that contain magic numbers, 5, 123, 567 or whatever, i wanted to create a NumberConstant class where we save numbers used in tests, everything is good we have something like this

public static final int ZERO = 0;
public static final int ONE = 1;
public static final int TWO = 2;
public static final int THREE = 3;
public static final int FOUR = 4;
public static final int FIVE = 5;

the problem is when doing the refactoring, the code is "ok" for SonarQube, but something seems off, the code somehow becomes "cluttered",

i mean just compare these two lines

before

private LocalDateTime endtDateOfFiscalYear2018 = LocalDate.of(2018, Month.DECEMBER, 31).atTime(LocalTime.MAX);

after

private LocalDateTime endtDateOfFiscalYear2018 = LocalDate.of(TWO_THOUSAND_EIGHTEEN, Month.DECEMBER, THIRTY_ONE).atTime(LocalTime.MAX);

I thought a good compromise would be :

private LocalDateTime endtDateOfFiscalYear2018 = LocalDate.of(_2018, Month.DECEMBER, _31).atTime(LocalTime.MAX);

and having my NumberConstant class like this

 public static final int _0 = 0;
 public static final int _1 = 1;
 public static final int _2 = 2;
 public static final int _3 = 3;
 public static final int _4 = 4;
 public static final int _5 = 5;

is this a good compromise or is the whole approach incorrect? what is your approach to keeping your test clean and understandable?

Aucun commentaire:

Enregistrer un commentaire