if else 类构造函数中的条件...这是好的做法吗?
我编写了一个构造函数并传递一个布尔标志来决定将哪个值设置为类变量。代码如下
public PDFParagraph(PDFPhrase phrase,boolean isRtl) {
super(phrase);
if(isRtl)
this.setAlignment(Element.ALIGN_RIGHT);
else
this.setAlignment(Element.ALIGN_LEFT);
}
现在我很困惑,不确定是否应该在构造函数中添加 if...else 条件。设置类变量值的风格是否良好?
谢谢, 哈努曼特。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
构造函数中的条件本身没有问题。但是,在这种情况下,我倾向于像这样编写构造函数:
Conditionals in constructors aren't problematic per se. However, in this instance, I'd be inclined to write your constructor like this:
使用
if
/else
来执行此操作不存在样式问题。但是:你可以写得更简单:
很多人(包括我自己)认为你应该总是在“then”和“else”语句两边加上大括号。
相关的一点是:如果您发现自己编写了一个如下所示的构造函数:
这可能表明您需要重构构造函数。 (或者可能不是……这取决于细节。)
There is no style issue with using an
if
/else
to do that. However:You could write it more simply:
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:
it is possibly an indication that you need to refactor your constructors. (Or possibly not ... it depends on the details.)
如果您只是将初始对齐传递给 set,那么对于构造函数的用户来说可能会更清楚,特别是如果它是
Enum
并且这些是唯一的可能性。但是,如果您尝试限制初始对齐并且它类似于String
,那么您所做的似乎没问题。不过,为了清楚起见,您可能仍然需要考虑使用Enum
。它比传递给构造函数的true
或false
更容易阅读。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 aString
, what you're doing seems fine. You still might want to consider anEnum
for clarity though. It's easier to read thantrue
orfalse
being passed into a constructor.当然,您可以在构造函数中添加 if/else 语句。
通常,最佳实践是使方法尽可能原子(简短且切中要害)且定义清晰。这也适用于构造函数。您希望构造函数根据您传递的参数来设置您的对象。
如果您需要 if/else,那么您可以添加一个。
如果需要的话,您甚至可以疯狂地放入 for 循环! ;)
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! ;)
我建议您使用枚举和 switch 语句而不是布尔值。添加另一个对齐方式时会发生什么?
I would recommend you use an enum and a switch statement instead of a boolean. What happens when you add another alignment?