简体   繁体   中英

Java Mutator: initialize vs. passing to parameter

I have this java mutator setBoard,

public void setBoard(Cell[] board){
        for(int i=0; i < board.length; i++)
            this.board[i] = new Cell(0, "E");   
        makeChutes(numChutes);
        makeLadders(numLadders);
}

makeChutes and makeLadders are methods in the same class as setBoard. They place Chutes and ladders at random places across the board. numChutes and numLadders come from the constructor for this class.

My understanding is that I have created a mutator that first sets a blank board, then places some chutes and ladders. However my professor says that the setBoard method should not initialize the board, it should instead set what is passed to the parameter. Im not exactly sure what this means.

Cell is the following object,

public class Cell{

private String type;
private int space;

public Cell(){
}

public Cell(int m, String r){
    this.space = m;
    this.type = r;
}
public void setType(String r){
    this.type = r;
}
public void setSpace(int m){
    this.space = m;
}
public boolean isChute(){
    return type.equals("C");
}
public boolean isLadder(){
    return type.equals("L");
}
public boolean isEmpty(){
    return !type.equals("C") && !type.equals("L");
}
public String toString(){
    return this.type + Math.abs(this.space);

}
}

Initialization in this context refers to setting some internal state of your class to some default values. Typically, initialization is internal logic that is

  1. Not exposed as a public, callable method
  2. Does not require data to be supplied in order to be accomplished

These are general rules. Mutators, on the other hand, are normally callable methods that set the internal state of a class to something other than what it currently is. The data to be set is passed as an argument to the method. Mutators in Java are methods that accept a single argument, and follow the naming pattern setXXX , where XXX is the name of the property being mutated in the class. The single argument to the method should have the same type as the property being mutated. So in your example:

public void setBoard(Cell[] board){
    // ...
}

setBoard is a mutator for a property board , of type Cell[] . The implementation could very well be simply replacing the current value of board with what was passed in, eg:

public void setBoard(Cell[] board) {
    this.board = board;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM