Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

java - Is it violation of Clean Code to call init method in constructor like this

My concern in the code below is that the param to constructor is not actually directly mapped to the class's instance fields. The instance fields derive value from the parameter and for which I'm using the initalize method. Further, I do some stuff so that the object created can be used directly in the code that follows e.g. calling drawBoundaries(). I feel it's doing what is meant by creating(initializing) a Canvas in an abstract sense.

Is my constructor doing too much? If I add methods to call the stuff in constructor explicitly from outside, that'll be wrong. Please let me know your views.

public class Canvas {

private int numberOfRows;
private int numberOfColumns;
private final List<Cell> listOfCells = new LinkedList<Cell>();

public Canvas(ParsedCells seedPatternCells) {
     initalizeCanvas(seedPatternCells);
}

private void initalizeCanvas(ParsedCells seedPatternCells) {
    setNumberOfRowsAndColumnsBasedOnSeedPatten(seedPatternCells);
    drawBoundaries();
    placeSeedPatternCellsOnCanvas(seedPatternCells);
}
...

P.S.: Sorry if this looks like a silly question; my code is going to be reviewed by an OOP guru and I'm just worried :-0

EDIT:

I read some concerns about the methods in initalizeCanvas() being over-ridden - luckily these methods are private and do no call any other methods.

Anyways, after further research on net I've started liking this more... I hope you guys agree !!??

public class Canvas {

private int numberOfRows;
private int numberOfColumns;
private final List<Cell> listOfCells = new LinkedList<Cell>();

private Canvas() {
}

public static Canvas newInstance(ParsedCells seedPatternCells) {
    Canvas canvas = new Canvas();
    canvas.setNumberOfRowsAndColumnsBasedOnSeedPatten(seedPatternCells);
    canvas.drawBoundaries();
    canvas.placeSeedPatternCellsOnCanvas(seedPatternCells);
    return canvas;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It is generally a bad idea for a constructor to contain non-trivial code. As a rule, constructors should at most assign supplied values to fields. If an object requires complex initialization, that initialization should be the responsibility of another class (typically a factory). See Mi?ko Hevery's great write-up on this topic: Flaw: Constructor does Real Work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...