Java:当多个方法共享相同参数时的首选设计(类成员?) [英] Java : preferred design when multiple methods share same arguments (class member ?)
问题描述
我有多个函数共享相同的参数:
-
detectCollision(ArrayList< Mobile>,ArrayList< Inert> double dt)
-
updatePositions(ArrayList< Mobile> double dt)
- 等。
我看到它,有两种方法来组织它们(见下面的代码):
- define(可能 static ,不一定)方法并转发每个调用的参数
- 使用私有成员变量和remove参数列表创建一个临时对象。
请注意, Mover
对象没有私有内部状态,只是一堆算法,使用arguments ArrayList< Mobile>
, ArrayList< Inert>
, double dt
。
问题:哪种方法是首选方法?它有成本吗?
这里有一段代表第一点的片段:
public class Mover {
public static void updatePositions(ArrayList< Mobile> double dt){...}
/ *如果你需要多态,它不改变问题* /
public static Collision detectCollision(ArrayList< Mobile>,ArrayList< Inert>,double dt){...}
//等。
}
这里是一个代表第二点的片段:
public class Mover {
public Mover(ArrayList< Mobile>,ArrayList< Inert> double dt){...}
public void updatePositions(){...}
public Collisions detectCollision(){...}
//等。
private ArrayList< Mobile>手机;
private ArrayList< Inert>惰性物质
//等。
}
去与第二个变种。除了良好的可读性,它还将允许您以后扩展类(请参阅 SOLID < a> - >开/闭原理)。一般来说,我永远不会创建这样的实用程序类,因为它不是OOP( OOP替代实用程序类)。
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<Mobile>, ArrayList<Inert>, double dt)
updatePositions(ArrayList<Mobile>, 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<Mobile>
, ArrayList<Inert>
, 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<Mobile>, double dt){...}
/* remove the static keyword if you need polymorphism, it doesn't change the question */
public static Collisions detectCollision(ArrayList<Mobile>, ArrayList<Inert>, double dt){...}
//etc.
}
Here is a snippet illustrating the second point:
public class Mover{
public Mover(ArrayList<Mobile>, ArrayList<Inert>, double dt){...}
public void updatePositions(){...}
public Collisions detectCollision(){...}
//etc.
private ArrayList<Mobile> mobiles;
private ArrayList<Inert> 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).
这篇关于Java:当多个方法共享相同参数时的首选设计(类成员?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!