Shared methods between enums - java

I want to refactor an emun in two new enums, but I don't like to copy/paste the enum methods in all new enums.
enum EmailType {
REMINDER_ADMIN('reminderForAdmin')
REMINDER_PRODUCTION('reminderForProduction')
REMINDER_MANAGEMENT('reminderForManagement')
REMINDER_CUSTOMER('reminderForCustomer')
private final propertiesIdentifier
String getTemplate(type) {
...
}
String getFrom(type) {
...
}
String getTo(type) {
...
}
String getBcc(type) {
...
}
...
}
It's possible to implements only one time the methods and use in several enums?
enum EmailTypeAdministration {
REMINDER_ADMIN('reminderForAdmin')
REMINDER_PRODUCTION('reminderForProduction')
...
}
enum EmailTypeClients {
REMINDER_MANAGEMENT('reminderForManagement')
REMINDER_CUSTOMER('reminderForCustomer')
...
}

As my old friend Clippy would say, "it looks like you're using Groovy". If so, you can use a mixin to add the common methods to both enums.
// This class holds the methods that will be mixed-in to the enums
class EnumUtils {
String getTemplate(type) {
"template" + type
}
String getFrom(type) {
}
String getTo(type) {
}
String getBcc(type) {
}
}
// This annotation adds the common methods to the enum
#Mixin(EnumUtils)
enum EmailTypeAdministration {
REMINDER_ADMIN('reminderForAdmin'),
REMINDER_PRODUCTION('reminderForProduction')
EmailTypeAdministration(str) {}
}
// This annotation adds the common methods to the enum
#Mixin(EnumUtils)
enum EmailTypeClients {
REMINDER_MANAGEMENT('reminderForManagement'),
REMINDER_CUSTOMER('reminderForCustomer')
EmailTypeClients(str) {}
}
// Quick test to prove the methods exist and return the expected values
EmailTypeAdministration emailTypeAdmin = EmailTypeAdministration.REMINDER_ADMIN
assert 'templateParam' == emailTypeAdmin.getTemplate('Param')
You can run the code above in the Groovy console to prove it works as advertised

Enums cannot extend any other class since all enums automatically extend class named Enum. So, your only option is to delegate the methods implementation to separate utility. This may be relevant if the implementation is not trivial (more than one line). Otherwise delegation does not give you serious benefits.
Other possibility is to extend Enum manually but I be ready to write verbose code like valueOf(), values() etc., so I am not sure you really need this.
EDIT:
Take a look on my article about Hierarchical Enums. It can probably help you too.

Finally the Mixin solution don't works because #Mixin annotation only works with classes instead of enums.
I use a similar approach with delegate. Delegate transformation works fine! This code can be improve to use EnumUtils with factory or singleton pattern.
class EnumUtils {
String getTemplate(type) {
"template" + type
}
String getFrom(type) {
}
String getTo(type) {
}
String getBcc(type) {
}
}
enum EmailTypeAdministration {
REMINDER_ADMIN('reminderForAdmin'),
REMINDER_PRODUCTION('reminderForProduction')
#Delegate EnumUtils enumUtils = new EnumUtils()
EmailTypeAdministration(str) {}
}
enum EmailTypeClients {
REMINDER_MANAGEMENT('reminderForManagement'),
REMINDER_CUSTOMER('reminderForCustomer')
#Delegate EnumUtils enumUtils = new EnumUtils()
EmailTypeClients(str) {}
}
EmailTypeAdministration emailTypeAdmin = EmailTypeAdministration.REMINDER_ADMIN
assert 'templateParam' == emailTypeAdmin.getTemplate('Param')

The Enum type can't do that but you can use Groovy Mixins or a factory with an interface:
In the enums, just define the constants. All enums must implement a common marker interface.
Create a factory which accepts the marker interface and contains the getters.
The factory approach allows you to move the configuration (like templates, email addresses) into a config file which the factory reads at startup.
Lesson: Don't put configuration into enums. Enums are constants. Configuration changes.

Related

Dynamic access of method based on external field in Spring boot

We have multiple external variables in application.yml in spring boot application and i want to access this variable from my java code and based on the field value I want to redirect the call to various functions.
Example:
String externalVariable1 abc;
String externalVariable2 xyz;
method: if(string == abc) {
call function1; }
else {
call function2; }
Now problem here is there might be further addition to external variable in furture, I want to write robust method which should be adaptable to future addition to external variable without changing my core code. i might add the functionality as part of helper methods.
All I can think of reflection way, Can you guys help me with better approach given i am using spring boot application.
Don't do reflection for this. Instead, wrap function1/function2 into some kind of strategy object:
interface Strategy {
void doStuff();
}
class Function1 implements Strategy {
void doStuff() {
function1();
}
}
class Function2 implements Strategy {
void doStuff() {
function2();
}
}
Then, register all of these with some factory-style class:
class StrategyFactory {
private Strategy defaultStrategy = new Function2();
Map<String, Strategy> strategies = ....
strategies.put("abc", new Function1());
...
Strategy getStrategy(String key) {
return strategies.getOrDefault(key, defaultStrategy);
}
}
Finally, use it:
factory.getStrategy(valueFromYaml).doStuff();
Make key a more complex object than just String if you need to accommodate for more complicated scenarios, or use a more sophisticated way of selecting a strategy than a map lookup.
If you don't know the available strategies before runtime (e.g. if the configuration for these comes from a DB or files) keep only the class name of the Strategy implementation in a map:
Map<String, String> strategyClassNames = ...;
strategy.put(keyFromDB, valueFromDB);
...
and use it by:
Class<? extends Strategy> strategy = Class.forName(strategyClassNames.get(key));
strategy.newInstance().doStuff();

Varying enums in Java being accessed by common method

Essentially what I'm trying to do is create a generic method that can take many different kinds of enums. I'm looking for a way to do it how I'm going to describe, or any other way a person might think of.
I've got a base class, and many other classes extend off that. In each of those classes, I want to have an enum called Includes like this:
public enum Includes {
VENDOR ("Vendor"),
OFFERS_CODES ("OffersCodes"),
REMAINING_REDEMPTIONS ("RemainingRedemptions");
private String urlParam;
Includes(String urlParam) {
this.urlParam = urlParam;
}
public String getUrlParam() {
return urlParam;
}
}
I've got a method that takes in a generic class that extends from BaseClass, and I want to be able to also pass any of the includes on that class to the method, and be able to access the methods on the enum, like this:
ApiHelper.Response<Offer> offer = apiHelper.post(new Offer(), Offer.Includes.VENDOR);
public <T extends BaseClass> Response<T> post(T inputObject, Includes... includes) {
ArrayList<String> urlParams = new ArrayList<String>();
for (Include include : includes){
urlParams.add(include.getUrlParam());
}
return null;
}
Is there a way to be able to pass in all the different kinds of enums, or is there a better way to do this?
---EDIT---
I've added an interface to my enum, but how can I generify my method? I've got this:
public <T extends BaseClass> Response<T> post(Offer inputObject, BaseClass.Includes includes) {
for (Enum include : includes){
if (include instanceof Offer.Includes){
((Offer.Includes) include).getUrlParam();
}
}
return null;
}
But I get an error on apiHelper.post(new Offer(), Offer.Includes.VENDOR); saying the second param must be BaseClass.Includes.
Enums can implement interfaces, so you can create an interface with these methods that you'd like to be able to call:
interface SomeBaseClass {
String getUrlParam();
void setUrlParam(String urlParam);
}
and then your enum can implement this interface:
public enum Includes implements SomeBaseClass {
VENDOR ("Vendor"),
OFFERS_CODES ("OffersCodes"),
REMAINING_REDEMPTIONS ("RemainingRedemptions");
private String urlParam;
Includes(String urlParam) {
this.urlParam = urlParam;
}
#Override
public String getUrlParam() {
return urlParam;
}
#Override
public void setUrlParam(String urlParam) {
this.urlParam = urlParam;
}
}
If you want to get really fancy, it's possible to restrict subtypes of the interface to enums, but the generic type declaration will be pretty ugly (thus hard to understand and maintain) and probably won't provide any "real" benefits.
Unrelated note regarding this design: it's a pretty strong code smell that the enum instances are mutable. Reconsider why you need that setUrlParam() method in the first place.

Java - Alternatives to forcing subclass to have a static method

I often find I want to do something like this:
class Foo{
public static abstract String getParam();
}
To force a subclasses of Foo to return a parameter.
I know you can't do it and I know why you can't do it but the common alternative of:
class Foo{
public abstract String getParam();
}
Is unsatisfactory because it requires you to have an instance which is not helpful if you just want to know the value of the parameter and instantiating the class is expensive.
I'd be very interested to know of how people get around this without getting into using the "Constant Interface" anti pattern.
EDIT: I'll add some more detail about my specific problem, but this is just the current time when I've wanted to do something like this there are several others from the past.
My subclasses are all data processors and the superclass defines the common code between them which allows them to get the data, parse it and put it where it needs to go.
The processors each require certain parameters which are held in an SQL database. Each processor should be able to provide a list of parameters that it requires and the default values so the configuration database can be validated or initialised to defaults by checking the required parameters for each processor type.
Having it performed in the constructor of the processor is not acceptable because it only needs to be done once per class not once per object instance and should be done at system startup when an instance of each type of class may not yet be needed.
The best you can do here in a static context is something like one of the following:
a. Have a method you specifically look for, but is not part of any contract (and therefore you can't enforce anyone to implement) and look for that at runtime:
public static String getParam() { ... };
try {
Method m = clazz.getDeclaredMethod("getParam");
String param = (String) m.invoke(null);
}
catch (NoSuchMethodException e) {
// handle this error
}
b. Use an annotation, which suffers from the same issue in that you can't force people to put it on their classes.
#Target({TYPE})
#Retention(RUNTIME)
public #interface Param {
String value() default "";
}
#Param("foo")
public class MyClass { ... }
public static String getParam(Class<?> clazz) {
if (clazz.isAnnotationPresent(Param.class)) {
return clazz.getAnnotation(Param.class).value();
}
else {
// what to do if there is no annotation
}
}
I agree - I feel that this is a limitation of Java. Sure, they have made their case about the advantages of not allowing inherited static methods, so I get it, but the fact is I have run into cases where this would be useful. Consider this case:
I have a parent Condition class, and for each of its sub-classes, I want a getName() method that states the class' name. The name of the sub-class will not be the Java's class name, but will be some lower-case text string used for JSON purposes on a web front end. The getName() method will not change per instance, so it is safe to make it static. However, some of the sub-classes of the Condition class will not be allowed to have no-argument constructors - some of them I will need to require that some parameters are defined at instantiation.
I use the Reflections library to get all classes in a package at runtime. Now, I want a list of all the names of each Condition class that is in this package, so I can return it to a web front end for JavaScript parsing. I would go through the effort of just instantiating each class, but as I said, they do not all have no-argument constructors. I have designed the constructors of the sub-classes to throw an IllegalArgumentException if some of the parameters are not correctly defined, so I cannot merely pass in null arguments. This is why I want the getName() method to be static, but required for all sub-classes.
My current workaround is to do the following: In the Condition class (which is abstract), I have defined a method:
public String getName () {
throw new IllegalArugmentException ("Child class did not declare an overridden getName() method using a static getConditionName() method. This must be done in order for the class to be registerred with Condition.getAllConditions()");
}
So in each sub-class, I simply define:
#Override
public String getName () {
return getConditionName ();
}
And then I define a static getConditionName() method for each. This is not quite "forcing" each sub-class to do so, but I do it in a way where if getName() is ever inadvertently called, the programmer is instructed how to fix the problem.
It seems to me you want to solve the wrong problem with the wrong tool. If all subclasses define (can't really say inherit) your static method, you will still be unable to call it painlessly (To call the static method on a class not known at compile time would be via reflection or byte code manipulation).
And if the idea is to have a set of behaviors, why not just use instances that all implement the same interface? An instance with no specific state is cheap in terms of memory and construction time, and if there is no state you can always share one instance (flyweight pattern) for all callers.
If you just need to couple metadata with classes, you can build/use any metadata facility you like, the most basic (by hand) implementation is to use a Map where the class object is the key. If that suits your problem depends on your problem, which you don't really describe in detail.
EDIT: (Structural) Metadata would associate data with classes (thats only one flavor, but probably the more common one). Annotations can be used as very simple metadata facility (annotate the class with a parameter). There are countless other ways (and goals to achieve) to do it, on the complex side are frameworks that provide basically every bit of information designed into an UML model for access at runtime.
But what you describe (processors and parameters in database) is what I christened "set of behaviors". And the argument "parameters need to be loaded once per class" is moot, it completely ignores the idioms that can be used to solve this without needing anything 'static'. Namely, the flyweight pattern (for having only once instance) and lazy initialization (for doing work only once). Combine with factory as needed.
I'm having the same problem over and over again and it's hard for me to understand why Java 8 preferred to implement lambda instead of that.
Anyway, if your subclasses only implement retrieving a few parameters and doing rather simple tasks, you can use enumerations as they are very powerful in Java: you can basically consider it a fixed set of instances of an interface. They can have members, methods, etc. They just can't be instanciated (as they are "pre-instanciated").
public enum Processor {
PROC_IMAGE {
#Override
public String getParam() {
return "image";
}
},
PROC_TEXT {
#Override
public String getParam() {
return "text";
}
}
;
public abstract String getParam();
public boolean doProcessing() {
System.out.println(getParam());
}
}
The nice thing is that you can get all "instances" by calling Processor.values():
for (Processor p : Processorvalues()) {
System.out.println(String.format("Param %s: %s", p.name(), p.getParam()));
p.doProcessing();
}
If the processing is more complex, you can do it in other classes that are instanciated in the enum methods:
#Override
public String getParam() {
return new LookForParam("text").getParam();
}
You can then enrich the enumeration with any new processor you can think of.
The down side is that you can't use it if other people want to create new processors, as it means modifying the source file.
You can use the factory pattern to allow the system to create 'data' instances first, and create 'functional' instances later. The 'data' instances will contain the 'mandatory' getters that you wanted to have static. The 'functional' instances do complex parameter validation and/or expensive construction. Of course the parameter setter in the factory can also so preliminary validation.
public abstract class Processor { /*...*/ }
public interface ProcessorFactory {
String getName(); // The mandatory getter in this example
void setParameter(String parameter, String value);
/** #throws IllegalStateException when parameter validation fails */
Processor construct();
}
public class ProcessorA implements ProcessorFactory {
#Override
public String getName() { return "processor-a"; }
#Override
public void setParameter(String parameter, String value) {
Objects.requireNonNull(parameter, "parameter");
Objects.requireNonNull(value, "value");
switch (parameter) {
case "source": setSource(value); break;
/*...*/
default: throw new IllegalArgumentException("Unknown parameter: " + parameter);
}
}
private void setSource(String value) { /*...*/ }
#Override
public Processor construct() {
return new ProcessorAImpl();
}
// Doesn't have to be an inner class. It's up to you.
private class ProcessorAImpl extends Processor { /*...*/ }
}

how to pass different enum types to a method?

I have a method which takes an enum and uses it in some fashion. The issue is that I have many different enum types and am not what acceptable practice is to pass an enum to a method.
I'm assuming that you mean you have a bunch of different enum classes that mean separate things, and that you want to pass them into one method.
To do that, use a marker interface:
public interface SpecialEnumType {
}
then:
public enum MySpecialEnumType implements SpecialEnumType {
...
}
public enum AnotherSpecialEnumType implements SpecialEnumType {
...
}
Now your method will accept a parameter of type SpecialEnumType:
public doSomething(SpecialEnumType specialEnumType) {
...
}
Having done that, you can do:
obj.doSomething(MySpecialEnumType.SomeThing);
obj.doSomething(AnotherSpecialEnumType.SomethingElse);
In general, it's perfectly alright to use an enum as a parameter type for a method argument.
UPDATE
I've used this pattern while integrating with third-party API's. For example, a little while ago I had to integrate with different shipping providers. To do this, I provided a general interface that allowed the developer to send in shipping information (like the addresses, packages, weights, packing options, etc.). If you wanted to implement integration with a new provided, all you needed to do was implement the interface.
Now each shipping provider had its own set of options. Before using marker interfaces, I had a single enum which contained all the options (of all the different shipping providers). This is obviously hard to maintain. But I couldn't split the enums into different classes because the interface specified a specific type of enum for the method arguments.
Using a marker interface, I was able to get around this problem. I created an interface called ShippingProviderOption. Then for each provider, I extended the interface and created an enum, with the specific options for that provider. This way I was able to separate out the options, but still present a common interface.
As far as code is concerned (greatly simplified and somewhat contrived, for demonstration purposes):
public interface ShippingProviderOption {
}
public enum UPSOption implements ShippingProviderOption {
...
}
public enum FedexOption implements ShippingProviderOption {
...
}
public interface ShippingProvider {
public ShippingResponse ship(ShippingProviderOption option);
}
public class UPSProvider implements ShippingProvider {
#Override
public ShippingResponse ship(ShippingProviderOption option) {
if(option == UPSOption.PackageType) {
...
}
}
}
public class FedexProvider implements ShippingProvider {
#Override
public ShippingResponse ship(ShippingProviderOption option) {
if(option == FedexOption.PickupType) {
...
}
}
}
Now in my actual implementation, I have a few methods in the marker interface. So it doesn't really even have to be a marker interface; it can contain methods.

Best practice for use constants in scala annotations

I use tapestry 5 as my choice of web framework. Tapestry allows me to define symbols in the configure class and inject symbols into other components.
for example,
public interface SymbolConstants {
static String DEFAULT_TIMEOUT_KEY = "default.timeout";
}
public class AppModule {
void contributeApplicationDefault(Configuration conf) {
conf.add(SymbolConstants.DEFAULT_TIMEOUT_KEY, "10");
}
}
public class MyComponent {
#Symbol(SymbolConstants.DEFAULT_VALUE_KEY)
private long timeout;
}
The ability to define static constants and use them as annotation values gives me compile time check.
I am wondering how to define constants and use them as values of scala annotations. If not, what is the best practice to define/limit the value that we can assign to annotations in scala.
The 'final' keyword is required to make the compiler emit it as you would do it in Java. E.g.,
object Foo
{
final val MY_SYMBOLIC_CONSTANT="whatever"
}
It seems that, otherwise, you only get an accessor method under the hood which is not statically calculable.
It doesn't seem possible w/ scala versions 2.8.1.final, 2.8.2.final, or 2.9.1.final (the result was the same with all):
object Constant { val UNCHECKED = "unchecked" }
class Test {
#SuppressWarnings(Array(Constant.UNCHECKED))
def test: Unit = println("testing.. 1, 2... 3")
}
.
<console>:7: error: annotation argument needs to be a constant; found: Constant.UNCHECKED
#SuppressWarnings(Array(Constant.UNCHECKED))

Categories