Should all methods be static if their class has no member variables

前端 未结 20 2341
悲哀的现实
悲哀的现实 2020-12-02 14:18

I\'ve just had an argument with someone I work with and it\'s really bugging me. If you have a class which just has methods like calculateRisk or/and calc

20条回答
  •  旧时难觅i
    2020-12-02 15:00

    The answer is yes and no. It all depends on the purpose of the method behavior. For example:

    1. if these methods are simply utility methods then it makes perfect sense to make them static.

    2. If the methods represent some sort of business logic of your application (let's say... a web application) then you may want to make them as flexible as possible. In this case, they would become a simple POJO class, as instance methods. This has the not so obvious benefit that they can be converted to Spring transactional beans, or even EJB3 session beans with very little effort. It also makes the methods easier to test. You can also create interfaces for this bean and add additional aspects to it the way you need.

提交回复
热议问题