So I got married, to someone with a last-name of Jackson. I laughed when I came back to this ancient blog of mine, as I wrote a whole thing about the Jackson parser. Well, I am now Christian Edward Jackson-Gruber, but I assure you, it has nothing to do with parsers, and Jackson-Gruber is not a new framework... well... maybe a marital framework.
Friday, 3 May 2024
Wednesday, 16 September 2020
Jackson, YAML, and Kotlin data classes, and SnakeYaml formatting
There have been a few articles on how to use YAML parsing with kotlin data classes, including early frustrations with snakeyaml, how to do it with Jackson's wrapping of SnakeYaml, and generally you can get a functional setup going.
Cool as far as it goes, but Jackson doesn't really expose much of SnakeYaml's DumperOptions (where all the fun config is). SnakeYaml has quite a few formatting options available to it which are essential to writing readable YAML, but these aren't exposed in the Jackson-supplied APIs. So, how to get this configuration exposed?
Unfortunately the answer is, while not hard, messy. Thankfully, Jackson's code is pretty open to extension. This is necessary, because to get your DumperOptions configuration in, you have to intercept where this option class is created, and you have to do that in an override of YAMLGenerator. But... YAMLGenerator is constructed by YAMLFactory, so you also need to intercept THAT in a subclass which overrides the creation method, in order to plumb through your custom YAMLGenerator. Messy, but doable.
Here's what mine looked like:
val mapper: YAMLMapper = YAMLMapper(MyYAMLFactory()).apply {
registerModule(KotlinModule())
setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
}
class MyYAMLGenerator(
ctx: IOContext,
jsonFeatures: Int,
yamlFeatures: Int,
codec: ObjectCodec,
out: Writer,
version: DumperOptions.Version?
): YAMLGenerator(ctx, jsonFeatures, yamlFeatures, codec, out, version) {
override fun buildDumperOptions(
jsonFeatures: Int,
yamlFeatures: Int,
version: DumperOptions.Version?
): DumperOptions {
return super.buildDumperOptions(jsonFeatures, yamlFeatures, version).apply {
defaultScalarStyle = ScalarStyle.LITERAL;
defaultFlowStyle = FlowStyle.BLOCK
indicatorIndent = 2
nonPrintableStyle = ESCAPE
indent = 4
isPrettyFlow = true
width = 100
this.version = version
}
}
}
class MyYAMLFactory(): YAMLFactory() {
@Throws(IOException::class)
override fun _createGenerator(out: Writer, ctxt: IOContext): YAMLGenerator {
val feats = _yamlGeneratorFeatures
return MyYAMLGenerator(ctxt, _generatorFeatures, feats,_objectCodec, out, _version)
}
}
This is pretty gross. It's overriding some internal methods in YAMLFactory and YAMLGenerator, but thankfully, it's only two classes, and not terribly deep into the mess. As a result, I managed to make use of the FlowStyle.BLOCK option, which fixes a known problem in Jackson's YAML handling, where instead of this:
employees:
- name: John
age: 26
- name: Sally
age: 31you get this:
employees:
-
name: John
age: 26
-
name: Sally
age: 31There are other formatting niceties that you can do with SnakeYaml that aren't exposed by Jackson - no longer!
Anyway - this can always be factored into something improved. I'm honestly not sure how easy the Jackson project is to contribute to, but this could be exposed in public APIs without too much irritation. Regardless, I'm licensing the above code with MIT license (as permissive as I know how to make it) and also available at this github gist so you can just use it if you feel like it.
P.S. I really wish Moshi did YAML.
Thursday, 21 February 2019
Bazely thinking and the tale of the content-addressable cache...
It all came down to the content addressable cache.
So... what the heck am I talking about? Let me set the stage.
Misleading cache hits
I dug around and finally found out that (a) I had put in the wrong sha256 - the one from the default 1.2.70 version, and (b) it was satisfying my request, not from the network, but from a machine-wide "content-addressable" cache. On my colleague's machine, it had never downloaded any files before for bazel, so it tried to satisfy it from the network and choked when it fingerprinted the file. And (c) after digging I realized that it was supplying 1.2.70 when I asked for 1.2.71, because the content-addressable cache indexes by the hash, and the URL has no part in the cacheing. It literally only cared about the name when it wrote the file contents from the cache into my build working directory.
Wait what? The URL played no part in the cache index?
Must be a bug
So, bazel was putting this in the CA cache because it was literally saying - the content is they key. Whatever the file name is, if the content hashes to <some number>, then any request for something with the same number must want the same content.
I, on the other hand, was thinking in URL-centric terms. I wanted the file found at that location (I thought), and I supplied the hash to verify. These aren't incompatible world-views for the most part. Usually I actually do want the content, I just assumed it's going to be downloaded from that location. It's only around this error-handling question that they diverge, and when I consider Bazel's perspective on wanting to create fast, hermetic builds.
Bazel simply assumes that you mean it when you put in the expected sha256. Bazel assumes you're not just naively cutting and pasting. It'll check the first time you go to download it, but in this case, I used a perfectly valid sha256 hash for which it had a valid file. And it served it. From the cache that is... addressed/keyed by the content of the file (or at least its hash).
Is bazel right here?
To what benefit? Well, assuming I don't make an error on my side, there are quite a few. For one, download poisoning is harder in a variety of ways out of scope here. Additionally, anything addressable by sha256 can now be downloaded once, and never downloaded again from the wire, even on a clean build (since it isn't "dirtied" because the hashes are the same). This can lead to a lot of benefits in continuous-integration machines where many projects downloading the same files over and over can avoid them. It also provides some solid ground for building distributed caches.
I went to file the bug, but have decided that this, surprisingly, is a feature, not a bug.
Thinking more bazely
I realize that, in retrospect, this might seem obvious. It seems that way to me, too, now. Thinking about the web, privileging addresses not content is pretty easy. It's hard to quantify or express in words, but a lot of subtle things that bugged me about Bazel's (and Starlark's) design and idiosyncrasies have smoothed out in my brain because of this simple perspective adjustment. Hopefully it helps others reason more effectively about such things as well.
Wednesday, 10 October 2018
Suiting up
Then I took a job at Google, and everything changed. My role was decidedly technical, but all my customers were also technical. I lost the primary purpose of geekinasuit, and even more, Googler culture really venerates the geek, not so much the suit. To be honest, I kind of got shamed out of the suit. Lots of social pressure was applied, as well as a nearly endless supply of t-shirts - I swear, 20% of my compensation, by weight, was t-shirt. So I relented, and spent most of a decade wearing jeans and t-shirts, usually with nerdy slogans or fan-service. While in one sense, it didn't matter, I had come to like dressing up a bit. I enjoyed taking a bit of time for self-care and grooming beyond simple standard hygiene. So I was sadder than I realized, when I finally accepted it, and stopped upgrading my wardrobe as jackets and shoes and pants succumbed to wear and tear (and got a little tight, I admit). It was with sadness a couple of months ago that I realized that my last suit was actually no longer going to fit me. The lining was worn out, and the wedding I was preparing to fly to would require actually buying a new suit. I had let things go that far.
That wedding coincided with my departure from Google/YouTube. I left for a variety of reasons, moral, financial, emotional - I left with some sadness and wistfulness, but also with a sense of maybe getting back to myself. I had gone down a deep hole in Google, lost a lot of professional contacts, reduced to only Google's technology stack. I mitigated it with doing a lot of my work in open-source, but it certainly wasn't a life I had led before, connecting with colleagues at conferences, serving customers more directly, and working with the technologies most of the industry uses. But also... I stopped appreciating having my identity swallowed by the behemoth that Google had become. Don't get me wrong - there are lots of good people and ideas and challenges at Google. I did work there that I'm very proud of (the Dagger and Truth frameworks, for example) but it also took me over, in many ways. So I left, to join Square, and help in their mission of economic empowerment (by helping them scale up their development).
And I suited up. I decided to restore at least that, even if just as a symbol to myself, to be better, to push myself, to care for myself, as superficial as clothing and appearance are. So far, I've been suited-up 95% of the days I've been in the office, and it feels really good. It's a state-change in my brain, segmenting a work mode from other modes, and it oddly helps me stay focused (pretty necessary in the open-office wasteland that characterizes basically every tech company for some reason).
I am, once again, a geek in a suit. And I love it.
Thursday, 17 November 2016
WTF does "vend" mean? A terminological journey with no clear ending.
So there I was, in the middle of a code review, adding a method which (in the language of dependency-injection) "provided" a value into a managed object graph with a different key, in advance of a migration. Doesn't matter why. But the word "provided" is so frequent that I went with a different word that (in my brain) seemed to mean the same thing: vend.
Now, the root of this little language odyssey is simply that I hate repeating words unnecessarily. If you use dependency-injection, the word Provider is vastly overused thanks to Guice's Provider<T> interface, the JSR-330 which standardized it, and it's baby brother Dagger and other frameworks which adopted the standard terminology (Spring, J2EE, Tapestry, etc.)
Since the API involved was a method annotated with @Provides and the method was called provideBlah() (real method name changed to protect the innocent), and I just wanted some variety in my life. So I described the change this way:
Vends a [redacted] into the dagger graph, in advance of an API change where [redacted] will consume that in place of [redacted]. Part of a migration to make [redacted] require fewer assumptions (and fewer build deps) of its consumers.Could have been "supplies" but I didn't want to imply the Supplier<T> interface, which is a thing. I went with "to vend".
In that context, I got a drive-by comment.
I was doing a cleanup using some of our awesome google-made bulk refactoring tools (notably Rosie), so this was one of those "dammit, why can't you just approve my change and let me get on with my life moments."
At first, I just went ahead and answered:
Not to be disuaded, "someuser" pressed on:
Ok... gonna try again to avoid the digression and nerd-sniping...
And vend only means sell in a societal context of capitalist voluntary exchange. I can't imagine it would mean sell in the context of an API. :)
This last paragraph was a total indulgence on my part, and the result of my having mainlined (liked, literally injected into my arm) econ textbooks and treatises for the last few years. And obviously my big mistake in the effort to avoid being nerd-sniped.
Not to be so easily dismissed... "someuser" decided to call me out.
I agree that "vend" implies supplying something, but I have only seen it in the context of a sale. With all due respect, can you point to a definition of vend that means to supply or provide, that is not in a "societal context of capitalist voluntary exchange"? (I'm actually really curious, as in, I quite often read etymologies of words. :-) )
</nit-picking-mode>
Thanks for changing the description though :-)
Oh, it's on like the break of dawn, now.
I started looking. I couldn't find definitional resources (but I knew this was a particular inflection of use in the context of computer software and API design.
I started with a web-search of the terms: "api which vends a type" just for starters. I was not disappointed. Nine relevant examples in the first three pages.
Then I got philosophical, noticing that the code examples in which APIs which were described to "vend" things seemed to always be in Objective-C or Java sources. I started to think back, way into the early days of my career, steeped as they were in NeXTSTEP, and wondered whether there was a connection.
Here is what I replied.
▾
Some of these you have to ctrl-f/cmd-f and search for "vend" as they're not in the description but in comments. Also, in some cases it is synonymous with "supplies" (as in via the return type) and in other cases with "offers" in the sense of exposing an API):
https://github.com/attic-labs/noms/issues/2589
https://github.com/realm/realm-cocoa/issues/3981
http://stackoverflow.com/questions/37128296/rest-api-oauth2-type-authentication-using-aws-cognito/37141020
http://nlp.stanford.edu/nlp/javadoc/javanlp-3.5.0/edu/stanford/nlp/objectbank/DelimitRegExIterator.html
https://framework.zend.com/apidoc/1.12/packages/Zend_Pdf.Fonts.html
https://docs.oracle.com/javaee/7/api/javax/faces/render/package-summary.html
https://vaadin.com/api/7.5.7/com/google/web/bindery/requestfactory/shared/InstanceRequest.html
https://jeremywsherman.com/blog/2016/07/23/why-im-meh-about-json-api/ http://liftweb.net/api/25/api/net/liftweb/http/LiftRules.html
(sourced from the first few pages of the google query "api which vends a type")
I have a hypothesis: This language originated in the NeXTSTEP community (of which I was a part), and entered into the MacOS/iOS community lexicon from that source, and also into the Java community by way of a lot of NeXTSTEP folks joining Sun and related Java-oriented enterprises (at one point Javasoft was 25% populated by former Lighthouse Design people, of which I was one). So I suspect I picked it up early, but it is a very uncommon (as I find out in researching it) usage... but not purely in my head. :)
Small addendum... a straw poll of my team which includes iOS developers as well as android developers suggests that it is vastly less common than I would have imagined from my own biases. That doesn't discount the above links but provides a bit of a ratio, a denominator for the numerator of anecdotes I cited above. Seems like a fringe usage, and sadly, provides no insight into from whence this minority usage actually derives.
How common is this in use behind the walls of corporate secrecy? Doing an internal code-search I see a handful of examples with a cursory scan of initial results - all in API docs with this usage of "supply". It at least seems that I'm not entirely out of my mind, or at least others share my heterodox usage.
So now I'm damned curious. How did I pick this up? I see these examples of the usage - is there a common source? Did we all pick it up from one place, or did we independently start using it the same way?
If any of the three people left following this blog have a clue about this, I'd love to hear more insights.
Wednesday, 1 June 2016
Google had this to say about the matter.
From here on in, I don't want to talk about the particulars of the case - I'm a Google employee, but my opinion is rooted in both copyright critique and my views as a software engineer. In fact, I used to work for Oracle, and probably would have resigned over this, to be honest, if I still worked there.
I'm not happy about this. Don't get me wrong - it is a partial victory for sanity in software. But it leaves the travesty of applying copyright to APIs unanswered (though I'm not sure, since IANAL, that this case could have resolved anything about what I'm concerned about, since it's a lower-court ruling about specifics).
The issue for me is this: a higher court found that APIs (application programmer interfaces - or in layman's terms, the specification of how to talk to a software library) are subject to copyright. Fair use means only it's a legitimate exception to what is otherwise copyright-able. So while I'm glad that this was a legit exemption, the whole underlying theory is problematic... and that has yet to be fixed.
Having APIs (and their "structure and organization") be copyright-able in theory at all is insane. It's like saying "English grammar is subject to copyright, but if you want to talk to an English speaker, it's cool to use that grammar and lexicon - it's fair use."
No... it's not merely fair use - it's the entire point of language. If you have to use different names, that's like saying "you can speak English, but you need to use different words when you speak". That means you're using a different language - specifically defeating the whole purpose of using...well... language.
An API exists for the express purpose of providing a means by which one piece of code can speak to another piece of code. A public API (which one must rely on to write software on a language like Java, or using someone's supplied libraries) is a protocol - a language (or a specific subset of language, anyway - a local slang, if you will). Letting us copyright an API strains credulity to the breaking point.
So I'm not convinced it's all over and our industry can breathe again, but at least we can catch a short-breath (until appeals happen, and until this fair-use exemption is used as precedent in other cases).
Wednesday, 9 March 2016
Keep maven builds safe from "M.A.D. Gadget" vulnerability
Per this blog article from Nov 2015 there is a rather large security vulnerability observed within the apache commons-collections library versions 3.0, 3.1, 3.2, 3.2.1, and 4.0. In the spirit of the fact that vulnerable classes are called "gadgets", a colleague of mine referred to this as the M.A.D. Gadgets bug. In essence, classes which reference Apache commons' vulnerable versions and perform serialization can effectively turn the entire JVM into a remotely exploitable exec() function (metaphorically speaking).
While people are busy swapping out vulnerable versions for newer ones, the way dependency graphs work in automated dependency management systems like maven, ivy, gradle, etc, is that a project might be obtaining vulnerable versions from a transitive dependency. That's bad bad bad. So, apart from updating deps, it's important to guard against a recurrence, and you can do that, at least in maven, via the maven-enforcer-plugin.
I threw together this github gist with an example configuration that can ban this dep from your deps graph, including (most importantly) inclusions via transitive dependencies that you didn't even know you had. Here is the gist's content (I'll try to keep both updated if I change them).
<project>
<!-- ... -->
<build>
<plugins>
<plugin>
<artifactId>maven-enforcer-plugin</artifactId>
<executions>
<execution>
<goals><goal>enforce</goal></goals>
<configuration>
<rules>
<bannedDependencies>
<excludes>
<exclude>commons-collections:commons-collections:[3.0,3.2.1]</exclude>
<exclude>commons-collections:commons-collections:4.0</exclude>
</excludes>
</bannedDependencies>
</rules>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
So... fix your projects... but also make them better. Throw this into your project's parent pom, and then it will give you a build-breaking knowledge of whether you're vulnerable, and you can update your deps or use dependency exclusions to prune out any found occurrences you get from your upstream.
Edited to include all affected versions, and re-published from my original article in March, because blogger.com's url management is frustrating.
Tuesday, 20 August 2013
Wow, I suck at blogging.
I just discovered, because of a bug filed on the Guice project, that my blog DNS settings were pointing at a domain parking page. Whoops! When I made the transition from Canadia to Amurika this year I totally neglected to fix up some domain settings. My bad.
But it sort of highlights that I don't have a good discipline around blogging. Examining this, I see about ten draft posts in my blogger account, that I never got around to posting, and which are now sort of obsolete and irrelevant. I'm not so narcissistic to think that everyone cares what I have to say but I provide zero value by never writing at all. :( So, sorry for that. I look with irony at my post of a few years ago stating that "I'm totally gonna blog again, now, promise!" Apparently not.
Life has been crazy - being at Google is a whirlwind. It's exciting, stressful, but also charming. You get very much "dug in" in certain ways, but most of those ways aren't awful - they just occupy your attention.
What IS wonderful is that I've been able to work on primarily open-sourced projects, being a part of the the java core-libraries team. This has meant working on the google core libraries offering Guava, dependency-injection frameworks such as Guice, and Dagger, as well as a host of smaller projects such as Auto (let robots write it!) and contributing to my little testing/proposition framework, Truth. Seeing these things evolve, sometimes in response to each other, has been wonderful. And I get paid to do it! Why? Not because Google is purely altruistic, though Googlers seem to have a really strong bent towards contributing back. But these things really help Google develop world-class software at-scale.
I was in a little internal un-conference of core-librarians of the various supported languages, and my boss pointed out that the fact that we HAVE core libraries and tooling efforts like this is a major contributor to Google's competitiveness and capability. We fund people to figure out what patterns people use and what code developers re-write on every project and creating hardened, efficient, common implementations/APIs/frameworks out of them, where appropriate. We don't try to re-use everything, but we dig and see where we can "maximize the productivity of labour" (to borrow from the economists) of our colleagues by reducing their coding and testing burden to focus on the things that make their application unique from others. In short, we invest in future production, in future capacity for our developers, both in quality and velocity.
Often, we aren't writing tons of code to do it, but rather examining patterns and tweaking, deprecating certain approaches in favor of others, and using the rather stunning tooling we've evolved (blogged about elsewhere) and tools we've open-sourced, to migrate our entire code-base from deprecated forms to new ones. But we also consider new approaches, libraries, and frameworks, both developed internally and externally. It's actually remarkable (to me) that a company this big can change direction so quickly, and adapt to new realities so quickly. The joke among my team is that we're starting to be less a core-libraries team, and more of a javac-enhancement team, since we are also doing a lot of building in static analysis and checks (thanks error-prone folks) into our tooling to prevent error at compile time as we are building new frameworks and tools.
While we've had a few false starts here and there, we are increasingly engaging in joint projects and accepting contributions into the codebase from external parties who benefit from the open-source work as well, which is gratifying. Nothing quite so happy as win-win exchanges.
All told, it's been a couple of years of full engagement, and not a lot of time to do tech blogging. But I'll give it another go, even if it's just to do updates like this from time to time. It's the best job I've had to date, and I am thrilled to be in contact with such high-quality professionals as I am on a daily basis.
Thursday, 14 July 2011
Five years out, and still stable. (Or how I installed new git on old unix)
So, I have an OpenBSD 3.9 machine. It's circa 2006 since I last updated it. Lame, I know, but it's stable, doesn't really do much, has few problems and security holes, and runs nearly no services. But I store some files on it and have been using SVN to manage them. I wanted to start using Git, since I use it more consistently these days. I thought about Mercurial, but - meh - I've stopped fighting religious wars, even with myself.
Problem is - Git, even an old 1.4 version, doesn't exist in the ports tree of OpenBSD until 2007. So, what am I to do? I could update my copy of OpenBSD - an option. A good one that, in the long run, I really should do, even just for security fixes. I could bump the ports tree up a couple of versions until the git port exists, and then try to build it and hope the toolchain works. There are a lot of moving parts to the ports infrastructure, and they evolve between releases of OpenBSD. I played with that for a minute, and in the end, decided to go for broke, and do the naive thing that shouldn't work.
I un-tarred the latest Git 1.7 that's part of the latest OpenBSD release, into /usr/local, deleted the +DESC and +COMMENT files, and basically ran it to see what broke.
Well... it couldn't link to libc.so.58.0 - fair, since I only had libc.so.39.0. So I symbolically linked it. Did the same for libcrypto and libiconv. Seriously. Just symlinked them, hoping no symbols were used by git that had been added or changed in more recent versions.
Worked like a charm.
OpenBSD, and the various core libraries have been stable enough that half-again as many version bumps in libc haven't changed it enough that git needed it - likewise libcrypto. Kudos! I know I lucked out, but still - impressive.
Wednesday, 21 July 2010
Singleton and Request scope considered harmful? No! Scopelessness considered harmful.
I watched an e-mail thread discuss how Singleton and Request scope in Guice were harmful, because Singletons can only depend on Singletons (without magic) and that Request Scoped items can only depend on Request Scoped and Singletons... followed by the idea that because "we're stateless" with minimal global state, so we shouldn't need global things. And because it's cheap to build things so we can build them all the time.
I feel that this perspective comes from a lot of fighting with scopes and scoping problems and probably is an honest attempt at resolving them - if you're stateless, then scope IS somewhat irrelevant... but it also turns out that if you're not stateless (by accident) and you go scope-less, then you have state accidentally scattered all around your object graph without realizing you've copied it. Leave aside entirely that you're going to thrash garbage collection because your dependencies are stored in ivars which will go on the heap...
So what should happen here?
Other than Guice, all other dependency-injection containers of any substantial distribution use "Singleton" as the default scope, not "scopeless" (or what spring calls prototype scope). This is because Singleton is actually cleaner and easier to understand. There is one copy of this in the system... so it needs to either be stateless or carefully guard its state for multi-threaded access. But also the lifecycle is clearer - app starts up, component starts up, component shuts down, app shuts down. Scopeless (Guice "default" scope) actually have an arbitrary lifecycle based on who asks for them.
If you have Foo -> Bar (where -> means depends-on), and Foo is any real scope (singleton, session, request, per-thread, whatever), but Bar is scopeless (meaning a new one is created on every demand), then Bar's lifecycle is different if Foo depends on it than if Bash depends on it because it attaches to the lifecycle (lifetime... or scope, if you will <ahem>) of the dependent component.
This is freaky because it means it's sort of indeterminate until used (I call it the Heisenberg scope). And each time it's used it could be different.
Again, if it's stateless, no problem... but if it's stateless, Singleton is no problem... and cleaner... because you'll uncover scoping problems more quickly with more restrictive scope policies. But moving everything to no-scope means no clear lifecycle... or rather, whatever lifecycle and lifetime you happen to have in whatever calls it.
I think people look at scope as "magical" - especially in the Guice community. I don't see this kind of thrash in Picocontainer, Tapestry-IOC, or Spring user communities. And I think it's because "prototype" scope (scopeless) is seen as a quasi-factory behaviour, not a dependency/collaborator injection behaviour. The two are subtly different, and I think the distinction is lost in the Guice user community. I have ideas as to why this distinction arose between the Guice community's thinking and others', but I'll leave that for another post.
The point is, Scope implies a validity within a lifetime, and if something is stateless, there's no reason it shouldn't be the one and only copy with a lifetime of the entire application's lifetime. I've long posited that "games with scopes" is a dangerous thing in dependency injection, but this is solving the problem by dropping a 16 ton weight on your own head. It uses the most magical quasi-scope to create a fan of instances where a very small set of collaborators are required.
I'm getting close to believing that Fowler, Martin, and others were wrong, and that Dependency Injection (heck, occasionally O-O) are just too dangerous. Seriously. I can't imagine not using them, personally, but I find so many teams and projects where they just think about the problem so unhelpfully and then their clean-up efforts are worse than the mess they created. <sigh>
Thursday, 11 February 2010
Shu-Ha-Ri not harmful... it's misunderstood and mis-applied.
Rachel Davies, for whom I have incredible respect, posted this post called "Shu-Ha-Ri considered harmful". In it she points out that the basic notion of Shu-Ha-Ri from Aikido of graduated styles of learning - the novice, the advanced student, the master should learn in different ways, the novice learning more by rote, and more importantly, from a single master, the advanced student trying the techniques in varying ways and comparing styles, then the master innovating new combinations and techniques. Cockburn, often cited in the Agile community somewhat gets this, but his adaptation varies from this concept just a bit.
Rachel has an important critique, which I accept. She points out that agile boot-camps and other styles of training for organizations and groups and teams in Agile practices often cite Shu-Ha-Ri, and require that teams do "just the scrum by the book" (or whichever method is to be used), at least initially. Then, as they master these techniques as they are put forth, they can adapt. She, however, sees a disrespect for the unique circumstance of the student in this. In her words, "I'm uncomfortable with approaches that force students to follow agile practices without questioning." I agree. But this is not what Shu-Ha-Ri implies. Shu should always include questioning... but the student should test the technique as presented, and part of the discovery is finding out its limits - how it works, and how it does not. But it's an experiment. It requires a control... and the control is the basic form, attempted as instructed, to get a baseline. Teaching any technique, physical or mental has a similarity in that respect. Is the metaphor limited - yes, and I argue that it is the agile-boot-camp folks who often mis-apply the martial arts concept.
I understand the concern she raises, especially the respect for context and unique character of the teams and the flexible nature of knowledge work... but this betrays a misunderstanding, or mis-application of Shu-Ha-Ri. Shu doesn't imply that the students are fungible. Technique is still taught in the context of the student (team). Sutherland has it wrong when he days "only when you have mastered the basic practices are you allowed to improvise." In Aikido, the students who are in a "Shu" mode are not improvising with "different" techniques, but they are applying them in different situations, and seeing how they fit. One adapts HOW to do the technique for a tall person, for a short person, a heavy person, and advanced Aikidoka, an unranked novice, etc. Likewise with Scrum, you apply the technique, but the coach helps the team use the technique in context. That's Shu. Ha then is where a team combines the techniques in unique ways. They may remove a practice, or replace it and see how that fits. Ri (mastery), they are inventing new techniques, or altering the basic forms in different ways. This is all quite reasonable, even in an agile coaching context.
In Aikido, especially, students practice the techniques in multiple contexts, so they can get a sense of the suppleness. Students are asked not to innovate initially, nor combine techniques before they have at least mastered the basic technique itself - so they're not thinking through each step of a move while they're doing it - they "get" it. They they can move closer to innovation.
Rachel's post, while understandably compassionate, confuses two separate things... models of instruction, training, and practice with notions of respect, oppression, and dominance. Telling a student to try the basic move and get it better before expanding isn't disrespectful, it's understanding the learning models of the student. In practice, it is quite possible for a student to grok the technique more quickly, and if Sensei observes this, he will show the student something slightly more advanced, and have him practice this. Or, Sensei may see the student struggling to apply the move, and may change the context to let the student appreciate what's happening. The point of Shu-Ha-Ri is, as Rachel points out, to ensure that one doesn't miss the basics while playing with the innovative and the expansive. If it's being used to hold a student back, or somehow contains a disrespect for the student - that's a failing of the teacher (coach). Student-sensei relationships are adaptive to the needs of the student, else they become a mere posture of dominance and submission, without the deeper communication that's supposed to occur within a relationship of trust.
I feel Rachel is (unintentionally and understandably) mischaracterizing Aikido and Shu-Ha-Ri based on mis-perceptions prevalent in the community on how its concepts can be applied. Aikido is taught in many forms, but Agile is not looser, nor is Aikido tighter a discipline. Aikido is, in any good Dojo, taught with great sensitivity to the needs, the capacities and readiness of the student. It is taught to groups, individually - that is to say, it is demonstrated to the group, then practiced in pairs, with Sensei observing, correcting... coaching. If anything, rolling Agile out in a large organization, and taking large groups through paces in boot-camps which do one-size-fits-all is UNLIKE Aikido training.
Bootcamps fail to do Shu-Ha-Ri if they insist that all steps of Shu are learned at equal pace by all learners. This is not Shu-Ha-Ri being harmful - this is Shu-Ha-Ri being ignored.
Wednesday, 26 August 2009
I don't believe in "Business Value" (sort of)
Ok, let's define terms. I'm not against value-oriented thinking. in fact, I'm all about the customer. I think whatever can add value to the customer or the output the customer wants (presumably software, in my case), the better. But this term "Business Value" has crept in to the Agile community, as a bastardization of the Lean concept of "Customer Value-Added activities" and it worries me. I'm concerned with terms here, and the term is used two ways. I'm increasingly concerned about it's sloppy use and the impacts of such.
In Lean, specifically in Value Stream Mapping there are two kinds of activities - those which add value to the customer, and those which do not. You analyze a process (say, software development from feature request to delivery into production) and you identify the time each activity takes, and whether that activity added or failed to add value to the customer. Writing code, writing tests, designing, working out clarifications of the requirements - these were customer-value-added activities. Waiting for a server to be deployed, waiting for three VPs to sign off on a design, etc. these were non-value-added activities. I like this kind of cycle-time measurement, because it forces the observer to be in the mind of the customer. If there's a business process which slows down the process, or, in lean terms, lengthens the cycle-time, it's an inefficiency and you try to find a way to remove it, circumvent it, etc.

At a fairly large financial service client, I saw a rather crazy thing occur. The coaches and suits were doing a value stream mapping. There were business activities whose performance served a business need, but not the needs of the customer. This might be a strategic steering committee meeting which a Team Lead might be required to attend, or a process step that existed to satisfy a regulatory requirement imposed on the business. These weren't really "customer value added" activities, but the coaches and business were unwilling to see them as non-value-added activities, or "waste". This led to an interesting compromise - the concept of "business value added" activities.
Now, I don't mind if there's a piece of waste in your cycle, and you acknowledge it, but then decide, for strategic trade-off reasons, to keep it. That's a sane business decision, even if it rankles my personal aesthetic. It is the prerogative of a company's decision makers to judge the interests of their customer against the interests of the organization and of the shareholders and come to whatever balance they feel best serves the principles and values and mission of their company. But by calling it "business value added" what they did, in effect, was move it out of non-customer-value-added column, which effectively stopped people from considering whether or not to reduce or eliminate it. It became synonymous with "customer value".
On the other hand, often when people use the term "business value" in the Agile community, they mean it as the customer value of a product feature, and are using it to help focus people's prioritization of work/features on the backlog (worklist for the uninitiated). And I get it. In that context, you need to have product managers prioritizing based on value, not cost, for reasons that Arlo Belshee can better explain. But the term business value gets mixed up in these various contexts, and I have heard consultants who, two years earlier would have called that committee review of design "waste" simply brush it off as "business value added" activity, and I think it's the sloppy language around BV and CV and NVA that is at the root of this phenomenon. In other words, hard nosed management consultants have stopped calling out the Emperor's nakedness. Since these external entities are the few empowered to call bullshit on a client, this means that less such is being called, to the detriment of our industry.
So yes, this is an argument about definitions and semantics. Yadda yadda yadda. But for my money, I want crisp meaning - especially if it allows the "cloak of truthiness" to descend and sow confusion about what's important. And if delighting your customers is critical to your long-term business survival, then anything not in that "value conversation" is waste (sorry, but it is - deal with it). You might have to live with some waste you can't get rid of yet, but you should never stop calling it like it is. Otherwise you begin to sink back into the very state from which you used value stream mapping to escape. And as far as I'm concerned, serving, nay, delighting the customer is the only way to be in business for the long haul.
Saturday, 20 June 2009
Make Fake/Stub objects simpler with proxies.
I recently wrote a convenience component. It's a Java dynamic proxy creator with a default handler that simply delegates any methods called on it to a provided delegate, throwing an UnsupportedOperationException if such a method isn't implemented. Why? Because I was sick of writing huge Fake implementations of medium-to-huge interfaces when I needed a fake, not a mock, and I was frustrated with using EasyMock as a convenience to create Fakes and Stubs. This delegator allowed me to implement only the parts of the API provided by the Interface, and just not bother with the rest. This was useful for such things as factories or other "lookup" components which I was going to feed (in my tests) from some static hash-map.
This gets back to my new motto: I hate boilerplate. If I have to implement every interface method in a fake object, then I'm going to go crazy implementing public String getFoo() { return null; } all over the place. Especially since that method will never get called in my test, and in fact if it does, I want it to fail noisily. So I could write public String getFoo() { throw UnsupportedOperationException("Test should not call this method"; }. That's great, but if I have to do that for a component that's got thirty methods, my test classes are going to be littered with this. Instead, I can do:
public class MyTestClass {
private final hMap<Long> BAR_CACHE;
@BeforeClass
public void classInit() {
BAR_CACHE = new HashMap<Long>();
BAR_CACHE.put(1, new Bar(1, true));
BAR_CACHE.put(2, new Bar(2, false));
BAR_CACHE.put(3, new Bar(3, true));
BAR_CACHE.put(4, new Bar(4, true));
}
@Test
public void testFooValidityCount() {
BarFactory fooDep = Delegator
.createProxy(BarFactory.class,new FooDelegate());
Foo foo = new Foo(fooDep);
foo.processBars();
assertEquals(3, foo.getCountOfValidBars());
}
... more test methods that need to look stuff up...
public static class FooDelegate {
public void init() { /* ignore */ }
public Bar getBarWithId(int id) { BAR_CACHE.get(id); }
}
}
If we assume that FooFactory is an insanely long interface, then this allows me to do a very clean Fake implementation with only a few bits of implementation. Otherwise, a FakeFooFactory could be longer than all the test code in this testing class. The other thing I like about this, is that - especially if you're testing code that uses dependencies you're not intimately familiar with, nor have access to the source, you can quickly implement an empty delegate and let the exceptions in the test guide you towards the leanest implementation. You'll get an exception any time your delegate is missing a method used by your System Under Test on your dependency. Handy.
Essentially, the Delegator is simply a pre-fab proxy InvocationHandler, with some reflection jazz in the invoke() method to lookup methods on the delegate, or throw... but it saves a bunch of extra boilerplate. I've had fake classes so large THEY needed tests. This is a much nicer approach for non-conversational dependencies (where mocks would be better). I tried to do this with EasyMock, but the implementations were really awkward due (ironically) to the fluent interface style. This is just a rare case where it's cleaner to just have a minimal implementation.
Unfortunately, the code I wrote is closed-source for my employer, but it's simple enough that everything I've done above should let you implement your own.
... and remember, kids... Mocks, Stubs, and Fakes are all Test Doubles, but they're all not the same thing.
Sunday, 12 April 2009
Re-thinking Object-Relational Mapping in a Distributed Key-Store world
JDO, JPA, Hibernate, Toplink, Cayenne, Enterprise Object Framework, etc., are workable object to datastore mapping mechanisms. However, you still have to optimize your approach to the underlying data system, which in most cases historically have been RDBMS. Hence these systems, their habits and idioms are all quite strongly tied to Object-Relational Mapping. Since Google's App-Engine released a Java app hosting service, with a datastore wrapped in JDO or JPA via DataNucleus this week, people have been playing, and the difficulties of these very habits have become clearer. It's easy, when using JDO or JPA with BigTable, to design as if we're mapping to an RDBMS, which a distributed column-oriented DBMS like BigTable is not. There are some good articles on the net about how to think about this sort of data store:
http://www.mibgames.co.uk/2008/04/15/google-appengine-bigtable-and-why-rdbms-mentality-is-harmful/
http://torrez.us/archives/2005/10/24/407/
http://highscalability.com/how-i-learned-stop-worrying-and-love-using-lot-disk-space-scale
I'm struggling with this myself, being a long-time (longer than most) user of Object-Relational mapping frameworks. For example, one cannot do things with BigTable like join across relationships to pre-fetch child object data - a common optimization. Keystores are bad at joins, because they're sparse and inconsistently shaped. The contents of each "row" may not have the same "columns" as each other, so building indexes to join against is difficult. We actually need to re-think normalization, because it's not the same kind of store at all.
Interestingly, OO and RDBMS actually DIDN'T have an impedance mis-match in one key area in that Entity-Relationship models bore a striking structural resemblance to Object-Composition or Class diagrams, and the two could be mapped. Both RDBMS schemata and Object Models were supposed to be somewhat normalized, except where they were explicitly de-normalized for performance reasons. With distributed key-stores, we're potentially better off storing duplicate objects, or possibly building massive numbers of crazy indices. At this point, I don't know what the right answer is, habit wise, and I work for the darned company that made this thing. It's a different paradigm, and optimizing for performance on a sparce key-store is a different skill and knack. And since we're mapping objects to it, we'll have to get that knack then work out what mapping habits might be appropriate to that different store.
Eventually we will work out the paradigms, with BigTable and its open-source cousins (HBase and HyperTable) creating more parallelism and horizontal scaling on a "cloud-y web" as I've seen it called. The forums - especially the google-appserver-java and other forums where objects and keystores have to meet - they will grow the skills and habits within the community. But we have to re-think it, lest we just turn around and say "that's crap" and throw the baby (performance/scaling) out with the bathwater (no joins/set-theory).
Saturday, 28 March 2009
Hiatus... should be over
So apologies that I haven't posted anything - I never intended to be away from the blog for this long, so soon after starting it. I have recently been in transition, and am now working for Google as an internal software development coach. Having disclosed that, I should mention that this blog isn't Google-specific, and mostly the things I'm speaking about here are things I have seen elsewhere, fodder from discussions with other Agile Community members and practitioners, and may include aspects from my current job, but not specifically, and usually blended in with the former. In other words, I won't be leaking Google's secrets on this page. ;)
Having said that, it's so far quite a fun place to work, with a wide variety of development cultures. There's a great spirit of exploration and experimentation in my new firm, which allows different teams to try different things. I leave it as an exercise for the reader to see how this can be challenging, organizationally, but it certainly allows G to innovate - as is nicely shown in the marketplace.
Anyway, I have four or so articles partially written from before that I hope to publish in the next couple of weeks. It's been an adjustment (haven't been an actual employee for quite some time now), but I'm starting to get a bit of a stable schedule so I can pay attention to this sort of thing (blogging).
Cheers,
Christian - the Geek in a Suit
Oh, P.S. I wore a suit to my first meeting with the team I'll be working with, and got soundly ribbed for it. lol. It's ok... I'm a big boy. I can take the heat. -cg.
Friday, 23 January 2009
Are mocks just stubs by another name, or something more?
[An older article that I published internally to a client community, reprinted with changes to remove client references]
An opinion that I've run into among some of my clients is that mock objects are just what we've always called stubs, and that it's an old approach. It's actually a quite common perspective - one I have held myself for part of my career. In fact early mock object approaches were very much like "fake implementations", but modern mocks are different. While they can both be considered "test doubles" or "test stand-ins", stubbed out interfaces or provide expected data for the system under test, mock objects provide behavioural expectation. These terminologies can be confusing, but we can sort that out.
jMock and EasyMock are two examples of mock object frameworks which allow for the specification of behaviour. jMock uses a domain specific language (DSL) such that you code the expectations in a fairly verbal syntax (often called a fluent interface). Something along the lines of
myMock.expects(methodCall(SOME_METHOD)
.which().returns(A_VALUE))
.then().expects(methodCall(OTHER_METHOD))
... which should be vaguely like english to the initiated. EasyMock, on the other hand, uses a "proxy/record/replay" approach instead, which some find easier. The point is that they both define a set of expected interactions, rather than a first this state, then the next state only.
Martin Fowler, around the middle of his article "Mocks Aren't Stubs", after describing fakes vs. mocks approaches in more detail. He starts to use a clarifying terminology which I like:
"In the two styles of testing I've shown above, the first case uses a real warehouse object and the second case uses a mock warehouse, which of course isn't a real warehouse object. Using mocks is one way to not use a real warehouse in the test, but there are other forms of unreal objects used in testing like this.
"The vocabulary for talking about this soon gets messy - all sorts of words are used: stub, mock, fake, dummy. For this article I'm going to follow the vocabulary of Gerard Meszaros's book. It's not what everyone uses, but I think it's a good vocabulary and since it's my essay I get to pick which words to use.
"Meszaros uses the term Test Double as the generic term for any kind of pretend object used in place of a real object for testing purposes. The name comes from the notion of a Stunt Double in movies. (One of his aims was to avoid using any name that was already widely used.) Meszaros then defined four particular kinds of double:
- Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists.
- Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production (an in memory database is a good example).
- Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'.
- Mocks are what we are talking about here: objects pre-programmed with expectations which form a specification of the calls they are expected to receive.
"Of these kinds of doubles, only mocks insist upon behavior verification. The other doubles can, and usually do, use state verification. Mocks actually do behave like other doubles during the exercise phase, as they need to make the SUT believe it's talking with its real collaborators - but mocks differ in the setup and the verification phases."
This use of behavioural expectations for "Test Double" objects is quite handy, especially in systems where you have components which make use of heavy service objects or (gasp) singletons which may do more than a simple "call-and-answer" method-call on the object. Deep call chains may require stronger behavioural testing. Being able to provide an object to the system under test that expects to be called a certain way and in a certain order can create a much more precise test, and reduce the amount of code you have to write in a "fake" object. Otherwise, to fully and precisely test, one ends up with severely large number of Test Dummies and ballooning "Fake Objects", which themselves could have error and often have to be tested. Having a system like jMock or EasyMock can reduce the size of your testing code, thus removing some code that could easily become out-of-sync with the system under test, and either introduce false-positive errors or become insufficient and therefore meaningless. So less code, less maintenance, less syncing problems, and the tests are able to be more precise at the same time.
Another approach is to radically re-factor your code into smaller components, each of which is substantially simpler to test. If a component does one thing and does it well, and components interact and collaborate, then you often can use simpler mock behaviours, or simple fakes without as much effort on the testing. Great resources for testable code are available here .
Mocks aren't always easily intuitive for someone used to building fakes (it wasn't for me, and it still occasionally trips me up), but once you're comfortable with the approach, it can be much crisper. This is especially true as people try to get better coverage in isolated unit tests, or who are trying to test-drive their software. The linked Fowler article is a good one, and certainly worth reading for those trying to figure out how to more meaningfully test components without having to start up external servers or simulators.
Friday, 2 January 2009
Why I hate the java.util collection library.
<rant>
It's very simple. While it was a vast improvement over Vector and Dictionary of their day, the Collections library as of Java 1.2 did what all new Java APIs from Sun seem to do... require lots of code to use simply and allow the user to do invalid things.
I won't spend a lot of time on the former, since it could be the topic of a whole other blog post, and I should preface all of this by saying that Java is my most proficient language. So this is not an anti-Java bigot speaking... just a frustrated user who wishes Sun and the community wouldn't keep heaping bad APIs on top of bad APIs.
Sorry... back to the point.
Immutability - it's all backwards... what's with that?
The big issue I have with the Collections API are about allowing the user to do wrong things. This amounts to Sun having inverted Mutability vs. Immutability in the class heirarchy. Immutability, in any language that wants to guarantee semantics, ease concurrency and resource contention, and otherwise clean things up should have immutability as a default. Something set shouldn't be volatile or mutable unless specified as such, and the semantics should enforce this. But with the collections API, we have immutability as an optional characteristic of Collections. To use a simplistic example, you can do this:
Collection c = new ArrayList(); c.add(foo); c.add(bar);
Collection has an add() method. This means that, by definition, Collection is mutable. "But wait!" you cry, you can obtain an immutable version of this collection by calling Collections.immutableCollection(c);. Sure. At which point you have something that conforms to the contract of Collection, but which may throw exceptions if part of that contract is relied upon. In other words, you should not have access to methods that allow you to break the contract. To allow this is to have written a bad contract with ambiguity. Now, to properly guard against the possibility of stray immutable collections, you may be forced to check immutability before executing the contract (the add() method) or you may have to guard against the exceptions with try-catch logic and exception handling. You can see some of this in the concurrent library's implementations of concurrent collections. It's not bad, but could be simpler with an immutable collection interface.
Additionally, consider how hard it is to create anonymous one-off implementations of Collection. You have to implement not only size, contains(), iterator(), but all the storage logic. If you're wrapping an existing data structure and merely wanted a read-only view on the structure, you are forced to implement all that extra API in your code purely to satisfy the optional contract provided in the Collection definition.
The point here is that an immutable Collection is a sub-set of the functionality of a MutableCollection. That should be obvious, but apparently wasn't to Sun. Consider had Sun used the model used in NeXTSTEP (and now Apple's Cocoa) APIs. Collection would have been defined as (simplified):
public interface Collection<T> extends Iterable<T> {
public Iterator<T> getIterator();
public int getSize();
public boolean isEmpty();
public boolean contains(T object);
public boolean containsAll(Collection<T> object);
public T[] toArray(T[]);
}
and
public interface MutableCollection<T> extends Collection<T> {
public boolean add(T object);
public boolean addAll(Collection<T> objects);
public boolean remove(T object);
public boolean removeAll(Collection<T> objects);
public boolean retainAll(Collection<T> objects);
public void clear();
}
This would, ultimately, mean that a Collection instance, typed as a Collection would not have any mutable methods available to invoke, let alone that would need guarding against stray immutable invocations. There would then be two strategy for guaranteeing immutability. One... cast the stupid thing as Collection, and onothing that has access to the cast can get at the MutableCollections methods (except by explicit reflection). Alternately, add a "getImmutableCopy()" method to the MutableCollection interface that creates a shallow copy that is NOT an implementor of MutableCollection... merely of Collection. Then you have a safe "snapshot" of the mutable object that can be freely passed around without worry that something else will modify it.
Ok, why is this such a big deal? It's about having code that means what it says. If I have to guess about the run-time state, or more concrete type of an instance to know if it's OK to invoke one of its methods or not, then I'm working with implicit contract, and that's murky territory. Java, by making an ImmutableCollection a special implementation of Collection, has inverted the hierarchy of contract, and exposed methods that are not truly available for all implementors. Optional interfaces are fine, but you don't expose the optional interface above where it's true. It's a basic piece of encapsulation that the Java folks just seemed to forget.
Now, this is a decade too late, this little rant. Truth is, I made it when I worked at Sun, but was quite the junior contracting peon, and had no real voice. Now, I have a blog, and am free to whine and be annoyed in public. :) But I hope to make a more general point here about contract. Optional contracts (APIs) need to be handled very carefully, and in a way such that an unfamiliar programmer can understand what you meant from how the contract reads. Look at your interfaces from the perspective that it should not offer what it (potentially) cannot satisfy. Polymorphism doesn't require "kitchen-sinkism" in an API. Just careful, thought-out layers.
The issues of testability also arise here, insofar as a class that has to implement optional APIs must, therefore, have more tests to satisfy what are, in essence, boilerplate code. If I made a quick-and-dirty implementation of Collection as a wrapper around an already existing, immutable data structure, then I have to implement all of those methods and test them, when in fact, half of them will throw an exception. This means (to me) that they probably shouldn't even exist. Code with a lot of boilerplate code (lots of extra getters and setters, or over-wrought interfaces) tend to be hard to test, and one of my big annoyances in life (these days) is testing boilerplate code. Ick.
</rant>

