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

Rainer
Have you seen the new features that will be available in the upcoming C# 9 release? C# is taking a lot of input from functional l...
New
AstonJ
Which apps do you think are killing it right now? Either from a technical perspective or ones that you like personally or feel have been...
New
AstonJ
If you could work on any project, what would it be? :upside_down_face:
New
AstonJ
Always interested in seeing what apps people use and how they organise their phones/home screens! Here’s mine…
New
AstonJ
Great paper by Igor Kopestenski on Erlang and GRiSP: Erlang as an Enabling Technology for Resilient General-Purpose Applications on Edge ...
New
AstonJ
Are you a touch typist? :keyboard: poll If you haven’t checked your typing speed yet, you can do so here here :smiley:
New
Margaret
Hello everyone! This thread is to tell you about what authors from The Pragmatic Bookshelf are writing on Medium.
1139 25467 754
New
Exadra37
Kubernetes is everywhere. Transactional apps, video streaming services and machine learning workloads are finding a home on this ever-gro...
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
Exadra37
My brother got a VPS on https://contabo.com hosting provider, but I was not aware of them, and when my brother told me the price and spec...
New

Other popular 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’...
1021 17087 374
New
axelson
I’ve been really enjoying obsidian.md: It is very snappy (even though it is based on Electron). I love that it is all local by defaul...
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
Thanks to @foxtrottwist’s and @Tomas’s posts in this thread: Poll: Which code editor do you use? I bought Onivim! :nerd_face: https://on...
New
dimitarvp
Small essay with thoughts on macOS vs. Linux: I know @Exadra37 is just waiting around the corner to scream at me “I TOLD YOU SO!!!” but I...
New
PragmaticBookshelf
Learn different ways of writing concurrent code in Elixir and increase your application's performance, without sacrificing scalability or...
New
AstonJ
Seems like a lot of people caught it - just wondered whether any of you did? As far as I know I didn’t, but it wouldn’t surprise me if I...
New
rustkas
Intensively researching Erlang books and additional resources on it, I have found that the topic of using Regular Expressions is either c...
New
Maartz
Hi folks, I don’t know if I saw this here but, here’s a new programming language, called Roc Reminds me a bit of Elm and thus Haskell. ...
New
First poster: joeb
The File System Access API with Origin Private File System. WebKit supports new API that makes it possible for web apps to create, open,...
New