canadian_scholar
canadian_scholar

Reputation: 1325

Nesting conditionals in Java

The Problem

Given the following code:

if (enforceLength && rawContents.length != recordLength) {

Right now if enforceLength and rawContents does not match recordLength, it returns true and triggers our warning system. Some of our recordLength however are HEADER_DIFF characters longer than the rawContents.length.

So we are hoping to put an or on rawContents.length so that it can either match recordLength or recordLength + HEADER_DIFF.

Question

Is there a straightforward way to create an OR conditional on just the second part of this if statement? i.e. so that it triggers the alert if rawContents.length does not equal recordLength but it does not if recordLength happens to be exactly HEADER_DIFF longer than expected.

A failed attempt

One attempt that failed:

if (enforceLength && rawContents.length != recordLength + HEADER_DIFF 
  || rawContents.length != recordLength)

Upvotes: 1

Views: 72

Answers (5)

user8537453
user8537453

Reputation: 80

Have you thought about using a nested if?

if (enforceLength)
{
    if(test for header diff)
     {
        rawContents.length != recordLength + HEADER_DIFF 
     }

    else
    {
     rawContents.length != recordLength)
    }
}

It is more convoluted but eaiser to understand.

Upvotes: 0

OldCurmudgeon
OldCurmudgeon

Reputation: 65869

This is a classic problem with trying to fold too much into one if statement through an irrational fear of the arrow pattern.

Surely this would be much clearer.

    if (enforceLength) {
        // Can be correct or out by HEADER_DIFF
        if(!(rawContents.length == recordLength + HEADER_DIFF || rawContents.length == recordLength)) {

        }
    }

Upvotes: 2

Andrew Dant
Andrew Dant

Reputation: 91

If I'm understanding your problem correctly, you just need to use parentheses around the OR, and replace it with an AND, as such:

if (enforceLength && (rawContents.length != recordLength && rawContents.length != recordLength + HEADER_DIFF))

Upvotes: 1

stark
stark

Reputation: 13189

Fail if neither of the 2 conditions is true:

if (enforceLength && !(rawContents.length == recordLength + HEADER_DIFF || rawContents.length == recordLength))

Upvotes: 1

Joop Eggen
Joop Eggen

Reputation: 109613

The not-or-ious logic knot

if (enforceLength && rawContents.length != recordLength
        && rawContents.length != recordLength + HEADER_DIFF) {

Maybe negatives are more understandable

if (enforceLength && !(rawContents.length == recordLength
        || rawContents.length == recordLength + HEADER_DIFF)) {

Upvotes: 2

Related Questions