How do you make a service stateless?

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật