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.
TypeScript was developed by Microsoft to make it easier to write large code bases. Essentially, it's just JavaScript, with static typing.
A static method uses the static keyword instead of the function keyword when we define it. Static members can be encapsulated with the public, private and protected modifiers. We call a static method directly on the class, using the class name and dot notation. We don't need to create an object instance.
Static methods of a class, unlike instance methods, belong to (are visible on) the class itself (not an instance of it). They do not depend on the instance members of a class and will usually take input from the parameters, perform actions on it, and return some result. They act independently.
A static method provides NO reference to an instance of its class (it is a class method) hence, no, you cannot call a non-static method inside a static one.
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#
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With