I want to model some error codes. The classic enum approach
public enum FileError implement FormattedError {
_10 ("some error with parameters [{0}] and [{1}]"),
_20 ("some other error");
private final String description;
private Error(String description) {
this.description = description;
}
public String getDescription(Object... parameters) {
return // logic to format message
}
...
}
it is not good for me because I have many modules, each with it's error codes and I don't want to copy and paste the boilerplate (constructors, getters, logic..) in all these enums.
So I went for a "manual" enum implemented like this
public class FileError extends BaseError {
public final static FileError _10 = new FileError (10, "some message with parameters [{0}] and [{1}]");
public final static FileError _20 = new FileError (20, "some other message");
}
where I can define my logic in BaseError and reuse it.
but it is still bad because there is no way to link the variable name to the number (_10 to 10) and people copy pasting might reuse the same number without noticing. I could add a test to check that via reflection but then how do I enforce people to use that test for their implementations.
so do you guys have a better idea about how I could achieve this ?
[edit] please keep in mind that I don't want to put error codes in properties files because I want the ide to link error codes in the code with their message.
To answer your question of how to check for reused numbers, you can do that simply by using a static set of all numbers registered so far, and check that when a new one is registered it does not yet exist:
public class BaseError {
// ...
private static Set<Integer> registeredNums = new HashSet<>();
public BaseError(int N, String msg) {
synchronized(registeredNums) {
assert(!registeredNums.contains(N)) : "Duplicated error code";
registeredNums.add(N);
}
// ...
}
}
The users will need to have assertions enabled. If you want the check to always happen, you could throw an AssertionError manually.
A combination of both your approaches may be what you are looking for:
enum ErrorCode {
_10(new FileError(10, "some message with parameters [{0}] and [{1}]")),
_20(new FileError(20, "some other message"));
private final FileError error;
private ErrorCode(FileError err) {
error = err;
}
public FileError getError() {
return error;
}
}
With this code there is an explicit link between the error code and the variable. To avoid other people using the same error code you may prevent them from creating their own FileError instances entirely by making the constructor package private. If that is not an option, you may create an additional subclass as follows:
public class UserDefinedFileError extends FileError {
public UserDefinedFileError(int code, String msg){
super(checkCode(code),msg);
}
static int checkCode(int code){
if(code <= 100){ // or check if it exists in a set of used codes
throw new IllegalArgumentException("Error codes lower than 100 are reserved.");
}
}
}
It is necessary to use some boilerplate code but you can keep it at a minimum by making the enum implement an interface and put much of the functionality statically in the interface - assuming you are using Java-7+ of course.
interface Error {
/**
* Keeps track of error ranges - for sanity check when errors are registered.
*/
static final Map<ErrorRange, Set<? extends Error>> errors = new HashMap<>();
/**
* Lookup range.
*/
static final Map<Error, ErrorRange> range = new HashMap<>();
public static <E extends Enum<E> & Error> void register(ErrorRange errorRange, Class<E> theClass) {
// Keep track of all errors - TODO - Make sure each is registered only once.
errors.put(errorRange, EnumSet.allOf(theClass));
// We need the range.
for (Error e : theClass.getEnumConstants()) {
range.put(e, errorRange);
}
}
/**
* Get a formatted string for the error with the provided parameters.
*/
static <E extends Enum<E> & Error> String format(E error, Object... parameters) {
// The error number comes from it's range + its ordinal.
int errNo = range.get(error).range + error.ordinal();
// The string comes from the formatted description.
return errNo + "\t" + String.format(error.getDescription(), parameters);
}
// All Errors must have a description.
public String getDescription();
}
/**
* Register of all error ranges.
*/
enum ErrorRange {
// All File errors start at 10,000
FileError(10_000);
final int range;
private ErrorRange(int range) {
this.range = range;
}
}
public enum FileError implements Error {
ParameterError("some error with parameters [{0}] and [{1}]"),
OtherError("some other error");
//<editor-fold defaultstate="collapsed" desc="Description">
// Start boilerplate
private final String description;
private FileError(String description) {
this.description = description;
}
#Override
public String getDescription() {
return description;
}
// End boilerplate
//</editor-fold>
}
static {
// Statically register me with the Error object.
Error.register(ErrorRange.FileError, FileError.class);
}
Hope you'll get some idea with this:
public enum FileError {
SOME_ERROR1("0", "Error something1"),
SOME_ERROR2("1", "Error something2"),
SOME_ERROR3("2", "Error something3"),
private final String code;
private final String message;
FileError(String code, String message) {
this.code = code;
this.message = message;
}
public String get() {
return new CustomException(code, message).toString();
}
}
And you're CustomException class
public class CustomException {
...
#Override
public String toString() {
return String.format(Locale.getDefault(), "%s, %s", code, message);
}
}
Related
Error:
...
Caused by: java.lang.ExceptionInInitializerError
...
Caused by: java.lang.ClassCastException:
class com.evopulse.ds2150.TechTrees$BuildingTechTree
not an enum
at java.util.EnumSet.noneOf(Unknown Source)
at java.util.EnumSet.of(Unknown Source)
at com.evopulse.ds2150.TechTrees$BuildingTechTree.<clinit>(TechTrees.java:38)
Here is a snippet of my enumeration
public enum BuildingTechTree {
//Name SoftName Requirements
NONE ("NULL", null),
--> This next line is where it crashes
BARRACKS ("Barracks", EnumSet.of(NONE),
WALLS_SANDBAGS ("Sandbag wall", EnumSet.of(NONE),
POWERPLANT ("Power plant", EnumSet.of(BARRACKS)),
GUARDTOWER ("Guard Tower", EnumSet.of(BARRACKS));
Replacing EnumSet.of(NONE) and EnumSet.of(BARRACKS) with null, lets initialization work, but breaks my code, due to missing data structure... obviously, but I did it to test the rest of my code wasn't somehow the cause.
Removing EnumSet.of(NONE) and replacing with just NONE, and the same for BARRACKS, and changing all related variables, constructor, and methods, that didn't work either... (and even couldn't use the contains.all, since is wasn't "applicable to my changed variable"... )
I extended this example, using the second implementation:
https://gamedev.stackexchange.com/a/25652/48573
I also tried retracing my steps by copying the example verbatim. added
private static Set<BuildingTechTree> techsKnown;
techsKnown = (BuildingTechTree.BIODOME);
test = TechTrees.researchTech(techsKnown);
to another class to be called from for testing initialization. and had to change
public boolean researchTech(BuildingTechTree tech) {
to static
This resulted in the same "in not an enum" error. I don't have any rep, to comment on his answer to point out the initialization error...
Added info for both current answers, as both solutions cause the same new error:
public class TechTrees {
private static Set<BuildingTechTree> techsKnown;
public TechTrees() {
techsKnown = EnumSet.of(BuildingTechTree.NONE); //Using this
techsKnown = EnumSet.noneOf(BuildingTechTree.class); //Or this
}
public static boolean researchTech(BuildingTechTree tech) {
if (techsKnown.containsAll(tech.requirements)) { //Causes null pointer
return true; //exception # techsKnown
}
return false;
}
Your declaration structure is so clever it's a shame it doesn't work. But EnumSet apparently needs the enum to be fully initialized first. It tries to fetch the array of constants from the enum so that, among other things, it knows how much space is needed for its internal bitset.
Here's one workaround. It uses a helper method that creates an ordinary set (HashSet) first, and then, in a static initialization block, it iterates the enum constants and replaces all the sets with EnumSets.
public enum BuildingTechTree {
// Named constants
//Name SoftName Requirements
NONE ("NULL", null),
BARRACKS ("Barracks", setOf(NONE)),
WALLS_SANDBAGS ("Sandbag wall", setOf(NONE)),
POWERPLANT ("Power plant", setOf(BARRACKS)),
GUARDTOWER ("Guard Tower", setOf(BARRACKS));
private final String softName;
private Set<BuildingTechTree> requirements;
private BuildingTechTree(String softName, Set<BuildingTechTree> requirements) {
this.softName = softName;
this.requirements = requirements;
}
private static Set<BuildingTechTree> setOf(BuildingTechTree... values) {
return new HashSet<>(Arrays.asList(values));
}
static {
for (BuildingTechTree v : values()) {
if (v.requirements == null) {
v.requirements = EnumSet.noneOf(BuildingTechTree.class);
} else {
v.requirements = EnumSet.copyOf(v.requirements);
}
}
}
}
You have a chicken and egg problem. You could refactor your enum to something like this:
public enum BuildingTechTree {
NONE("NULL"),
BARRACKS("Barracks"),
WALLS_SANDBAGS("Sandbag wall"),
POWERPLANT("Power plant"),
GUARDTOWER("Guard Tower");
static {
NONE.trees = EnumSet.noneOf(BuildingTechTree.class);
BARRACKS.trees = EnumSet.of(NONE);
WALLS_SANDBAGS.trees = EnumSet.of(NONE);
POWERPLANT.trees = EnumSet.of(BARRACKS);
GUARDTOWER.trees = EnumSet.of(BARRACKS);
}
private String name;
private Set<BuildingTechTree> trees;
private BuildingTechTree(String name) {
this.name = name;
}
public String getName() {
return name;
}
public Set<BuildingTechTree> getTrees() {
return Collections.unmodifiableSet(trees);
}
}
EDIT:
regarding your second problem: you're accessing a static variable, from a static method. But this variable is initialized when the constructor of the class has been called (which is a huge design problem). Don't use non-final static fields. And don't initialize static fields from instance methods or constructors. That doesn't make sense. You don't set the color that all cars should have when constructing a car. Initialize your static fields statically:
public class TechTrees {
private static final Set<BuildingTechTree> TECHS_KNOWN =
EnumSet.of(BuildingTechTree.NONE);
public static boolean researchTech(BuildingTechTree tech) {
return TECHS_KNOWN.containsAll(tech.requirements));
}
}
I have a bunch of error codes being returned to me by the server. Based on these error codes I need to write some logic for each error code. I don't want to place the plain error in my function. What is the best way to represent these error codes?
I am using an enum for now,
private enum LoginErrorCode{
EMAIL_OR_PASSWORD_INCORRECT("101"),
EMAIL_INCORRECT("102");
private final String code;
LoginErrorCode(String code){
this.code=code;
}
public String getCode(){
return code;
}
}
But I do not know how to handle it if I get an error code unknown to me. Please let me know.
Here is the solution using your Enum that I typically employ to deal with error codes as you have explained in your scenario:
import java.util.HashMap;
import java.util.Map;
public class EnumSample {
public static enum LoginErrorCode {
EMAIL_OR_PASSWORD_INCORRECT("101"), EMAIL_INCORRECT("102"), UNKNOWN_ERROR_CODE("---");
private static Map<String, LoginErrorCode> codeToEnumMap;
private final String code;
LoginErrorCode(String code) {
this.code = code;
}
public String getCode() {
return code;
}
/**
* Looks up enum based on code. If code was not registered as enum, it returns UNKNOWN_ERROR_CODE
* #param code
* #return
*/
public static LoginErrorCode fromCode(String code) {
// Keep a hashmap of mapping between code and corresponding enum as a cache. We need to initialize it only once
if (codeToEnumMap == null) {
codeToEnumMap = new HashMap<String, EnumSample.LoginErrorCode>();
for (LoginErrorCode aEnum : LoginErrorCode.values()) {
codeToEnumMap.put(aEnum.getCode(), aEnum);
}
}
LoginErrorCode enumForGivenCode = codeToEnumMap.get(code);
if (enumForGivenCode == null) {
enumForGivenCode = UNKNOWN_ERROR_CODE;
}
return enumForGivenCode;
}
}
public static void main(String[] args) {
System.out.println( LoginErrorCode.fromCode("101")); //Prints EMAIL_OR_PASSWORD_INCORRECT
System.out.println( LoginErrorCode.fromCode("102")); //Prints EMAIL_INCORRECT
System.out.println( LoginErrorCode.fromCode("999")); //Prints UNKWNOWN_ERROR_CODE
}
}
The point of an enum is that there are no invalid values; invalid values do not exist. There can't be an LoginErrorCode.EMAIL_ERROR_DOES_NOT_EXIST value. You shouldn't have to deal with a non-existent value. That is what makes an enum the best representation, because you have a known set of values to represent.
EDIT
Since you need to translate the error code strings to your enum, include a Map of the error code Strings to your enum values:
public enum LoginErrorCode
{
EMAIL_OR_PASSWORD_INCORRECT,
EMAIL_INCORRECT;
private static Map<String, LoginErrorCode> map;
// static initializer
static {
map = new HashMap<String, LoginErrorCode>();
map.put("101", EMAIL_OR_PASSWORD_INCORRECT);
map.put("102", EMAIL_INCORRECT);
}
public static LoginErrorCode fromCode(String code)
{
return map.get(code);
}
}
The fromCode method will return null on an invalid code.
I am using Tapestry 5.3.6 for a web application and I want the user to edit an instance of a Java class (a "bean", or POJO) using a web form (which immediately suggests the use of beaneditform) - however the Java class to be edited has a fairly complex structure. I am looking for the simplest way of doing this in Tapestry 5.
Firstly, lets define some utility classes e.g.
public class ModelObject {
private URI uri;
private boolean modified;
// the usual constructors, getters and setters ...
}
public class Literal<T> extends ModelObject {
private Class<?> valueClass;
private T value;
public Literal(Class<?> valueClass) {
this.valueClass = valueClass;
}
public Literal(Class<?> valueClass, T value) {
this.valueClass = valueClass;
this.value = value;
}
// the usual getters and setters ...
}
public class Link<T extends ModelObject> extends ModelObject {
private Class<?> targetClass;
private T target;
public Link(Class<?> targetClass) {
this.targetClass = targetClass;
}
public Link(Class<?> targetClass, T target) {
this.targetClass = targetClass;
this.target = target;
}
// the usual getters and setters ...
}
Now you can create some fairly complex data structures, for example:
public class HumanBeing extends ModelObject {
private Literal<String> name;
// ... other stuff
public HumanBeing() {
name = new Literal<String>(String.class);
}
// the usual getters and setters ...
}
public class Project extends ModelObject {
private Literal<String> projectName;
private Literal<Date> startDate;
private Literal<Date> endDate;
private Literal<Integer> someCounter;
private Link<HumanBeing> projectLeader;
private Link<HumanBeing> projectManager;
// ... other stuff, including lists of things, that may be Literals or
// Links ... e.g. (ModelObjectList is an enhanced ArrayList that remembers
// the type(s) of the objects it contains - to get around type erasure ...
private ModelObjectList<Link<HumanBeing>> projectMembers;
private ModelObjectList<Link<Project>> relatedProjects;
private ModelObjectList<Literal<String>> projectAliases;
// the usual constructors, getters and setters for all of the above ...
public Project() {
projectName = new Literal<String>(String.class);
startDate = new Literal<Date>(Date.class);
endDate = new Literal<Date>(Date.class);
someCounter = new Literal<Integer>(Integer.class);
projectLeader = new Link<HumanBeing>(HumanBeing.class);
projectManager = new Link<HumanBeing>(HumanBeing.class);
projectMembers = new ModelObjectList<Link<HumanBeing>>(Link.class, HumanBeing.class);
// ... more ...
}
}
If you point beaneditform at an instance of Project.class, you will not get very far before you have to supply a lot of custom coercers, translators, valueencoders, etc - and then you still run into the problem that you can't use generics when "contributing" said coercers, translators, valueencoders, etc.
I then started writing my own components to get around these problems (e.g. ModelObjectDisplay and ModelObjectEdit) but this would require me to understand a lot more of the guts of Tapestry than I have time to learn ... it feels like I might be able to do what I want using the standard components and liberal use of "delegate" etc. Can anyone see a simple path for me to take with this?
Thanks for reading this far.
PS: if you are wondering why I have done things like this, it is because the model represents linked data from an RDF graph database (aka triple-store) - I need to remember the URI of every bit of data and how it relates (links) to other bits of data (you are welcome to suggest better ways of doing this too :-)
EDIT:
#uklance suggested using display and edit blocks - here is what I had already tried:
Firstly, I had the following in AppPropertyDisplayBlocks.tml ...
<t:block id="literal">
<t:delegate to="literalType" t:value="literalValue" />
</t:block>
<t:block id="link">
<t:delegate to="linkType" t:value="linkValue" />
</t:block>
and in AppPropertyDisplayBlocks.java ...
public Block getLiteralType() {
Literal<?> literal = (Literal<?>) context.getPropertyValue();
Class<?> valueClass = literal.getValueClass();
if (!AppModule.modelTypes.containsKey(valueClass))
return null;
String blockId = AppModule.modelTypes.get(valueClass);
return resources.getBlock(blockId);
}
public Object getLiteralValue() {
Literal<?> literal = (Literal<?>) context.getPropertyValue();
return literal.getValue();
}
public Block getLinkType() {
Link<?> link = (Link<?>) context.getPropertyValue();
Class<?> targetClass = link.getTargetClass();
if (!AppModule.modelTypes.containsKey(targetClass))
return null;
String blockId = AppModule.modelTypes.get(targetClass);
return resources.getBlock(blockId);
}
public Object getLinkValue() {
Link<?> link = (Link<?>) context.getPropertyValue();
return link.getTarget();
}
AppModule.modelTypes is a map from java class to a String to be used by Tapestry e.g. Link.class -> "link" and Literal.class -> "literal" ... in AppModule I had the following code ...
public static void contributeDefaultDataTypeAnalyzer(
MappedConfiguration<Class<?>, String> configuration) {
for (Class<?> type : modelTypes.keySet()) {
String name = modelTypes.get(type);
configuration.add(type, name);
}
}
public static void contributeBeanBlockSource(
Configuration<BeanBlockContribution> configuration) {
// using HashSet removes duplicates ...
for (String name : new HashSet<String>(modelTypes.values())) {
configuration.add(new DisplayBlockContribution(name,
"blocks/AppPropertyDisplayBlocks", name));
configuration.add(new EditBlockContribution(name,
"blocks/AppPropertyEditBlocks", name));
}
}
I had similar code for the edit blocks ... however none of this seemed to work - I think because the original object was passed to the "delegate" rather than the de-referenced object which was either the value stored in the literal or the object the link pointed to (hmm... should be [Ll]inkTarget in the above, not [Ll]inkValue). I also kept running into errors where Tapestry couldn't find a suitable "translator", "valueencoder" or "coercer" ... I am under some time pressure so it is difficult to follow these twisty passages through in order to get out of the maze :-)
I would suggest to build a thin wrapper around the Objects you would like to edit though the BeanEditForm and pass those into it. So something like:
public class TapestryProject {
private Project project;
public TapestryProject(Project proj){
this.project = proj;
}
public String getName(){
this.project.getProjectName().getValue();
}
public void setName(String name){
this.project.getProjectName().setValue(name);
}
etc...
}
This way tapestry will deal with all the types it knows about leaving you free of having to create your own coersions (which is quite simple in itself by the way).
You can contribute blocks to display and edit your "link" and "literal" datatypes.
The beaneditform, beaneditor and beandisplay are backed by the BeanBlockSource service. BeanBlockSource is responsible for providing display and edit blocks for various datatypes.
If you download the tapestry source code and have a look at the following files:
tapestry-core\src\main\java\org\apache\tapestry5\corelib\pages\PropertyEditBlocks.java
tapestry-core\src\main\resources\org\apache\tapestry5\corelib\pages\PropertyEditBlocks.tml
tapestry-core\src\main\java\org\apache\tapestry5\services\TapestryModule.java
You will see how tapestry contributes EditBlockContribution and DisplayBlockContribution to provide default blocks (eg for a "date" datatype).
If you contribute to BeanBlockSource, you could provide display and edit blocks for your custom datatypes. This will require you reference blocks by id in a page. The page can be hidden from your users by annotating it with #WhitelistAccessOnly.
http://tapestry.apache.org/current/apidocs/org/apache/tapestry5/services/BeanBlockSource.html
http://tapestry.apache.org/current/apidocs/org/apache/tapestry5/services/DisplayBlockContribution.html
http://tapestry.apache.org/current/apidocs/org/apache/tapestry5/services/EditBlockContribution.html
http://tapestry.apache.org/current/apidocs/org/apache/tapestry5/annotations/WhitelistAccessOnly.html
Here's an example of using an interface and a proxy to hide the implementation details from your model. Note how the proxy takes care of updating the modified flag and is able to map URI's from the Literal array to properties in the HumanBeing interface.
package com.github.uklance.triplestore;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
public class TripleStoreOrmTest {
public static class Literal<T> {
public String uri;
public boolean modified;
public Class<T> type;
public T value;
public Literal(String uri, Class<T> type, T value) {
super();
this.uri = uri;
this.type = type;
this.value = value;
}
#Override
public String toString() {
return "Literal [uri=" + uri + ", type=" + type + ", value=" + value + ", modified=" + modified + "]";
}
}
public interface HumanBeing {
public String getName();
public void setName(String name);
public int getAge();
public void setAge();
}
public interface TripleStoreProxy {
public Map<String, Literal<?>> getLiteralMap();
}
#Test
public void testMockTripleStore() {
Literal<?>[] literals = {
new Literal<String>("http://humanBeing/1/Name", String.class, "Henry"),
new Literal<Integer>("http://humanBeing/1/Age", Integer.class, 21)
};
System.out.println("Before " + Arrays.asList(literals));
HumanBeing humanBeingProxy = createProxy(literals, HumanBeing.class);
System.out.println("Before Name: " + humanBeingProxy.getName());
System.out.println("Before Age: " + humanBeingProxy.getAge());
humanBeingProxy.setName("Adam");
System.out.println("After Name: " + humanBeingProxy.getName());
System.out.println("After Age: " + humanBeingProxy.getAge());
Map<String, Literal<?>> literalMap = ((TripleStoreProxy) humanBeingProxy).getLiteralMap();
System.out.println("After " + literalMap);
}
protected <T> T createProxy(Literal<?>[] literals, Class<T> type) {
Class<?>[] proxyInterfaces = { type, TripleStoreProxy.class };
final Map<String, Literal> literalMap = new HashMap<String, Literal>();
for (Literal<?> literal : literals) {
String name = literal.uri.substring(literal.uri.lastIndexOf("/") + 1);
literalMap.put(name, literal);
}
InvocationHandler handler = new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getDeclaringClass().equals(TripleStoreProxy.class)) {
return literalMap;
}
if (method.getName().startsWith("get")) {
String name = method.getName().substring(3);
return literalMap.get(name).value;
} else if (method.getName().startsWith("set")) {
String name = method.getName().substring(3);
Literal<Object> literal = literalMap.get(name);
literal.value = args[0];
literal.modified = true;
}
return null;
}
};
return type.cast(Proxy.newProxyInstance(getClass().getClassLoader(), proxyInterfaces, handler));
}
}
enum generalInformation {
NAME {
#Override
public String toString() {
return "Name";
}
},
EDUCATION {
#Override
public String toString() {
return "Education";
}
},
EMAIL {
#Override
public String toString() {
return "Email";
}
},
PROFESSION {
#Override
public String toString() {
return "Profession";
}
},
PHONE {
#Override
public String toString() {
return "Phone";
}
}
}
I have that information are avaiable in enum.
How to print all enum values like: print.generalInformation?
That outputs:
Name
Education
Email
Phone
How to pass that enum generalInformation as an arg in another function?
System.out.println(java.util.Arrays.asList(generalInformation.values()));
Your second part... Just the same as an interface or a class
Firstly, I would refactor your enum to pass the string representation in a constructor parameter. That code is at the bottom.
Now, to print all enum values you'd just use something like:
// Note: enum name changed to comply with Java naming conventions
for (GeneralInformation info : EnumSet.allOf(GeneralInformation.class)) {
System.out.println(info);
}
An alternative to using EnumSet would be to use GeneralInformation.values(), but that means you have to create a new array each time you call it, which feels wasteful to me. Admittedly calling EnumSet.allOf requires a new object each time too... if you're doing this a lot and are concerned about the performance, you could always cache it somewhere.
You can use GeneralInformation just like any other type when it comes to parameters:
public void doSomething(GeneralInformation info) {
// Whatever
}
Called with a value, e.g.
doSomething(GeneralInformation.PHONE);
Refactoring using a constructor parameter
public enum GeneralInformation {
NAME("Name"),
EDUCATION("Education"),
EMAIL("Email"),
PROFESSION("Profession"),
PHONE("Phone");
private final String textRepresentation;
private GeneralInformation(String textRepresentation) {
this.textRepresentation = textRepresentation;
}
#Override public String toString() {
return textRepresentation;
}
}
With your current values, you could actually just convert the name to title case automatically - but that wouldn't be very flexible for the long term, and I think this explicit version is simpler.
Since Java 8 I would suggest the following solution:
public static String printAll() {
return Stream.of(GeneralInformation.values()).
map(GeneralInformation::name).
collect(Collectors.joining(", "));
}
In applications, it's good practice to separate data from presentation. It allows the data to be used in different user interfaces, it makes the data objects more lightweight, and it allows for the future possibility of internationalization.
With that in mind, it's good to avoid strongly coupling the display name to the enum constant. Fortunately, there is a class which makes this easy: EnumMap.
public class ApplicationUI {
private final Map<GeneralInformation, String> names;
public ApplicationUI() {
names = new EnumMap<>(GeneralInformation.class);
names.put(GeneralInformation.NAME, "Name");
names.put(GeneralInformation.EDUCATION, "Education");
names.put(GeneralInformation.EMAIL, "Email");
names.put(GeneralInformation.PROFESSION, "Profession");
names.put(GeneralInformation.PHONE, "Phone");
assert names.keySet().containsAll(
EnumSet.allOf(GeneralInformation.class)) :
"Forgot to add one or more GeneralInformation names";
}
public String getNameFor(GeneralInformation info) {
return names.get(info);
}
}
If you are still on Java 1.7 this is what worked for me:
String genInfoValues = "";
boolean firstRun = true;
for (generalInformation info : generalInformation.values()){
if (firstRun) {
firstRun = false;
genInfoValues += info.name();
} else {
genInfoValues += ", " + info.name();
}
}
values() on the enum returns an array. So, it would be simple to do the following to:
System.out.println(Arrays.toString(generalInformation.values()));
In the enum below I see three three distinct classes of messages that exist within the Message enum: Form, Site and Admin.
Is it possible to implement a type of namespace mechanism in an enum so that, instead of writing
Message.SITE_ERROR
Message.ADMIN_ERROR
you write, this:
Message.Site.ERROR
Message.Admin.ERROR
so that Site and Admin represent the "namespace" below which additional categories of messages can exist?
public enum Message {
//FORM
FORM_EMPTY("You've gotta put something in the form."),
//SITE
SITE_ERROR("Whoa. What happened?"),
SITE_ALERT("Hey, it's that time again.");
//ADMIN
ADMIN_ERROR("Gotta look into this, dude."),
ADMIN_ALERT("Time to get the lead out.");
private String messageString;
private Message(String messageString){
this.messageString=messageString;
}
#Override
public String toString() {
return messageString;
}
}
You could use packages?
for example:
com.foo.messages
is your base package. Then you can expand from that
com.foo.messages.site
com.foo.messages.admin
Et cetera...
You could make Message an interface that declares enums Site and Admin. But then, of course, you can't pass around a Message object and expect an enum, just a Message.<something> object.
What do you want this for?
Of course, just use inner classes.
public interface State {
String getMessageString();
}
public class Message {
public static enum Form implements State {
EMPTY("You've gotta put something in the form."),
private final String msg;
public Form(String msg) { this.msg = msg; }
public String getMessageString() { return msg; }
}
public static enum Site implements State {
ERROR("Whoa. What happened?"),
ALERT("Hey, it's that time again.");
private final String msg;
public Site(String msg) { this.msg = msg; }
public String getMessageString() { return msg; }
}
public static enum Admin implements State {
ADMIN_ERROR("Gotta look into this, dude."),
ADMIN_ALERT("Time to get the lead out.");
private final String msg;
public Admin(String msg) { this.msg = msg; }
public String getMessageString() { return msg; }
}
}
I think you may get rid of the repeated code with a common base class but my memory is fuzzy on extending enums so that may not work...