void with Generics in Java - java

I have a function that returns void
public interface IProductService {
void delete(String id);
}
Generic method
public interface IRequestHandler<C , R> {
R handler(C c);
Class<C> commandType();
}
Implementation of generic interface
#Singleton
public record DeleteProductCommandHandler(IProductService iProductService)
implements IRequestHandler<DeleteProductCommand, Void> {
#Override
public Void handler(DeleteProductCommand deleteProductCommand) {
return iProductService.delete(deleteProductCommand.id);
}
#Override
public Class<DeleteProductCommand> commandType() {
return DeleteProductCommand.class;
}
}
How can I use void in IRequestHandler<DeleteProductCommand, Void> so that I can map void from iProductService.delete(deleteProductCommand.id);

Option 1:
Just return null:
#Override
public Void handler(DeleteProductCommand deleteProductCommand) {
iProductService.delete(deleteProductCommand.id);
return null;
}
Option 2:
Update the IProductService::delete method to return something meaningful, e.g. a boolean value like Collection::remove does:
public interface IProductService {
boolean delete(String id);
}
#Singleton
public record DeleteProductCommandHandler(IProductService iProductService)
implements IRequestHandler<DeleteProductCommand, Boolean> {
#Override
public Boolean handler(DeleteProductCommand deleteProductCommand) {
return iProductService.delete(deleteProductCommand.id);
}
#Override
public Class<DeleteProductCommand> commandType() {
return DeleteProductCommand.class;
}
}

Related

How to extract the common condition check in a class

If I have a class, where all methods should evaluate only if a boolean attribute is true, what is the best way to define it in terms of best practices?
Is there a way to replace the recurring isEnabled check in all the methods by a single check? The current form works, I'm looking for a way to improve it to not have isEnabled checked in all the methods.
#Singleton
public class SomeClass implements SomeInterface {
EventPublisher eventPubilsher;
boolean isEnabled;
#Inject
public SomeClass(final Decider decider, EventPublisher, eventPublisher) {
this.isEnabled = decider.isSomethingEnabled();
this.eventPublisher = eventPublisher;
}
#Override
public void method1() {
if(isEnabled){
eventPublisher.publishSomething1();
}
}
#Override
public void method2() {
if(isEnabled){
eventPublisher.publishSomething2();
}
}
#Override
public void method3() {
if(isEnabled){
eventPublisher.publishSomething3();
}
}
}
You can have implementation for enabled stuff, and one for disabled stuff. The disabled implementation won't do anything:
public class DisabledSomeClass implements SomeInterface {
#Override
public void method1() {
}
#Override
public void method2() {
}
#Override
public void method3() {
}
}
Enabled one will publish stuff:
public class EnabledSomeClass implements SomeInterface {
EventPublisher eventPublisher;
public EnabledSomeClass(EventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
#Override
public void method1() {
eventPublisher.publishSomething1();
}
#Override
public void method2() {
eventPublisher.publishSomething2();
}
#Override
public void method3() {
eventPublisher.publishSomething3();
}
}
Then extract the logic, if functionality is enabled in new factory class - SomeInterfaceFactory (probably not the best name, but you get the idea), it will return the correct implementation, depending on whether something is enabled.
public class SomeInterfaceFactory {
public static SomeInterface getInstance(Decider decider, EventPublisher eventPublisher) {
if (decider.isSomethingEnabled()) {
return new EnabledSomeClass(eventPublisher);
} else {
return new DisabledSomeClass();
}
}
}
This should work
#Singleton
public class SomeClass implements SomeInterface {
EventPublisher eventPubilsher;
boolean isEnabled;
#Inject
public SomeClass(final Decider decider, EventPublisher, eventPublisher) {
this.isEnabled = decider.isSomethingEnabled();
this.eventPublisher = eventPublisher;
}
#Override
public void method1() {
publish(ep->ep.publishSomething1());
}
#Override
public void method2() {
publish(ep->ep.publishSomething2());
}
#Override
public void method3() {
publish(ep->ep.publishSomething3());
}
private void publish(Consumer<EventPublisher> callback){
if(isEnabled) callback.accept(eventPublished);
}
}
A Runnable interface can receive a lambda without args and run a lambda function with run() method. So, you can create a method inside your Decider class and receive a Runnable as a parameter, like:
class Decider{
private boolean enabled;
//...
public void execute(Runnable runnable){
if(enabled) runnable.run();
}
}
And receive your Decider and do:
//...
EventPublisher eventPubilsher;
Decider decider;
#Inject
public SomeClass(final Decider decider, EventPublisher, eventPublisher) {
this.decider = decider;
this.eventPublisher = eventPublisher;
}
#Override
public void method1() {
Decider.execute(() -> eventPublisher.publishSomething1());
}
//...
You're locking the evaluation of the condition to the constructor. If you want any flexibility, you should pull it out.
public class SomeClass implements SomeInterface {
boolean isEnabled;
public SomeClass(EventPublisher, eventPublisher) {
//
}
public void addDecide(boolean value){
isEnabled = value;
}
boolean getEnabled(){
return isEnabled;
}
#Override
public void method3() {
if(getEnabled()){
eventPublisher.publishSomething3();
}
}
}
You can even go crazy and add a supplier:
public void addDecide(Supplier<Boolean> supplier){
supplier = supplier;
}
boolean getEnabled(){
return supplier.get();
}

Is there a way to give boolean type as generic in Java?

I have a code block like below:
public Interface ISupClass{
void call();
void call1();
...
}
public class NormalClass implements ISupClass{
void call(){
....operations...
}
void call1(){
....operations...
}
...
}
public class DailyClass implements ISupClass{
void call(){
....operations...
}
void call1(){
....operations...
}
...
}
Then I call them from main service like that;
Instances:
private INormalClass dailyClass = new DailyClass();
private INormalClass normalClass = new NormalClass();
Method:
public void call(int type, boolean isDaily){
if(type == 0) {
if(isDaily){
dailyClass.call();
}
else{
normalClass.call();
}
}
if(type == 1) {
if(isDaily){
dailyClass.call1();
}
else{
normalClass.call1();
}
}
...
}
Is there a way to escape from isDaily check in above code block? Or how can I implement it effectively? I have just tried to implement with Java Generics but this doesn't look possible?
I know this looks like related with polimorfizm. But I wonder somethink like about it;
public Interface ISupClass<E>
call(E type)
...
public class NormalClass implements ISupClass<Boolen.FALSE>
...
public class DailyClass implements ISupClass<Boolen.TRUE>
...
public void call(int type, boolean isDaily){
supClass.call(isDaily);
(In case I understood what is the question)
This is the point of using interfaces. Simply do something like this:
public class Example {
public static interface ISupClass {
void doSomething();
}
public static class NormalClass implements ISupClass {
#Override
public void doSomething() {
System.out.println("I am a normal class.");
}
}
public static class DailyClass implements ISupClass {
#Override
public void doSomething() {
System.out.println("I am a daily class.");
}
}
public static void doSomething(ISupClass clazz) {
clazz.doSomething();
}
public static void main(String[] args) {
doSomething(new DailyClass());
doSomething(new NormalClass());
}
}
So, in your case instead of passing boolean isDaily, pass argument ISupClass in call method.
public void call(int type, ISupClass caller) {
caller.call();
}
Now, generics is a totally different story and I am not able to see how it is related to the question.
From what I understand, public void call(int type, boolean isDaily){...} is an orchestrator/mediator method that manipulates the one or the other instance according to the flags received in the parameters.
In this case, why not use a Map<Boolean, INormalClass> to store the two instances in a way where you can retrieve them from a boolean key :
Map<Boolean, INormalClass> map = new HashMap<>();
map.put(Boolean.TRUE, new DailyClass());
map.put(Boolean.FALSE, new NormalClass());
//...
public void call(int type, boolean isDaily){
INormalClass obj = map.get(isDaily);
if(type == 0) {
obj.call();
}
if(type == 1) {
obj.call1();
}
}
You could add default method to the interface:
public interface ISupClass {
default void call(int type) {
if (type == 0) {
call();
} else if(type == 1) {
call1();
}
}
void call();
void call1();
}
It leads you to following code:
public static void call(int type, boolean isDaily) {
if (isDaily) {
dailyClass.call(type);
} else {
normalClass.call(type);
}
}

How to implement and fire an event when a change occurs in a property of `T` in `List<T>` within the owning class in Java

Any clue if it is possible to convert code below to Java (Android) from C#?
It is based on my prev.question
How to implement and fire an event when a change occurs in a property of `T` in `List<T>` within the owning class
public class ItemPropertyChangedNotifyingList<T> : IList<T>, INotifyPropertyChanged where T : INotifyPropertyChanged
{
private List<T> _listImplementation = new List<T>();
public void Add(T item)
{
item.PropertyChanged += ItemOnPropertyChanged;
_listImplementation.Add(item);
}
private void ItemOnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
PropertyChanged?.Invoke(sender, e);
}
public IEnumerator<T> GetEnumerator()
{
return _listImplementation.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)_listImplementation).GetEnumerator();
}
public void Clear()
{
_listImplementation.ForEach(x => x.PropertyChanged -= ItemOnPropertyChanged);
_listImplementation.Clear();
}
public bool Contains(T item)
{
return _listImplementation.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
_listImplementation.CopyTo(array, arrayIndex);
}
public bool Remove(T item)
{
item.PropertyChanged -= ItemOnPropertyChanged;
return _listImplementation.Remove(item);
}
public int Count => _listImplementation.Count;
public bool IsReadOnly => false;
public int IndexOf(T item)
{
return _listImplementation.IndexOf(item);
}
public void Insert(int index, T item)
{
item.PropertyChanged += ItemOnPropertyChanged;
_listImplementation.Insert(index, item);
}
public void RemoveAt(int index)
{
_listImplementation.RemoveAt(index);
}
public T this[int index]
{
get => _listImplementation[index];
set => _listImplementation[index] = value;
}
public event PropertyChangedEventHandler PropertyChanged;
}
Have we use PropertyChangeListener for this task? Like it is shown here.
public FocusManagerListener implements PropertyChangeListener {
public void propertyChange(PropertyChangeEvent e) {
String propertyName = e.getPropertyName();
if ("focusOwner".equals(propertyName) {
...
} else if ("focusedWindow".equals(propertyName) {
...
}
}
...
}
I just ported ItemPropertyChangedNotifyingList to ItemChangeList.
In code, I changed this part.
Used 'ArrayList' to hold elements instead of 'List` in C#
In copyTo, I used Java 8 Stream. Since you tag 'android', I used Lightweight-Stream-API to achieve same feature of copyTo.
Java doesn't support get, set syntax, i divide to two methods.
import com.annimon.stream.Stream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ItemChangedList<T> {
private List<T> _listImplementation = new ArrayList<>();
private List<OnPropertyChangedObserver<T>> _changedObserverList = new ArrayList<>();
public static final String ITEM_ADDED = "bbed36af-0b7b-4e53-abc9-02d6a14d7f34";
public static final String ITEM_REMOVED = "7390116e-586d-4e62-9343-5b82b0a8c6c5";
public void add(T item) {
sendPropertyChanged(item, ITEM_ADDED);
_listImplementation.add(item);
}
public Iterator<T> iterator() {
return _listImplementation.iterator();
}
public void clear() {
for (T item : _listImplementation) {
sendPropertyChanged(item, ITEM_REMOVED);
}
_listImplementation.clear();
}
public boolean contains(T item) {
return _listImplementation.contains(item);
}
public void copyTo(T[] array, int arrayIndex) {
// Using https://github.com/aNNiMON/Lightweight-Stream-API
_listImplementation.addAll(Stream.of(array).skip(arrayIndex).toList());
// Traditional Java way
// _listImplementation.addAll(Arrays.stream(array).skip(arrayIndex).collect(Collectors.toList()));
}
public boolean remove(T item) {
sendPropertyChanged(item, ITEM_REMOVED);
return _listImplementation.remove(item);
}
public int count() {
return _listImplementation.size();
}
public boolean isReadOnly() {
return false;
}
public int indexOf(T item) {
return _listImplementation.indexOf(item);
}
public void insert(int index, T item) {
sendPropertyChanged(item, ITEM_ADDED);
_listImplementation.add(index, item);
}
public void removeAt(int index) {
_listImplementation.remove(index);
}
public T get(int index) {
return _listImplementation.get(index);
}
public void set(int index, T item) {
_listImplementation.set(index, item);
}
public void addObserver(OnPropertyChangedObserver<T> observer) {
_changedObserverList.add(observer);
}
public void removeObserver(OnPropertyChangedObserver<T> observer) {
_changedObserverList.remove(observer);
}
public void clearObserver() {
_changedObserverList.clear();
}
private void sendPropertyChanged(T item, String args) {
for (OnPropertyChangedObserver<T> observer : _changedObserverList) {
observer.onChanged(item, args);
}
}
public interface OnPropertyChangedObserver<T> {
void onChanged(T item, String args);
}
}
Other way is extends ArrayList instead _listImplementation. it can be provide more functionally. Personally, I prefer this way. Gist
Edit-1) Oh, i forget add args in OnPropertyChangeObserver.
Edit-2) Let Kotlin optimize this! Gist

Create Enum with list of the same object

I would like to create an enum containing one attribut, a list of objects extending the same interface or the same abstract class.
The objective is to have a loop on each list of my enum to call methods dynamically.
public interface Regles {
void verifier();
}
public class Regle01 implements Regles {
#Override
public void verifier() {
}
}
public class Regle02 implements Regles {
#Override
public void verifier() {
}
}
public enum ListRegles {
ENUM1(Arrays.asList(new Regle01(), new Regle02())),
ENUM2(Arrays.asList(new Regle01()))
private List<Regles> regles = new ArrayList<Regles>();
ListRegles(List<Regles> r) {
regles = r;
}
}
how can i do this please ?
enum:
public enum ListRegles {
ENUM1(new Regle01(),new Regle02()),
ENUM2(new Regle01());
private List<Regles> regles ;
ListRegles(Regles... regles) {
this.regles = new ArrayList<>(Arrays.asList(regles));
}
public void verify() {
for (Regles regle : regles) {
regle.verifier();
}
}
}
Will call verifier for Regle01 and Regle02
ListRegles.ENUM1.verify();

Storing Methods in an Enum? [duplicate]

This question already has an answer here:
Methods in Enums [duplicate]
(1 answer)
Closed 8 years ago.
Right now, I have an enum for a variety of values, and I was wondering if there is any way I would be able to store a method in an enum. For example:
public enum myEnum{
one("first", callFirstMethod),
two("second", callSecondMethod),
three("last", callThirdMethod);
public String message;
public Method met;
myEnum(String m, Method meth){
message = m;
met = meth;
}
}
public class myMethods{
public void callFirstMethod(){
System.out.println("First!");
}
public void callSecondMethod(){
System.out.println("Second!");
}
public void callThirdMethod(){
System.out.println("Third!");
}
}
Then by using something like:
Method method = myEnum.one.callFirstMethod();
To call the method. Is something like this possible? I've tried playing around/looking around on google, and nothing is really turning up. Thank you for the help!
Use an interface and have the interface instance as the second enum parameter, or give it an abstract method that is implemented in the instance. For instance:
enum MyEnum {
ONE("first", new MyInterface() {
#Override
public void commonMethod() {
System.out.println("First!");
}
}) {
#Override
public void abstractEnumMethod() {
System.out.println("abstract enum meuthod, first!");
}
},
TWO("second", new MyInterface() {
#Override
public void commonMethod() {
System.out.println("Second!");
}
}) {
#Override
public void abstractEnumMethod() {
System.out.println("abstract enum meuthod, second!");
}
},
THREE("last", new MyInterface() {
#Override
public void commonMethod() {
System.out.println("Third!");
}
}) {
#Override
public void abstractEnumMethod() {
System.out.println("abstract enum meuthod, third!");
}
};
private String message;
private MyInterface myType;
private MyEnum(String m, MyInterface myType) {
message = m;
this.myType = myType;
}
public String getMessage() {
return message;
}
public MyInterface getMyType() {
return myType;
}
public void enumMethod() {
System.out.println(message);
}
public abstract void abstractEnumMethod();
}
interface MyInterface {
void commonMethod();
}
The answer all depends on what it's you want to achieve. For example, you could provide a common method within you enum and inspect the instance of the enum calling it...
public class TestEnum {
public static void main(String[] args) {
MyEnum.ONE.doStuff();
MyEnum.TWO.doStuff();
MyEnum.THREE.doStuff();
}
public enum MyEnum {
ONE("first"),
TWO("second"),
THREE("last");
public String message;
MyEnum(String m) {
message = m;
}
public void doStuff() {
System.out.println(name());
if (ONE.equals(this)) {
System.out.println("...Do stuff for one");
} else if (TWO.equals(this)) {
System.out.println("...Do stuff for two");
} else if (THREE.equals(this)) {
System.out.println("...Do stuff for three");
}
}
}
}
Which outputs...
one
...Do stuff for one
two
...Do stuff for two
three
...Do stuff for three

Categories