快速提问
这是...
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...");
}
}
最佳答案
不,这不对。它们是不同的,
第一个将布尔值“ isPregnant”设置为true,然后将其传递给“ setPregnant”方法,该示例是可怕的实践。
(大多数公司风格指南通常都有这样一行:“切勿将赋值和操作混为一谈。这会使代码更难以阅读。”)
第二个很清楚(但不执行赋值)。一个假设setPregnant方法再次执行赋值(但不能确定)。