java中的最佳练习布尔值

Tay*_*rie 0 java

快问,

这是...

this.setPregnant(isPregnant = true);
Run Code Online (Sandbox Code Playgroud)

......和你一样吗?

this.setPregnant(true);
Run Code Online (Sandbox Code Playgroud)

哪一个更好的做法?

@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...");

    }
}
Run Code Online (Sandbox Code Playgroud)

小智 5

不,这不对.它们是不同的,第一个将布尔值"isPregnant"设置为true,然后将其传递给"setPregnant"方法,这个例子是可怕的糟糕做法.

(大多数企业风格指南通常都有一行说明"一个人永远不应该混淆任务和操作.它会让代码更难阅读.")

第二个是明确的(但不进行赋值)可以假设setPregnant方法再次进行赋值(但是不能确定)