CQRS How to avoid repeating fields between command and event? - java

I'm implementing a project using CQRS and Event Sourcing. I realized that my commands and my events are nearly always the same.
Let's say I have a command CreatePost :
public class CreatePost implements Command {
private final String title;
private final String content;
}
The event fired from this command is the same :
public class PostCreated implements Event {
private final String title;
private final String content;
}
How do you handle that in your applications ?
EDIT : Of course I'm aware of basic OOP technics. I could create an abstraction having the common fields, but this question needs to be taken in the CQRS/ES context.

How to avoid repeating fields between command and event?
I wouldn't -- not until I absolutely can't stand it.
Fundamentally, commands and events aren't objects, they are messages - representations of state that cross boundaries. I think it's important that your in memory representation not lose sight of that.
One of the characteristics of message schemas is that they evolve over time, so you need to be aware of compatibility. And here's the kicker: events and commands evolve on different time scales.
Command messages are how your domain model communicates with other processes; changes to that part of the API are driven by exposing/deprecating functionality.
But in an event sourced world, events are messages from previous versions of the domain to the current version. They are part of the support we need to deploy new models that resume work from where the old model left off.
So I would keep commands and events separate from one another - they are different things.
If you are seeing a lot of duplication in the fields, that may be a hint that there's some value type that you haven't yet made explicit.
CreatePost
{ Post
{ Title
, Contents
}
}
PostCreated
{ Post
{ Title
, Contents
}
}

Simply implement a model for your Post, i.e.:
public class PostModel {
private String title;
private String content;
// Add get/set methods
}
Then re-use this in both your events and commands.

Just compiling this answer from the discussion we had in comments.
Compose, don't inherit
I would definitely not use inheritance in a situation like this because it will just add unnecessary complexity, also there is no behavior to inherit there.
Another option is to have a well-defined contract for your commands and events. That is to have two interfaces — IPost and IEvent — and implement those in the commands and events.
Regarding naming: we all know that naming is hard, so you should choose names wisely, according to your business or technical language/vocabulary requirements.
Why split into two interfaces?
Because a command usually carries more information required for its handler than an event carries for its event handler, event handlers should be kept as thin as possible. It's better to carry only the needed payload.
Closing words
Separating commands and events is a must, since commands are representing an operation that's happening now, whereas events are representing actions that happened in the past. They might usually be an outcome of a command, indicating to the outside world — from the viewpoint of a bounded context — that something happened inside your current BC.

How to avoid repeating fields between command and event?
Just don't. The cost of dependency + risk of wrongful mutualization are higher than the maintenance gain. You can live with that duplication, just like you probably live with duplication between your domain model, view model, query model, etc. today.

You can use whatever you want as long as it is just an implementation detail.
In PHP I use a lot traits for this kind of reusability. You can use even inheritance but the clients (the code that uses those classes) should not depend on the base class; it would be best if they even don't find out that your event and command class share something but I don't have enough Java experience to tell you how to do it.
P.S. I would not go with creating interfaces, as I specified above, this should be just an implementation detail.

I've run into this, and almost universally I've not found a case where the event needed different properties than the command for a particular domain action. I definitely find the menial copy/paste duplication of property getters/equals/hashCode/toString pretty annoying. If I could go back, I'd define a marker interface Action and then
interface Command<T extends Action> {
T getAction();
// other properties common to commands of all action types...
}
class AbstractCommand<T extends Action> implements Command<T> {
public T getAction() { ... }
// other properties...
}
interface Event<T extends Action> {
T getAction();
// other properties common to events of all action types...
}
class AbstractEvent<T extends Action> implements Event<T> {
public T getAction() { ... }
// other properties...
}
Then for each domain action, define concrete implementations.
class ConcreteAction implements Action {
// properties COMMON to the command and event(s)...
}
class ConcreteCommand extends AbstractCommand<ConcreteAction> { ... }
class ConcreteEvent extends AbstractEvent<ConcreteAction> { ... }
If the command and event action properties need to diverge for some reason, I'd put just those particular properties in the ConcreteCommand or ConcreteEvent classes.
The inheritance model here is very simple. You may only rarely need to do anything more than extend the abstract classes with nothing more to implement than the common Action. And in the case where there are no properties needed for the Action, just define a class EmptyAction implements Action implementation to use in those types of commands and events.

Related

Using the Command Pattern with Parameters

I have a ReloadableWeapon class like this:
public class ReloadableWeapon {
private int numberofbullets;
public ReloadableWeapon(int numberofbullets){
this.numberofbullets = numberofbullets;
}
public void attack(){
numberofbullets--;
}
public void reload(int reloadBullets){
this.numberofbullets += reloadBullets;
}
}
with the following interface:
public interface Command {
void execute();
}
and use it like so:
public class ReloadWeaponCommand implements Command {
private int reloadBullets;
private ReloadableWeapon weapon;
// Is is okay to specify the number of bullets?
public ReloadWeaponCommand(ReloadableWeapon weapon, int bullets){
this.weapon = weapon;
this.reloadBullets = bullets;
}
#Override
public void execute() {
weapon.reload(reloadBullets);
}
}
Client:
ReloadableWeapon chargeGun = new ReloadableWeapon(10);
Command reload = new ReloadWeaponCommand(chargeGun,10);
ReloadWeaponController controlReload = new ReloadWeaponController(reload);
controlReload.executeCommand();
I was wondering, with the command pattern, with the examples I've seen, other than the object that the command is acting on, there are no other parameters.
This example, alters the execute method to allow for a parameter.
Another example, more close to what I have here, with parameters in the constructor.
Is it bad practice/code smell to include parameters in the command pattern, in this case the constructor with the number of bullets?
I don't think adding parameters into execute will be bad design or violate command pattern.
It totally depends on how you want to use Command Object: Singleton Or Prototype scope.
If you use Prototype scope, you can pass command parameters in Constructor methods. Each command instance has its own parameters.
If you use Singleton scope (shared/reused instance), you can pass command parameters in execute method. The singleton of the command should be thread safe for this case. This solution is a friend of IoC/DI framework too.
The very purpose of this pattern is to allow to define actions, and to execute them later, once or several times.
The code you provide is a good example of this pattern : you define the action "reload", that charges the gun with an amount of bullets=10 ammunition.
Now, if you decide to modify this code to add bullets as a parameter, then you completely lose the purpose of this pattern, because you will have to define the amount of ammunition every time.
IMHO, you can keep your code as it is. You will have to define several ReloadWeaponCommand instances, with different value of bullets. Then you may have to use another pattern (such as Strategy) to switch between the commands.
Consider a case you have 95 bullets in hand in starting, and you have made 9 commands with 10 bullets and 1 command with 5 bullets. And you have submitted these commands to Invoker, now invoker doesn't have to worry about how much bullets are left. He will just execute the command. On the other hand if invoker has to provide the no of bullets at run time then it could be the case supplied number of bullets are not available.
My point here is that Invoker must not have to worry about any extra information needs to execute the command. And as mentioned in wiki "an object is used to encapsulate all information needed to perform an action or trigger an event at a later time"
Using the Command Pattern with Parameters
Consider the related 'Extension Patterns' in order to hold to a Top-Down Control paradigm 'Inversion of Control'.
This pattern, the Command Pattern, is commonly used in concert with the Composite, Iterator, and Visitor Design Patterns.
Commands are 'First Class Objects'. So it is critical that the integrity of their encapsulation is protected. Also, inverting Control From Top Down to Bottom Up, Violates a Cardinal principle of Object Oriented Design, though I see people suggesting it all of the time...
The Composite pattern will allow you to store Commands, in iterative data structures.
Before going any further, and while your code is still manageable, look at these Patterns.
There are some reasonable points made here in this thread. #Loc has it closest IMO, However, If you consider the patterns mentioned above, then, regardless of the scope of your project (it appears that you intend to make a game, no small task) you will be able to remain in control of lower-level dependency. As #Loc pointed out, with 'Dependency Injection' lower class Objects should be kept 'in the dark' when it comes to any specific implementation, in terms of the data that is consumed by them; this is (should be) reserved for the top level hierarchy. 'Programming to Interfaces, not Implementation'.
It seems that you have a notion of this. Let me just point out where I see a likely mistake at this point. Actually a couple, already, you are focused on grains of sand I.e. "Bullets" you are not at the point where trivialities like that serve any purpose, except to be a cautionary sign, that you are presently about to lose control of higher level dependencies.
Whether you are able to see it yet or not, granular parts can and should be dealt with at higher levels. I will make a couple of suggestions. #Loc already mentioned the best practice 'Constructor Injection' loosely qualified, better to maybe look up this term 'Dependency Injection'.
Take the Bullets for e.g. Since they have already appeared on your scope. The Composite Pattern is designed to deal with many differing yet related First Class Objects e.g. Commands. Between the Iterator and Visitor Patterns you are able to store all of your pre-instantiated Commands, and future instantiations as well, in a dynamic data structure, like a Linked List OR a Binary Search Tree even. At this point forget about the Strategy
Pattern, A few possible scenarios is one thing, but It makes no sense to be writing adaptive interfaces at the outset.
Another thing, I see no indication that you are spawning projectiles from a class, bullets I mean. However, even if it were just a matter of keeping track of weapon configurations, and capacities(int items) (I'm only guessing that is the cause of necessary changes in projectile counts) use a stack structure or depending on what the actual scenario is; a circular queue. If you are actually spawning projectiles from a factory, or if you decide to in the future, you are ready to take advantage of Object Pooling; which, as it turns out, was motivated by this express consideration.
Not that anyone here has done this, but I find it particularly asinine for someone to suggest that it is ok to mishandle or disregard a particular motivation behind any established (especially GoF) Design pattern. If you find yourself having to modify a GoF Design pattern, then you are using the wrong one. Just sayin'
P.S. if you absolutely must, why don't you instead, use a template solution, rather than alter an intentionally specific Interface design;

MVP : : Event Bus pattern instead of Listener

This question more towards paradigm. Why is that we don't use Event Bus instead of listeners in an MVP environment ? Typically, the "P" part has dependency injection of view and model references. Sure this has an advantage of showing explicit contract between the view and model via presenter, which is more readable.
However, wouldn't it be a cleaner approach to have presenter listen to events from views and events carry the view payload (eg: json representation). Same is the case with presenter talking back to the view. View will listen for events from presenter. Major advantage is, we don't have to write interfaces for each contract between view and presenter. If you look at the code you will see that presenter is getting exposed to view details like Text Fields, which i believe is increasing coupling between view and presenter. Say, if i'm replacing front end JavaFx instead of Vaadin, i will have to alter presenter as well.
This class is an example from a live project. Here we have different types of events ie i don't create event class for different cases. Eg: LoginViewEvent , DashBoardEvent etc which i believe is a maintenance pain.
public class UrayEvent {
public static enum EventType {
SESSION_SELECTED(1),
DOCUMENT_SELECTED(2),
DOCUMENT_EDIT_COMPLETE(3),
DOCUMENT_EDIT_CANCELED(4),
SHOW_SESSION_TABLES(5),
SHOW_SESSION_DOCUMENTS(6),
SHOW_SESSION_COLLABORATORS(7),
USER_REQUESTED_REFRESH(8),
AUTO_REFRESH(9),
TABLE_SELECTED(10),
DETACHED(11),
SCHEDULER_NAVIGATION(12),
JIRA_USER_SELECTED(13),
DOCUMENT_SAVE_SUCCESS(14),
DOCUMENT_SAVE_FAILURE(14);
private final int value;
private EventType(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
public static class Event {
private final EventType type;
private final Object payload;
public Event(EventType type, Object eventPayload) {
this.type = type;
this.payload = eventPayload;
}
public EventType getEventType() {
return type;
}
public Object getEventPayload() {
return payload;
}
}
}
Simple enough, the view send the event DOCUMENT_EDIT_COMPLETE .The presenter layer handles this event. I found this way, a better way to decouple views from presenter.
#Subscribe
public void handle(UrayEvent.Event event) {
switch (event.getEventType()) {
case DOCUMENT_EDIT_COMPLETE:
// event payload contains document model data
// like document id etc
saveDocument(event.getEventPayload);
break;
default:
break;
}
}
Advantage
Less boiler plate code, for n-views we don't need n-interfaces
New event means adding event element to enum and updating respective
subscribe methods handling this event.
Disadvantage
Memory leak if we forget to unregister from eventbus (faced it plenty of time)
Questions
1) This approach means, there would larger set enum elements as the application grow. Is this approach an anti pattern ?
2) As we saw it uses Event Bus extensively are there any drawbacks of
using bus system instead of interface-listener pattern ?
Wanted your valuable suggestion on this regard. The main issue is, if i blindly apply this pattern extensively across the project i shouldn't regret doing so, what would be a possible pitfall in this approach.
1) This approach means, there would larger set enum elements as the
application grow. Is this approach an anti pattern ?
If there are many events you need many event identifiers. They can be simple ints or enums or Interfaces.
The mechanism you demonstrated is simple and works well with small applications. It has been proven many times over with multiple frameworks. Take for example Microsoft's Win32 API and MFC.
In some projects I have seen the event interceptors implemented with Annotations which provides an elegant way for handling the events. The previous time was in a project utilizing the Apache Wicket framework.
2) As we saw it uses Event Bus extensively are there any drawbacks of
using bus system instead of interface-listener pattern ?
It is basically the same thing in a different package. In Java world it is de facto standard to use listener interfaces. Take for example Swing and Android.
The event bus approach is used in Facebook's Javascript based React framework. It is interesting to notice the similarity of Model-View-Presenter and Flux design patterns. Particularly the unidirectional data flow is highlighted in both architectures.
You mentioned the use case of replacing JavaFx with Vaadin as the UI framework. In my opinion, changing the UI framework so that you are able to reuse even some portions of it very rarely happens. I would not pay the price of added abstraction layers and complexity upfront just because the framework might change. Rather you should start with KISS and YAGNI principles. If you want to change the UI framework later, then you just implement the UI layer again from scratch.

Appropriate use of Event-Listener pattern

I appreciate this may not be a right/wrong type question, possibly more a stylistic thing but I often find myself pondering the use (overuse?) of custom Event and EventListener classes.
Frequently I have a class (often a GUI component) that needs to make other components aware of some change in it's state.
I could maintain a list of ChangeListeners (or some other already defined, general purpose listener type) and then call them on a state change, for example:
for (final ChangeListener cl : changeListeners)
cl.stateChanged(new ChangeEvent(this));
then retrieve the value in the listener:
class SomeListener implements ChangeListener {
#Override
public void stateChanged(ChangeEvent e) {
((MyClass) e.getSource()).getSomeStateProperty();
.
.
.
}
However the cast to MyClass strikes me as bad practice as the listener class is now making an explicit assumption about the contents of that ChangeEvent which has not been explicitly declared as the ChangeEvent constructor takes type Object.
So I frequently find myself creating pairs of custom Event and EventListener classes/interfaces i.e.
public interface SomeThingChangeListener extends EventListener {
/**
* Invoked when the target of the listener has changed some thing.
*
* #param e a SomeThingChangeEvent object
*/
void someThingChanged (SomeThingChangeEvent e);
}
With a corresponding Event class that contains a reference to the pertinent change information (probably a reference to an interface or abstract class in the event constructor).
The thing that bothers me about this however is the large proliferation of these small connector classes/interfaces for all 'things' that might 'happen' that may only ever have one concrete implementation.
So I guess the question is; is it best just to use general purpose events/listeners wherever you can or to always make class/event specific events and listeners?
The main reason that I seem to create quite a lot of these is that it often occurs to me that the association between two (or more) classes tends to be fairly weak, they are often not really related to each other in any way but one may be interested in information/state created/modified by another but not care about the details of the source. I find the observer or event/listener pattern a good way to keep coupling between unrelated classes to a minimum.
Any thoughts?
Thanks in advance,
Simon.
In my opinion defining specific types for each event, which makes up your domain model, is a good practice (one I do prefer / follow most of the times). Having as many event listeners as different event types may cause class pollution. On the other side, a generic listener approach leads to either determine the event type by sequences of instanceof or using the Visitor Pattern to dispatch events. The Visitor Pattern couples events to the listener. Perhaps a compromise between listeners capable of consuming more than one event (having change listener methods for related events) will reduce the number of different listeners by preserving event specific consuming, avoiding sequences of instanceof.
A proper solution depends on the concrete project and is always a tradeoff of many aspects.

Best practice - Declaring an event as part of a Java interface

I'm attempting to decouple some UI code using interfaces and events, and I would like to know if there is way/best practice in Java for declaring an event as part of a Java interface - something like what C# provides:
// C# event declaration in interface
public interface IAction
{
event EventHandler OnAction;
}
My goal is simply to mark an interface so that it is known it (implementors) fires events of a particular type. I'm hoping I can include more than documentation only to enforce that behaviour. I realize Java does not provide the "event" keyword or a direct way of doing this, so I'm hoping for some advice on a workaround or best practice on achieving this.
One way I can think of doing this is by creating a generic marker interface that represents the capability to fire events:
public interface FiresEvent<T extends Event> {
public void fireEvent();
}
... and then to inherit that interface in my custom interface.
public interface MyInterface extends FiresEvent<ActionEvent> {
}
The problem with this approach is that "FiresEvent" can only be inherited once, even if the generic type changes, so the solution does not seem generic enough for the case where an object may be the source of multiple events.
I'd be curious to know how people would handle this, and if there is a better way than to just document the need to fire events.
EDIT:
Maybe the following will clear up my question:
I understand the Java handler list approach and self-handling by allowing callers to register handlers against an object. In my case I am relying on an event bus, so we can view "firing" events as putting them out there, for something else to redirect to handlers.
I'd like to define the interface responsibility as:
The interface implementer fires an event of type T into the world/event bus/anything
The interface implementer does not have to delegate to registered listeners itself
Java handles events a bit differently than what you're used to, however the concept is the same. You create what's called an event listener, and it's called when the event happens. This can be a better construct as it allows for multiple listeners to be registered.
I suggest browsing this tutorial
The presence of a method
registerXListener(XListener listener)
in the interface indicates that a class will send out XEvents to those that care. That is, the 'marker' is just another method. The nearest analog of the C# idiom (I think) would be to lift that method into an interface, like
public interface XEventFirer
{
public void registerXListener(XListener listener)
}
This seems like a natural place to use annotations. I have come across EventBus which uses annotations to for publishing and subscribing to events. This approach is naturally self-documenting and depending on how it's implemented could make your code more readable and maybe allow you to enforce the annotation.

Organizing Actions in a Swing Application?

My current application has a JFrame with about 15 actions stored as fields within the JFrame. Each of the actions is an anonymous class and some of them are pretty long.
Is it common to break actions into their own classes possibly within a sub-package called actions?
If not, how's this complexity usually tamed?
Thanks
If it is possible that your actions could be reusable (e.g., from keyboard shortcuts, other menus, other dialogs, etc.) and especially if they can work directly on the underlying model (rather than on the UI), then it is generally better not to have them as anonymous classes.
Rather, create a separate package, and create classes for each.
Often, it also makes sense to not instantiate these directly but rather have some sort of a manager that defines constants and initializes and returns sets of actions, so that you could, for example, offer different action sets at different versions or set certain actions only for internal releases.
Finally, check whether your actions can be refactored into a class hierarchy. They often can, which saves code replication, and also helps you add robustness (e.g., check for certain conditions before letting the action execute).
That's typically how I do it. Each action gets it's own class which has a reference to the "app" object so it can get to resources it needs. I usually have an action manager that holds all the actions so there's one place to access them as well as one place to update their enablement and stuff.
Eventually this also becomes unmanageable at which point you should start thinking about using an app framework like Eclipse RCP, the NetBeans framework, JIDE, etc. This is especially true if you want to support user-defined keymaps and stuff like that.
What I do is create a package (package tree actually) for action classes, then instantiate each class according to context. Almost all of my action classes are abstract with abstract methods to get the context (ala Spring).
public abstract class CalcAndShowAction extends AbstractAction {
//initialization code - setup icons, label, key shortcuts but not context.
public void actionPerformed(ActionEvent e) {
//abstract method since it needs ui context
String data = getDataToCalc();
//the actual action - implemented in this class,
// along with any user interaction inherent to this action
String result = calc(data);
//abstract method since it needs ui context
putResultInUI(result);
}
//abstract methods, static helpers, etc...
}
//actual usage
//...
button.setAction(new CalcAndShowAction() {
String getDataToCalc() {
return textField.getText();
}
void putResultInUI(String result) {
textField.setText(result);
}
});
//...
(sorry for any mistakes, I've written it by hand in this text box, not in an IDE).

Categories

Resources