我想知道以下哪一项是更好的编程实践:
// Below is the contents of a dummy method which is passed a boolean "condition" as a parameter.
int valueA = 3;
int valueB = 5
if (condition == true) {
return valueA
}
else {
return valueB
}
Run Code Online (Sandbox Code Playgroud)
或者,我可以这样编写相同的代码:
int valueA = 3;
int valueB = 5
if (condition == true) {
return valueA
}
return valueB
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,仅当条件等于 false 时才会返回 valueB,因此不需要“else”,但是无论如何包含它是更好的做法吗?
我在编码时总是使用多个 if 语句:
if(logicalCheck){
...
}
if(secondLogicalCheck){
...
}
Run Code Online (Sandbox Code Playgroud)
并且很少使用If Else。我知道使用我的方式意味着我可以完成不止一项逻辑检查,并且只有一个 if else 链可以发生。
我的问题是,在 C、Java 或 JavaScript 中使用一种方法是否比另一种方法有任何性能优势?使用多个 if 语句有什么特别的错误吗?
所以我有一个问题,我现在已经有很长一段时间了,使用 else if 和链式 if 语句之间有什么区别,它们不是产生相同的东西吗?例如,以这个基本示例为例:
short age {0};
std::cin >> age;
if(age > 18) cout << "You are an adult";
if(age < 18) cout << "YOu are a teen";
if(age == 0) cout << "YOu are born";
Run Code Online (Sandbox Code Playgroud)
和
short age {0};
std::cin >> age;
if(age > 18) cout << "You are an adult";
else if(age < 18) cout << "YOu are a teen";
else if(age == 0) cout << "YOu are born";
Run Code Online (Sandbox Code Playgroud)
它们有何不同?
作为一个例子,在开始时有很多ifs 和很多else if在一个之后if。我在下面添加了一些伪代码。
if (x=1)
print x;
if (x=2)
print x;
if (x=3)
print x;
Run Code Online (Sandbox Code Playgroud)
或者
if (x=1)
print x;
else if (x=2)
print x;
else if (x=3)
print x;
Run Code Online (Sandbox Code Playgroud) 我必须在字符串中找到*的出现,并且基于字符串中*的位置,必须执行某些操作.
if(* found in the beginning of the String) {
do this
}
if(* found in the middle of the String) {
do this
}
if(* found at the end of the String) {
do this
}
Run Code Online (Sandbox Code Playgroud)
我使用了matcher.find()选项,但它没有给出所需的结果.