Saturday, 15 March 2014

Java and naming of method to get enum from int -



Java and naming of method to get enum from int -

i have enum, each enum maps integer, doesn't match enum's ordinal(). , need method convert integer enum. think have 2 options:

a new method unique name, such (idiomatic?):

public static myenum fromint(int i) {}

overload of valueof():

public static myenum valueof(int i) {}

are both ok, or 1 of them bad or good?

would or bad provide both? if yes, should identical or behave subtly differently, such behave differently if i not valid value.

or there 3rd alternative superior both of these?

i'm looking short reply telling how should done conform established java coding practices. enum used others , maintained long time. please reply kind of authoritative reference, or strong experience, not purely sentiment or feeling of better.

also, question not how implement method, it's how should named, , if name depends on exact behaviour, consistent rest of "java world".

opinion first:

i name enum mill methods based on purpose, not valueof or anything. illustration consider, hypothetically:

public enum language{ german(345), english(342); private int isocode; public static language fromisocode(int isocode){ //do logic here } }

in case, telling library users should passed fromisocode, isocode, not ordinal, or other integer may part of enum.

so suggest, reconsider naming fromint or valueof, , name based on integer represent in context of enum.

java enums type-conversion

No comments:

Post a Comment