简体   繁体   中英

if else condition in class constructor … is it good practice?

I have written a constructor and passing one boolean flag to decide which value to set to class variable. Code is as follows

public PDFParagraph(PDFPhrase phrase,boolean isRtl) {
            super(phrase);
            if(isRtl)
                    this.setAlignment(Element.ALIGN_RIGHT);
            else
                    this.setAlignment(Element.ALIGN_LEFT);
    }

Now I am confused and not sure if I shall add if...else conditions in constructor. Is it good style to set the class varible value?

Thanks, Hanumant.

Conditionals in constructors aren't problematic per se. However, in this instance, I'd be inclined to write your constructor like this:

public PDFParagraph(PDFPhrase phrase, boolean isRtl) {
    super(phrase);
    setAlignment(isRtl ? Element.ALIGN_RIGHT : Element.ALIGN_LEFT);
}

There is no style issue with using an if / else to do that. However:

  • You could write it more simply:

     setAlignment(isRtl ? Element.ALIGN_RIGHT : Element.ALIGN_LEFT); 
  • A lot of people (myself included) think that you should always put curly braces around the "then" and "else" statements.


On a related point: if you find yourself writing a constructor that looks like this:

public Thing(boolean cond, ...) {
    super(...);
    if (cond) {
        // Lots of statements
    } else {
        // Lots of different statements
    }
    ...
}

it is possibly an indication that you need to refactor your constructors. (Or possibly not ... it depends on the details.)

It might be more clear to users of your constructor if you just pass the initial alignment to set, especially if it's an Enum and those are the only possibilities. If however you're trying to restrict the initial alignment and it's something like a String , what you're doing seems fine. You still might want to consider an Enum for clarity though. It's easier to read than true or false being passed into a constructor.

Of course you can add if/else statements to the constructor.

It's usually best practice to keep methods as atomic (short and to-the-point) and clearly-defined as possible. This goes for the constructor also. You want the constructor to set up your object given the parameters you pass.

If you need an if/else, then you can put one in. You can even go crazy and put a for loop in if you need to! ;)

I would recommend you use an enum and a switch statement instead of a boolean. What happens when you add another alignment?

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