Reputation: 2646
We've got an Angular
app consisting of excel-like grids. There are at least 20 components, each with a unique grid.
Each component has a save()
function which cycles through any added, edited or deleted items and saves them accordingly. save()
is a large function and exists on each component's .ts file, since there are differences between each save()
.
I wanted to refactor save()
, so I started with one of the components. Then I realized that it may have been easier if I centralized the function within a service and just had one save()
for the whole app, rather than 20 (one on each component). However, I also see cons to this. I'm hoping other Angular devs can give me some insight into reasons to put a function into a service, rather than leaving it in each component.
PROS
- might make development easier - aka if refactor is needed, only need to refactor in one place. However, may not be the case:
CONS
- might make development/maintenance more difficult, or not any easier. Because, the differences between save()
on each component are sometimes rather significant, and:
- likely will decrease performance of save()
, since differences will require additional switch case
statements to determine which component is calling save()
. It may not be a noticeable performance hit, but there will be a hit.
- this will take weeks to consolidate and test - everything's working right now and would be a shame to break something
Thoughts?
Upvotes: 2
Views: 76
Reputation: 12357
An approach to creating a service for the save functionality would be to have a BaseSave
class which would have protected
methods (same as private but available to classes that extend it) that have all of the functionality that is common to the different save scenarios. The BaseSave
would not itself be provided as a service
For each of the different components (where save would differ), you would create an injectable service that extends BaseSave. These would use the protected methods, but would also provide their own unique implementations of the public save()
function
Unit tests could be written for the BaseSave
class and also for each of the extended implementations
Upvotes: 1