mardi 29 juin 2021

[Java] Enum lookup values by label

L'utilisation des énumérations (enums) pour les valeurs de recherche est une pratique courante en Java, et pour de bonnes raisons. Dans cet article, nous allons discuter des avantages de cette pratique et expliquer comment elle peut améliorer la lisibilité, la sécurité et la maintenabilité de votre code.

  • Lisibilité améliorée

Lorsque vous utilisez des énumérations pour définir des valeurs de recherche, vous donnez à votre code une signification claire et facilement compréhensible. Par exemple, au lieu de définir une chaîne de caractères telle que "M" pour représenter un mois, vous pouvez utiliser une énumération telle que "Janvier", "Février", etc. Cela rend votre code plus lisible et plus facile à comprendre pour les autres développeurs qui peuvent travailler sur votre code.

  • Sécurité renforcée

Les énumérations offrent également une sécurité supplémentaire à votre code. En effet, elles garantissent que seules les valeurs prédéfinies peuvent être utilisées pour une recherche donnée. Cela évite les erreurs de saisie ou les valeurs incorrectes, qui peuvent entraîner des résultats inattendus ou des exceptions lors de l'exécution. Les énumérations sont également plus sûres que les chaînes de caractères, qui peuvent facilement être modifiées ou corrompues.

  • Maintenabilité améliorée

En utilisant des énumérations pour les valeurs de recherche, vous pouvez également améliorer la maintenabilité de votre code. Si vous devez modifier une valeur de recherche, vous n'aurez qu'à le faire dans une seule classe, plutôt que de rechercher et de remplacer cette valeur dans plusieurs endroits du code. Cela rend les modifications plus rapides et moins risquées, car vous n'avez pas besoin de vous soucier des effets de bord ou des modifications involontaires dans d'autres parties du code.

  • Exemple de code

Voici un exemple de code qui utilise une énumération pour les valeurs de recherche :

public enum SortOrder {

    ASC("asc"),
    DESC("desc");

    private static final HashMap<String, SortOrder> MAP = new HashMap<String, SortOrder>();

    private String value;

    private SortOrder(String value) {
        this.value = value;
    }

    public String getValue() {
        return this.value;
    }

    public static SortOrder getByName(String name) {
        return MAP.get(name);
    }

    static {
        for (SortOrder field : SortOrder.values()) {
            MAP.put(field.getValue(), field);
        }
    }
}

After that, just call:

SortOrder asc = SortOrder.getByName("asc");

https://www.baeldung.com/java-enum-values#caching

lundi 28 juin 2021

[Java] String format() Format Specifiers

From Javadoc : https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Formatter.html 

 Example :

Suppose we have int x = 123, and we want to pad 0 .

String.format("%1$013d", x);
  • The format specifiers for general, character, and numeric types have the following syntax:
       %[argument_index$][flags][width][.precision]conversion
     

    The optional argument_index is a decimal integer indicating the position of the argument in the argument list. The first argument is referenced by "1$", the second by "2$", etc.

    The optional flags is a set of characters that modify the output format. The set of valid flags depends on the conversion.

    The optional width is a positive decimal integer indicating the minimum number of characters to be written to the output.

    The optional precision is a non-negative decimal integer usually used to restrict the number of characters. The specific behavior depends on the conversion.

    The required conversion is a character indicating how the argument should be formatted. The set of valid conversions for a given argument depends on the argument's data type.

  • The format specifiers for types which are used to represents dates and times have the following syntax:
       %[argument_index$][flags][width]conversion
     

    The optional argument_indexflags and width are defined as above.

    The required conversion is a two character sequence. The first character is 't' or 'T'. The second character indicates the format to be used. These characters are similar to but not completely identical to those defined by GNU date and POSIX strftime(3c).

  • The format specifiers which do not correspond to arguments have the following syntax:
       %[flags][width]conversion
     

    The optional flags and width is defined as above.

    The required conversion is a character indicating content to be inserted in the output.

Format SpecifierData TypeOutput
%afloating point (except BigDecimal)Returns Hex output of floating point number.
%bAny type"true" if non-null, "false" if null
%ccharacterUnicode character
%dinteger (incl. byte, short, int, long, bigint)Decimal Integer
%efloating pointdecimal number in scientific notation
%ffloating pointdecimal number
%gfloating pointdecimal number, possibly in scientific notation depending on the precision and value.
%hany typeHex String of value from hashCode() method.
%nnonePlatform-specific line separator.
%ointeger (incl. byte, short, int, long, bigint)Octal number
%sany typeString value
%tDate/Time (incl. long, Calendar, Date and TemporalAccessor)%t is the prefix for Date/Time conversions. More formatting flags are needed after this. See Date/Time conversion below.
%xinteger (incl. byte, short, int, long, bigint)

Hex string.    


Source : 

https://www.javatpoint.com/java-string-format

https://stackoverflow.com/questions/5762836/what-does-1-mean-when-used-in-string-format-java

https://www.geeksforgeeks.org/format-specifiers-in-java/

vendredi 25 juin 2021

[Java 8] Iterating over enum values in java using Java 8 findAny to find from string

public enum ContratType {

CDD,

CDI,

TEMPORARY;

public static ContratType fromString(String type) {

    return Stream.of(ContratType .values())

.filter(typec -> typec.name().equals(type))

.findAny().orElse(null);

}

}