if else在类构造函数中的条件......是不是很好的做法?

han*_*ant 3 java constructor coding-style

我编写了一个构造函数并传递一个布尔标志来决定将哪个值设置为类变量.代码如下

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

现在我很困惑,不知道我是否会在构造函数中添加if ... else条件.设置类变量值是不错的风格?

谢谢,Hanumant.

Chr*_*ung 5

构造函数中的条件本身并不成问题.但是,在这种情况下,我倾向于像这样编写你的构造函数:

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