I have an interface and 2 classes implementing the interface. The only difference between the classes is the constant name, they are being used for the same thing but from different locations. I just want to count how many times the method is called from each different location. Is there a better way of doing this without the repetition or passing in the metric name as a string?
public interface OldIdResolver {
Optional<String> getNewIdFromOldId();
}
public class CustomFieldIdResolver implements OldIdResolver {
Optional<String> getIdFromLegacyId(String oldId) {
Optional<Id> newIdOptional = idService.getNewIdFromOldId(oldId);
if (newIdOptional.isPresent()) {
statsDClient.incrementCounter("customField.oldIdUsed");
}
return newIdOptional;
}
}
public class SearcherIdResolver implements OldIdResolver {
Optional<String> getIdFromLegacyId(String oldId) {
Optional<Id> newIdOptional = idService.getNewIdFromOldId(oldId);
if (newIdOptional.isPresent()) {
statsDClient.incrementCounter("searcher.oldIdUsed");
}
return newIdOptional;
}
}
Ordinarily you'd simply make one class and make a constructor:
public class AnyMetricIdResolver implements OldResolver {
private final String metricName;
public AnyMetricIdResolver(String metricName) {
this.metricName = metricName;
}
Optional<String> getIdFromLegacyId(String oldId) {
Optional<Id> newIdOptional = idService.getNewIdFromOldId(oldId);
if (newIdOptional.isPresent()) {
statsDClient.incrementCounter(metricName);
}
return newIdOptional;
}
}
If for some reason that's not good enough (you were rather vague with 'passing the metric name as a string'), you can make an actual class for each kind of metric string, but still do some code reuse. Keep the IdResolver from above (you may want to make it package private if you must), then start subclassing that:
public class SearcherIdResolver extends AnyMetricIdResolver {
public SearcherIdResolver() {
super("searcher.oldIdUsed");
}
}
You can't make a bunch of classes without actually writing them all, unless you use code generation tools such as Annotation Processors which is certainly possible, but I doubt that's what you're looking for here.
Ok, so I have whole module that is in charge of generating player class in my game and after hours and hours of hard labour I came up with this hierarchy (snippets of code without making it too graphic but still providing enough to go on)
I have a base interface for Entities (which are either Player or Monsters):
public interface Entity {
public int getHP();
...
// all getters that denote all stats the Entities have in my game, nothing
else is in the interface
}
Then there is second interface extending Entity, called Classes, that contains all the setters relevant to classes:
public interface Classes extends Entity {
void setHP(int a);
... //and so on}
Finally getting to some real class, class PlayerClasses is responsible for building the classes:
public class PlayerClasses implements Classes {
private int HP, ATK, DEF, DAMAGE, DROP;
#Override
public int getHP() {
return HP;
}
#Override
public void setHP(int a) {
HP = a;
}
// this is how I build the player class
public void Rogue(){
setHP(150);
setATK(30);
setDEF(20);
setDAMAGE();
}
And finally a class which constructor is used to create the player instance that is then passed into other modules (no inheritance or direct access to any other class field or requiring any state in constructor, so win right?)
public class Player {
private int HP,ATK,DEF,DAMAGE,DROP;
private PlayerClasses c;
public Player() {
c = new PlayerClasses();
c.Rogue();
HP = c.getHP();
ATK = c.getATK();
DEF = c.getDEF();
DAMAGE = c.getDAMAGE();
DROP = c.getDrop();
}
Kind of long question, but I tried to keep it civil. Any feedback is very appreciated.
Edit: Ok to clarify why I choose to design like this, I want the player instance to be immutable object that can only be instanced with correct values, while keeping the initialization in other modules as clean as possible without any dependencies. So for example values from two different player classes cannot mix up in case it is instances in module that shows player stats and monster stats. I feel passing private HP and ATK variables in inheritance and then pulluting namespace with same variables is not a way to go for example.
I think I don't understand the reason for an immutable Player class that contains a PlayerClass. But anyways, IMO your Player class is what should inherit the Entity trait. Not the PlayerClasses object that is used as sort of template(?). Because what's the point of having a Player and I assume a similarly constructed Monster class if they aren't both Entity?
You also mix responsibilites / abstractions in an odd way. What is it that is encapsulated in the PlayerClasses and in the Player? PlayerClasses looks like it should represent the class type like "Rogue", not the actual player. And for that it shouldn't have setter methods and neither is a class type an entity.
And a factory like method that initializes a PlayerClasses object is "bad" style. You should always try to guarantee based only on class type that things are right, not have magic methods that need to be called for objects to be right (i.e. no init methods besides the constructor).
Take for example a method that takes a PlayerClasses object as parameter and you want someone else to use that code. They see that they need a reference to PlayerClass and a no-argument constructor for that class, but they can't know what all the initialization steps are. Constructor or various factory / builder patterns can guarantee exactly that.
Here's a draft of how I would have done it:
interface PlayerClass {
int getBaseHp();
int getBaseAtk();
... // more class attributes
}
// as utility so I don't have to write 20 full classes
abstract class PlayerClassBase implements PlayerClass {
private final int hp, atk, ..;
protected PlayerClassBase(int hp, int atk, ...) {
this.hp = hp;
this.atk = atk;
}
#Override
public int getBaseHp() {
return hp;
}
....
}
// short class but guaranteed that every instance of Rogue has the correct values
class Rogue {
public Rogue() {
super(40, 23, 123, ...);
}
}
// something to represent entities
interface Entity {
int getCurrentHp();
int takeDamageFrom(Entity other);
...
}
// maybe an abstract base class here as well
// represents a player that has an immutable class and it can't exist without
class Player implements Entity {
privte final PlayerClass playerClass;
private int currentHp;
...
public Player(PlayerClass playerClass) {
this.playerClass = playerClass;
currentHp = playerClass.getHp();
...
}
public int takeDamageFrom(Entity other) {
currentHp -= other.getCurrentAtk();
return currentHp;
}
}
The PlayerClass part could also be a simple enum instead of a big class hierarchy.
enum PlayerClass {
ROGUE(23, 23, 4, ...),
...
;
private final int hp;
PlayerClass(int hp, int atk, ...) {
this.hp = hp;
...
}
public int getHp() { return hp; }
...
}
That way you could statically reference PlayerClass.ROGUE and create a player like this: new Player(PlayerClass.ROGUE). Instead of currently new Player(new PlayerClass().Rogue()). Or with the big hierarchy: new Player(new Rogue())
I have a code which was initially designed for just a single team where they were passing an enum [which stores list of tasks] to an api. This api then progates the use of this enum to many other classes.
Now i have a task where this code needs to be used by multiple teams and they can pass there own set of tasks in form of enums.
Given the current implementation i dont think it is feasible to support multiple teams which completely overhauling the code because enum's cannot extend other enums.
Is there any way to implement this without massive changes?
But... enums can implement interfaces, for example:
public interface Task {
int getPriority(); // just for example
// plus whatever methods define a task
}
public enum Team1Task implements Task {
Task1(1),
Task2(3);
private final int priority;
private Team1Task(int priority) {
this.priority = priority;
}
public int getPriority() {
return priority;
}
}
Now we can employ java generic kung fu to specify a generic parameter bounded to a suitable enum:
public class TaskProcessor<T extends Enum<T> & Task> {
public void process(T task) {
// do something with task
}
}
To use it:
TaskProcessor<Team1Task> p = new TaskProcessor<Team1Task>();
p.process(Team1Task.Open); // will only accept a Team1Task instance
FYI, as a curiosity of generics, you can alternatively use this bound to achieve the same thing:
public class TaskProcessor<T extends Enum<? extends Task>> {
Although I can find no practical difference in effect, I find it lacks the clarity and familiar pattern of the intersection bound above. For more on this see this question.
It is comparatively easy to make much of the work around enums generic.
Here's a severely cut-down example. It defines a generic database Table class that takes an enum Column as its defining type. The enum defines what columns are in the table. The defining type is an enum that also implements an interface which is a really useful trick.
public class Table<Column extends Enum<Column> & Table.Columns> {
// Name of the table.
protected final String tableName;
// All of the columns in the table. This is actually an EnumSet so very efficient.
protected final Set<Column> columns;
/**
* The base interface for all Column enums.
*/
public interface Columns {
// What type does it have in the database?
public Type getType();
}
// Small list of database types.
public enum Type {
String, Number, Date;
}
public Table(String tableName,
Set<Column> columns) {
this.tableName = tableName;
this.columns = columns;
}
}
You can now create your real table with something like:
public class VersionTable extends Table<VersionTable.Column> {
public enum Column implements Table.Columns {
Version(Table.Type.String),
ReleaseDate(Table.Type.Date);
final Table.Type type;
Column(Table.Type type) {
this.type = type;
}
#Override
public Type getType() {
return type;
}
}
public VersionTable() {
super("Versions", EnumSet.allOf(Column.class));
}
}
Note that this is a truly trivial example but with a little work it is easy to move a lot of your enum work into the parent class.
This technique does retain the type-safety checks you get when using generics.
Enums can implement interfaces. I would recommend coming up with a reasonable interface for the task. make your enum implement the interface and your code will continue to work just fine. other teams can use whatever interface implementation they desire (their own enum or something else). (note, without code it's hard to make very explicit recommendations).
You probably should not use enums for this, but if you want, you can implement logic in helper class, or set of classes that extend each other, and make enums a thin wrappers saround it:
public enum MyTaskEnum {
A, B, C;
private final TaskEnumHelper helper = new TaskEnumHelper();
public void foo (int x, int y)
{
helper.foo (x, y);
}
}
I have two abstract classes, lets call them Car's and Wheel's. I am handling different types of cars using some inheritance. So lets say there are two derivations MonsterTruckCar and ToyCar. Additionally there are different types of wheels that correspond to the Cars, say TreadedWheel's and PlasticWheel's (the mapping does not necessarily need to be one-to-one from types of cars to types of wheels). Further Car's are composed of Wheel's.
The way I thought I would be able to do this in Java is by using an attribute of Car's to be type ArrayList<Wheel>. The issue I am having is that now when I want to use polymorphism on the Wheel's I cannot because whenever I deal with a Wheel it is through an ArrayList which is not a derived class of Wheel's.
I thought I might be able to use bounded wildcards, or just a lot of switch statements to handle different combinations but I dont think either of those would be the greatest solutions. How can I handle such a structure?
Further, how do you add Wheel's to the composition/collection in Car's. That is, I need to be able to add a variable amount of concrete Wheel's to a Car, further this is going to be based off of some user input. so I would like to have a while loop in the default constructor that prompt the user if he/she wants to add another wheel and then if he/she does I add another Wheel to whatever is aggregating/collecting them in Car's.
Edit: Edited the names of the classes themselves from plural (Wheels) to singular with a 's (Wheel's) to clarify the relationship. Added the last paragraph which explains further the behavior I am looking for.
Add a generic parameter to your Car class that specified the wheel type. Here's a very basic implementation you can build on:
Edited:
Includes updated requirements, which is tricky, but doable...
public interface Wheel {
void setSize(int diameter);
}
public static abstract class Car<T extends Wheel> {
private List<T> wheels = new ArrayList<T>();
protected Car(int numberOfWheels, Class<T> wheelClass) {
while (wheels.size() < numberOfWheels) {
T wheel;
try {
wheel = wheelClass.newInstance();
} catch (Exception e) {
throw new RuntimeException(e); // simplified exception handling
}
wheel.setSize(5); // Ask user for wheel details etc
wheels.add(wheel);
}
}
public List<T> getWheels() {
return wheels;
}
}
public static class PlasticWheel implements Wheel { // or extends Wheel
#Override
public void setSize(int diameter) {
}
}
public static class ToyCar extends Car<PlasticWheel> {
public ToyCar() {
super(6, PlasticWheel.class); // or you could pass number of wheels in to this constructor
}
}
public static class TreadedWheel implements Wheel { // or extends Wheel
#Override
public void setSize(int diameter) {
}
}
public static class MonsterTruckCar extends Car<TreadedWheel> {
public MonsterTruckCar() {
super(4, TreadedWheel.class); // or you could pass number of wheels in to this constructor
}
}
I just found out that Java allows enums to implement an interface. What would be a good use case for that?
Here's one example (a similar/better one is found in Effective Java 2nd Edition):
public interface Operator {
int apply (int a, int b);
}
public enum SimpleOperators implements Operator {
PLUS {
int apply(int a, int b) { return a + b; }
},
MINUS {
int apply(int a, int b) { return a - b; }
};
}
public enum ComplexOperators implements Operator {
// can't think of an example right now :-/
}
Now to get a list of both the Simple + Complex Operators:
List<Operator> operators = new ArrayList<Operator>();
operators.addAll(Arrays.asList(SimpleOperators.values()));
operators.addAll(Arrays.asList(ComplexOperators.values()));
So here you use an interface to simulate extensible enums (which wouldn't be possible without using an interface).
Enums don't just have to represent passive sets (e.g. colours). They can represent more complex objects with functionality, and so you're then likely to want to add further functionality to these - e.g. you may have interfaces such as Printable, Reportable etc. and components that support these.
The Comparable example given by several people here is wrong, since Enum already implements that. You can't even override it.
A better example is having an interface that defines, let's say, a data type. You can have an enum to implement the simple types, and have normal classes to implement complicated types:
interface DataType {
// methods here
}
enum SimpleDataType implements DataType {
INTEGER, STRING;
// implement methods
}
class IdentifierDataType implements DataType {
// implement interface and maybe add more specific methods
}
There is a case I often use. I have a IdUtil class with static methods to work with objects implementing a very simple Identifiable interface:
public interface Identifiable<K> {
K getId();
}
public abstract class IdUtil {
public static <T extends Enum<T> & Identifiable<S>, S> T get(Class<T> type, S id) {
for (T t : type.getEnumConstants()) {
if (Util.equals(t.getId(), id)) {
return t;
}
}
return null;
}
public static <T extends Enum<T> & Identifiable<S>, S extends Comparable<? super S>> List<T> getLower(T en) {
List<T> list = new ArrayList<>();
for (T t : en.getDeclaringClass().getEnumConstants()) {
if (t.getId().compareTo(en.getId()) < 0) {
list.add(t);
}
}
return list;
}
}
If I create an Identifiable enum:
public enum MyEnum implements Identifiable<Integer> {
FIRST(1), SECOND(2);
private int id;
private MyEnum(int id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
Then I can get it by its id this way:
MyEnum e = IdUtil.get(MyEnum.class, 1);
Since Enums can implement interfaces they can be used for strict enforcing of the singleton pattern. Trying to make a standard class a singleton allows...
for the possibility of using reflection techniques to expose private methods as public
for inheriting from your singleton and overriding your singleton's methods with something else
Enums as singletons help to prevent these security issues. This might have been one of the contributing reasons to let Enums act as classes and implement interfaces. Just a guess.
See https://stackoverflow.com/questions/427902/java-enum-singleton and Singleton class in java for more discussion.
It's required for extensibility -- if someone uses an API you've developed, the enums you define are static; they can't be added to or modified. However, if you let it implement an interface, the person using the API can develop their own enum using the same interface. You can then register this enum with an enum manager which conglomerates the enums together with the standard interface.
Edit: #Helper Method has the perfect example of this. Think about having other libraries defining new operators and then telling a manager class that 'hey, this enum exists -- register it'. Otherwise, you'd only be able to define Operators in your own code - there'd be no extensibility.
The post above that mentioned strategies didn't stress enough what a nice lightweight implementation of the strategy pattern using enums gets you:
public enum Strategy {
A {
#Override
void execute() {
System.out.print("Executing strategy A");
}
},
B {
#Override
void execute() {
System.out.print("Executing strategy B");
}
};
abstract void execute();
}
You can have all your strategies in one place without needing a separate compilation unit for each. You get a nice dynamic dispatch with just:
Strategy.valueOf("A").execute();
Makes java read almost like a tasty loosely typed language!
Enums are just classes in disguise, so for the most part, anything you can do with a class you can do with an enum.
I cannot think of a reason that an enum should not be able to implement an interface, at the same time I cannot think of a good reason for them to either.
I would say once you start adding thing like interfaces, or method to an enum you should really consider making it a class instead. Of course I am sure there are valid cases for doing non-traditional enum things, and since the limit would be an artificial one, I am in favour of letting people do what they want there.
Most common usage for this would be to merge the values of two enums into one group and treat them similarly. For example, see how to join Fruits and Vegatables.
For example if you have a Logger enum. Then you should have the logger methods such as debug, info, warning and error in the interface. It makes your code loosely coupled.
One of the best use case for me to use enum's with interface is Predicate filters. It's very elegant way to remedy lack of typness of apache collections (If other libraries mayn't be used).
import java.util.ArrayList;
import java.util.Collection;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
public class Test {
public final static String DEFAULT_COMPONENT = "Default";
enum FilterTest implements Predicate {
Active(false) {
#Override
boolean eval(Test test) {
return test.active;
}
},
DefaultComponent(true) {
#Override
boolean eval(Test test) {
return DEFAULT_COMPONENT.equals(test.component);
}
}
;
private boolean defaultValue;
private FilterTest(boolean defautValue) {
this.defaultValue = defautValue;
}
abstract boolean eval(Test test);
public boolean evaluate(Object o) {
if (o instanceof Test) {
return eval((Test)o);
}
return defaultValue;
}
}
private boolean active = true;
private String component = DEFAULT_COMPONENT;
public static void main(String[] args) {
Collection<Test> tests = new ArrayList<Test>();
tests.add(new Test());
CollectionUtils.filter(tests, FilterTest.Active);
}
}
When creating constants in a jar file, it is often helpful to let users extend enum values. We used enums for PropertyFile keys and got stuck because nobody could add any new ones! Below would have worked much better.
Given:
public interface Color {
String fetchName();
}
and:
public class MarkTest {
public static void main(String[] args) {
MarkTest.showColor(Colors.BLUE);
MarkTest.showColor(MyColors.BROWN);
}
private static void showColor(Color c) {
System.out.println(c.fetchName());
}
}
one could have one enum in the jar:
public enum Colors implements Color {
BLUE, RED, GREEN;
#Override
public String fetchName() {
return this.name();
}
}
and a user could extend it to add his own colors:
public enum MyColors implements Color {
BROWN, GREEN, YELLOW;
#Override
public String fetchName() {
return this.name();
}
}
Another posibility:
public enum ConditionsToBeSatisfied implements Predicate<Number> {
IS_NOT_NULL(Objects::nonNull, "Item is null"),
IS_NOT_AN_INTEGER(item -> item instanceof Integer, "Item is not an integer"),
IS_POSITIVE(item -> item instanceof Integer && (Integer) item > 0, "Item is negative");
private final Predicate<Number> predicate;
private final String notSatisfiedLogMessage;
ConditionsToBeSatisfied(final Predicate<Number> predicate, final String notSatisfiedLogMessage) {
this.predicate = predicate;
this.notSatisfiedLogMessage = notSatisfiedLogMessage;
}
#Override
public boolean test(final Number item) {
final boolean isNotValid = predicate.negate().test(item);
if (isNotValid) {
log.warn("Invalid {}. Cause: {}", item, notSatisfiedLogMessage);
}
return predicate.test(item);
}
}
and using:
Predicate<Number> p = IS_NOT_NULL.and(IS_NOT_AN_INTEGER).and(IS_POSITIVE);
Enums are like Java Classes, they can have Constructors, Methods, etc. The only thing that you can't do with them is new EnumName(). The instances are predefined in your enum declaration.
Here's my reason why ...
I have populated a JavaFX ComboBox with the values of an Enum. I have an interface, Identifiable (specifying one method: identify), that allows me to specify how any object identifies itself to my application for searching purposes. This interface enables me to scan lists of any type of objects (whichever field the object may use for identity) for an identity match.
I'd like to find a match for an identity value in my ComboBox list. In order to use this capability on my ComboBox containing the Enum values, I must be able to implement the Identifiable interface in my Enum (which, as it happens, is trivial to implement in the case of an Enum).
I used an inner enum in an interface describing a strategy to keep instance control (each strategy is a Singleton) from there.
public interface VectorizeStrategy {
/**
* Keep instance control from here.
*
* Concrete classes constructors should be package private.
*/
enum ConcreteStrategy implements VectorizeStrategy {
DEFAULT (new VectorizeImpl());
private final VectorizeStrategy INSTANCE;
ConcreteStrategy(VectorizeStrategy concreteStrategy) {
INSTANCE = concreteStrategy;
}
#Override
public VectorImageGridIntersections processImage(MarvinImage img) {
return INSTANCE.processImage(img);
}
}
/**
* Should perform edge Detection in order to have lines, that can be vectorized.
*
* #param img An Image suitable for edge detection.
*
* #return the VectorImageGridIntersections representing img's vectors
* intersections with the grids.
*/
VectorImageGridIntersections processImage(MarvinImage img);
}
The fact that the enum implements the strategy is convenient to allow the enum class to act as proxy for its enclosed Instance. which also implements the interface.
it's a sort of strategyEnumProxy :P the clent code looks like this:
VectorizeStrategy.ConcreteStrategy.DEFAULT.processImage(img);
If it didn't implement the interface it'd had been:
VectorizeStrategy.ConcreteStrategy.DEFAULT.getInstance().processImage(img);