Kotlin: Let’s Kill the Dreaded Java Null Pointer Exception

I’ve been spending some time with Kotlin this weekend. While I’m still getting to know Kotlin myself, it seems like a language that’s worth your time as an enterprise developer, particularly if you’ve got a legacy enterprise Java code base that you can’t realistically migrate en masse. Helpfully, Kotlin can run side by side with that legacy code and buy you modern language features incrementally (more on this later).

nullpointerexceptionKotlin has many benefits — from cleaner, more succinct enterprise code to modern, functional capabilities (especially with funKTionale). In this post, I want to drill in on a mundane issue, an issue near and dear to many enterprise Java developers: solving the dreaded null pointer exception problem, a problem also known as the “billion dollar mistake.”

First of all, Kotlin takes an oblique approach to the null pointer problem: it simply doesn’t allow accidental null pointers. For example, you can’t do the following because you’ll get a compile error (try it yourself):

If you must have a variable that might be null, you need to demarcate it as optional with the following (clean, IMO) syntax:

Notice the question mark? As you might have guessed, it denotes a variable that could be null, which is similar to (but so much more succinct than) Optional in Java 8+ (or similar Guava features).

Given that syntax, the Kotlin compiler is able to provide you substantial null safety. In the following example, it is always going to be safe to ask for the length of the string in name because the variable name can never be null — ever.

However in the next example, if you try to compile code that checks the length of the name string in example 2 without checking for null first, you’ll get an error.

Let’s look at a somewhat more elaborate example:

In this example, we have two classes where the Address of a Person could be null. We also have some instances of people, one of which can never be null and one that can. Again you can see the compiler won’t let you directly access a nullable variable null without handling the possibility of the null (with the “?” syntax above).

The Kotlin compiler is smart about null safety in other ways too:

As you can see, in the first example, the compiler detects when you access the address field within a null check, which is a pattern familiar to Java developers (maybe painfully familiar?), and lets you proceed.

The second example is a little more interesting and succinct. It shows how you can use the Kotlin elvis operator to safely access a variable that could be null. The first part will print the postal code if it’s non-null and the second, optional, operator (?:) will respond with a different string when address is null — no if statements required!

Also interesting to note in the examples are the string templates, which we will discuss in another post.

Hello, world with Kotlin and Maven

Kotlin seems like an interesting language for Java enterprise developers who want to introduce a new simpler language with modern functional features but who can’t realistically leave their legacy Java code behind. Also, Kotlin is super easy to read, learn, and code — IMO, anyway.

Since a lot of Java developers are used to Maven and the project object model (“POM”), I thought this post might be somewhat useful for you. First, we need is a simple Maven POM:

Next, create a file named hello.kt in src/main/kotlin. Write some Kotlin code and run it in your IDE:

JetBrains has a nice, succinct Maven guide for Kotlin with current version numbers. Also, this code is available on my Github account here: https://github.com/mrice/kotlin-maven-hello-world


Software Stranded Me in New England for Four Days

Craftsmanship in software matters to our lives more and more every day. I am reminded of that now that I am stuck in New England for four days because of a glitch with Southwest Air’s backend systems.

The only thing we seem to know about the root cause right now is that there was an issue with a “router,” but who knows what kind? Maybe a network router or maybe it was an API router. Maybe the hardware burned up, but more likely it was some kind of failure deep in the software stack of the device. Worse, for some reason the fail over systems failed too. Southwest reportedly had to “reboot everything” to get the whole system up and running again.

How ironic it was that I was reading about SOLID principles (an important aspect of craftsmanship) in functional programming in the Providence airport as all hell was breaking loose around me. Little by little my phone kept buzzing, letting me know I was getting increasingly delayed and then finally cancelled. The system failure was so bad that they can’t get me on a return flight until four days later.

Only a few years ago Southwest was able to issue paper boarding tickets and recover with old fashioned manual systems. These days, the software is so deeply intertwined that the failure was more massive (almost 1,200 flights cancelled). There was no way to recover.

Getting it right in software is more important than ever. Craftsmanship is one way to do it.

Leading Your Team to Craftsmanship — by Example! (No. 9)

Hey Software Crafter,

Hope you had a good Fourth of July!

Today I was starting some new consultants at my biggest client. These are junior consultants dropped into roles where they have to both excel technically and also exert quite a bit of influence with the client’s engineering team. As if that isn’t hard enough, they have to do this with absolutely no authority; it’s all non-positional leadership they have to demonstrate. I’m here to help them, but such can be the life of a junior consultant.

And their experience made me think about you. I suspect you are either discovering craftsmanship and/or you want to bring more professionalism to your team. Unfortunately, you don’t have the formal authority to mandate the change (both in practices and attitudes) you’d like to see.

Still, getting your team to follow you to a better place is a classic “leadership without authority” opportunity, just like the one my consultants are contemplating in their hotel rooms tonight. Here’s the opportunity: if you can get good at this, you can make amazing things happen with both your code base and your career far, far beyond your individual contributions.

But I’ll warn you, as I warned my consultants this morning, it’s not easy. Indeed, it’s the kind of choice that can lead to frustration, disaffection, and withdrawal if you go about it the wrong way.

For example, what if you read Clean Code over the holiday weekend (you did too, right??), you couldn’t wait for Tuesday to come, you can’t wait to refactor, and you got fueled up on Philz on the way in this morning. You burst into the office and announce on Slack, “Hey folks!! I’m renaming all our variables!!!” I already know the response you’re going to get — I’ve seen it.

It’s easy to get transported to a new mental place by an influential book like Clean Code, but most of your coworkers are probably still in the same mental place they were in last Friday afternoon (or even a little foggier than you left them after the Fourth of July weekend). They aren’t there with you and your over-caffeinated, evangelized self. Most coders are a little skeptical of evangelists. Which stings a bit and could leave you cynically thinking all the puppies and unicorns must be on the other side of some other rainbow with some other team.

So here’s an idea to try before brushing up your resume: lead by example. In The Software Craftsman, Sandro Mancuso says, “When it comes to driving technical changes, especially if the change is about attitude and practices like TDD, nothing will help you more than the ability to lead by example.” He’s right. I’ve seen it. I learned TDD by chance years ago when one of my peers just grabbed a couple of us out of a hallway and said something like, “hey I want to show you how I do TDD.” While I didn’t start doing it consistently right away, as others starting doing more of it, we all started doing more, and I saw the value.

If he hadn’t done that one act of leading by example, I wouldn’t be writing this email today.

(By the way, this post originally appeared as a letter to the LA Software Craftsmanship community. Consider joining us in LA or Phoenix.)

Want to be a Leader? Remember This: Insight < Outsight

“Most of the good things that ever happened to me – both professionally and personally – happened after I finally took myself out of my comfort zone,” I found myself saying more than once in Silicon Valley last week. Sounds inspirational, but I’m a lousy Tony Robbins imitation.

I lack Tony Robbin’s fire but the getting-out-of-your-comfort-zone-to-grow is one of the few principles I know to be absolutely true. We can discuss other things, but this is not open to debate. If you stay in your comfort zone, your world and your opportunities will shrink. Period. Full stop. End of discussion.

So let’s talk about comfort zones. My world, my social network is limited to software engineers and front-line engineering managers; so if you’re reading this post you’re almost certainly smart. You’re smart, and you’re surviving or thriving in the tech business. Your comfort zone is being as smart as you can be.

Smart people usually think before they act. This is the trait that got us where we are, so we think a lot. A L-O-T. Then we act a little. Then shoegaze, navel gaze, talk to some other engineers, think some more, then act a little more. Then reflect on the experience. This is where we’re comfortable. But it’s not an evil pattern. Many of my most effective, thoughtful, and conscientious consultants do this today too. In fact, I believe that thoughtfulness is absolutely key to developing high quality code and reliable systems. And it’s comfortable for us.

rsz_10953_500Here’s the problem for your career, however: you can’t think your way into leadership. Only stretching to do leadership work will turn you into a leader, which obliterates your comfort zone. For a software engineer who wants to be a manager or lead architect it might mean speaking up even when you don’t have all the facts, setting up code reviews and embracing the difficulties of those conversations, demoing a prototype despite the ambiguity and political issues, reaching out to authority figures, and/or a million other uncomfortable possibilities.

Put simply, you have to take a position that takes you outside your comfort zone. Notice how the loudmouths on the team tend to progress faster than the quieter, more thoughtful folks (up to a point)? Painful (and it is very uncomfortable, bordering on painful sometimes) as it is, humans only truly evolve from the outside in, not the inside out.

It’s this very “outsight” as INSEAD professor Herminia Ibarra calls it, the outside-in, that makes the difference. It molds leaders. So take yourself out of your comfort zone. For more on this, read Ibarra’s book, Act Like a Leader, Think Like a Leader.

Act first. Think later.

How-to: An Embedded jBPM hello, world example

Ok, I admit it. BPM is not the hottest of hot trends right at the moment. But it still has a place. For example, BPM is rock solid at collaboratively modeling business processes with diagrams and orchestrating enterprise services — especially microservices. In fact, BPM might let you keep your microservices finely grained, as they should be, and avoid too many composite microservices.

But what if you don’t want to implement an entire BPM server and suite? Instead, you want to flip it around (as I argued for in mode 3 of my draft whitepaper on the same subject). You want to expose a service that embeds the workflow execution engine. If this is what you’re thinking about doing, then I think this is the hello, world example you’ve been Googling for.

Model your hello, world “business process”

I did this TDD, but let’s start our discussion with a super simple business process model. The workflow it describes accepts some initial parameters and then calculates a new string saying “Hello ____.” That is, the example sets a process variable as input — in BPM-speak — and then reads a different process variable to use as output.


Above you see my BPMN 2.0 diagram really is simple: it’s comprised of a start event, an end event, and a script task reading the input process variable string (“name”) and setting a new process variable (“welcomeText”) to be consumed later.

First, I defined an input process variable as a data element in the properties window of the overall BPM2 process.


One thing I should mention is that the tooling didn’t let me actually specify the string datatype for the incoming type. I had to manually edit the XML file (which is on my Github repo below), but I think it’s just that I’m a little new to the tooling — not that it’s impossible.

Next, I defined the following script task, which reads the process variable named “name.”



I saved the file as say_hello.bpmn in my Maven project’s resources directory.

Now embed the jBPM execution engine

Remember, I don’t want to deploy the BPMN file into a standalone server. I want to flip it around and embed the server. We can do that with just a few lines of Java code. Before we get too far into this, the JBoss documentation says that my approach is “not recommended for real application development but more for try outs.” Instead, they recommend using the RuntimeEngine to give you finer-grained control over your execution. For now, I’ll leave it to you to explore the distinction.

Under this scenario, we just need to create an object that has access to the BPM execution engine and then create a session from that engine. Specifically, the first step is to set up our KieBase, which has the execution engine inside it, and feed it the BPM workflow (documented above). Then we get a reference to a KieSession. KieBase is a relatively heavyweight operation but creating new sessions is pretty lightweight.

Next we’re going to set our process variables on the session and start the workflow (while holding a reference to the ProcessInstance).

Notice the typecast in there? It’s from the kie-based ProcessInstance to the jBPM process instance from the org.jbpm package, which is useful in later steps.

Finally, we extract the “output” of the BPM process by getting access to the workflow’s process variables after the workflow completes as follows:

I don’t like all the typecasts, but this is my first cut. It works, and it’s pretty fast. Comments? All the code is on Github here.

warningAn important caution about this approach: One initial comment you may have is that running a process in this way will cause a lot of problems if you’re trying to run a long-running process or take advantage of the full suite of options in BPMN. I know, I know. But I’m imagining a microservices-like use case that’s pretty limited. By this I mean you’re going to run mostly quick, short orchestrations (likely of other microservices) and you don’t need to incorporate human interaction in the process nor do you need to even store the state of the process as it runs. In short, you’re getting a very limited suite of BPM services, but that’s ok for this use case.

Craftsmanship, flow, and engagement – Software Craftsmanship Letter No. 6

What if you woke up in the morning actually looking forward to your day job? Maybe it’s because of the people you work with; uncommon, but it does happen.

Or what if you love coming to work because you know you’re going to be tightly focused on your code, and external things like tooling, crappy dependencies, or lame-ass processes won’t get in your way. Maybe the other engineers care as much as you do about the quality of the code base. Maybe you work with a supportive group of engineers who don’t make you self-conscious about every pull request. Maybe your manager works hard to give you some time to focus on quality, not just deadlines. Maybe the management and your team give you the autonomy to try things and they support you when you make mistakes or fail.

Personally, I have to use my imagination because I’ve never had a working experience like what I just described. Almost all my days were varying orders of magnitude away from that, probably your days are too. Now that I have more ability to change the environment, I actually do enjoy coming in, and I still love writing code. But yeah… there were a lot of days I didn’t feel much like going to work no so long ago.

That “what if” world I’m imagining comes from flow theory, and I think it’s how a software craftsman would ideally design his or her working environment. That matters because flow theory leads directly to high levels of engineer engagement. And it just so happens that flow, craftsmanship, and high levels of engagement should matter to your boss because it means both low turnover and high productivity.

“How far do you want to fall?” Git rebase

Think about the last time you were mountain climbing. You clip your carabiner as you go depending on how far you’re willing to let yourself fall if you slip. So how far apart do you set them if no one is watching? What if you friends are watching? A little farther?

That’s the analogy I got from Rob Richardson the other day at a Meetup on advanced git topics, and it perfectly captured the value of git’s rebase to me.

If you’re not familiar with git rebase, it’s basically a way of revising your source code commit history before you publish it to a place like Github. With it, you can make lots and lots of small local commits — even if your code sucks in any given commit — and then remove or compress certain unsightly commits when you publish.

For an example, you’re working locally on your repo. You’ve committed some changes that worked, some didn’t. Your revision history looks like this:


But when publishing to Github (or behind your firewall to your snarky coworkers), you want to make your revision history cleaner so that the world doesn’t have to see the commits that didn’t work out. Enter git rebase (interactive):


And suddenly (magically, even), those two unfortunate commits disappear when you publish. Snarky coworkers silenced.


Honestly, having this feature might actually change the way I think about coding a bit. All of us have a little anxiety about checking in crappy code, so being able to commit a rosier picture than you had locally takes a little pressure off.

And speaking of anxiety, git is from Linux Torvalds and I presume the kernel community uses it heavily. If I were contributing to the kernel, personally I’d have a ton of anxiety about my revision history. I wonder if that was the inspiration for the feature…?

(For a much better description of how to use git rebase, use this Atlassian tutorial.)


A proposal for immutable Docker containers to run the Drools engine

People don’t talk enough about rules engines, but they hold a lot of promise. Even if you’re not a financial institution or an insurance company, engineers and architects should consider them whenever they find the team writing too many algorithms with too many nested if/then conditionals.

Red Hat has an open source rules engine you’ve probably heard of — Drools. Drools is solid technology but there are many ways the core execution runtime gets bundled in various other products, so that flexibility and adaptability make it appear complex at first glance. I want to propose yet another open source permutation for you to consider, but I think it’s a lightweight one.

Let’s say your rules use cases are simple and you’ve got a small, engineering-driven environment

Let’s say you’ve got just a few rules you ever need to execute. The rules, which are written in DRL, are authored and maintained by the engineers, not business people. Given this, you believe all you really need is the open source Drools execution engine. But, you’ve got a bursty environment where you can suddenly have a lot of data show up that you want the rules engine to operate on. So you don’t want to run it embedded in your other code.

For this, may I propose immutable Docker containers running the Drools execution engine and either a REST-based or JMS-based messaging microservices entry point? Something like what Mauricio Salatino proposed.

Immutability, Docker, Drools, and (maybe even) Kubernetes might simplify things for you

Sure, my proposal means you’d lose a ton of the services that the Drools and jBPM team have worked hard to produce, but you’d buy some simplicity and possibly a different kind of scalability.

The developer’s architecture would be simple. The workflow for the developer would be as easy as modifying the DRL files, unit testing, and then committing. Ideally, you’d have Jenkins or Bamboo building the code, running integration and automated acceptance testing (may I suggest Cucumber for Drools??), and then build and push the Docker image.

The runtime architecture would be simple too. The server would pull the latest Docker-based runtime. The runtime would operate on the facts it receives from the microservice entry point. The DRL would be baked right into the container. Immutability.

And if you want to get scalable, you could use Kubernetes to orchestrate it all. (Incidentally, if this all sounds like OpenShift to you, you’d be right.)

To those on the leading edge, this proposal won’t shock you. But I thought it was worth writing up since I didn’t see anything else like it.

Engineering Managers Are Leading a Revolution in Management. Let’s Have a Survey About It.

Between agile and holacracy, both the demands on management and the role of management are evolving rapidly. And as you know, innovation in software isn’t limited to technology. Software engineering management seems to be leading the path into this new, uncharted, and promising territory.

Even a decade ago, most software development managers (that’s what we were called back then, right?) were heavily focused on task management, project management, and process generally. Agile encroached on management’s turf, handing a big part of our jobs to specialized scrum masters. Holacracy is more oblique; it simply exiled managers. Our work has fundamentally changed — maybe for the better, maybe for the worse, time will tell.

Given all this, you probably don’t know enough about what other software engineering managers or engineering directors are doing out there right now. Oh sure, you know what other managers at your company are doing – but how does your work compare to the rest of the industry? I’ll speak first: I don’t know.

So let’s figure this out together. I finally got around to putting together a survey I’ve been thinking about for months now — a survey for engineering directors, software engineering managers, or anyone whose job description includes a requirement to herd nerds. I think it will help establish a baseline, without diving into anything proprietary or sensitive to your company.

I know you’re busy, but can you share five to ten minutes to respond to it? Maybe while you’re waiting in line at Philz? Thanks in advance!

Here’s your link: http://goo.gl/forms/Dq0PZgkq97.