Marin Petkov
Marin Petkov

Reputation: 2158

Angular 2 (ng2) - Service vs util, when to use which?

After looking at many different forum posts and example projects, people seem to choose between a service or a util for the same type of functionality. What I have read so far is people saying that Services are better because of dependency injection which will make testing easier. Others say utils are better because they are faster. I was wondering if there is any type of preferred rule on when to use a service vs a util and why?

Here is an example that is extracting table columns from loaded data:

Service

export class TableService {
  getColumns(data:Array<any>):Array<GridColumnInterface> {
    let columns:Array<GridColumnInterface> = [];

    data.forEach((column:any, index:number) => {
      columns.push({
        headerName: column.name,
        field: String(index),
        hide: column.isHidden,
        class: 'text-center'
      });
    });

    return columns;
  }
}

Util

export class TableUtil {
  static getColumns(data:Array<any>):Array<GridColumnInterface> {
    let columns:Array<GridColumnInterface> = [];

    data.forEach((column:any, index:number) => {
      columns.push({
        headerName: column.name,
        field: String(index),
        hide: column.isHidden,
        class: 'text-center'
      });
    });

    return columns;
  }
}

So which would you choose and why?

Upvotes: 13

Views: 5231

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657536

If you care about maintainability and testability use a service.

If you run into situations where profiling reveals that using the service takes up a notable amount of CPU resources, then switch to an util-class and do benchmarks to get proper numbers how much faster your app runs with util-classes. If this makes a difference in your application (highly unlikely btw) then change that service class to an util-class. I'd consider everything else premature optimization.

I'm confident that, when you are able to reduce the number of requests your app makes to your server, it will contribute more to the user experience of your application then you will ever be able to make with service vs util.

Angular2 AoT converts DI code to static code anyway, therefore there is not much potential for performance improvement.

Upvotes: 20

Related Questions