Robert

40%
Flag icon
If you override the toString method in an enum type, consider writing a fromString method to translate the custom string representation back to the corresponding enum.
Robert
In line with an earlier soapbox of mine (https://www.goodreads.com/notes/37646821-effective-java/74-robert/cd025f84-7dcb-4402-86a3-13ae1acf2050), I would discourage this. I encourage `toString()` be used exclusively for developers (and not for code/parsing nor end-users), and this proposed counterpart,`fromString`, is intended for code. On top of the reasons in the previous comment, also consider if you may need to maintain compatibility with consumers who might use fromString long after toString (i.e., across running instances), which then prevents you from rename your enums (or you have to refactor to introduce capability to support toString that's different from the enum name). This is a lot like the 'Use instance fields instead of ordinals' item. Instead, either use an external "formatter" (e.g., PlanetEncoder) or at least create explicit methods like toCode and fromCode.
Effective Java
Rate this book
Clear rating
Open Preview