My service classes tend to have quite a few instance variables ...
This is not necessarily a code smell. If you need a lot of dependencies to do your job, then this is just a fact.
... they seem to do a lot of work (i.e. there are many methods).
Is it desirable to create more targeted services?
As a rule, the more granular you can make your service interfaces (i.e. fewer methods), the better (have you ever had to trawl through an interface with fifty methods on it, looking for the one you want to name?). But if you do not publish a public API, then the granularity of your service interfaces can be refined as you progress. Often, when starting a project, I will start with one service and divorce it over time. If you are a consumer of these services, then when you start to feel pain in the interface, reaching a large, you will know that the time has come to break it. Of course, if this is a public API, then you will have to make a much more advanced design.
Also, should classes be provided to hold instance instances for other objects? I read something about services that have no status, I'm not sure if I break this rule by having these instance variables.
Saving dependencies as instance variables does not necessarily mean that your service is not stateless if the instance variables are stateless as well. To be considered stateless, method calls in a service should in no way depend on previous methods being called. You should be able to download one instance of the service and share it for your application (i.e. a stateless service instance should not be specific to a particular user session). In other words, your service should not maintain any state between method calls. Saving repository dependencies without saving as a variable in a service instance does not violate this requirement.
The reason stateless services is the desired goal, stateless, greatly reduces the chance of errors. This makes it easier to test a service method by restricting test cases to changing the passed parameters, rather than worrying about the previous state of the service. It can also offer performance benefits.
Mj richardson
source share