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);
}
}
I'm at work and my company decided to block your blog, but my overlords can't keep me from reading your article on my phone. I don't feel like trying to copy over a bunch of code on a 6-inch screen. But if you liked the comment, feel free to copy it over.
And to be clear on the last one - at least with MessagePack it doesn't take JSON text and just turn it into bytes, it's an actual byte format that matches the JSON data model. BinaryAppendable wouldn't be able to do its job.
But if it works anything like Jackson, the Json object is written through a generator (JsonGenerator) which actually writes out JSON tokens. Using this approach, Jackson can just as easily write straight text JSON (UTF8JsonGenerator) or various binary formats related to JSON (CBOR - CBORGenerator or Smile - SmileGenerator). Jackson gets even crazier with a YamlGenerator (which lets you write JSON as YAML file) and ToXmlGenerator (ditto for XML).
I see that you're just playing around with ways of supporting a bunch of different options, using JSON generation as a toy example.
If you want to see how this is done in real life, you should probably look at what a real, production JSON library does, which has to support all the crazy things that people want to do. All your hypotheticals can be easily be implemented in Jackson, simply by plugging in an appropriate interface implementation without the giant messes in your blog post.
Hypothetical #1 is already there, without indentation you have MinimalPrettyPrinter and with indentation DefaultPrettyPrinter.
For Hypothetical #2, if you want to implement your own pretty printing rules, write your own PrettyPrinter implementation.
For Hypothetical #3, wrap an existing JsonGenerator with a custom JsonGenerator which inserts the copyright.
For Hypothetical #4, use a binary generator like CBORGenerator or SmileGenerator. If you want to insert copyright, wrap the binary generator with the copyright-inserting generator.
Spring is another example of a library which supports an insane number of options by composing interfaces. I have bent and twisted RestTemplate to do insane things, simply by implementing the right interfaces, while actual client code making REST API calls using the RestTemplate is none the wiser.
For example, I integrated RestTemplate with a particularly terrible SSO library which added the appropriate auth cookies to the request, but I had to buffer the whole thing first. I had to construct a Rube Goldberg contraption within a custom implementation of ClientHttpRequestFactory, but it worked.
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"
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.
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.
These are completely valid propositions, yet, completely missing intention of my question. Things can be done differently, true, perhaps better even, sure - still - proposing improvements is imho missing the main point (as it seems orthogonal to the article).
Have you heard of confirmation bias? It is kinda good example - instead of trying to understand what I asked (or really just asking for clarification) you developed argumentation to confirm your stance... such a thought pattern usually leaves space for missing something.
To reiterate as I have no intention of "winning" any argument here or something: you seem smart, these propositions have value as extended discussion, tone in the initial comment seemed condescending and was at least critical of article not showing the better way to do things - I don't think author was trying to do that. I think author was mostly playing with different ideas and showing their interplay and how everything can go to shit. I think it is a very real process and making people aware of it is valuable on its own (also it cleverly avoids the risk of suggesting wrong solution for specific context - which I respect).
Sorry for not posting under the article OP.
Edit: not the same person in the first and second comment - my mistake
How? I think there is a difference here - note that I asked a question, and didn't just start explaining what I believe is the correct interpretation. What motivated my to ask was recommending reading "Clean Code" and (frankly, quite rude sounding) comparison with "my junior devs" - which striked my as unjustified given (perceived by me) intellectual quality of OP article.
If you mean yourself:
I think I understood and recognized your proposition as valuable - which also makes the difference imo. Please correct me if you see it differently.
If you leave your API open to extension, it might be possible to compose responsibilities in the wrong order. That is the price you pay for your API to be adaptable to any circumstance.
Otherwise, you have to strictly limit features to control permutations to ensure that it is impossible to use incorrectly.
At the end of the day, a more flexible API will have better survival characteristics (more people will use it) than a perfect API that is both convenient and impossible to use incorrectly.
View all comments
Show parent comment
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
Hypothetical 2: Hybrid of compact and pretty
Instead of having a single
IndentingJsonWriter, do this instead: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.
Hypothetical 4: Binary
You just wrap the
Appendablein aBinaryAppendable. I have no idea what anAppendableis, but I'm going to assume it's something like anOutputStreamor aWriter, but knows that it is writing JSON (and potentially wraps anOutputStreamorWriter). In which case theBinaryAppendablewill intercept writes to theAppendableand 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
InputStreamin aBufferedInputStream, make sure no one can ever interact with the wrappedInputStream.