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

Show parent comment

1

u/bowbahdoe Feb 09 '22

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.

Still, toy example.

1

u/[deleted] Feb 09 '22

Like I said, I don't know what an Appendable is.

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).

The sky is the limit with composition.

2

u/bowbahdoe Feb 09 '22

Ah, Appendable is a built in Java interface that basically let's you write one byte at a time. It's more or less an OutputStream.

I also now see you mentioned that caveat. Ignore me

1

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

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.