r/java • • Feb 08 '22

Java's Options for Options

https://mccue.dev/pages/2-8-22-options-for-options
192 Upvotes

80 comments sorted by

View all comments

1

u/torwinMarkov Feb 08 '22

Cute, but you're not separating your concerns. This reads very much like how my junior devs at work think about problems. Here are your requirements:

  1. Output JSON text (in any format)

  2. Format / style JSON (separate concern)

  3. Amend JSON payload (with copyright)

  4. Output as binary

Taken as separate tasks with silo'd requirements, your hypotheticals become much easier to think about, solve, and test. For more, I recommend reading "Clean Code" by Robert C. Martin.

14

u/Az4hiel Feb 08 '22

You sure you understood the premise of the article, mate?

22

u/[deleted] Feb 08 '22 edited Feb 08 '22

Are you sure you understood the premise of the objection to the article?

Instead of providing all of those options as a tangled mess if statements, enums, options or whatever, just use composition. You can break down the problem into individual responsibilities and then compose the responsibilities.

For example:

Hypothetical 1: Compact vs. Pretty

public class CompactJsonWriter implements JsonWriter {
}

public class IndentingJsonWriter implements JsonWriter {
}

Hypothetical 2: Hybrid of compact and pretty

Instead of having a single IndentingJsonWriter, do this instead:

public class DefaultIndentingJsonWriter extends IndentingJsonWriter {
    // Or make this a static factory method of IndentingJsonWriter if you really hate inheritance
    public DefaultIndentingJsonWriter() {
        super(
            new DefaultObjectIndentingStrategy(),
            new DefaultArrayIndentingStrategy()
            // I don't think JSON has any other things that can be indented
        );
    }
}

IndentingJsonWriter myFunkyJsonWriter = new IndentingJsonWriter(
    new DefaultObjectIndentingStrategy(),
    new CompactArrayIndentingStrategy()
    // CompactJsonWriter could actually be composed of all compact intenting strategies
);

Hypothetical 3: Inject copyright

By wrapping the writer in a proxy, it doesn't matter what combination of options you use. The proxy doesn't have time for any of that.

public CopyrightInjectingJsonWriter implements JsonWriter {
    public CopyrightInjectingJsonWriter(JsonWriter proxied) {
        this.proxied = proxied;
    }

    public void writeJson(Appendable out, Json json) { 
        // Is it legal? I will make it legal.
        Json json = addCopyright(json);
        proxied.writeJson(out, json);
    }
}

Hypothetical 4: Binary

You just wrap the Appendable in a BinaryAppendable. I have no idea what an Appendable is, but I'm going to assume it's something like an OutputStream or a Writer, but knows that it is writing JSON (and potentially wraps an OutputStream or Writer). In which case the BinaryAppendable will intercept writes to the Appendable and convert them to a binary encoding.

When you do stuff like this, you have to be careful, since the mapping isn't one-to-one, so composition order matters. For example, if you wrap an InputStream in a BufferedInputStream, make sure no one can ever interact with the wrapped InputStream.

public BinaryJsonWriter implements JsonWriter {
    public enum Endianness {
    }

    public BinaryJsonWriter(JsonWriter proxied, Endianness endinaness) {
        this.proxied = proxied;
        this.endianness = endianness;
    }

    public void writeJson(Appendable out, Json json) {
        proxied.writeJson(new BinaryAppendable(endianness, out), json);
    }
}

3

u/TenYearsOfLurking Feb 09 '22

Are you suggesting that it is a good API if the consumer must exactly know which subtype of JsonWriter to instantiate? Which explode in complexity if more options are added. Which require to instantiate obscure "Strategy" objects instead of an enumeration which clearly and exhaustively(!) shows the available "modes".

Instead of browsing the api java doc for the X classes needed, it might be preferable to offer a single entry point, where the IDE shows all parameters that can or must be filled via techniques explained in the article.

It always depends. To present your (enterprise-y) solution as strictly better is... lets say "debatable"

4

u/[deleted] Feb 09 '22 edited Feb 09 '22

Are you suggesting that it is a good API if the consumer must exactly know which subtype of JsonWriter to instantiate?

I think so. But then again, I've been using OOP APIs for years. If you use a decent enough IDE, it's actually very easy to enumerate all the available types of interfaces/base classes to instantiate. For example, if I hit Ctrl+T on the Jackson JsonGenerator base class, IntelliJ will show me every available type of JsonGenerator available on the classpath. In fact, that's how I learned it is possible to configure Jackson to generate YAML (YAMLGenerator).

Which explode in complexity if more options are added.

The complexity does not explode. In fact, there is a specific metric that can be used to measure complexity - cyclomatic complexity. Composition is branchless, while adding a bunch of feature flags and corresponding if statements significantly increases complexity, in combinatorial fashion. You can even put a number on it!

instead of an enumeration which clearly and exhaustively(!) shows the available "modes"

There are two things wrong with this statement.

First, a modern IDE will clearly and exhaustively show you the available "modes" through available interface implementations.

Second, you are limited by the modes baked into the API if you use feature flags. Jackson, because it uses OOP techniques for extension, is unlimited in the modes that are available.

To present your (enterprise-y) solution as strictly better is... lets say "debatable"

In my experience, what you call the "enterprise-y" approach leads to much more flexible libraries. For example, Spring's RestTemplate is also built around the same principle of strategy interfaces. I have been able to adapt RestTemplate to situations never imagined by its authors. This has allowed me to use Spring in situations where I might not have been able to use a more rigid library.

1

u/WikiSummarizerBot Feb 09 '22

Cyclomatic complexity

Cyclomatic complexity is a software metric used to indicate the complexity of a program. It is a quantitative measure of the number of linearly independent paths through a program's source code. It was developed by Thomas J. McCabe, Sr. in 1976. Cyclomatic complexity is computed using the control-flow graph of the program: the nodes of the graph correspond to indivisible groups of commands of a program, and a directed edge connects two nodes if the second command might be executed immediately after the first command.

[ F.A.Q | Opt Out | Opt Out Of Subreddit | GitHub ] Downvote to remove | v1.5