When coding I noticed I started to get into a habit of not using if-else statements when the else block only has one line of code. For example, if I have code that can be solved like this:
public Person(int initialAge) {
if(initialAge < 0){
System.out.println("Age is not valid, setting age to 0.");
age = 0;
}
else{
age = initialAge;
}
}
I will instead remove the else
statement entirely to cut down on a few lines of code. This results in my code looking more like this:
public Person(int initialAge) {
age = initialAge;
if(initialAge < 0){
System.out.println("Age is not valid, setting age to 0.");
age = 0;
}
}
I'm wondering if this is a bad coding habit to get into and if I should break out of this coding habit or if it'll be fine to continue doing this. Would doing this be a bigger issue down the line when I get onto more complex programs?
Edit: Just wanted to give some more information for why part of the code is written the way it is. The snippet provided is part of a coding challenge where one of the requirements is to set any negative number inputted to 0.
age
isfinal
, so it may not be a viable option. \$\endgroup\$