mjk

mjk

Java by Comparison: Thoughts on "Avoid Negations" (page 4)

TL;DR: words that incorporate negation are acceptable, eg. independent, asymmetric, nondeterministic.

An example in the book is to rename isInorganic() to isOrganic(), but I think this is too mechanical and goes too far. The field of inorganic chemistry thinks of itself positively, and its domain vocabulary includes the word. More important than recognizing words that contain negation is to respect the domain terminology. Also it is more important to consider the typical usage in code. For example, when following the “Fail Fast” pattern, we expect something like this pseudocode: if isInvalid(arg) { throw new exception } I think that the authors might recognize this as they use isUnknown(), a positive statement of negation, is a later example.

I agree it is generally better to avoid negative logic, and that coders should know De Morgan’s laws (page 7), but I find it ironic that turning this

boolean isValid() {
    return missions >= 0 && name != null && !name.trim().isEmpty();
}

into

boolean isValid() {
    boolean isValidMissions = missions >= 0;
    boolean isValidName = name != null && !name.trim().isEmpty();
    return isValidMissions && isValidName;
}

is considered better than this

boolean isInvalid() {
    return missions < 0 || name == null || name.trim().isEmpty();
}

(which can be easily lambda-ized to boot).

Most Liked

Ted

Ted

I like the sentiment of the “Avoid Negations” section, especially in how negations can weasel their way into naming, but I agree with @mjk that renaming isInorganic() to isOrganic() is in fact a good cautionary tale of going too far and not considering the domain context. :thinking: Also, I think the fact that the Result.INORGANIC constant exists and couldn’t be renamed is a big clue that the term “inorganic” is probably an important domain concept.

Regarding the three-line version of isValid(), I think the book would be better served if it skipped the foreshadowing and presented it in the “Simplify Boolean Expressions” section instead of the preceding “Return Boolean Expressions Directly”, that way we can see the two approaches, i.e., introducing local vars versus extracting methods, closer together.

And perhaps this is covered later, but I also think the book misses an opportunity to suggest using libraries to simplify expressions. For example, using a string-utility library such as StringUtils in Commons Lang 3 would also simplify isValid() in a clear and concise way:

boolean isValid() {
    return missions >= 0 && StringUtils.isNotBlank(name);
}

I don’t propose adding a new dependency only for the sake of simplifying one single line of code, but in this specific example of string logic, a sizable project most likely already has such a library as a dependency.

And finally, I think the example in the “Avoid Negations” section could be carried forward into a discussion of the proper use of conditional expressions, i.e., ternaries, to get some really concise yet expressive code.

Here’s the example from the book:

class Laboratory {

    Microscope microscope;

    Result analyze(Sample sample) {
        if (microscope.isInorganic(sample)) {
            return Result.INORGANIC;
        } else {
            return analyzeOrganic(sample);
        }
    }

    private Result analyzeOrganic(Sample sample) {
        if (!microscope.isHumanoid(sample)) {
            return Result.ALIEN;
        } else {
            return Result.HUMANOID;
        }
    }
}

And here’s how it looks after inlining the private analyzeOrganic(), replacing if/else with a cascading ternary expression, flipping a negation, and applying some code formatting:

class Laboratory {

    Microscope microscope;

    Result analyze(Sample sample) {
        return
            microscope.isInorganic(sample) ? Result.INORGANIC :
            microscope.isHumanoid(sample)  ? Result.HUMANOID  :
            /* else */                       Result.ALIEN;
        }
    }

The key is to keep ternaries simple and cleanly formatted, kinda like cond in lisps such as Clojure. I love 'em! :heart_eyes:

Popular General Dev topics Top

Devtalk
Reading something? Working on something? Planning something? Changing jobs even!? If you’re up for sharing, please let us know what you’...
1016 16836 371
New
AstonJ
poll poll Be sure to check out @Dusty’s article posted here: An Introduction to Alternative Keyboard Layouts It’s one of the best write-...
New
AstonJ
Please share your favourite Vim tips here :nerd_face:
New
AstonJ
Things like smart speakers (such Amazon Alexa), smart TVs or other devices with built in microphones, cameras or with other features that...
New
Sylvia
About talentbay Our online networking platform connects students with teams in business and industry. It consists of our mobile app for ...
New
AstonJ
Do we have any digital nomads here? Anyone fancy it? If so, which countries would you consider? I’ve been toying with the idea for a wh...
New
OvermindDL1
Yet another rust-made text editor, though I’m really liking the looks of how this one works!
New
First poster: mindriot
LG 28-inch 16:18 DualUp Monitor with Ergo Stand and USB Type-C™ (28MQ780-B) | LG USA. Shop LG 28MQ780-B on the official LG.com website ...
New
AstonJ
Chris Seaton, the creator of TruffleRuby has died. It appears from suicide :cry: He left this note on Twitter on the weekend: And one...
New
First poster: bot
zig/http.zig at 7cf2cbb33ef34c1d211135f56d30fe23b6cacd42 · ziglang/zig. General-purpose programming language and toolchain for maintaini...
New

Other popular topics Top

wolf4earth
@AstonJ prompted me to open this topic after I mentioned in the lockdown thread how I started to do a lot more for my fitness. https://f...
New
Exadra37
On modern versions of macOS, you simply can’t power on your computer, launch a text editor or eBook reader, and write or read, without a ...
New
Rainer
Not sure if following fits exactly this thread, or if we should have a hobby thread… For many years I’m designing and building model air...
New
AstonJ
If you are experiencing Rails console using 100% CPU on your dev machine, then updating your development and test gems might fix the issu...
New
AstonJ
Continuing the discussion from Thinking about learning Crystal, let’s discuss - I was wondering which languages don’t GC - maybe we can c...
New
wmnnd
Here’s the story how one of the world’s first production deployments of LiveView came to be - and how trying to improve it almost caused ...
New
AstonJ
We’ve talked about his book briefly here but it is quickly becoming obsolete - so he’s decided to create a series of 7 podcasts, the firs...
New
husaindevelop
Inside our android webview app, we are trying to paste the copied content from another app eg (notes) using navigator.clipboard.readtext ...
New
PragmaticBookshelf
Author Spotlight: Karl Stolley @karlstolley Logic! Rhetoric! Prag! Wow, what a combination. In this spotlight, we sit down with Karl ...
New
AstonJ
This is a very quick guide, you just need to: Download LM Studio: https://lmstudio.ai/ Click on search Type DeepSeek, then select the o...
New