Typescript and AngularJS - Static methods vs services

泪湿孤枕 提交于 2019-12-23 15:00:39

问题


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.


回答1:


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#



来源:https://stackoverflow.com/questions/39011788/typescript-and-angularjs-static-methods-vs-services

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!