My question is how to use constant field values defined in predefined classes like I am practicing on the events program, and currently on action event, I have understand
the action listener part but when I go to action event part , I don't know how to use the static field constant, only I am able to use methods of the that classes, it will be more helpful if a simple example is given by you (simple not complex)
Elaboration:
I want to know how to use the ALT_MASK, ACTION_FIRST, ACTION_LAST constant
Also please show me how to create events of my own
Let's imagine you have class:
public Class ConstantsHere {
public static final int INTEGER_CONSTANT = 5;
}
Then, you want to use it in another class, and you write code like this:
//some code
if (myValue < ConstantsHere.INTEGER_CONSTANT) {
//do something
}
As mentioned in commens, Java Enum may be a good choice for this task:
public enum Action {
ALT_MASK, ACTION_FIRST, ACTION_LAST;
}
Usage:
//some code
if (myValue == Action.ACTION_LAST) {
//do something
}
To make things clear, Enum should be used in case when some variable may take limited number of values. For example, human gender can be only male or female (please do not take this as offensive for transsexuals, statement used only for explanation purposes), so it might be a good idea to use Enum for that instead of constants 0 and 1 (or M and F), just because we can put other number (or constant) there and break the logic.
Using enums example.
public enum UserStatus {
PENDING("P"), ACTIVE("A"), INACTIVE("I"), DELETED("D");
private String statusCode;
private UserStatus(String s) {
statusCode = s;
}
public String getStatusCode() {
return statusCode;
}
}
public void method(UserStatus status) {
System.out.println(status.getStatusCode());
}
}
Related
Say I have a class:
public enum Enums
{
// about thousand different Enums
}
and I have another class where a user signs in, and based on whether or not hes an admin or a regular user, the user has access to a limited list of enums. I know I can get the full list of all the enums from the class, but what is an elegant way to filter these by some criteria, without the Enums class knowing about user information?
Edit:
Here is a snip of what it looks like today:
#GET
#RolesAllowed({ADMIN})
#Path("/test")
public Response reply(#Auth User user)
{
JSONObject jsonObject = new JSONObject();
jsonObject.put("enums", Arrays.toString(Enums.values()));
return Response.ok(jsonObject.toJSONString()).build();
}
I am returning the full list of 1000+ events, when admin should only see a limited amount.
Let us take example of a week days name as enum. See below
public enum DaysOfWeekEnum {
SUNDAY("off"),
MONDAY("working"),
TUESDAY("working"),
WEDNESDAY("working"),
THURSDAY("working"),
FRIDAY("working"),
SATURDAY("off");
private String typeOfDay;
DaysOfWeekEnum(String typeOfDay) {
this.typeOfDay = typeOfDay;
}
// standard getters and setters
public static Stream<DaysOfWeekEnum> stream() {
return Stream.Of(DaysOfWeekEnum.values());
}
}
Now we will write an example in order to print the non-working days:
public class EnumStreamExample {
public static void main() {
DaysOfWeekEnum.stream()
.filter(d -> d.getTypeOfDay().equals("off"))
.forEach(System.out::println);
}
}
The output we get when we run this:
SUNDAY
SATURDAY
Sorry m on phone, please format code in answer.
Let us say your enum looks like
private enum Enums {
A,
B,
C,
D
}
where A, B are admin specific.
Create a class that allows access to the Enums based on whether the person is admin or not.
public class SO {
EnumSet<Enums> adminEnums = EnumSet.allOf(Enums.class);
EnumSet<Enums> nonAdminEnums = EnumSet.of(Enums.C, Enums.D);
public Set<Enums> getEnums(User user) {
boolean isAdmin = user.isAdmin(); //An example
return isAdmin ? adminEnums : nonAdminEnums;
}
An EnumSet is a special Set implementation optimized for storing a set of enums. adminEnums stores the list of all enums whereas nonAdminEnums has the limited set of enums.
You either have to explicitly specify the list of restricted enums for admin or specify the open enums and derive the other based on this. Not only this is tedious but error-prone. In the future, when you add a new enum instance, you have to update this too and it is easy to forget this.
It would be better if the enums itself contained this information like,
private enum Enums {
A(false),
B(false),
C(true),
D(true);
private boolean adminSpecific;
Enums(boolean adminSpecific) {
this.adminSpecific = adminSpecific;
}
public boolean isAdminSpecific() {
return adminSpecific;
}
}
In this case, we can derive the list based on the information contained in the enum instance.
Set<Enums> adminEnums = Arrays.stream(Enums.values())
.filter(Enums::isAdminSpecific)
.collect(Collectors.toSet());
The Application
I am writing an application that executes certain functions depending on user input.
E.g. if the user input were to be
"1 2 add" the output would be "3".
I aim to implement many such methods (div, modulo, etc.). As my Scanner recognizes a function name like "add" the function "add()" should be called.
My Way
My way to do this is to let a FunctionHandler class evaluate the input.
Main:
String inputCommand = sc.nextCommand();
functionHandler.handle(inputCommand);
Function Handler:
public class FunctionHandler {
public void handle (String functionName) {
if (functionName.equals("add")) {
add();
} else if (functionName.equals("div") {
div();
}
}
private void add() {
.......
}
....
}
The Problem with that
As I am adding more and more functions the if statement gets very large, and of course the FunctionHandler class too. Also, whenever I add a new function, I have to change code in two places: I have to define the function, and then add the else if clause in handle() to call the function. Which means two pieces of information that should be encapsulated are "stored" completely independent from each other.
I was wondering what the best practice was to solve this kind of situation?
My Ideas
I was thinking about using enums, but they don't seem to fit well in this case.
Another idea I had was creating an interface Function, and then a class for each function that implements Function. The interface would have two methods:
getName()
execute()
Then I could create an array (manually) of Functions in the FunctionHandler, through which I could loop to see if the command the user enters matches getName().
However, having a different class for each function is not very clean either, and it also does not get rid of the problem that for each function I am adding I have to do it in two places: the class and the array.
This question is only about finding out how to solve this problem cleanly. A pointer in the right direction would be appreciated!
Thanks a lot!
Another option would be to keep a Map of handlers. If you're using Java 8, they can even be method references.
// InputType and ResultType are types you define
Map<String, Function<InputType, ResultType>> operations = new HashMap<>();
operations.put("add", MathClass::add);
// ...
ResultType result = operations.get(userInput).apply(inputObject);
One downside to doing it this way is that your input and output types must be the same for all operations.
You could create a custom annotation for the various functions. Then you could employ your array idea, but have it use reflection to discover which functions have your new annotation and what their names are.
As background, take a look at http://www.oracle.com/technetwork/articles/hunter-meta-2-098036.html and http://www.oracle.com/technetwork/articles/hunter-meta-3-092019.html. They're a bit old, but seem to address the necessary ideas.
You can always use reflection if you want a short solution.
In your handle method you could do something like this:
Method m = this.getClass().getMethod(functionName, new Class[]{});
m.invoke(this, new Object[]{});
Assuming you do not have a lot of functions that you want to do this way, and do not want to expose yourself to the security risks caused by reflection, you could use a string switch, like this:
void handleFunction(String function) {
switch (function) {
case "foo":
foo();
break;
case "bar":
bar();
break;
default:
throw new IllegalArgumentException("Unknown function " + function);
break;
}
}
Starting Java 7, you can use Strings in a switch statement and the compiler will make something reasonable out of it
I would do something like this:
public class FunctionTest {
private static final Map<String, Runnable> FUNCTIONS = new HashMap<String, Runnable>() {{
put("add", () -> System.out.println("I'm adding something!"));
put("div", () -> System.out.println("I'm dividing something!"));
}};
public void handle(String functionName) {
if (!FUNCTIONS.containsKey(functionName)) {
throw new IllegalArgumentException("No function with this name: " + functionName);
}
FUNCTIONS.get(functionName).run();
}
}
You basically can use any functional interface in place of Runnable, I used it, because it matches your add() method. You can map the names of the functions to their actual executable instance, get them by name from the Map and execute them.
You could also create an enum with the desired executable blocks:
public class FunctionsAsEnumsTest {
private static enum MyFunction {
ADD {
#Override public void execute() {
System.out.println("I'm adding something");
}
},
DIV {
#Override public void execute() {
System.out.println("I'm dividing something");
}
};
public abstract void execute();
}
public void handle(String functionName) {
// #toUpperCase() might not be the best idea,
// you could name your enums as you would the methods.
MyFunction fn = MyFunction.valueOf(functionName.toUpperCase());
fn.execute();
}
}
G'day, errata ... My plan was as shown below. This update is to clarify and apologise for a late night question. The compile error was due to a problem elsewhere in the file.
Clarification: a simple Java enum, like this:
public enum ServiceSource
{
NONE,
URL,
FILE;
}
Want to checking like, isURL():
public boolean isURL(){
return (URL == this);
}
This works (and compiles) ... There's no question -- Correctly answered by: dasblinkenlight and Elliott Frisch. Thank you very much for your time.
see also:
Lookup enum by string value
How to test enum types?
Since this is an instance method, you need to check that this is equal to URL, like this:
public boolean isURL(){
return (URL == this);
}
Demo on ideone.
If you want to have methods that are polymorphic - i.e. exhibit different behaviour for different instances (values) of your enum class, my preference is to override a common method:
public enum ServiceSource {
NONE("no_value"),
URL("url"){
#Override
public boolean isURL() {
return true;
}
},
FILE("file");
private final String val;
private ServiceSource(String val) {
this.val = val;
}
public boolean isURL() {
return false;
}
}
But for methods that check whether this is specific enum value then adding an isXXX method for each constant seems very wasteful. Really, the very reason to use an enum, is so that you can write
if(thing == ServiceSource.URL)
Elsewhere in your code.
If I understand your question, the correct method in your enum is to use this like so,
public enum ServiceSource
{
NONE( "no_value" ),
URL( "url" ),
FILE( "file" );
ServiceSource(String v) {
text =v;
}
private String text;
public boolean isURL() {
return this == URL;
}
}
You can make a method on your Enum to check the value of itself like this:
public boolean isURL(){
return (URL == this);
}
But it's hard to see the value in this approach since every Object has a built in equals() method that accomplishes the same thing.
if (serviceSource.equals(ServiceSource.URL)) { ... }
This would be a more common and obvious way to check the assigned value of an Enum variable (or any variable for that matter). Taking the first approach would require you to have a new isX() method on your Enum; every time you add an Enum constant, you would probably want a new method to accompany it.
I have enum say ErrorCodes that
public enum ErrorCodes {
INVALID_LOGIN(100),
INVALID_PASSWORD(101),
SESSION_EXPIRED(102) ...;
private int errorCode;
private ErrorCodes(int error){
this.errorCode = error;
} //setter and getter and other codes
}
now I check my exception error codes with this error codes. I don't want to write if this do this, if this do this. How I can solve this problem (writing 10+ if blocks)
Is there any design patter to that situation ?
Thanks
Either you do it with a if-statement or a switch, or you just implement the logic in question into the ErrorCode somehow.
In an OO fashion it all depends on how you want the application or system react to the error code. Lets say you just want it to output somekind of dialog:
public doSomethingWithError() {
ErrorCodes e = getError();
// the source of error, or originator, returns the enum
switch(e) {
case ErrorCodes.INVALID_LOGIN:
prompt('Invalid Login');
case ErrorCodes.INVALID_PASSWORD:
prompt('Invalid password');
// and so on
}
}
We could instead create an ErrorHandler class that does this instead:
// We'll implement this using OO instead
public doSomethingWithError() {
ErrorHandler e = getError();
// the originator now returns an ErrorHandler object instead
e.handleMessage();
}
// We will need the following abstract class:
public abstract class ErrorHandler {
// Lets say we have a prompter class that prompts the message
private Prompter prompter = new Prompter();
public final void handleMessage() {
String message = this.getMessage();
prompter.prompt(message);
}
// This needs to be implemented in subclasses because
// handleMessage() method is using it.
public abstract String getMessage();
}
// And you'll have the following implementations, e.g.
// for invalid logins:
public final class InvalidLoginHandler() {
public final String getMessage() {
return "Invalid login";
}
}
// E.g. for invalid password:
public final class InvalidPasswordHandler() {
public final String getMessage() {
return "Invalid password";
}
}
The former solution is easy to implement, but becomes difficult to maintain as the code grows larger. The latter solution is more complex, (aka. Template Method pattern following the Open-Closed Principle) but enables you to add more methods into the ErrorHandler when you need it (such as restoring resources or whatever). You can also implement this with the Strategy pattern.
You won't get away completely with the conditional statements, but in the latter the conditional is pushed to the part of the code where the error is originated. That way you won't have double maintenance on conditional statements both at the originator and the error handling code.
EDIT:
See this answer by Michael Borgwardt and this answer by oksayt for how to implement methods on Java Enums if you want to do that instead.
Java enums are very powerful and allow per-instance method implementations:
public enum ErrorCode {
INVALID_LOGIN {
public void handleError() {
// do something
}
},
INVALID_PASSWORD {
public void handleError() {
// do something else
}
},
SESSION_EXPIRED {
public void handleError() {
// do something else again
}
};
public abstract void handleError();
}
Then you can simply call errorCode.handleError();. However, it is questionable whether an ErrorCode enum is really the right place for that logic.
As pointed out by Spoike, using polymorphism to pick the right error handling method is an option. This approach basically defers the 10+ if blocks to the JVM's virtual method lookup, by defining a class hierarchy.
But before going for a full-blown class hierarchy, also consider using enum methods. This option works well if what you plan to do in each case is fairly similar.
For example, if you want to return a different error message for each ErrorCode, you can simply do this:
// Note singular name for enum
public enum ErrorCode {
INVALID_LOGIN(100, "Your login is invalid"),
INVALID_PASSWORD(101, "Your password is invalid"),
SESSION_EXPIRED(102, "Your session has expired");
private final int code;
private final String
private ErrorCode(int code, String message){
this.code = code;
this.message = message;
}
public String getMessage() {
return message;
}
}
Then your error handling code becomes just:
ErrorCode errorCode = getErrorCode();
prompt(errorCode.getMessage());
One drawback of this approach is that if you want to add additional cases, you'll need to modify the enum itself, whereas with a class hierarchy you can add new cases without modifying existing code.
I believe the best you can do is implementing the strategy pattern. This way you won't have to change existing classes when adding new enums but will still be able to extend them. (Open-Closed-Principle).
Search for Strategy Pattern and Open Closed Principle.
You can create a map of error codes(Integer) against enum types
Edit
In this solution, once the map is prepared, you can look up an error code in the map and thus will not require if..else look ups.
E.g.
Map<Integer, ErrorCodes> errorMap = new HashMap<Integer, ErrorCodes>();
for (ErrorCodes error : ErrorCodes.values()) {
errorMap.put(error.getCode(), error);
}
Now when you want to check an error code coming from your aplpication, all you need to do is,
ErrorCodes error = errorMap.get(erro_code_from_application);
Thus removing the need for all the if..else.
You just need to set up the map in a way that adding error codes doesn't require changes in other code. Preparation of the map is one time activity and can be linked to a database, property file etc during the initialization of your application
In my opinion there is nothing wrong with ErrorCodes as enums and a switch statement to dispatch error handling. Enums and switch fit together really well.
However, maybe you find the following insteresting (kind of over-design), see an Example
or "Double dispatching" on Wikipedia.
Assumed requirements:
Error-handling should be encapsulated in an own class
Error-handling should be replacable
Type safety: Whenever an error is added, you are forced to add error handling at each error-handler implementation. It is not possible to "forget" an error in one (of maybe many) switch statments.
The code:
//Inteface for type-safe error handler
interface ErrorHandler {
void handleInvalidLoginError(InvalidLoginError error);
void handleInvalidPasswordError(InvalidLoginError error);
//One method must be added for each kind error. No chance to "forget" one.
}
//The error hierachy
public class AbstractError(Exception) {
private int code;
abstract public void handle(ErrorHandler);
}
public class InvalidLoginError(AbstractError) {
private String additionalStuff;
public void handle(ErrorHandler handler) {
handler.handleInvalidLoginError(this);
}
public String getAdditionalStuff();
}
public class InvalidPasswordError(AbstractError) {
private int code;
public void handle(ErrorHandler handler) {
handler.handleInvalidPasswordError(this);
}
}
//Test class
public class Test {
public void test() {
//Create an error handler instance.
ErrorHandler handler = new LoggingErrorHandler();
try {
doSomething();//throws AbstractError
}
catch (AbstractError e) {
e.handle(handler);
}
}
}
I have a dialog that displays various things depending on state of the application, security for the current user etc.
I am currently passing in several boolean flags and then enabling and/or hiding UI components depending on these flags.Eg:
new MyDialog(showOptionsTable, allowFooInput, allowBarInput, isSuperUser)
Initially this started out as a couple of flags and that was fine. But now with changing requirements, it has evolved into an input of five boolean flags.
What is the best practices way of handling behavior like this? Is this something that I should subclass depending on how the dialog should look?
As with many things, "it depends".
Ben Noland suggested a class to hold configuration options. This is doable, but favor immutability, and optionally use the builder pattern. Because booleans are built-in types, writing a small builder will really help people understand the code. If you compare this to MyDialog(true, true, ...) you know what I mean:
Options.allowThis().allowThat().build()
Chris suggested bit fields, but as some of the commenters point out, bit fields are evil because of many reasons outlined in Josh Bloch's Effective Java. Basically they are hard to debug and error prone (you can pass in any int and it will still compile). So if you go this route, use real enums and EnumSet.
If you can reasonably subclass (or compose), meaning that you usually only use a couple of combinations of all the booleans, then do that.
Once you get more than two or three flags, I would consider creating a class to store these settings to keep your design clean.
Create a class to hold your configuration options:
public class LayoutConfig
{
public boolean showOptionsTable = true;
public boolean allowFooInput = true;
public boolean allowBarInput = true;
public boolean isSuperUser = true;
}
...
LayoutConfig config = new LayoutConfig();
config.showOptionsTable = false;
new MyDialog(config);
This approach makes it easy to add new options without changes your interface. It will also enable you to add non-boolean options such as dates, numbers, colors, enums...
use the decorator pattern in order to dynamically adding behavior to your dialog
To build on Ben Noland answer, you could define some options as enum, then have a varargs constructor:
class MyDialog {
enum DialogOptions {
SHOW_OPTIONS_TABLE, ALLOW_FOO_INPUT, ALLOW_BAR_INPUT, IS_SUPER_USER
}
public MyDialog(DialogOptions ...options) { ... }
}
...
new MyDialog(DialogOptions.ALLOW_FOO_INPUT, DialogOptions.IS_SUPER_USER);
I have found that this kind of thing becomes MUCH more readable if I use enums for the boolean choices.
public enum ShowOptionsTable { YES, NO }
public enum AllowFooInput { YES, NO }
public enum AllowBarInput { YES, NO }
public enum IsSuperUser { YES, NO }
new MyDialog(ShowOptionsTable.YES, AllowFooInput.NO, AllowBarInput.YES,
IsSuperUser.NO);
With enums like this, usage of code with a lot of boolean parameters becomes easy to understand. Also, since you are using objects rather than booleans as parameters, you have use other patterns to easily refactor things later if you want, to use a decorator or a facade or some other pattern.
I prefer flagged enums to a settings class if the parameters are all going to be boolean. If you can't guarantee that in the future though it would be better safe than sorry though. Here's another implementation for flags:
[Flags]
public enum LayoutParams
{
OptionsTable = 1,
FooInput = 2,
BarInput = 4,
SuperUser = 8,
}
public MyDialog(LayoutParams layoutParams)
{
if (layoutParams & LayoutParams.OptionsTable)
{ /* ... Do Stuff ... */ }
}
public static MyDialog CreateBasic()
{
return new MyDialog(LayoutParams.OptionsTable | LayoutParams.BarInput);
}
Depending on just how different your display is going to be, you might consider subclassing your display class (i.e. MyDialogSuperUser or somesuch). You need to consider just how orthogonal the inputs to your dialog class are and how to express that orthogonality.
I have a favorite way to handle this, but it's not valid for all use cases. If the booleans are not entirely independent (say there are some invalid combinations of booleans, or combinations of booleans are reached through identifiably scenarios.) I create an enum for the state and then define a constructor that holds onto the flags:
public enum status {
PENDING(false,false),
DRAFT(true,false),
POSTED(false,true),
;
public boolean isSent;
public boolean isReceived;
status(boolean isSent, boolean isReceived) {
this.isSent = isSent;
this.isReceived = isReceived;
}
}
The advantage to a piece of code like this is that you can construct your enum constants relatively tersely, but still allow code to only care about one particular aspect of state. For example:
//I want to know specifically what the state is
if (article.state == status.PENDING)
// Do something
//I really only care about whether or not it's been sent
if (article.state.isSent)
// Do something
//I want to do something specific for all possible states
switch(article.state)
// A string of case statements
Another plus is that illegal states are never reached if you define your enum well:
if (article.state.isReceived && !article.state.isSent) {
// This block can never execute ever.
}
Granted, it's not all the time that there's a logical relationship among booleans, but I do recommend mapping them out. If a subset of booleans have logical relationships, it might be worth breaking those off into an enum.
Set it up so MyDialog(false, false, .....) is the expected default behaviour. (ie: The most common case should take all false. You may need to reverse the semantics of the flags.)
Now, define constants:
OPTION1 = 1
OPTION2 = 2
OPTION3 = 4
OPTION4 = 8
...
Change the method to take an int options parameter
public void MyDialog(int options) ...
Now call it:
MyDialog(OPTION1 | OPTION3) // enable Opt1, opt2)
inside the method:
if (options & OPTION1) // use Option 1 config.
etc.
If the GUI depends on the state of the app ( where one state leads to another ) You can take a look at the State pattern. Where each new state will be handled by a different object and you can code whether the flags should go or no.
ie.
abstract class State {
public abstract boolean [] getFlags();
public abstract State next();
}
class InitialState extends State {
public boolean [] getFlags() {
return new boolean [] { true, true, false, false, false };
}
public State next() { return new MediumState(); }
}
class MediumState extends State {
public boolean [] getFlags() {
return new boolean[] { false, false, true, true, false };
}
public State next() { return new FinalState(); }
}
class Final extends State {
public boolean [] getFlags() {
return new boolean[]{false, false, false, false, true };
}
public State next() { return null;}
}
And the show your dialog using this states
new MyDialog(showOptionsTable, new InitialState() );
....
When the state of the application changes, you change the State object.
public void actionPerfomed( ActionEvent e ) {
this.state = state.next();
repaint();
}
To paint the sections of your dialog you query the state:
if( state.getFlags()[SECURITY] ) {
/// show security stuff
} if ( state.getFlags()[VIEW_ONLY] ) {
// enable/disable stuff
} ....
You can go a step further ant let the State define what is presented.
abstract class State {
public abstract JComponent getComponent();
public abstract State next();
}
So each state shows a different section:
Dialog.this.setContentPane( state.getComponent() );