快速提问,
这是......
this.setPregnant(isPregnant = true);
......与此相同?
this.setPregnant(true);
哪一个更好的做法?
@ScheduledMethod(start = 3)
public void mate() {
if (this.isFemale == true) {
Context context = ContextUtils.getContext(this);
Geography<Agent> geography = (Geography)context.getProjection("Geography");
Geometry geom = geography.getGeometry(this);
// get coordinates of the female
Coordinate femCoord = geom.getCoordinates()[0];
List<Agent> males = new ArrayList<Agent>();
//create an envelope around the female
Envelope envelope = new Envelope (femCoord.x + 0.9, femCoord.x - 0.9, femCoord.y + 0.9, femCoord.y - 0.9);
//get all the males around the female
for(Agent male: geography.getObjectsWithin(envelope, Agent.class)) {
if(male.isFemale != true)
//add them to a list
males.add(male);
}
//randomly choose one, set isPregnant to be true and move to his coordinates
int index = RandomHelper.nextIntFromTo(0, males.size() -1);
Agent mate = males.get(index);
Context matecontext = ContextUtils.getContext(mate);
Geography<Agent> mategeography = (Geography)matecontext.getProjection("Geography");
Geometry mategeom = mategeography.getGeometry(mate);
Coordinate mate = mategeom.getCoordinates()[0];
this.setPregnant(isPregnant = true);
// or this.setPregnant(true);
moveTowards(mate);
System.out.println("Female can now lay eggs...");
}
}
答案 0 :(得分:5)
不,不是。它们是不同的, 第一个设置布尔值&#34; isPregnant&#34;为真,然后将其传递给&#34; setPregnant&#34;方法和那个例子是可怕的可怕做法。
(大多数企业风格指南通常都有一行说明&#34;一个人不应该混淆任务和操作。它会使代码更难阅读。&#34;)
第二个是明确的(但不进行赋值)可以假设setPregnant方法再次进行赋值(但是不能确定)
答案 1 :(得分:1)
从未见过像setter方法那样的顶级语法。最下面的一个更具可读性和实用性,所以请避开另一个。
答案 2 :(得分:0)
如果您在具有isPregnant
属性的班级内,则可以直接指定属性。不需要方法调用。
isPregnant = true;