Object-oriented – How to make a service stateless

Architecturedesigndomain-driven-designobject-oriented

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.

Best Answer

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    
    }
}