Zampanò
Zampanò

Reputation: 594

A Few Questions About Service Classes

I have been learning to use service classes as templates for creating and modifying the values of an object.

My questions are as follows:

  1. What is the definition of a service class? The book I am learning from does not define them and I have had trouble finding a definition online.

  2. Why would we want to use a separate service class when all the methods can be written in one class?

  3. Should all service classes follow the structure of:

Instance variables.

Default and non-default constructors

Accessor and mutator methods

toString method

Equals method

Other help methods as required

Or can service classes serve as something other than as a template for objects?

Upvotes: 6

Views: 18971

Answers (4)

J T
J T

Reputation: 59

I know this is an old post, but I hope this helps you or others who come across it.

  1. What is the definition of a service class? The book I am learning from does not define them and I have had trouble finding a definition online.

Everyone's definition is either very specific or very general. I take the general definition of, "a service class separates your business logic from other classes that you want to be reusable throughout an app".

  1. Why would we want to use a separate service class when all the methods can be written in one class?

Using the below as an example. Say you're building a GUI. You'll have,

  1. View class - creates your visuals for your gui.
  2. Controller class - contains the methods and functions for interacting with the view. (passing objects to the view from the DAO and vice versa, but ideally the DAO should be replaced by a service class).
  3. DAO class - handles the actual CRUD operations in a database (ideally light weight and little if any business logic).

Suppose your app needs to return a record. Your controller calls the Dao, gets the record and sends it to the view. Simple, until you need to do more with the record as part of a process, like getUser(), isUserActive(), sendAccountDisabledEmail(), updateUser(), removeUserAssignedProjects()...

Where would you put that code?

You wouldn't put it in the view, because of separation of concerns, other classes couldn't use the methods, readability and just plain tight coupling making changes harder. You can put it in the controller, but other classes wouldn't be able to reference those functions, and again, readability and tight coupling. You could put it in your Dao, and it would allow other classes to make use of the Dao and those operations, but now anytime you need to change something internal to the Dao, you risk breaking the Dao, you will have a big class that may be too hard to read and what would you do if you want to reference another Dao? At this point the Dao is doing too much.

Ideally, you would create a "service" class that handles all business logic for a group of operations. The benefit is you now have a place to call other classes (DAO's including other service classes) and have them interact with each other. Chances are you would refactor anyway to using "service" classes as your app grows and becomes harder to refactor without breaking other classes.

I'm not saying everything needs a service or has to use a service, because sometimes you can just call the DAO directly for simple things, but it's just a lot easier to manage your app if you have a consistent class hierarchy with a service layer from the start (aka don't put business logic in your DAO or reference other DAO's in your DAO).

Should all service classes follow the structure of:

Instance variables.

Default and non-default constructors

Accessor and mutator methods

toString method

Equals method

Other help methods as required

Or can service classes serve as something other than as a template for objects?

This is very broad and it really depends on what your trying to do. Services can be instantiated for an operation and discarded, or manage states through it's own methods or others classes. The key being, as long as your class is "orchestrating" and not actually playing any tunes, then I'd feel comfortable accepting it as a service class.

Upvotes: 0

Adam Siemion
Adam Siemion

Reputation: 16039

It used to be a popular practice to place behaviour methods not inside classes holding data, but in separate classes called services (sometimes also called managers or handlers).

The biggest problem with this approach is that it leads to procedural (not object-oriented) design as your domain classes are just bags with getters and setters and all the logic of your application is inside service classes. More about the Anemic Domain Model anti-pattern.

Please note that does not mean, you should not have service classes in your application at all. When they should be used is described in the provided link.

Upvotes: 10

Pritam Banerjee
Pritam Banerjee

Reputation: 18933

A service class can be thought of as a way of a client to interact with some functionality in the application. The is typically public, with some business meaning. For example, a Employee class might have properties such as employeeId, firstName, lastName, address which should be declared as private. And then there should be accessor methods for those known as setters and getters. Now there should be an overriden hashcode and equals method to find equality between objects. There may or may not be any business rule in the service classes , depending on the design pattern you plan to use. One should also override the toString method in this object. Helpers are advised to be written in separate helper classes. A simple example could be a MVC pattern where you can think of Models as the service classes and Controller as the helper classes (though they are not exactly same). For more information about the topics you can refer to the following links :

  1. getters and setters
  2. Equals and HashCode

Upvotes: 0

Nathaniel Ford
Nathaniel Ford

Reputation: 21239

There is no hard definition for what you're asking about, only 'general practices' that people adhere to more or less, depending on the circumstance.

Typically, a 'service' class handles requests from a user of some sort, encapsulating business logic and persistence away from the action being taken.

For instance, a user wants to buy an item. The service class exposes some method buy(Item item). The service class was instantiated with some notion of who is taking the action. It does all the 'heavy lifting' of marking that the item is bought, of calling the class that handles the money transfer, of calling the class responsible for placing a 'receipt' in the user's data, etc.

What it does not do is any of these things directly. It does not write to the database, but defers to the User, Item, Inventory and Receipt classes as needed, who all know how to persist their own information. (Or it talks to a database service that does this.) A 'service' class really glues together a lot of lower-level functionality.

The reason you do this in a service class is for code base structure. For instance, if you have an Item object, it might be modified by a sale, by an administrator reducing the price, by an employee marking it as missing, etc. You could put all these methods into one class, but then where do you go when you want to update the checkout process? It becomes painful. Instead, you have different services: PurchaseService, InventoryManagementService, etc. The particular services are dependent on your use-case, and where it makes sense to logically divide things up: for instance, it can be by action category ('Purchase') or it could be by user type ('CustomerService', 'OwnerService', 'EmployeeService', etc.) in order to make things like handling different permissions easier.

Further, there is no reason for the service class to care about the particulars of how or where the data is ultimately stored. It should be 'agnostic' to details about the database, or files, or what have you. It's really only manipulating the specific classes that actually have that responsibility. Remember: each class should really only have a single domain of responsibility. If a class talks to the database, it should not be doing 'business logic' of also calculating, for example, the tax owed on a purchase.

Note that the Java language in no way enforces any of these practices. They are just things that people do in order to provide additional structure and make their life easier. The compiler does not care.

What you mean by 'template' is unclear, but the template you lay out is really a template for any class, and thus isn't constrained to this context.

Upvotes: 13

Related Questions