Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
So I have just gotten a bunch of old code where I should improve the performance of. After looking for a while I came accross this piece of code:
//Reference on how the global Variables look like:
private static final int PLS_4_SYSTEM_MALFUNCTION_FL = 4;
private static final int SPS1_20_PUFFER_EMPTY = 20;
private static final int SPS1_30_STOPPERFL_LOCKED = 30;
//...
int disturbance1 = bMessage.getDisturbanceSps1().intValue();
int disturbance2 = bMessage.getDisturbanceSps1().intValue();
if (disturbance1 == SPS1_20_PUFFER_EMPTY && disturbance2 == 0) {
checkWarnings(bMessage, PLS_5_PUFFER_EMPTY);
}
if (disturbance1 == SPS1_30_STOPPERFL_LOCKED && disturbance2 == 0) {
checkWarnings(bMessage, PLS_6_STOPPERFL_LOCKED);
}
if (disturbance1 == SPS1_40_DISTURBANCEFL && disturbance2 == 0) {
if (bMessage.getDisturbanceType().intValue() == DISTURBANCETYPE_SYSTEMDISTURBANCE_SHORT) {
checkWarnings(bMessage, PLS_3_SHORTDISTURBANCE_FL);
}
else if (bMeldung.getStoerungsartMde().intValue() == DISTURBANCETYPE_SYSTEMDISTURBANCE_LONG) {
checkWarnings(bMessage, PLS_4_SYSTEMMALFUNCTION_FL);
}
}
//...
This is just a small example of the code. There are like 300+ more lines that goes on like this.
Now I know that there are many answers on the web already, and I have looked at some of them, but I am unsure which answer would help me the best in this case.
You could change that to something like enums, new-style switches etc. This can certainly make the code more readable and maintainable.
However, you were talking about enhancing performance. Changing this code most likely will have hardly any impact on performance, at least not in a positive way.
If you want to improve performance, measure and find the bottlenecks in the code and focus on those.
this might help !!
if(disturbance2 == 0) {
switch (disturbance1){
case SPS1_20_PUFFER_EMPTY:
checkWarnings(bMessage, PLS_5_PUFFER_EMPTY);
break;
case SPS1_30_STOPPERFL_LOCKED:
checkWarnings(bMessage, PLS_5_PUFFER_EMPTY);
break;
case SPS1_40_DISTURBANCEFL:
if (bMessage.getDisturbanceType().intValue() == DISTURBANCETYPE_SYSTEMDISTURBANCE_SHORT) {
checkWarnings(bMessage, PLS_3_SHORTDISTURBANCE_FL);
}
else if (bMeldung.getStoerungsartMde().intValue() == DISTURBANCETYPE_SYSTEMDISTURBANCE_LONG) {
checkWarnings(bMessage, PLS_4_SYSTEMMALFUNCTION_FL);
}
break;
}
}
also you can write
if(disturbance2 != 0){
// return or exit if requires
}
// then start switch() , you can remove one branch of block
Switch on disturbance1 can help.
Check out the new switch style from Java17. It makes code really lean.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am trying to rewrite my if else statement so I skip the //do nothing part but I can't get my around to find the opposite of the if statement.
someone please help?!
if (decision.equals("repay")){
String riskClass = null;
if (doc.hasItem("riskclass")){
riskClass = doc.getItemValueString("riskclass");
}
if ( (null == riskClass) || (riskClass.equals("")) || (riskClass.equals("repay")) ){
//do nothing
} else{
//do something
}
}
You can simply invert the condition. Try the snippet below.
if ( !((null == riskClass) || (riskClass.equals("")) || (riskClass.equals("repay"))) ){
//do something
}
Another way to invert the check is invert individual conditions and replace or's with and's:
if ( (null != riskClass) && (!riskClass.equals("")) && (!riskClass.equals("repay")) ){
Another point:
Avoid call equals on variables passing constants: the constant will never be null. So in this particular case would be better write:
if (!"repay".equals(riskClass) && !"".equals(riskClass))
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
while (head <= tail) {
if (Choice == possibleNumbers[(head + tail)/2]) {
foundNumber = true;
break;
}
else if (Choice < possibleNumbers[(head + tail)/2]) {
tail = (head + tail)/2 - 1;
}
else
head = (head + tail)/2 + 1;
}
return foundNumber;
}
This is part of a number searcher lab I did in class.
If you're worried about the length of the code, I'd suggest favouring clarity over brevity. Code it communication, and it's more important that your code is readable and extensible than that it be short.
If this was production code, I'd say use a library method - I think this is equivalent to Arrays.binarySearch, but looks like you're doing it as an exercise.
One code style change I'd suggest - break can make loop logic harder to follow. If you changed the condition to while (head <= tail && !foundNumber) then you could remove that.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Imagine you want to write a simple method, which take a String argument named "foo". The method should return the int "1" if foo equals "toto" and "2" in the others cases. What is the best way to write this method without using a ternary expression ?
I have several solutions but can't decide by myself which one is the best in Java.
Solution 1 :
public int method1(String foo){
if("toto".equals(foo)){
return 1;
}
return 2;
}
Solution 2 :
public int method2(String foo){
if("toto".equals(foo)){
return 1;
} else {
return 2;
}
}
Solution 3 :
public int method3(String foo){
int result = 2;
if("toto".equals(foo)){
result = 1;
}
return result;
}
Solution 4 :
public int method4(String foo){
int result = 0;
if("toto".equals(foo)){
result = 1;
} else {
result = 2;
}
return result;
}
Any other ideas?
Remember, I search a solution without ternary condition.
Thanks,
EDIT : I know that all the previous methods give the expected result, so all of them can be used. What I wanted to know and what wasn't clear in my initial question is : Is there some kind of standard in the Java community about this situation ?
For example, I know there is a standard about the position of the brackets : you can put them a line after the if-statement but most of the people won't do it in Java.
I know that the ternary expression is probably the best here. But, as you can imagine, my "real" method is more complicated than that and can't used ternary. The problem I presented here is just a simplification, not the entire, real problem.
I think, the best is the most readable
public int method(String foo){
return "toto".equals(foo)?1:2;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
public void declareWinner()
{
compare and declare winner
if(getLive_player1()==0 && getLive_player2()>0)
{
System.out.println("Player 2 wins with "+getLive_player2()+" cells alive.");
}
else if(getLive_player2()==0 && getLive_player1()>0)
{
System.out.println("Player 1 wins with "+getLive_player1()+" cells alive.");
}
else
{
System.out.println("There is a tie.");
}
}
Well, it's clear that you have a handful of different branches in your code, so you'll want to implement unit tests where you can hit your if and else if statements:
player1 = 0 and player2 > 0
player1 = 0 and player1 > 0
As well as a test where you hit your else statement:
Clearly multiple options, but player1 > 0 and player2 > 0 will suffice to reach that branch.
So that's at least three different #Test methods.
I'm assuming your concern is determining how to capture the System.out calls. You can change the out stream to one which points to something that can be captured programmatically. That is achieved with System.setOut():
#Test
public void testSomething() {
ByteArrayOutputStream myOut = new ByteArrayOutputStream();
System.setOut(new PrintStream(myOut));
// do your setup and then execute declareWinner()...
String methodOutput = myOut.toString();
// Use Assert.assertEquals(...) to check methodOutput against expected value...
}
By the way
Based on what I can see, how do you know that two scores > 0 end in a tie? Seems like the else statement hasn't really closed out all of the options. But then again, I'm not sure what you're underlying code is doing...
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Good morning/afternoon/night,
I'm writting a simple function which will return a boolean if the string given as an argument (in this case a two character code) is matched.
I was wondering which would be considered the "Best" way to go about this, would it be using a number of || operators within a single if like below:
private boolean isCodeSpecial(String code){
if( code.equalsIgnoreCase("AA") ||
code.equalsIgnoreCase("AB") ||
code.equalsIgnoreCase("SS") ||
code.equalsIgnoreCase("DD") ||
code.equalsIgnoreCase("YY") ||
code.equalsIgnoreCase("ZZ") ||
code.equalsIgnoreCase("AX") ){
return true;
}
return false;
}
Or perhaps using a series of else if statements like the below:
private boolean isCodeSpecial(String code){
if(code.equalsIgnoreCase("AA")){
return true;
}else if(code.equalsIgnoreCase("AB")){
return true;
}else if(code.equalsIgnoreCase("SS")){
return true;
}else if(code.equalsIgnoreCase("DD")){
return true;
}else if(code.equalsIgnoreCase("YY")){
return true;
}else if(code.equalsIgnoreCase("ZZ")){
return true;
}else if(code.equalsIgnoreCase("AX")){
return true;
}else{
return false;
}
}
I'm not really concerned about performance in this application, as I know any gains/penalies will likely be minimal and almost unnoticable - but if possible I would like to know whats generally considered best practice for future reference. I guess the argument could be made that this is exactly what else if is for ?
Thanks in advance,
Edit: Forgot to mention that I am using Java 1.6 (so I dont beleive a simple switch is possible without the use of Enums ?)
Why use an if statement at all?
return code.equalsIgnoreCase("AA") ||
code.equalsIgnoreCase("AB") ||
code.equalsIgnoreCase("SS") ||
code.equalsIgnoreCase("DD") ||
code.equalsIgnoreCase("YY") ||
code.equalsIgnoreCase("ZZ") ||
code.equalsIgnoreCase("AX");
If you really want the if statements, then I'd definitely go with the first approach. It will perform exactly the same number of comparisons as the if/else/if/else code due to shortcircuiting - if the first operand of the || operator evaluates to true, then the second operand won't be evaluated... but it's a lot clearer.
Another alternative would be to create a fixed case-insensitive set so you could then say:
return VALID_CODES.contains(code);
You could do that with a TreeSet:
private static final Set<String> VALID_CODES =
new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
static {
VALID_CODES.add("AA");
VALID_CODES.add("AB");
VALID_CODES.add("SS");
VALID_CODES.add("DD");
VALID_CODES.add("YY");
VALID_CODES.add("ZZ");
VALID_CODES.add("AX");
}
First case is the way to go, as lesser the code its better from readability and maintenance point of view
In fact Jon suggestion is best if just if you just want to return Boolean as it involves even lesser code
in your case I'd use a regexp:
return code.toUpperCase().matches( "(AA|AB|SS|DD|ZZ|XX|CC)" );
An array with all these strings and a loop that goes trough and returns at the first true occurence would be even more maintainable (and less verbose).
What is the possibility if we use a switch case ? Is that would be better ?
considering both the best and worst case scemerios, both of your choices will be equally efficent because in both the cases same number of comparisons are to be performed... but as answered by jon first one will be little readable than the second one...
what if you also try switch case ... that will have a performance edge i guess..
I would go with the first way as it's more clearer and easier to read than the second one and also easy to maintain and does the exact same thing.
Additionally, you can try some thing even better in performance and easier to read - Switch
Here is how the same thing above will look as:
private static boolean isCodeSpecial(String code){
switch(code.toUpperCase()){ //Convert code to upper case so that
case "AA": //you don't have to do case sensitive search
case "AB":
case "SS":
case "DD":
case "YY":
case "ZZ":
case "AX":
return true;
}
return false;
}
Additional Note:
You can only use Switch in java for String on JDK 7 or later versions. If you are using a earlier version of java, then go for if else version.