What does this boolean setter mean? - java

I am assigned some maintenance task for a Java program and found this:
public void setActiveCode(boolean isActiveCode) {
this.isActiveCode = isActiveCode & Boolean.TRUE;
}
The type of this.isActiveCode is a boolean, The same concept is repeated for every boolean setters in the class. I can't figure out why it is done this way and I can't ask the original developer.
Would there be any valid reason for doing this?

Would there be any valid reason for doing this?
No. This is just more verbose code with zero gain in clarity (and arguably a loss in clarity since here you are wondering what it's all about).
It reminds me of
public boolean isTrue(boolean b) {
if(b == true) {
return true;
}
else {
return false;
}
}
which unfortunately you will see in the wild from time to time. It's just so sad.

Its weird. Booleans can be used with logical &, but this is useless because a & true = a. Seems to be a developer specific OCD.

Related

Java boolean "Unexpected return value"

I'm new to Java and I can't understand why the IDE says that "Unexpected return value" inside the forEach where I declared that the boolean is true or false by an If statement.
My goal is to check that there is an object inside the "States" HashMap which already uses the name that I want to set to a new state. (The HashMap's key is a String which is called IdentifierOfState and the value is my State object which contains variables like its name.) Thank you for your help in advance!
public boolean isStateNameClaimed(String NameOfState)
{
States.forEach((IdentifierOfState, ValueOfState) ->
{
if (ValueOfState.getNameOfState().equalsIgnoreCase(NameOfState)) {return true;}
else {return false;}
});
return false;
}
The problem is that you are attempting to return the results in the wrong place. The {return true;} and {return true;} are in a lambda, so they are attempting to return a result for the lambda. But the inferred type signature for that lambda doesn't allow any values to be returned.
If your intention is that those return statements should be returning a result from isStateNameClaimed, then the better solution is to just use a for loop to iterate the elements of States.
It doesn't help things that your Java code contains a number of egregious Java style violations. You should NOT start the name of a variable with an upper-case letter. It will confuse ... and then annoy ... other people reading your code.
You may say: "Nah, I don't need to follow the rules, 'cos nobody else will be reading my code". But you are asking >>us<< to read your code.
I'm new to Java ...
... so NOW is the time to learn to do it correctly. Java style matters to people reading your code.
This is how I would write it in classic Java:
public boolean isStateNameClaimed(String name) {
for (State v: states.values()) {
if (v.getNameOfState().equalsIgnoreCase(name)) {
return true;
} else {
return false;
}
}
return false;
}
Or using streams:
public boolean isStateNameClaimed(String name) {
return states.values().stream().anyMatch(
(v) -> v.getNameOfState().equalsIgnoreCase(name));
}
Actually ... I just noticed that those two solutions are not equivalent. And based on your description of what you are trying to do, it probably means that the first one and your original attempt are algorithmically incorrect.
forEach will invoke a given callable function for every element. We can't have return value to that function.
Try using "filter" or assign result to local variable.
Return from lambda forEach() in java

Java Error/Exception handling with returning value

So my friend and I are programming Blackjack in Java, and we wanted to test our input fields for the correct input(e.g only number input). So we sat at his PC and he wrote this solution:
public static boolean testeTextFieldInt(JTextField textField, int geld) {
if (!textField.getText().isEmpty()) {
try {
if(Integer.parseInt(textField.getText())>0 && Integer.parseInt(textField.getText())<geld ) {
return true;
}
} catch (NumberFormatException e) {
return false;
}
}
return false;
}
now I disagree with this solution, because your code shouldn't depend on an error, or am I getting this wrong? so i sat down and wrote this:
public static boolean checkInput(JTextField textField, int spielerGeld, String eingabe) {
boolean matched = false;
switch (eingabe) {
case "num":
if (!textField.getText().isEmpty() && textField.getText().matches("^[0-9]*$")) {
int geldinput = Integer.parseInt(textField.getText());
if (geldinput > 0 && geldinput < spielerGeld) {
matched = true;
}
}
break;
case "string":
if (!textField.getText().isEmpty() && textField.getText().matches("^[a-zA-Z]*$")) {
matched = true;
}
break;
default:
break;
}
return matched;
}
Keep in mind, we yet dont have any textfields we have to check, but I just implemented it to get a grasp of how you could do multiple checks within one method.
So now my question is, what code is "better"? and what could we/I do better?
Thanks in advance!
EDIT1:
So as some already have mentioned, you say my method is not build up after the Single responsibility principle.
But if split up into 'checkInputIsnumber' and checkInputIsString' would the first solution(my friend), still be the "better" one?
EDIT2:
Better is defined as in, the method should be of low cyclomatic complexity, easy readability and be easy to maintain in the long run.
The first approach is much better than the second one.
Single responsibility: You should avoid creating methods that do more than one thing.
Open–closed principle: Your 'validation' is not extensible. Try creating a Validator interface and then an implementation per validation type.
Switch statements increase cyclomatic complexity and make testing harder.
Also, don't use textField.getText() everywhere, it's quite possible that it will change between calls. Assign it to a local variable or even better use a String as your argument and not JText. As Fildor pointed out you correctly avoid using exceptions for flow control and it is indeed better to have a single return point. Having said that, for simple cases when you just parse/check and return, it is acceptable.
You should put every check in a single function. After a while your "all in one function" will be unreadable an unmaintainable. Also it easier to change the checks if they are in single functions. Using try/catch for control flow is no good idea. It is expensive at runtime. It is not a good style and most developers won't expect control flow in a catch block.Excpetions are for exceptional situations.

Android Studio reports "Unreachable Code" with enum comparison

I'm doing something that should be trivial- retrieving an enum value from a property and comparing it with a constant of that enum in an if statement. However Android Studio claims the true case is unreachable code and won't compile.
The block is:
if (ScanState.getScanMode() != ScanState.ScanModeEnum.SCAN_IDLE)
{
//We're already scanning, but user wants to stop.
stopScanning();
}
else
{
ScanState.setScanMode(newMode);
restartScan();
buttonFlashMode = btnMode;
buttonFlasher();
}
where in an extra ScanState class, I have:
public static ScanModeEnum getScanMode() {
return scanMode;
}
public static void setScanMode(ScanModeEnum scanMode) {
ScanState.scanMode = scanMode;
}
public enum ScanModeEnum
{
SCAN_IDLE,
SCAN_PERSON,
SCAN_BIKE,
SCAN_SEARCH
}
private static ScanModeEnum scanMode = ScanModeEnum.SCAN_IDLE;
Variants I've tried, which Android Studio claims will all evaluate to false are
if(ScanState.getScanMode() == ScanState.ScanModeEnum.SCAN_IDLE)
if(ScanState.getScanMode().compareTo(ScanState.ScanModeEnum.SCAN_IDLE)!=0)
if(ScanState.ScanModeEnum.SCAN_IDLE == ScanState.ScanModeEnum.SCAN_IDLE)
if(ScanState.ScanModeEnum.SCAN_IDLE.equals(ScanState.ScanModeEnum.SCAN_IDLE))
I'm new to Java (more familiar with C#), but an answer to this question suggests that my understanding of this is sound. Is there some stupid mistake I'm making?
Have you tried debugging this and verifying that the block is never actually reached?
I agree this is a very strange situation. If it persists, I can recommend swapping the enum for int constants, and conducting the check on them. It's not a real fix, but more of a workaround, but at least it can unblock you for the moment.
Good grief. After making a seperate method as suggested and discovering the problem lay elsewhere I had a look further up the code. The complete method was;
public void onScanButtonPress(#ButtonFlashMode int button)
{
ScanState.ScanModeEnum newMode;
#ButtonFlashMode int btnMode = 0;
switch (button)
{
case FLASH_BIKE:
newMode = ScanState.ScanModeEnum.SCAN_BIKE;
btnMode = FLASH_BIKE;
case FLASH_PERSON:
newMode = ScanState.ScanModeEnum.SCAN_PERSON;
btnMode = FLASH_PERSON;
default:
//Unhandled.
return;
}
if (ScanState.getScanMode() != ScanState.ScanModeEnum.SCAN_IDLE)
{
//We're already scanning, but user wants to stop.
stopScanning();
}
else
{
ScanState.setScanMode(newMode);
restartScan();
buttonFlashMode = btnMode;
buttonFlasher();
}
}
Since I've forgotten to put break statements in the cases of the switch, it'll always return before the if is ever evaluated. It'll therefore never evaluate to true and so the error is correct- if misleading since it implies (to me at least!) that the if statement does get evaluated. Thanks for the comments, and I figured this was worth leaving (despite being indeed a stupid mistake) because others might be caught out by this.
EDIT: As mentioned by #Bubletan and #MarkoTopolnik, this would not result in a compiler error. Leaving the response as documentation of something that would NOT cause this error.
Do you call anywhere in your code setScanMode? (outside that else block). The compiler may be detecting that the static variable scanMode is never modified, and therefore ScanState.getScanMode() is always ScanState.ScanModeEnum.SCAN_IDLE, thus code not reachable.
Try invoking setScanMode somewhere in your code (with a value different than ScanState.ScanModeEnum.SCAN_IDLE) and see if this error disappears.

Return keywords for a boolean statement

I am writing an incredibly primitive blackjack game for a high school programming class and I am playing with writing a boolean as such:
public boolean DealerTracker()
{
if(a==11 || a==12|| a==13)
{
a = 10;
}
dealerHandValue = a + dealerHandValue;
if(dealerHandValue>21)
{
DealerHand.setText("The House went bust!! Everybody wins!!");
return true;
}
else if(dealerHandValue<21)
{
return null;
}
else if(dealerHandValue==21)
{
return false;
}
}
I keep getting an error saying that return null (I couldn't manage to get the fancy blockquote to work) is invalid. However, for this boolean to work I really need three return statements. So my question is this: Is there a way to make null work, or is there something I can put in its place that is still usuable, or am I just being stupid here.
Please note that I do not really need this boolean, so if you think that there is no solution, just advise deletion of the boolean.
Primitives booleans can only return values true or false. You need to return the Object wrapper type for boolean
public Boolean dealerTracker() {
...
boolean primitives cannot be null. You basically have two options I can see:
Have your function return a Boolean (note the capital 'B'). Boolean is an object, rather than a primitive, and so can be null.
A better solution would be to define an enum. That helps you preserve the semantic meaning of the return value, which will make your code more readable and easier to maintain.
If you don't really need the boolean, make the return type void and remove all return statements. If you do need boolean AND null, change the return type to Boolean, which will return a boolean wrapped in an object that can actually be null. The method that calls this method can then receive a true, false, or null, since null actually represents something too (although I'm not sure in this case it represents anything meaningful).

applying casting in the return of a function in java?

I just wrote this simple methode that must return a double value. It's a function to withdraw money from the bank account. The function must let the user get the money only if he entries a value smaller than his the amount of money he has in his account.
There is a condition where, if he is a special user, he can take the money even if he tries a value = balance+1000.
As I'm a beginner to java, I'm not yet familiar with this thing of types (I'm a php programmer, so I never really had to worry about this, but I'm getting troubles to make this code work, because I'm returning a double, if it's ok, but a false, if it's not, and I can't do this in java.. This is my methode.. (the variables 'balance' and 'special' belongs to my class).
public double getMoney (double value) {
if (value <= balance) {
balance = balance - value;
} else {
if (special == true && value < (balance+1000)) {
return balance-value;
} else {
return false;
}
}
}
I know it's a noob question, but I just started studying java and I was used to code using PHP, where I don't need to worry about the type of my variables, so I was wondering if you could give me some advices.
Thanks
You could return Double.NEGATIVE_INFINITY, instead of false.
Then the caller explictly checks for that value, and detects ist as invalid withDrawn().
The caller checks that by
double val = getMoney(5000000);
if (val == Double.NEGATIVE_INFINITY) {
// money could not be withdran
// print message
} else {
// ok money could be withdrawn
}
If you want to do that more professional you would have to retun a transactionInfo:
TransActionInfo info = getMoney(500000);
if (info.getStatus == Status.LIMIT_EXCEEDED) {
// could not withraw
} else {
...
}
Instead of the if you could use a switch statement:
TransActionInfo info = getMoney(500000);
switch (info.getStatus()) {
case: Status.OK:
break;
case Status.LIMIT_EXCEEDED:
// inform on display of bankomat. or similar
break;
...
}
Note that for money values, using a double is usually a bad idea. You certainly don't want a loss in precision happen, right?
Try looking into decimal types, such as BigDecimal, or consider using cents stored in a large enough integer type (if you do not need to support fraction of a cent values).
Don't return false. Return either 0 ("no money withdrawn"), or use exceptions for error handling. Even in loosely typed languages such as PHP or JavaScript this usually is a bad idea, because it causes unexpected behaviour. Try to be strict whereever possible!
Another user suggested to use Double.NEGATIVE_INFINITY. You might as well use Double.NaN but I strongly advise against this. It will make things go wrong in a very subtle way, and that is not what you want. You probably want a big fat exception. You do want the user of the getMoney function to handle this case, so I recommend using an exception that actually must be handled by whoever calls getMoney.
I think you should pass as a method parameter all your variables. So, in the method scope, you solve your question and return true or false ... or return nothing (void).
public boolean hasMoney(double need, double balance, boolean special) {
if( special ) {
return balance+1000 >= need;
} else {
return balance >= need;
}
}
if the return was true, you know that the customer has enoght money

Categories

Resources