One Language Resumes

Reviewing resumes as a manager, tech lead, or even just a developer is no one’s favorite activity. Resume’s are inefficient, misleading and so often boring. If you’re a prospective hire boring is bad.

A simple case is the standard corporate style J2EE developer resume. There are host of bullet points claiming skills I already expect them to have with 10+ years of development experience.

  • Spring
  • Hibernate
  • Tomcat, JBoss, Weblogic, or WebSphere
  • A smattering of design patterns from Singleton to Template Method
  • Javascript and some JQuery
  • Some selection of Java’s innumerable web frameworks.
  • Oracle/SQL Server/MySQL

At this point they’ve done nothing to distinguish themselves from the pile of already screened and rejected resumes beside them. You’ve developed on the JVM for 10+ years and you’ve never looked into alternative JVM languages. No Groovy, Scala, or Clojure. Not even some adventure off the JVM into Ruby, Go, Elixir, Python.

Java is by design a simple if verbose language with a huge amount of libraries and IDE tooling. It has never been the best solution for almost anything. Luckily there’s been a “Get out of Jail” free card option for a long time now. You can pull out a JVM language that better fits the problem space solve the problem more elegantly. All that and still produce compatible byte code and interop easily with existing Java libraries. It’s a career limiting to ignore that opportunity.

For the brave there’s always the option of leaving the JVM entirely and trying something like Ruby, Python or Go. It may require adjusting to life outside a familiar IDE or dealing with a new set of libraries, but it’s not a very difficult step to make.

So fair or not let me explain the conclusions I make when I see a J2EE developer resume with many years of experience and no mention of a second or third language experience:

  • Not very interested in learning in an engineering field that is constantly changing.
  • Did the majority of their learning by working on an existing Java codebase, and aren’t interested in spending any time coming up to speed on anything that isn’t currently required for the job.
  • Don’t enjoy development as a pursuit other than the fact that it’s fairly well compensated.
  • Are OK with doing things the hard way because they have one hammer in the toolbox.
  • Think they know a second language because they hack some javascript when required.
  • Copy and Paste is their most common approach to gaining code refuse.
  • Won’t be able to come up to speed quickly.
  • Are going to bomb out in a phone screen, so no point in scheduling one.

Cardboard Boxes and Modern Web Frameworks

My daughter spent an hour the other day cutting holes, drawing red bricks, and pasting grass along the bottom of a simple cardboard box. It’s a common story among parents, especially of small children that despite spending a lot of money on a gift, the kid ends up enjoying the box and ignoring the toy.

I’ve noticed a common quality of many newer web frameworks is that they provide you with a nice box to build from. Typically:

  • A default structure so you know where to find the models, views, controllers, extra libraries, etc.
  • A command line for generating stubs, running tests, and deploying.
  • A plugin system for easily adding functionality from swapping out javascript libraries to adding a security system.

Though there are probably others I’m aware of this model being used by Spring Roo, the Play Framework, Gryphon, Grails, and Rails. I don’t claim to be a historian on this, but Rails was my first experience with this style and I assume to be the originator of the approach.

The benefits of this approach are obvious from the first time you start off with a Hello World tutorial. For one you generally have a single download for the framework. After unpacking you’re able to use the command line to generate your Hello World controller, find the view in a predefined location, add the Hello World line, and fire up the application from the command line. Passing the 5 minute test is pretty important if you expect developers to give your framework a chance.

As a consultant working on numerous legacy code projects, there’s always the groan moment when you start looking into the code and you realize its non-obvious where to find things. I’ve seen libraries sprinkled about at random, key configuration files that were supposed to be moved into the users home directory, model classes mixed in with controllers, and a host of other inconsistencies. With a framework that reinforces the default structures it becomes easy to find things and much easier for plugin-authors to write plug-ins that make the framework much more valuable.

Finally, the plugin system is a critical part of new frameworks. Being able to add security framework on the fly, swap out your testing framework, or simply add in a nicer date library really starts to make things feel like magic. Indeed among these frameworks they are starting to push more and more modularity into the plugin systems to allow for the framework to evolve better over time.

I hope this trend continues in the world of web frameworks, as I really like a nice box to start a project from.

Mock With Spock

My default rule with mocking is to try to stick to stubs where possible. I don’t enjoy having to setup and verify interactions with mocks, but sometimes you have some code where that’s exactly what you need to do. I’ve used many frameworks in Java over the years from EasyMock to Mockito, but I was quite happy with how easy it was to do in Spock. I recently found myself having to build a test harness around some legacy code. The real world code was more involved, but it looked something like this:

1
2
3
4
5
6
7
8
9
10
11
    public void addDefaultQuestions(Category category) {
        if (categoryDao.getCategory(category.getId()).getQuestions().isEmpty()) {
            for (Question question : category.getQuestions()) {
                if (question.isDefaultQuestion()) {
                    categoryDao.addQuestion(question, true);
                } else {
                    categoryDao.addQuestion(question, false);
                }
            }
        }
    }

The method is taking a category, checking if any questions related to the category exist in the database and then saving all the questions with a valid flag set to true or false. Not unusual in a typical corporate application, but I want to test two things:

  • I can add new questions to the database with the proper valid flag.
  • If the database category already has some questions then do nothing.

After walking through the Spock mocking documentation I had a pretty good sense of the approach. In Spock it’s referred to as interactions, but it doesn’t follow the typical expect-run-verify pattern. You just verify what you need to if you need to. And given a choice I prefer not to have to verify the mock at all.

With this code I needed to mock the categoryDao which used straight JDBC and made calls to the real database. That meant I needed a way to verify that the questions were added correctly with calls to the categoryDao. Hence I needed the power of an actual mock and not just a stub class.

The first test would show that I could save new questions in a category to the database:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 def "should only insert new default questions"() {
    given:
    def question1 = new Question(defaultQuestion: true)
    def question2 = new Question(defaultQuestion: false)
    def category = new Category(questions: [question1, question2])

    CategoryDao dao = Mock()
    dao.getCategory(_) >> new Category()

    CategoryService service = new CategoryService()
    service.setCategoryDao(dao)

    when:
    service.addDefaultQuestions(category)

    then:
    1 * dao.addQuestion(_, true)
    1 * dao.addQuestion(_, false)

  }

So the steps are:

  1. Setup a Category object with two questions.
  2. Create a mock dao.
  3. Define a method and its default return value on the mock DAO.
    1. We define arguments to getCategory() with a wildcard operator the underscore standing in for an id.
    2. Then with the right shift operator (>>) we define that we will return a newly created Category object.
  4. Inject the mock into the service class we’re testing.
  5. Finally, we make verifications on the addQuestion() method by just stating the number of times we expect the method to be called with a given set of arguments, again reusing the wildcard underscore character.

You can even specify the particular order you expect by breaking the verifications into separate then: blocks. For this example it wouldn’t matter on the order, but in case it did the last when then block would change to:

1
2
3
4
5
6
7
8
    when:
    service.addDefaultQuestions(category)

    then:
    1 * dao.addQuestion(_, true)

    then:
    1 * dao.addQuestion(_, false)

And to round out testing the legacy Java code we need to test the negative example where it should do nothing if there are already questions in the database for the given category.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  def "should add no questions if questions are already in database"() {
    given:
    def question1 = new Question(defaultQuestion: true)
    def question2 = new Question(defaultQuestion: false)

    CategoryDao dao = Mock()
    dao.getCategory(_) >> new Category(questions: [question1])

    CategoryService service = new CategoryService()
    service.setCategoryDao(dao)

    when:
    service.addDefaultQuestions(new Category(questions: [question2]))

    then:
    0 * dao.addQuestion(_,_)

  }

So we can test for the negative case by just verifying that addQuestion was called zero times.

Grails Unit Testing: Mocking With MetaClass Stubs

On a recent project I ran into issues with testing controllers in Grails. Starting test first, I spent some early time figuring out how much support there was out of the box for unit testing Grails domain classes and controllers. I setup Spock as a plugin and plunged in. I was dealing with a legacy database which had 100% compound primary keys so many of the findBy type operations that are well supported for controller testing are of no help. Often I found I needed to mock a call to a find or findAll with HQL syntax or a criteria call. I knew metaClass mocking could work here, but I wanted to understand better how that would impact the rest of the code after I started replacing methods on the fly. Turns out Grails unit testing has built in support for cleaning up metaClass hacking after every test with the registerMetaClass() method in GrailsUnitTestCase. Mrhaki has a good post on this. Here’s an Spock example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import grails.plugin.spock.ControllerSpec


class ContractControllerSpec extends ControllerSpec {

  def setup() {
    registerMetaClass Contract
  }

 def "validateContract() returns true for an existing contract"() {
    given:
    mockDomain(Contract)
    def contract = new Contract(division: '33', unit: '99', contractNumber: 'C7777777').save(flush: true)
    controller.params.division = '33'
    controller.params.unit = '99'
    controller.params.contractNumber = 'C7777777'
    Contract.metaClass.static.find = { String query, Map namedArgs -> contract }

    when:
    controller.validateContract()

    then:
    "TRUE" == controller.response.contentAsString
  }

}

Grails has support for the same idea using mockFor(), but the syntax is much like EasyMock. The same test would look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import grails.plugin.spock.ControllerSpec


class ContractControllerSpec extends ControllerSpec {

 def "validateContract() returns true for an existing contract"() {
    given:
    mockDomain(Contract)
    def contract = new Contract(division: '33', unit: '99', contractNumber: 'C7777777').save(flush: true)
    controller.params.division = '33'
    controller.params.unit = '99'
    controller.params.contractNumber = 'C7777777'

  // EasyMock like syntax
  def mockContract = mockFor(Contract)
    mockContract.demand.static.find(0..5) { String query, Map namedArgs -> null }

    when:
    controller.validateContract()

    then:
    "TRUE" == controller.response.contentAsString
  }

}

For pure stubs I prefer the syntax of just using MetaClass. I often don’t care about validating the exact calls to the dependent class so I don’t really want a full mock. You don’t need a call to registerMetaClass() because mockFor() does this for you.

Spock Intro Tutorial

I gave a presentation on Spock a very nice BDD framework in Groovy a few months back to our Groovy Users Group in Sacramento. After using it on a real world Grails project the last few months it has grown on me to become my go to testing framework for Groovy/Grails or Java projects. A typical specification looks something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  def "a pager should calculate total pages, current page, and offset"() {
    when: "count, rows and page number"
    def pager = new Pager(count, rows, page)

    then: "should return correct total pages, the current page, and the offset"
    pager.totalPages == totalPages
    pager.currentPage == currentPage
    pager.offset == offset

    where: "you have a number of different scenarios"
    count | rows | page | totalPages | currentPage | offset
    100   | 10   |   1  |    10      |     1       |   0
    950   | 100  |   5  |    10      |     5       |   400
    72    | 20   |   3  |    4       |     3       |   40
  }

If that passed your 5 second test take a look at a fuller introductory tutorial I put together.

A Gentle Introduction to Spock

And if you want to try out executing real code the project has a nice browser based environment at Meet Spock.