Typescript and AngularJS - Static methods vs services
Asked Answered
C

1

5

TL;DR: Static basic functionality that has to do nothing with angular - implement as an AngularJS service vs plain static exported class / methods?

Long version : I've been programming in TS for about a month now, since we're refactoring our app to work with TS (preparing for angular 2.0). When started to go through some of our basic angular services, I was thinking - since it's so easy to implement static classes and methods - maybe some of our services shouldn't be services at all. Of course that any functionality that has to do with angular in some way i'd have to implement as a service. For instance, ColorConverter or ColorPicker - today angularjs services in our application that implement static logic that doesn't change or have to do with angular or any shared external resource - could be easily replaced with a static module that exports static functions. One argument that someone in my office raised pro the angular services is that later on we could easily mock this logic. But why would i want to mock static logic that doesn't change and doesn't access any external resources? Penny for your thoughts.

Confabulate answered 18/8, 2016 at 7:0 Comment(3)
I would say that it depends on how small it is and how sure you are that you will never have additional dependencies or need to substantially modify it. Using a service with dependency injection does simplify testing and gives you greater freedom to add dependencies without refactoring unrelated code.Ulrike
@MichaelAaronSafyan is right. Angular services are easy to testing and mocking.Dorinda
OK, thanks for your replies :)Confabulate
E
4

The problem is the same in Java or other languages. Static method are hard to extends and mock that why you should use services instead of static method.

For instance, if you use static method for ColorConverter you cannot extends its behaviour for a new feature you need in your application (supporting another range of colour or whatever).

The following answers add some element for other languages that are also applicable for TypeScript.

Java static methods pros & cons

When to use static classes in C#

Eli answered 18/8, 2016 at 7:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.