When doing Domain Driven Design it is advised that services should be stateless. There are several kinds of services when doing DDD:
- Application services.
- Domain services.
- Infrastructure services.
- Factories, Repositories, Specifications,…etc.
How exactly do I make a service stateless?
Does that mean I shouldn’t have any instance variables in a class? Is there any guidelines on making a service/class stateless?
I could really use a code sample that illustrate the difference between a stateful and stateless service.
Example: (Is this class stateful or not?)
Class DataToCsvFileGenerator{
private String filePath;
private ResultSet data;
public String createCsv(ResultSet data){
this.data=data;
this.createLocalFile();
this.loadDataIntoFile();
return this.filePath;
}
private void createLocalFile(){
this.filePath=//... logic to create file
}
private void loadDataIntoFile(){
//function uses this.filePath to load data
}
}
Notice that any successive calls to createCsv()
won’t be affected by any prior invocation.
Stateless services don’t track information from call to call. This means they can’t have instance variables that are set as a result of calling a method. They can have instance variables that the service needs, such as a logger or properties required to operate.
A customer service would not track any information about a customer from call to call. Any information needed to track the customer would be saved externally and retrieved as needed. Usually a database is used for persistence, but in some cases web services may use cookies or other client side mechanisms.
Your class appears to be stateful, although the state is not useful. However, additional methods could make your instance variables publicly accessible. A change as simple as running a generator in an IDE could do that. The following rewrite is stateless. Note that the logger variable, would hold a reference to the a logger and would not contain class state. Initialization and use of the logger has been omitted.
Class DataToCsvFileGenerator{ Static Logger logger; public String createCsv(ResultSet data){ String filePath = createLocalFile(); this.loadDataIntoFile(filePath, data); return filePath; } private String createLocalFile(){ string filePath=//... logic to create file return filePath; } private void loadDataIntoFile(String filePath, ResultSet data){ //function uses filePath to load data } }
2
Admittedly, the DDD book doesn’t make it very clear, but when it says “stateless” it means “without persistent or long-lived state”. So, service objects are allowed to keep state in their instance variables/fields, as long as it’s not state that gets persisted or externalized in some way.
The state the book cares about, when discussing statefullness, is the state kept in domain entities and in value objects, as said state normally gets stored into and reconstituted from some external storage (a relational database, files), or is kept in-memory for arbitrarily long periods of time and can be accessed by different threads (such as in an “online customer cart” object).
Service objects that are short-lived (ie, true objects), in particular, are particularly well-suited to have instance state, as they (normally) get created by a single thread and accessed only from that same thread.
Of course you can have instance variables in a class but the class-instance does not exist any more on the next call if you have a stateless service.
a classical statefull service is a cart where articles can be added to. with these statefull service-methods:
- createCart
- addArticleToCart(quantity, articleid)
- removeArticleFromCart(quantity, articleid)
- ….
you can make a service stateless if you provide all necessary infos as parameters of the call:
- createCart returns a cartID
- addArticleToCart(cartID, quantity, articleid)
- removeArticleFromCart(cartID, quantity, articleid)
the statefull cartService is responsible to remeber the cartID.
the stateless cartService gets the cartID on ever servicecall.
(Is this class stateful or not?)
Yes, it is stateful.
Now it’s not…
Class DataToCsvFileGenerator{
public string createCsv(ResultSet data, string filePath){
string fullFilePath = string.Empty;
fullFilePath = this.createLocalFile(filePath);
this.loadDataIntoFile(data, fullFilePath);
return fullFilePath;
}
private string createLocalFile(string filePath){
filePath=//... logic to create file
}
private void loadDataIntoFile(ResultSet data, string filePath){
//function uses filePath to load data
}
}
2
In your specific case it should be done as @radarbob said.
However to answer in a more general way, in my project most of my services are stateful if we talk only about raw design, but now if you consider that in fact i’m using a DI framework (Spring in my case), i’m only injecting others services, which themselves will get built by Spring like this. once it’s done, i don’t ever change one of my fields.
So it’s stateful on the design, but in the usage, they behave the same way as stateless object.
Exemple :
public class PeopleService{
private RightsService rightsService;
//+setter to init with spring
}
This is stateful by design because you have the possibility to change the rightsService, but as long you don’t do it, you will have the same behaviour than a stateless object (assuming RightsService
is following the same behaviour).
Note : if we want to be purist, instead of using setters, you could use final fields and initialize it in the constructor. This way you really will have a stateless object.