Taylor Marie
Taylor Marie

Reputation: 357

Best practice booleans in java

Quick question,

Is this...

this.setPregnant(isPregnant = true);

...the same thing as this?

this.setPregnant(true);

Which one is better practice?

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

    }
}

Upvotes: 0

Views: 187

Answers (3)

Eduardo Briguenti Vieira
Eduardo Briguenti Vieira

Reputation: 4579

If you are inside the class that have the isPregnant attribute, you can just assign the attribute directly. No method call is needed.

isPregnant = true;

Upvotes: 0

Damian Nikodem
Damian Nikodem

Reputation: 1289

No its not. they are different, The first one sets the boolean value "isPregnant" to true and then passes it to the "setPregnant" method and that example is terrible terrible practice.

(The majority of corporate style guides usually have a line which states "One should never mix assignment and operations. It makes code harder to read." )

The second is clear (but does not do the assignment) One would assume that the setPregnant method does the assignment again (but one cannot be sure )

Upvotes: 5

btrballin
btrballin

Reputation: 1464

Never saw syntax like the top one for a setter method. The bottom one is far more readable and practical, so avoid the other one.

Upvotes: 1

Related Questions