I'm searching for a simple Java implementation of Udi Dahan's
Domain Events pattern and infrastructure as detailed in this article.
It's pretty simple and I've implemented my own interpretation, however I'm a Java novice and don't want to be bitten by any mistakes due to inexperience with the language.
The only Java implementation I've found is in the Jdon Framework, but it's a little too heavyweight for my current in my project.
Thanks!
I have been looking for a solution to the same problem in Java EE for a while now. I looked at Axon and jdon (the page doesn't really bode well either :)). Both involve Event Sourcing which I could not "sell" to my employers/customers. I wanted to have Domain Events though since I very much got used to them in .NET/C# projects. So I came up with the following...
I used a similar static DomainEvents object to give me access to a publishing mechanism without the actual implementation details leaking all over my domain model entities. So the calls something like this:
DomainEvents.fire(new MySampleEvent(...some params...));
A pattern and mechanism that is available in CDI spec are the Events with #Observes that allow you to respond to certain events in normal beans with all the service available. That is similar to what I was used to when using DI frameworks like Castle Windsor where I could register generic handlers by interface. So I've got the observers (handlers, listeners, whatever you want to call them) covered. Example:
#Stateless
public class MySampleEventObserver {
public void listen(#Observes MySampleEvent event) {
...
doSomethingWithEvent();
}
}
Now for the publishing (firing in CDI) part. Since there is no way to access CDI in entities (with good reason!) I resolved to using JNDI and BeanManager. I used JNDI to get the BeanManager and use it's fireEvent method. To put bean manager resolving (as seen here) in code:
public class BeanHelper {
public static BeanManager getBeanManager() {
try {
InitialContext initialContext = new InitialContext();
return (BeanManager) initialContext.lookup("java:comp/BeanManager");
} catch (NamingException e) {
e.printStackTrace();
return null;
}
}
}
The final step is the DomainEvents object itself:
public class DomainEvents {
private static boolean mNopMode = false;
public static void setNopMode() {
mNopMode = true;
}
public static void reset() {
mNopMode = false;
}
public static <TDomainEvent> void fire(TDomainEvent event) {
if (mNopMode) {
return;
}
BeanManager manager = BeanHelper.getBeanManager();
manager.fireEvent(event);
}
}
The setNopMode and reset parts are there for testing purposes when there is no context. Manual mocking basically. Set it into NOP operation mode before unit tests and reset after them.
Works fine as a POC. Don't know if there are any serious limitations to it's use though. I leave async bus interactions and similar to the listeners implementation.
Would love any comments.
I'm currently looking at using Googles Guava EventBus to do something similar to the "Salvation" article you reference.
Using it similar to the "How to raise domain events" would look something like this, almost exactly the same as the article:
public class Customer
{
public void DoSomething()
{
MyEventBus.post(new CustomerBecamePreferred() { Customer = this });
}
}
I don't know whether or not you'd consider this as an "implementation of Udi Dahan's Domain Events pattern".
It doesn't require implementing any interfaces; event handlers are marked with annotations and the class is registered with the EventBus with MyEventBus.register(aListenerObject)
Related
Our application calls many external API's which take a session token of the current user as input. So what we currently do is in a controller, get the session token for the user and pass it into a service which in turn might call another service or some API client. To give an idea, we end up with something like this (example is .NET but something similar is I think possible in Java)
public IActionResult DoSomething(string something)
{
this.someService.DoSomethingForUser(this.HttpContext.SessionToken, something);
return View();
}
And then we have
public class SomeService
{
private readonly IApiClient apiClient;
public SomeService(IApiClient apiClient)
{
this.apiClient = apiClient;
}
public void DoSomethingForUser(string sessionToken, something)
{
this.apiClient.DoSomethingForUser(sessionToken, something);
}
}
It can also happen that in SomeService another service is injected which in turn calls the IApiClient instead of SomeService calling IApiClient directly, basically adding another "layer".
We had a discussion with the team if it isn't better to instead of passing the session token, inject it using DI so you get something like this:
public IActionResult DoSomething(string something)
{
this.someService.DoSomethingForUser(something);
return View();
}
And then we have
public class SomeService
{
private readonly IUserService userService;
private readonly IApiClient apiClient;
public SomeService(IUserService userService, IApiClient apiClient)
{
this.userService = userService;
this.apiClient = apiClient;
}
public void DoSomethingForUser(string something)
{
this.apiClient.DoSomethingForUser(userService.SessionToken, something);
}
}
The IUserService would have an IHttpContextAccessor injected:
public class UserService : IUserService
{
private readonly IHttpContextAccessor httpContextAccessor;
public UserService(IHttpContextAccessor httpContextAccessor)
{
this.httpContextAccessor = httpContextAccessor;
}
public string SessionToken => httpContextAccessor.HttpContext.SessionToken;
}
The benefits of this pattern are I think pretty clear. Especially with many services, it keeps the code "cleaner" and you end up with less boilerplate code to pass a token around.
Still, I don't like it. To me the downsides of this pattern are more important than its benefit:
I like that passing the token in the methods is concise. It is clear that the service needs some sort of authentication token for it to function. I'm not sure if you can call it a side effect but the fact that a session token is magically injected three layers deep is impossible to tell just by reading the code
Unit testing is a bit more tedious if you have to Mock the IUserService
You run into problems when calling this in another thread, e.g. calling SomeService from another thread. Although these problems can be mitigated by injecting another concrete type of IUserService which gets the token from some place else, it feels like a chore.
To me it strongly feels like an anti pattern but apart from the arguments above it is mostly a feeling. There was a lot of discussion and not everybody was convinced that it was a bad idea. Therefor, my question is, is it an anti pattern or is it perfectly valid? What are some strong arguments for and against it, hopefully so there can be not much debate that this pattern is indeed, either perfectly valid or something to avoid.
I would say the main point is to enable your desired separation of concerns. I think it is a good question if expressed in those terms. As Kit says, different people may prefer different solutions.
REQUEST SCOPED OBJECTS
These occur quite naturally in APIs. Consider the following example, where a UI calls an Orders API, then the Orders API forwards the JWT to an upstream Billing API. A unique Request ID is also sent, in case the flow experiences a temporary problem. If the flow is retried, the Request ID can be used by APIs to prevent data duplication. Yet business logic should not need to know about either the Request ID or the JWT.
BUSINESS LOGIC CLASS DESIGN
I would start by designing my logic classes with my desired inputs, then work out the DI later. In my example the OrderService class might use claims to get the user identity and also for authorization. But I would not want it to know about HTTP level concerns:
public class OrderService
{
private readonly IBillingApiClient billingClient;
public OrderService(IBillingApiClient billingClient, ClaimsPrincipal user)
{
this.billingClient = billingClient;
}
public async void CreateOrder(OrderInput data)
{
this.Authorize();
var order = this.CreateOrder(data);
await this.billingClient.CreateInvoice(order);
}
}
DI SETUP
To enable my preferred business logic, I would write a little DI plumbing, so that I could inject request scoped dependencies in my preferred way. First, when the app starts, I would create a small middleware class. This will run early in the HTTP request pipeline:
private void ConfigureApiMiddleware(IApplicationBuilder api)
{
api.UseMiddleware<ClientContextMiddleware>();
}
In the middleware class I would then create a ClientContext object from runtime data. The OrderService class will run later, after next() is called:
public class ClientContextMiddleware
{
public async Task Invoke(HttpContext context)
{
var jwt = readJwt(context.Request);
var requestId = readRequestId(context.Request);
var holder = context.RequestServices.GetService<ClientContextHolder>();
holder.ClientContext = new ClientContext(jwt, requestIO);
await this.next(context);
}
}
In my DI composition at application startup I would express that the API client should be created when it is first referenced. In the HTTP request pipeline, the OrderService request scoped object will be constructed after the middleware has run. The below lambda will then be invoked:
private void RegisterDependencies(IServiceCollection services)
{
this.services.AddScoped<IApiClient>(
ctx =>
{
var holder = ctx.GetService<ClientContextHolder>();
return new ApiClient(holder.context);
});
this.services.AddScoped<ClientContextHolder>();
}
The holder object is just due to a technology limitation. The MS stack does not allow you to create new request scoped injectable objects at runtime, so you have to update an existing one. In a previous .NET tech stack, the concept of child container per request was made available to developers, so the holder object was not needed.
ASYNC AWAIT
Request scoped objects are stored against the HTTP request object, which is the correct behaviour when using async await. The current thread ID may switch, eg from 4 to 6 after the call to the Billing API.
If the OrderService class has a transient scope, it could get recreated when the flow resumes on thread 6. If this is the case, then resolution will continue to work.
SUMMARY
Designing inputs first, then writing some support code if needed is a good approach I think, and it is also useful to know the DI techniques. Personally I think natural request scoped objects that need to be created at runtime should be usable in DI. Some people may prefer a different approach though.
See in dotnet the area that I am an expert is not an anti standard on the contrary it is the model that many adopt but it is not a model that I would follow for the following reasons
it is not clear where is the token for those who read and use it being an anti clean code
you load important information in a place that is frequently accessed by the framework in the case of .netCore
your classes will reference a large property carrying a lot of unnecessary information when you could have created a more clean model that costs less memory and allocation time, I'm saying this because the HttpAcessor carries all the information relevant to your request
As I would take care of readability (clean code) and improve my performance
I would make a middleware or filter in my flow mvc where I would do the authentication part and create a class like:
public class TokenAuthenciationValues
{
public string TokenClient { get; set; }
public string TokenValue { get; set; }
}
Of course my method is an example but in my middleware I would implement it by loading its token values after calling the necessary apis (of course this model needs an interface and it needs to be configured as .AddScoped() in the case of .net)
That way I would use it in my methods only instantiating my ITokenAuthenciationValues in the constructor and I would have clear and clean information loaded in memory during the entire request
If it is necessary in the middle of the request to change the token any class can access it and change its value
I would have less memory allocated unused in my classes since the IHttpAcessor contract the ITokenAuthenciationValues only has relevant information
Hope this helps
I'm currently working on a project that involves creating an abstraction layer. The goal of the project is to support multiple implementations of server software in the event that I might need to switch over to it. The list of features to be abstracted is rather long, so I'm going to want to look into a rather painless way to do it.
Other applications will be able to interact with my project and make calls that will eventually boil down to being passed to the server I'm using.
Herein lies the problem. I haven't much experience in this area and I'm really not sure how to make this not become a sandwich of death. Here's a chain of roughly what it's supposed to look like (and what I'm trying to accomplish).
/*
Software that is dependent on mine
|
Public API layer (called by other software)
|
Abstraction between API and my own internal code (this is the issue)
|
Internal code (this gets replaced per-implementation, as in, each implementation needs its own layer of this, so it's a different package of entirely different classes for each implementation)
|
The software I'm actually using to write this (which is called by the internal code)
*/
The abstraction layer (the one in the very middle, obviously) is what I'm struggling to put together.
Now, I'm only stuck on one silly aspect. How can I possibly make the abstraction layer something that isn't a series of
public void someMethod() {
if(Implementation.getCurrentImplementation() == Implementation.TYPE1) {
// whatever we need to do for this specific implementation
else {
throw new NotImplementedException();
}
}
(forgive the pseudo-code; also, imagine the same situation but for a switch/case since that's probably better than a chain of if's for each method) for each and every method in each and every abstraction-level class.
This seems very elementary but I can't come up with a logical solution to address this. If I haven't explained my point clearly, please explain with what I need to elaborate on. Maybe I'm thinking about this whole thing wrong?
Why not using inversion of control ?
You have your set of abstractions, you create several implementations, and then you configure your public api to use one of the implementations.
Your API is protected by the set of interfaces that the implementations inherit. You can add new implementations later without modifying the API code, and you can switch even at runtime.
I don't know anymore if inversion of control IS dependency injection, or if DI is a form of Ioc but... it's just that you remove the responsibility of dependency management from your component.
Here, you are going to have
API layer (interface that the client uses)
implementations (infinite)
wrapper (that does the IoC by bringing the impl)
API layer:
// my-api.jar
public interface MyAPI {
String doSomething();
}
public interface MyAPIFactory {
MyAPI getImplementationOfMyAPI();
}
implementations:
// red-my-api.jar
public class RedMyAPI implements MyAPI {
public String doSomething() {
return "red";
}
}
// green-my-api.jar
public class GreenMyAPI implements MyAPI {
public String doSomething() {
return "green";
}
}
// black-my-api.jar
public class BlackMyAPI implements MyAPI {
public String doSomething() {
return "black";
}
}
Some wrapper provide a way to configure the right implementation. Here, you can hide your switch case in the factory, or load the impl from a config.
// wrapper-my-api.jar
public class NotFunnyMyAPIFactory implements MyAPIFactory {
private Config config;
public MyAPI getImplementationOfMyAPI() {
if (config.implType == GREEN) {
return new GreenMyAPI();
} else if (config.implType == BLACK) {
return new BlackMyAPI();
} else if (config.implType == RED) {
return new RedMyAPI();
} else {
// throw...
}
}
}
public class ReflectionMyAPIFactory implements MyAPIFactory {
private Properties prop;
public MyAPI getImplementationOfMyAPI() {
return (MyAPI) Class.forName(prop.get('myApi.implementation.className'))
}
}
// other possible strategies
The factory allows to use several strategies to load the class. Depending on the solution, you only have to add a new dependency and change a configuration (and reload the app... or not) to change the implementation.
You might want to test the performances as well.
If you use Spring, you can only use the interface in your code, and you inject the right implementation from a configuration class (Spring is a DI container). But no need to use Spring, you can do that on the Main entry point directly (you inject from the nearest of your entry point).
The my-api.jar does not have dependencies (or maybe some towards the internal layers).
All the jar for implementations depend on my-api.jar and on you internal code.
The wrapper jar depends on my-api.jar and on some of the impl jar.
So the client load the jar he wants, use the factory he wants or a configuration that inject the impl, and use your code. It depends also on how you expose your api.
After reading an interesting article, I have a few questions around this. Please refer to Common Pitfall #8: Pretending Java is more like C (i.e. not understanding OOP) on [zero-turn-around]
I agree to the authors solution for the pitfall. I face a similar issue with my code (abuse of instanceof). But I cannot implement the code as the author has suggested. My scenario is as below
I have JMS as a messaging bus.
Messages float around the system. Listener typically listen to the messages.
All the messages have a single parent IMessage.
I use instanceof to distinguish between messages.
The listeners typically do domain specific business logic.
If I agree with the authors solution, I will have to implement domain specific business logic in the Message classes, which I think will bloat my light-weight message objects. Not just that, I will now have many references (composition) in my message objects which I think is unfair as the message objects will now have business (domain) behavior in it.
What is the reasonable solution to this problem? Example code below
public void onMessage(IMessage mssg)
{
if(mssg instanceof MoPn){
...
} else if(mssg instance of MoZn){
...
} else if(mssg instance of MoLn){
...
}
}
One reasonable solution is creating listeners that know to work with specific type of message.
Here is the interface.
interface MessageListener<M extends IMessage> {
void onMessage(M message);
}
Here is a skeleton of one of the classes:
class MoZnListener implements MessageListener<MoZn> {
public void onMessage(MoZn message) {
}
}
Now you can create mapping between messages and listeners. You can use properties file, hard coded map, annotations. It is up to you. Once you have it you can implement one JMS message listener that looks like
class MessageEntryPoint implements MessageListener {
public void onMessage(Message message) {
getMessageHandler(message).onMessage(message.getObject());
}
}
Now your system is extandable. No instanceof. To introduce new message type you just have to create appropriate class that implements IMessage and listener that supports it.
BTW more comments.
Using I as to mark interface is not java-style.
I am not familiar with your domain and probably name like MoPn is self-explainable for you, but IMHO it is not. Try to use more self explainable identifiers.
This might upset some purists, but I believe that using a language with OO features doesn't necessarily mean you have to apply OO to everything.
Messages are simply schema. They carry data. Forcing object-orientation upon structures that merely carry data from one place to another can be an anti-pattern as well.
Separating the logic from the data model is sometimes seen as being against OOP but is sometimes necessary for decoupling. The code sending the message doesn't need to know anything about how to respond to the message.
Some of the other problems with instanceof are that it's hard to find what needs updating when adding a new type, and there's no way to make sure all cases are covered. These problems can be solved by adding some new interfaces:
interface Message {
void callHandler(MessageHandler handler);
}
interface MessageHandler {
default void onMoPn(MoPn message) {
}
default void onMoZn(MoZn message) {
}
}
class MoPn implements Message {
public void callHandler(MessageHandler handler) {
handler.onMoPn(this);
}
}
class Mozn implements Message {
public void callHandler(MessageHandler handler) {
handler.onMoZn(this);
}
}
and add a handler:
class MessageHandlerImpl implements MessageHandler {
public void onMoPn(MoPn message) {
System.out.println("MoPn message: " + message);
}
}
When you get a message, you can call the handler like:
MessageHandler handler = new MessageHandlerImpl()
Message message = new MoPn();
message.callHandler(handler);
I recently stumbled upon this interesting concept that may save me much testing efforts.
What I do not understand is how can the provider be injected in runtime?
The scenario is trivial: I am constructing a mock object at run-time with my mocking framework of choice, but I do not know the name of the generated class in advance because it is a mock (so I can't configure it in advance, not do I want to).
Did anybody make successful use of this technique in unit tests?
Thank you.
The concept described in that article is an Ambient Context that uses a Service Locator in the background.
Because of the use of a static property and the use of the Service Locator, this pattern is very inconvenient for unit testing. To be able to run a test that verifies code that uses this singleton, you need to set up a valid Service Locator and configure it with the singleton (probably a mock instance) that you care about using testing.
Even the example given by the article already suffers from these problems, since the "Do you like singletons?" code, is hard to test:
if (DialogDisplayer.getDefault().yesOrNo(
"Do you like singletons?"
)) {
System.err.println("OK, thank you!");
} else {
System.err.println(
"Visit http://singletons.apidesign.org to"
+ " change your mind!"
);
}
A better alternative is to use constructor injection to inject that singleton (please excuse my French, but I'm not a native Java speaker):
public class AskTheUserController
{
private DialogDisplayer dialogDisplayer;
private MessageDisplayer messageDisplayer;
public AskTheUserController(DialogDisplayer dialogDisplayer,
MessageDisplayer messageDisplayer)
{
this.dialogDisplayer = dialogDisplayer;
this.messageDisplayer = messageDisplayer;
}
public void AskTheUser()
{
if (this.dialogDisplayer.yesOrNo(
"Do you like singletons?"
)) {
this.messageDisplayer.display("OK, thank you!");
} else {
this.messageDisplayer.display(
"Visit http://singletons.apidesign.org to"
+ " change your mind!"
);
}
}
}
There was another 'hidden' dependency in that code: System.err.println. It got abstracted using a MessageDisplayer interface. This code has a few clear advantages:
By injecting both dependencies, the consumer doesn't even need to know that those dependencies are singletons.
The code clearly communicates the dependencies it takes.
The code can easily be tested using mock objects.
The test code doesn't need to configure a service locator.
Your tests might look like this:
#Test
public void AskTheUser_WhenUserSaysYes_WeThankHim()
{
// Arrange
bool answer = true;
MockMessageDisplayer message = new MockMessageDisplayer();
MockDialogDisplayer dialog = new MockDialogDisplayer(answer);
AskTheUserController controller =
new AskTheUserController(dialog, message);
// Act
controller.AskTheUser();
// Assert
Assert.AreEqual("OK, thank you!", message.displayedMessage);
}
#Test
public void AskTheUser_WhenUserSaysNo_WeLetHimChangeHisMind()
{
// Arrange
bool answer = true;
MockMessageDisplayer message = new MockMessageDisplayer();
MockDialogDisplayer dialog = new MockDialogDisplayer(answer);
AskTheUserController controller =
new AskTheUserController(dialog, message);
// Act
controller.AskTheUser();
// Assert
Assert.IsTrue(
message.displayedMessage.contains("change your mind"));
}
Your test code will never be as intend revealing as the code above when you're using the 'injectable singleton' pattern as shown in the article.
There is nothing wrong with singletons, which are useful and necessary concepts in any software. The problem is that you shouldn't implement them with static fields and methods.
I use Guice to inject my singletons and I haven't had to use static in my code base and tests in a very long time.
Here are a couple of links you might find useful that explain how to achieve testable singletons with Guice:
Rehabilitating the Singleton pattern.
Guice and TestNG
I refer to "service provider framework" as discussed in Chapter 2 of Effective Java, which seems like exactly the right way to handle a problem I am having, where I need to instantiate one of several classes at runtime, based on a String to select which service, and an Configuration object (essentially an XML snippet):
But how do I get the individual service providers (e.g. a bunch of default providers + some custom providers) to register themselves?
interface FooAlgorithm
{
/* methods particular to this class of algorithms */
}
interface FooAlgorithmProvider
{
public FooAlgorithm getAlgorithm(Configuration c);
}
class FooAlgorithmRegistry
{
private FooAlgorithmRegistry() {}
static private final Map<String, FooAlgorithmProvider> directory =
new HashMap<String, FooAlgorithmProvider>();
static public FooAlgorithmProvider getProvider(String name)
{
return directory.get(serviceName);
}
static public boolean registerProvider(String name,
FooAlgorithmProvider provider)
{
if (directory.containsKey(name))
return false;
directory.put(name, provider);
return true;
}
}
e.g. if I write custom classes MyFooAlgorithm and MyFooAlgorithmProvider to implement FooAlgorithm, and I distribute them in a jar, is there any way to get registerProvider to be called automatically, or will my client programs that use the algorithm have to explicitly call FooAlgorithmRegistry.registerProvider() for each class they want to use?
I think you need to create a META-INF/services/fully.qualified.ClassName and list things there, but I don't remember the spec (JAR File Specification or this).
The Practical API design confessions of a Java architect book chapter 8 is about SPI.
The ServiceLoader might help you to list available implementations. For example with the PersistenceProvider interface:
ServiceLoader<PersistenceProvider> loader =
ServiceLoader.load(PersistenceProvider.class);
Iterator<PersistenceProvider> implementations = loader.iterator();
while(implementations.hasNext()) {
PersistenceProvider implementation = implementations.next();
logger.info("PersistenceProvider implementation: " + implementation);
}
You could have the client JAR register the providers in a static initializer block within some class that you know will be called before FooAlgorithmRegistry.getProvider(), something like:
static {
FooAlgorithmRegistry.registerProvider("test", new MyFooAlgorithmProvider());
}
But, it might be pretty hard to find a way to guarantee that this will run (static initializers are guaranteed to be run once and only once, when the class is first loaded) before the accessor method of the factory.