It depends on what you need.
Consider you have a requirement that stipulates you collect 2 data points that represent values that are greater than 0, and you have to give feedback on if and which values are invalid.
public Data(int x, int y)
{
if (x <= 0 || y <= 0) {
throw new IllegalArgumentException("Invalid data provided, got (x: %d, y:%d)", x, y);
}
}
Note that checking for null and then checking for a condition is a fairly normal pattern called a null guard.
public void setValue(SomeValue o) {
if (o == null || o.Value <= 0) {
// code to handle bad value
}
}
On the other hand, if you have a set of conditions that need to be checked in order, and fail out if one isn't met, you can (not recommended) use chained if
s like you have:
public void someOperation()
{
if (condition)
{
if (condition2)
{
if (condition3)
{
// operation here
}
}
}
}
Note that although you don't explicitly mention something other than control statements, if you have a situation similar to the preceeding example, I would strongly recommend refactoring the condition checks by inverting them, and if the checks are complicated, refactor them out to methods returning boolean
.
public void someOperation()
{
if (!condition)
{
// code to fail out
}
if (!condition2)
{
// code to fail out
}
if (!complexCondition())
{
// code to fail out
}
// operation here
}