I need to optimize my code. My boss asked me but I don't know how to do it.
I considered all possible validations, what would they remove or what would they add?
public obtenerNum() {
long numFI = daoF.getNumFI();
long numFA = daoF.getNumFA();
if (numFI>=0 && numFA>=0) {
if (numFI == numFA) {
if (numFI == 0) {
return numFI + 1;
}
return numFI + 1;
} else if (numFI > numFA) {
return numFI + 1;
} else if (numFA > numFI) {
return numFA + 1;
} else {
return -1;
}
} else {
return -1;
}
}
There are certain areas of your code that are unnecessary or can be grouped.
For example, this condition is unnecessary:
This check checks whether
numFI
it is worth0
returning the valuenumFI + 1
, which is the same value it would have returned if the condition was not met.The last two
else
can also be combined:Applying these two improvements you could reduce your code to this:
But if we analyze the operation of the program as a whole, and not line by line, we will understand that as long as
numFI
andnumFA
are greater than0
the value of the highest number plus one will be returned.So we could save most of the conditions by calculating the largest value, for example by using Math.max() instead of using conditions
if
:Finally, remind you of a detail: you need to indicate the type of data returned by the class method. I've edited my answer to add the return type in my examples.
Also, you can test the correct working code online ( hosted on github ) using Gitpod:
As mentioned before there are places where code is repeated.
From what you read in the code, what you need is: Return -1 if numFI or numFA are negative numbers
You can see this in the else of your first if
What I would recommend would be to invert the first if. Creating the condition in which it enters the previous else. So analyzing your first if we see that what you want is for numFI and numFA to be both positive. In other words, if one of the two or both are negative, we would enter the else. And it would stay like this.
And then we're going to go through the rest of the code that you had in your first if.
When parsing this piece of code, what you need to do is return the number between numFI and numFA highest plus 1. This is easily accomplished with a ternary operation. in the following way.
Since numFI is the largest number, we would return numFI + 1 . And if numFI is not the largest number, it means that:
In either case we can return numFA + 1 . And grouping all your function would be as follows.
If you still have doubts, keep asking, that's what the community is for and keep going.