java方法 共享,Java:当多个方法共享相同参数时的首选设计(类成员?)

Context: I believe that object creation and management in Java has a cost that we should bear in mind while programming. However, I don't know how big that cost is. Hence my question:

I have multiple functions that share the same arguments:

detectCollision(ArrayList, ArrayList, double dt)

updatePositions(ArrayList, double dt)

etc.

As I see it, there are two ways to organize them (see code below):

define (possibly static, but not necessarily) methods and forward the arguments for each call

create a temporary object with private member variables and remove argument list.

Note that the Mover object has no private internal state and is just a bunch of algorithms that use the arguments ArrayList, ArrayList, double dt.

Question: Which approach is the prefered one ? Does it have a cost ? Is there a more standard alternative ?

Here is a snippet illustrating the first point:

public class Mover{

public static void updatePositions(ArrayList, double dt){...}

/* remove the static keyword if you need polymorphism, it doesn't change the question */

public static Collisions detectCollision(ArrayList, ArrayList, double dt){...}

//etc.

}

Here is a snippet illustrating the second point:

public class Mover{

public Mover(ArrayList, ArrayList, double dt){...}

public void updatePositions(){...}

public Collisions detectCollision(){...}

//etc.

private ArrayList mobiles;

private ArrayList inerts;

//etc.

}

解决方案

I'd recommend you to go with the second variant. Besides the good readability it will also allow you to extend the class later (see SOLID -> open / closed principle). In general, I'd never create such utility classes, as it is not OOP (OOP Alternative to Utility Classes).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值