How does one get into do nothing Java?

1.5K    Asked by ananyaPawar in Java , Asked on Oct 12, 2022
In C++ when I wanted to mark that if is empty by design I added NULL; as statement:
if (cond1) {
    ...
} else if (cond2) {
    NULL;
} else {
    ...
}

However in Java it seems to be impossible to have a null; as statement. What is the correct way of marking empty by design if in Java (is it just a comment)?

Answered by ananya Pawar
To get do nothing Java - 
Firstly, how is this:
if (cond1) {
    ...
} else if (cond2) {
    NULL;
} else {
    ...
}
Better than:
if (cond1) {
    ...
} else if (cond2) {
} else {
    ...
}
The NULL;-statement doesn't tell anything, or does it?
Secondly, as others pointed out, you don't have to have that empty block, unless you need to say something about the condition or possibly leave space to handle it.
So this makes perfect sense:
if (cond1) {
    ...
} else if (cond2) {
    //cond2 is not handled, because 2 is the smallest prime number
} else {
    ...
}
Or this:
if (cond1) {
    ...
} else if (cond2) {
    //TODO: investigate whether/how this condition needs to be handled
} else {
    ...
}

However an undocumented empty consequence serves no purpose, whether you write NULL; in there or not. Lastly, if you feel like you are having too many conditions, then you should investigate how behavioural patterns and polymorphism in general could help you clean up your code.



Your Answer

Interviews

Parent Categories