#code in the constructor

1 messages · Page 1 of 1 (latest)

short flame
#

I have heard that putting code into the constructor is bad practice by my c++ lecturer and other people

public class Square {
    Square(int height,int width) {
        IO.println("square");
        for(int i = 0; i < height;i++) {
            IO.print("\n");
            for(int j = 0; j < width;j++) {
                IO.print("O");
            }
        }
    }
    public static void main(String[] args) {
        new Square(3, 7);
    }
}

can someone explain to me why putting code in the constructor is bad practice? I understand you can use a method but what is deemed except-able and where can the line be drawn. Is it just for setting the members/attributes? can i at least call a method in the constructor?

dark mapleBOT
#

<@&987246883653156906> please have a look, thanks.

copper python
#

there is nothing wrong with "code in a constructor". but it should be meaningful and serve the purpose of constructing the object

#

which it doesn't in ur case

#

so ur case is a very clear bad practice indeed

short flame
#

I will find a better example in one of my projects

copper python
#

btw, IO.println() not IO.print("\n")

short flame
#
Piano(int oct) {
        super();

        octaves = oct;

        if(!initialized) generateOctaves();
        initScale();

        this.setBorder(blackBorder);
        System.out.println(this.getHeight()+" "+this.getWidth());

    }

some of this code prolly doesnt belong here but here is the constructor of my piano object

dark mapleBOT
copper python
#

also, since ur on java 25 u should use the short main method

#

void main() {...}

#

👍

copper python
short flame
copper python
#

also, that super() is unnecessary

short flame
#

does it call super automatically?

copper python
#

yes, always 🙂

short flame
#

ah oke

#
private void generateOctaves() {
        initialized = true;
        int keyboardLength = getTotalWhiteCount();
        for (int i=0; i < keyboardLength; i++) {
            makeWhite(i);
            if(i+1==keyboardLength) endGap = true;
            makeBlack();
        }
    }
protected void initScale() {
        super.initScale();
        VISUALIZER.initScale();
        //enabling HGrow will cause pixel snapping
        // BLACK_NOTES.setGridLinesVisible(true); debug to see where the gaps are
        this.setWidth(Double.MAX_VALUE);
        this.setMinHeight(100);
        this.setHeight(100);
        GridPane.setFillWidth(BLACK_NOTES,true);
        BLACK_NOTES.setMaxHeight(60);

    }

the other functions do this

short flame
#
void main() {
    IO.println("Square: \n");
    new Square(3, 7);
}
public class Square {
    private int height;
    private int width;
    Square(int height,int width) {
        
        this.height = height;
        this.width = width;
        printSelf();
    }
    void printSelf() {
         for(int i = 0; i < height;i++) {
            for(int j = 0; j < width;j++) {
                IO.print("O");
            }
            IO.println();
        }
    }

}

so something like this would be more acceptable

primal oasis
#

No. You should never print while the constructor is running (except for debugging). The constructor is supposed to construct the object and nothing else. printSelf should be called from main because it's not part of creating a square

short flame
primal oasis
#

Using print for debugging is generally fine. This is not good because conceptually creating a square and printing it are separate operations. You might in the future want to create a square without printing it and your code doesn't allow that

short flame
#

Ahh I see why that makes sense. thanks for the info @primal oasis @copper python. Although i did kinda make the square for just an exercise, this does help me see what my lecturer might've been on about. Also is the constructor like a method that returns an instance of itself, or is there anything else going on behind the scenes.

primal oasis
#

Behind the scenes the constructor is a method called <init> that returns void. When you use new, you actually first create an empty object of the specified type and then call the constructor with the empty object as this. This really isn't important for the most part, as you'll mostly interact with the whole new+constructor combo, even as you move into more complicated things.

short flame
primal oasis
#

By empty I meant that every field is set to 0/false/null

copper python
#

dont bother with it

#

the important part is that its called on construction of the object/instance

#

so its ur chance to react to this event and do something

#

that's all

short flame
#

ah oke

plush ivy
copper python
plush ivy
#

Sure

#

Practically that's what happens though. It is important to specify that it is not specified

civic salmon
#

Same general reason you don't write a file when someone calls .getStuff()

#

Because people won't anticipate it

#

It's not a hard rule, but it is nicer to live in a program where you can assume constructors only compute values for fields

dark mapleBOT
#

@short flame

Your question has been closed due to inactivity.

If it was not resolved yet, click the button below to keep it
open, or feel free to create a new thread.

Note that usually the reason for nobody calling back is that your
question may have been not well asked and hence no one felt confident
enough answering.

When you reopen the thread, try to use your time to improve the quality
of the question by elaborating, providing details, context, all relevant code
snippets, any errors you are getting, concrete examples and perhaps also some
screenshots. Share your attempt, explain the expected results and compare
them to the current results.

Also try to make the information easily accessible by sharing code
or assignment descriptions directly on Discord, not behind a link or
PDF-file; provide some guidance for long code snippets and ensure
the code is well formatted and has syntax highlighting. Kindly read through
https://stackoverflow.com/help/how-to-ask for more.

With enough info, someone knows the answer for sure 👍