how to implement state pattern using ddd - java

I have a question about the state pattern and how to implement it using DDD.
For what I understand of the state pattern, the pattern is used to handle the transition between different states, so its the responsibility of each state to handle what the system has to do to transit to the new state.
To do so, using polymorphism, each state can be a class of its own that extends one base class, implementing the transitions from one state to the other, following a graph that defines the possible transitions.
I've been looking for information on how to do this using DDD and, among other web sites, I found this one that uses enums.
http://nurkiewicz.blogspot.co.uk/2009/09/state-pattern-introducing-domain-driven.html
The reason for using enums is that you can persist the current state, in this case the name of the enum, to a repository, so your aggregate can be recreated later. So, following the state pattern definition, the state can receive different parameters (for example, the new value of a field) so the context (in this case the aggregate) can transit to the new state and update its fields so the state is consistent. This means, the state would be the one responsible to update the values of the aggregate.
My question is, is this the right thing to do? For what I understand, in DDD the aggregate is the one that knows about its internals and, whenever an entity inside the aggregate has to be changed, the aggregate has to expose a method which later on would call the entity to change its value. This way the entities are encapsulated inside the aggregate and they cannot be accessed directly from outside it.
But using this implementation of the state pattern it's the entity (or value object, I don't know how to call the state) who changes the aggregate. You can even use the enum directly and call an operation inside it passing your aggregate and the aggregate would be changed.
Another question about this is; the moment you have to provide some behaviour to your aggregate that depends on the current state, where do you do the implementation? Inside the aggregate, adding more operations to the base class of the state to check if the state is one or the other? Or inside the state, so the state uses the aggregate to call the different methods that it exposes to provide that functionality? The first approach would mean that, depending on the number of states you have, you would have create many methods just to check if you are in the correct state for your purposes. The other one would imply that is again the state who coordinates the way the aggregate has to call its internals.
Sorry if this question has being asked before. I've looking for days and I couldn't find something similar to what I'm asking here.
Thanks in advance.
EDIT:
Sorry for the late response, I was on holidays.
In my case the states are rather simple. They would reflect the different states of a tournament (NEW, OPEN_REGISTRATION, CLOSED_REGISTRATION, IN_PROGRESS, FINISHED, CANCELLED). What I'm trying to do is a probe of concept following the approach from the link I provided.
My question here is: the moment the aggregate (context) has to do something that depends on the state (like register a player), where would you hold that logic? Inside the context, checking first if the state class is of type OpenRegistrationState? Or inside the state classes, providing an implementation inside the OpenRegistrationState that stores the player into the context (the method would expect both the context and the player as parameters) and throwing and exception from the other ones?
It seems like using the second approach, the logic inside the context is quite simple, it only has to call the current state to do the job for it. The problem is, the moment you have many different methods that relies on the state to operate, your state classes would have an explosion of different methods that only one or two of them would implement while the other ones would throw an exception. In that case, I don't know if it would be easier to forget about the state pattern and just use an enum and check the value whenever some logic depends on the current state.

The state pattern's context says that an object's behavior is dependent on its state, and its methods contain if/then (or case) logic reflecting conditions based on states. The pattern provides an alternative to those case statements.
The solution is to create classes for each state, implementing a common interface. State-dependent operations are delegated from the context object to its current state object. The context object points to a state object that reflects its current state.
So, if I understand your question, then Domain objects (à la DDD) are the context objects and you want to avoid case logic in them. Otherwise, you don't need the state pattern (and you can stop reading now if you want, since the rest doesn't apply).
Craig Larman's Applying UML and Patterns 3rd Edition book has a chapter on Designing a Persistence Framework with Patterns and a section on Transactional States and the State Pattern. I believe his approach is compatible with DDD as it has been defined here. Actually, it's a variant of the PersistentObject idea from Scott Ambler
Domain classes have state. In this example, the states are about persistence: New, OldClean, OldDirty, OldDelete and Deleted. See Larman's book for the details.
A couple of details I couldn't easily annotate on the PlantUML image above:
the PObjectState abstract class has default no-op bodies for each method (transition)
the implementations, e.g., OldDirtyState.commit(...) handle the implementation of the behavior based on state. For persistence, this makes sense since they are generally behaviors that aren't related to domain logic. A rollback of a persistent object is basically the same.
Larman has a footnote stating "Whenever a domain object class extends a technical services class, it should be pause for reflection, as it mixes architectural concerns (persistence and application logic)."
You didn't use a concrete example of what exactly the State is that you want to model, so I am not sure whether this example applies appropriately.
If your State is some cross-cutting concern that introduces unwanted coupling in your domain objects, then you have to ask yourself the question which is worse: Case logic in the Domain objects, or unwanted coupling. Designs are trade-offs and you have to pick your battles.

Related

Confusion between Inversion of Control and Hollywood Principle

I am reading Head First Design pattern and just stuck on the Hollywood Principle. Earlier I read about Inversion of Control and what I understood was, it's a design principle (some also call it pattern) through which conventional flow of program changes from "Higher level module calling Lower level module" to "Lower level module calling Higher level module" (generally through abstractions), so we can have very low dependency on specific low-level module and changing low-level modules does not have any impact on our higher level or near to business modules.
But I got confused when the author said the following line regarding the Hollywood principle:-
On page 296
With the Hollywood Principle, we allow low-level components
to hook themselves into a system, but the high-level
components determine when they are needed, and how. In
other words, the high-level components give the low-level
components a “don’t call us, we’ll call you” treatment.
In the last line, it is said that The high-level components give the low-level
components a “don’t call us, we’ll call you” treatment. This means our high-level components are actually calling low-level components and hence
this seems to break the Inversion of control principle and also Dependency Inversion principle.
Please clarify on this.
The seeming contradiction is cleared up if we focus on a different part of the Dependency Inversion Principle:
A. High level modules should not depend on low level modules. Both should depend upon abstractions.
B. Abstractions should not depend upon details. Details should depend upon abstractions.
That adds some context that clears up the potential confusion created by this statement:
The high-level components give the low-level components a “don’t call us, we’ll call you” treatment.
The high-level components don't directly deal with the low-level components at all. They deal with abstractions that represent the purpose or function of the low-level components.
So it doesn't "break" the Dependency Inversion Principle. Rather, it just needs to be understood in harmony with that principle. They are two different principles, so we could apply one and break the other. But if components communicate with each other as represented by abstractions then we can apply both.
They could have added that clarification into the sentence in question, but it would have made it wordier and more confusing.
FWIW I often find the terms "high level" and "low level" confusing because we don't tend to use them except when discussing the Dependency Inversion Principle. Whether a component is "high level" or "low level" the recommendation is to depend on abstractions. In other words, depend on abstractions. We can apply the principle without classifying components as high level or low level.
When we design software we implement two things API and Framework.
An API publish some endpoint so that caller uses those endpoints to get some useful information, so the caller doesn't have any action point to take, only endpoints and outputs.
The framework takes the strategy or business implementation from the caller and calls it when required.
In Hollywood Principle, we can feed our strategy or business implementation, denoting the framework implementation, which calls the fed strategy when required.
Inversion of control and Dependency Injection is to remove dependencies of an application. This makes the system more decoupled and maintainable.
If you go back to old computer programming days, program flow used to run in its own control.
if you analyze the program flow closely, it’s sequential. The program is in control of himself. Inversion of the control means the program delegates control to someone else who will drive the flow.
class Customer {
public function getCustomers() {
$conn = new MySQLConnection();
return $conn->getCustomers();
}
public function iocCustomers(MySQLConnection $conn) {
return $conn->getCustomers();
}
}
In the case of getCustomers(), we are creating the Database object inside Customer classes function - deeply coupled. Whenever the Customer object is created, the MySQLConnection object also will be created, which is not required.
If you consider the iocCustomers(), when we call the function we are passing the Database object as well. Here the Customer class is not concerned about the database till it need the data, it will use it when it required. Like, you no need to be in Hollywood to get a chance, when you needed they will call you, like, MySQLConnection object is injected to the function where it required by the class Customer.
Here two things are happening.
Customer class no need to worry/know about who provides the data. In other words, the client/calling class Customer doesn't have control over the data. [SRP in SOLID principles]
The connection object gets the control over the data and it can decide from which database(MySQL or SQLite) it need to provide data. If we create the object MySQLConnection in the getCustomers(), it will not get the flexibility to switch. This is called Inversion of Control. Taking the control from the caller to the class who generates the data.
Note: In the case of second function there are some advantages.
We can pass an interface called DBConnectionContract to iocCustomers() instead of MySQLConnection. So that we can pass any database object(MySQL, Sqlite, Postgres) which implements DBConnectionContract interface. This will help us to switch the database to one another with minimum modifications.
Modifications can be like below:
interface DBConnectionContract {}
class MySQLConnection implements DBConnectionContract {}
class SQLiteConnection implements DBConnectionContract {}
class Customer {
public function iocCustomers(DBConnectionContract $conn) {}
}
Another advantage is related to Unit testing. To the iocCustomers() we can pass mock database object while unit testing. Because to do the unit test of a function we need to make the environment needed for that function to execute.
The Hollywood Principle is not at odds with the Inversion of Control, although it can be programmed ignoring it.
In the book the Coffee example (I guess one page later, I have another edition) sub-classes two methods that get called via the Hollywood Principle. If the sub-classes just overwrites some abstract methods from the base class it does not really uses the Inversion of Control.
However since the called sub-class can adjust members of the base class it can take control that way. In the Q and A in my book one page earlier it explains a bit in the question: What are hooks really supposed to be used for. I will try to explain.
Say if you have a base class with an unsorted list and a call to print() the list. If you have a sub-class which via a hook can be called to overwrite print() that sub-class might decide to first sort the actual list of the base class and than call other functions if needed. In this way the low level function can take over control from the high level function.
IoC is sometimes referred to as the Hollywood Principle. They are the same... but, like all idiomatic expressions, it is always subject to semantics. The principle of controlling low-level dependencies from higher level abstractions is not "a pattern", it is a principle. It is also not exemplified well by associating that principle solely with sub-classing, though there it does most naturally exist.
More commonly it is accomplished through composition/aggregation by holding a reference to some Interface or abstract type in a low-level object and injecting dependencies into that class. It has no control or responsibility for what it receives, it only knows how to process it.
In other words, it (low-level) must wait by the phone, rather than call for its next screening, audition? what ever they call that in Hollywood.

Java Entity class Using Component and State Design Pattern

I'm trying to create a Entity for a game that uses both the Component and State design patterns. Let me explain.
The Components that make up an Entity will consist of an InputComponent, PhysicsComponent, and a GraphicsComponent (for now). Each Component will their own class to keep the clean nice and decoupled. This way you can implement your own components like for example a PlayerInputComponent to represent player input, and then create an Entity like this -> Entity player = new Entity(input, physics, graphics).
This system alone works really well for decoupling the code that makes up an Entity. It makes the Entity class flexible enough to accept all different types of components allowing for many variations. However, as stated in the question, I also want to use a State design pattern and I can't think of a way to make them coexist nicely.
The State design pattern is going to be used to represent a finite set of states that an Entity can be in. For example, there would be a RunningState, IdleState, JumpingState, etc... These states would be able to process input and update, deciding when to change states, and what state to change to. For example, if the movement keys are pressed in the IdleState, the IdleState would process this and decide to switch to a RunningState. This makes keeping track of animations easy and separates out the logic for changing states into their own class avoiding complex logic statements.
My question is how can I mix both of these patterns so they work well together? I need all Components to be able to access these States because state transitions may occur in the InputComponent or the PhysicsComponent (for right now), and the states also have to be accessible in the GraphicsComponent so I can draw the right frame for the current animation.
What's the best way to setup my Entity class so it can implement both patterns and have them interact with each other without creating a mess in the Entity class. Thanks!

Proxy & Memento Patterns

Proxy - what code (and where) translates ProxyService into RealService calls? Why/when use this?
Layers - how to implement?
Memento - why not just persist state to a cache or file?
My understanding of the Proxy pattern is that you have some kind of Service interface that has ProxyService and RealService concretions. For some reason, you can't access the RealService, so you code against a ProxyService instance and then let the framework link the proxy to the real instance of your service. Only two problems:
I can't think of a single example when I would have access to Service and ProxyService, but not RealService - can someone provide examples as to when this could happen?
How is this different from the Memento pattern? My understanding of Memento's definition is that it is used for saving an object state, which is what a Proxy is really doing, yes? If not please explain how Memento is different than Proxy! Thanks in advance!
First off, I'll caveat my answer by saying that I don't believe there are any hard and fast rules about patterns - you take what you need from them and nothing more. The way that I use certain patterns is undoubtedly different from how another developer might choose to use them. That said, here's my take on your question.
Proxy Pattern Explained
The way I know the Proxy design pattern, you use it to do two things:
Restrict access to otherwise public methods of a particular object instance
Prevent otherwise-expensive, and unnecessary instantiation costs, by instantiating the concrete object on the first call to the proxy, then passing all further calls on the proxy through to the concrete instance your proxy created.
Maybe RealService has a method doSomethingReallyDangerous() that you want to hide. Or even more innocuous, maybe RealService has several hundred methods that you don't need to see every time you type the . after a RealService instance's variable name. You'd use a proxy for any of this.
For further reading, this article has a lot of good information:
http://sourcemaking.com/design_patterns/proxy
Differences with Memento Pattern
The Memento pattern allows you to roll back an object to its original state, or some previous state, by storing intermediate states alongside the concrete object. Sort of like an "undo" for programming. You'd probably use a Proxy pattern to implement Memento, but Proxy doesn't guarantee saving of object state or rollback - it just lets you refer to the same object for method calls if instantiating that object over again is prohibitively expensive.
So hopefully that helps - I like to think of Memento as a more full-featured version of Proxy, but not all Proxy implementations are Mementos.
Proxy is when someone is expecting a certain object, and you lie to him, and you say: Yes, here you have your object, but you are actually giving him something else...
Common uses for proxy:
To implement Lazy initialization: You are asked for an object representing the contents of a big file, or something which is very expensive to acquire, and you know that it's not needed at this right moment, or it might in fact never be used really. So you pass a proxy, that will only acquire the resource when it's 100% completely necessary (You can also start acquiring the resource anachronistically, and make the process using the proxy only start waiting when it really needs it). This is pretty common in ORMs. Also futures and promises implement something like this
To intercept calls:
You can pass a proxy which actually knows the real object, and intercept the calls that it gets, and do something interesting like logging them, changing some of them, etc...
There are also a lot of advanced and complex usages of the proxy, given that you often have the ability to determine the behavior at runtime. sorry for going out of Java, but in C#, Castle Proxy is used to implement mock objects for testing. You can also implement with a proxy things like chaining in underscore. And you can simulate a lot of "dynamic languages" features in static languages using proxies. You can also evaluate a piece of code with a proxy that actually logs every call that is made, and returns new proxies every time, to reconstruct the "original source code" by just executing it.
Memento pattern: is another thing completely. You use it when you want to work with an object, save it current state, counting doing thins with that object, and after a while you might want to choose to rollback to the previous state. You can use it to implement transactional behavior in your objects, when undoing the things by code is difficult. You can implement undo & redo functionality with this. (Instead of saving the change-delta, you save the full state). You can use it in simulations to start every time from the same point (You could say that a Source Version Server uses memento every once in a while [they generally use a combination of memento + delta changes]). A snapshot of a virtual machine or an hibernate of a computer is also a use of the memento pattern. And saving the state of something, so you can reproduce the exact same situation is also memento.

How to perform different operations within Observer's update() in Java?

I just started playing with Observable, Observer and it's update() method and I can't understand what should I do when different actions call notifyObservers().
I mean, my Observable class has a few different methods that call setChanged() and notifyObservers() in the end. Depending on the called method, some part of the UI (Swing) needs to be updated. However, there is only one update() method implemented in the Observer class.
I though of passing something to the notifyObservers() method and then I can check the argument on update() but it doesn't feel like a good way to do it. Even if it did, what should I pass? A string with a short description of the action/method? An int, like an action/method code? Something else?
What's the best way to handle this situation?
in general you should update everything from the observable when you get a call to update(). if that is not practical, you can pass a hint to notifyObservers().
the gang-of-book says that one of the consequences of the observer pattern is:
"Unexpected updates. Because observers have no knowledge of each other's presence, they can be blind to the ultimate cost of changing the subject. A seemingly innocuous operation on the subject may cause a cascade of updates to observers and their dependent objects. Moreover, dependency criteria that aren't well-defined or maintained usually lead to spurious updates, which can be hard to track down.
This problem is aggravated by the fact that the simple update protocol provides no details on what changed in the subject. Without additional protocol to help observers discover what changed, they may be forced to work hard to deduce the changes.
"
also under implementation, they say:
"Avoiding observer-specific update protocols: the push and pull models. Implementations of the Observer pattern often have the subject broadcast additional information about the change. The subject passes this information as an argument to Update. The amount of information may vary widely.
At one extreme, which we call the push model, the subject sends observers detailed information about the change, whether they want it or not. At the other extreme is the pull model; the subject sends nothing but the most minimal notification, and observers ask for details explicitly thereafter.
The pull model emphasizes the subject's ignorance of its observers, whereas the push model assumes subjects know something about their observers' needs. The push model might make observers less reusable, because Subject classes make assumptions about Observer classes that might not always be true. On the other hand, the pull model may be inefficient, because Observer classes must ascertain what changed without help from the Subject.
"
The second parameter to update() is of type Object, so you can pass anything appropriate. As you note, the approach is rather general. In contrast, a class that maintains an EventListenerList can get a degree of run-time type safety when used as specified.

Model shared between two objects

I have three classes interacting in an interesting way. One is a model class, and it has to be accessed by both of the other classes, so a single instance of it is kept as a member of each. Both of these classes interact with the model in different ways.
There are a couple of instances where the model object has to be completely thrown away and replaced with a new instance, and this complicates things. And these occasions arise in both of the viewing/controlling classes. So, either one of those classes has to be able to send a signal to the other saying "We need to coordinate and facilitate the replacement of our Model object with a new Model object." Right now I have code in class B to tell class A to construct a new Model and send it back, but now I need to handle the opposite situation, where the event arises in class A, and unfortunately class A does not have a reference to class B and probably shouldn't.
What's a good way to handle this?
Update: Sorry, folks, this can't be a singleton. Singletons are when you need to guarantee there's only one of something. That has nothing to do with any of the requirements I expressed above. This class is not a singleton and shouldn't be.
Update: Up till now, there has actually only been one instance of this Model class, but I had a vague suspicion I needed to allow for more, and I didn't want to limit myself by using the Singleton design pattern when that actually addresses different concerns from what I have. Turns out I was right: yesterday I received a new requirement and now I need support an arbitrary number of these. :) Don't limit yourself when you don't have to, and don't misuse design patterns for situations where they were not intended!
You'll want an intermediary model layer, a model "holder" object that each of the two classes reference. The ModelHolder holds a reference to the model.
This ModelHolder should also support listeners, so when its model is thrown out, it can notify any listeners that the model has changed.
Ok, if you need to change the model (but not force) you can make a listener interface, and make both objects A and B implement it:
public interface ModelListener {
public void modelChanged(Model newModel);
}
and at the proper time you can notify the listeners of the new model change. You can also have a list that holds all the registered listeners.
List<ModelListener> modelListeners = new ArrayList<ModelListener>();
public void setNewModel(Model m) {
for (ModelListener aListener : m.modelListeners)
aListener.modelChanged(m);
}
As always there are tradeoffs between simplicity and robustness. You might want to experiment with the levels you need for your own case.
I encounter this design issue often in GUI projects (Swing, GWT). What I usually do is create a higher-level "State" model, which holds an instance of the object that is shared between 2 or more classes. State then has a ModelListener interface, which the other classes can implement to get notification of changes to the underlying model. State.setFoo() then fires ModelChanged events to the listeners, which respond accordingly.

Categories