Inverse Conway's law

Inverse Conway's law

Today I got to present at Devoxx Poland on being agile and managing your architecture.

One of the points I made during the talk had to do with Conway’s Law. For those unfamiliar with it, here it is:

organizations which design systems … are constrained to produce designs which are copies of the communication structures of these organizations M. Conway

This basically means that the code you create is likely to reflect the way the people and teams in your company communicate. For example, banks are usually pretty strict and have a tendency to document things. The code written at banks in turn have the tendency to use SOAP for example, verbose and strict.

The project I’m currently working on has a very agile mindset, we change a lot and have open communication. This reflects in our codebase as well, all the code is easy to understand and easy to change (thankfully!).

But lately we’ve started to move away from our old monolith and we’ve began cutting it up into microservices. That’s when I noticed something odd, which I call the Inverse Conway’s Law (maybe it is Roy’s Law?):

organisations which radically change their system design should expect changes in communication structure Roy van Rijn

What does this mean?

We’ve started to move towards a microservice environment, where each team has a responsibility over a couple of services. They’ve developed it and they own it. This ownership completely changed the culture in our team. Up to now if the monolithic backend was broken or offline, everyone was hurting and everyone wanted to fix this as soon as possible. With microservices, this is gone. The first thing we now do is check which microservice failed. If it isn’t theirs, it is not their problem, it’s someone elses problem now!

This is just one example on how changing the design of our system changed the culture and team dynamic. It is one thing that sounds logical when you think about it, but I didn’t expect this before we started the transition.


JavaOne Rock Star 2016

JavaOne Rock Star 2016

Today I got an email with the subject: “Congratulations JavaOne 2016 Rock Star!”. It turns out the JavaOne 2016 Ignite session was voted enough to receive a JavaOne Rock Star Award!

I was so excited, elated even!

Rocking that talk

But I quickly found out that the JavaOne Rock Star lifestyle isn’t as much fun as it sounds.

  • Being 3 hours late for a meeting, even a Rock Star can’t do that.
  • Peeing in the corner of your office while holding a bottle of Jack Daniels, still not appreciated.
  • Wearing ripped jeans, a leather jacket and other than that just chest hair, is considered too casual.
  • The groupies? It is like answering random Stack Overflow questions, non-stop, face to face.
  • After each coding session, smashing your MacBook on the floor… quickly becomes expensive.

Drunk Wombat holding bottle of Jack Daniels


Vikipedia: A Java YouTube bot

Vikipedia: A Java YouTube bot

YouTube, the future of television. I’ve got a lot of subscriptions to YouTube channels that deliver quality content, and those shows are ‘cast’ (using my Chromecast) to my TV. Another thing I often do is look up information, for example I watch talks from programming conferences like Devoxx using YouTube.

This gave me an idea, what if I can take some free information (like Wikipedia, all creative commons) and use that to create content for YouTube? Maybe I’ll even get some views :-)

So this is what I’ve come up with, the following video is generated completely automatically:

Step 1: Wikipedia API

The first step in creating these videos was to get some actual freely available content. For this I chose to use Wikipedia. This can be accessed using JSON/REST, and to quickly hack this into place I decided to use a framework called ‘Unirest’. This makes the while prototype easy:

// API URI for the English Wikipedia
private final String ENGLISH_WIKIPEDIA = "https://en.wikipedia.org/w/api.php";

// Using a 'search query', name of the page, retrieve the content:
private Optional<String> getPageContent(final String query) throws UnirestException {
    //Example URI created for query 'Stack Overflow': https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&titles=Stack%20Overflow&redirects=true
    HttpResponse<JsonNode> response = Unirest.get(ENGLISH_WIKIPEDIA)
            .queryString("format", "json")
            .queryString("action", "query")
            .queryString("prop", "extracts")
            .queryString("titles", query)
            .queryString("redirects", "true")
            .asJson();

    JSONObject pagesObject = response
            .getBody()
            .getObject()
            .getJSONObject("query")
            .getJSONObject("pages");
    if(pagesObject.keys().hasNext()) {
        String pageKey = pagesObject.keys().next();
        String htmlContent = pagesObject.getJSONObject(pageKey).getString("extract");
        return Optional.of(htmlContent);
    }
    return Optional.empty();
}

The resulting JSON (see this example) contains the Wikipedia page in simple processed HTML. From this HTML I used a library called ‘Jsoup’ to extract the plain text. The first alinea of text contains the introduction of the topic, this is what I’ve decided to use as content for the video. Initially I had all the content of the page in the videos, but they quickly turned out to be 30+ minutes long and very boring.

This is the code I used to go from HTML to the first alinea of text:

/**
 * Clean the HTML, get inner text of first alinea and break into sentences.
 * @param htmlContent
 * @return
 */
private List<String> cleanAndBreakIntoSentences(final String htmlContent) {
    Document document = Jsoup.parse(htmlContent);

    List<String> fullText = new ArrayList<>();
    Elements elements = document.body().children();

    Iterator<Element> iterator = elements.iterator();
    while(iterator.hasNext()) {
        Element elem = iterator.next();

        // All the text is contained in paragraph elements:
        if(elem.is("p")) {

            String source = elem.text();

            // Break the text into sentences using the smart JDK 'BreakIterator':
            BreakIterator breakIterator = BreakIterator.getSentenceInstance(Locale.US);
            breakIterator.setText(source);
            int start = breakIterator.first();
            for (int end = breakIterator.next(); end != BreakIterator.DONE; start = end, end = breakIterator.next()) {
                fullText.add(source.substring(start,end));
            }
        }
        // If we reach a header, stop processing, we only need the first section/alinea:
        if(elem.is("h2")) {
            // We break on the first (sub-) title:
            break;
        }
    }
    return fullText;
}

Step 2: Stunning visuals with Java 2D

We have some text, now how do we turn this into a video? We need visuals! I decided to cut the content into seperate lines, and for each line I have a single ‘slide’. This is an (buffered) image created using Java’s 2D API and saved to file.

/**
 * For each sentence, create a buffered image and paint some text on this.
 * We need the text to be 'wrapped', for this I repurpose a JTextArea, on a JPanel.
 * 
 * Also increase the font size so the text fits on the screen.
 */
public void paintText(Graphics2D g2, String text) {
    JPanel panel = new JPanel();
    panel.setOpaque(true);
    panel.setSize(new Dimension(1920, 1080));
    panel.setVisible(true);

    JTextArea area = new JTextArea();
    area.setSize(new Dimension(1920,1080));
    area.setFocusable(false);
    area.setBorder(BorderFactory.createEmptyBorder(BORDER_SIZE, BORDER_SIZE, BORDER_SIZE, BORDER_SIZE));
    area.setWrapStyleWord(true);
    area.setLineWrap(true);
    area.setText(text);
    area.setOpaque(true);

    int fontSize = 10;
    // Increase the font size as long as it fits on screen (and don't go bigger than 100, looks ugly):
    while(area.getPreferredScrollableViewportSize().getHeight() < 1080 && fontSize <= 100) {
        fontSize += 10;
        area.setFont(new Font("Futura", Font.PLAIN, fontSize));
    }
    area.setFont(new Font("Futura", Font.PLAIN, fontSize - 10));
    panel.add(area);

    // Print this panel on the Graphics2D object (which is a BufferedImage)
    panel.printAll(g2);
}

Step 3: Text-To-Speech

Instead of using a Java Text-To-Speech (TTS) library, which aren’t very clear or good, I decided to use the build-in OS/X command ‘say’. On the command line you can execute: say Hello world!

The ‘say’ command supports different voices and also has the ability to store the output in a file. Which is perfect for us!

    // Execute the say command with a given filename, voice and sentence to speak:
    final Process p = Runtime.getRuntime().exec("say -o " + filename + " -v " + voice + " -r 210 " + line + "");

    new Thread(() -> {
        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line1 = null;

        try {
            while ((line1 = input.readLine()) != null)
                System.out.println(line1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }).start();

    // Wait for the say-command to finish
    p.waitFor();

Step 4: Putting it all together

What do we have now? A list of sentences from Wikipedia, for each sentence we have an image and we have an audio snippet created with TTS. Now it is time to put everything together and create a video. The easiest way to do this is to use ffmpeg, a powerful command line video tool. To make this easier I created a small method ‘executeCommandLine’ which does the same thing as the snippet with ‘Runtime.getRuntime().exec’ shown above.

Combine the image (png file) and the TTS audio (mp4 file) into a series of MPG files:

    for(VikipediaSentence sentence : sentences) {
        String filename = sentence.getFilename();
        //Combine audio and image into a short video:
        executeCommandLine("ffmpeg -loop 1 -y -i " + filename + ".png -i " + filename + ".mp4 -tune stillimage -shortest " + filename + ".mpg");
    }

We now have a series of small MPG files. They need to be combined into a single video. For this we need a text file which contains a list of all the MPG files. This is stored on disc and next we execute the following command:

//merge all:
executeCommandLine("ffmpeg -f concat -safe 0 -i output/snippet_list.txt -c copy output/output.mpg");

Next we convert the video from one large MPG to MP4 file (which is a nicer, compressed format):

//convert to mp4:
executeCommandLine("ffmpeg -i output/output.mpg -c:v libx264 -c:a aac -strict experimental -b:a 192k -pix_fmt yuv420p -shortest output/output.mp4");

And to add a little more ‘production value’ I’ve gone online and found some soothing (free, creative commons) background music. This music is looped into a large audio file of 50 minutes (enough for all videos). Again using ffmpeg the audio is mixed in:

// add background music:
executeCommandLine("ffmpeg -i output/output.mp4 -i input/background_loop.mp3 -filter_complex amerge -c:v copy -c:a aac -strict experimental output/finaloutput.mp4");

There it is, we have a complete video with text audio, text visuals and background music! Only one thing left to do, uploading to YouTube!

Step 5: Uploading everything to YouTube

To automate the process of uploading, I first needed a place to put the videos, so I created a new YouTube channel named: Vikipedia

Next we can use the Google YouTube Data API. It turns out this is very easy and well documented. I don’t even need to share the code I wrote here because I used the example from Google’s website itself! Check out this amazing documentation. Very detailed and does exactly what I needed it to do.

The example code takes a video file and uploads it. The only things I changed were setting the correct description, I was ready to generate all the content!

Not implemented (yet?)

Things I wanted to implement (but didn’t and probably never will):

  • Add a little color to the videos (black and white is boring)
  • Add waveform from ffmpeg (just to keep it visually interesing)
  • Download (did this) and use (didn’t do this) the images from the Wikipedia page and add those to the video

Final thoughts

  • Yes, it is pretty easy to hack together a bot to create YouTube videos.
  • No, the quality isn’t that good… yet?
  • Yes, it can be made in a single afternoon!
  • No, I’m not going to automate the spidering of Wikipedia and upload a million videos… (but I could easily do that!)

Up to now all the videos created are based on a small list of ‘hot topics’ I found on Wikipedia and Twitter. I don’t want to automate the entire process and flood YouTube, the content just isn’t good enough for that. But it was a fun project for a lazy afternoon! I’ve learned a lot of new tricks, maybe you can benefit from that as well.

The next thing I want to do with the 400+ YouTube videos I’ve generated is to see how (and if) people are going to watch them. Do they show up in the search results? Which topics are searched and watched? Maybe more on that in a future post!

Do you have any good ideas on how to generate videos, let me know in the comments! I’ve created a bot that generates music some years, maybe I should improve that bot to upload its own YouTube music videos? ;-)


Three new JEPs

Three new JEPs

This morning Mark Reinhold submitted three brand new JEPs (JDK Enhancement Proposal).

  • JEP 300: Augment Use-Site Variance with Declaration-Site Defaults
  • JEP 301: Enhanced Enums
  • JEP 302: Lambda Leftovers

These proposals are enhancements to the JDK (Java Development Kit) and OpenJDK. A long term roadmap for the JDK projects, a look into what the future of Java might hold.

Let’s dive right in and take a quick look on what these proposals actually are!

JEP 300: Augment Use-Site Variance with Declaration-Site Defaults

When you currently use Java Generics you probably already know about wildcards. It is possible to set lower and upper bounds to generics using the keywords ? extends and ? super. There are two parts to using wildcards, declaration side and use side, this JEP focusses mainly on making the use side easier and more powerful.

Declaration side

It is possible to set a bound with a wildcard on the declaration side:

public class Shelter<X extends Animal> {
	...
}

In this example we’ve declared that the Shelter has to contain Animals. It is possible to create an Shelter<Cat> or Shelter<Dog> now, but not Shelter<Bike>.

Use side

The second way to use wildcards is on the use side. There we can speak of so called in and out-variable wildcards.

The following code uses the ‘extends’ keyword to create the in-variable:

    List<Animal> animals = new ArrayList<>();

    // Using extends we create an 'in' variable:
    List<? extends Animal> inAnimals = animals;

    // From the inAnimals we can read: Animal (not subclasses)
    Animal animal = inAnimals.get(0); // <- reading Animal is fine
    Cat cat = inAnimals.get(0); // <- compile error, we can't read Cat

    // We can write: nothing (!) making it almost read-only
    inAnimals.add(new Animal()); // <- compile error

There is also the ‘super’ keyword (not very common) to create an out-variable use side:

    List<Animal> animals = new ArrayList<>();

    // Using super we create an 'out' variable, setting an upper bound:
    List<? super Cat> outAnimals = animals;

    // From the outAnimals we can read: object (no superclasses!)
    Cat cat = outAnimals.get(0); // <- compile error, illegal
    Object o = outAnimals.get(0); // <- we can only read object

    // On the write side, we've set a bound to Cat:
    outAnimals.add(new Cat()); // <- correct!
    outAnimals.add(new Object()); // <- compile error
    outAnimals.add(new Animal()); // <- compile error

So what is JEP 300?

The motivation of the JEP states:

Since invariant uses of these type arguments are less flexible than their wildcard equivalents, while providing no extra power, a reasonable practice is to always use a wildcard when mentioning the type.

It is almost always more powerful and equivalent to use wildcards on the use side. The problem is that this is verbose and adds a lot of noise to your code. The proposal wants to make it possible to declare (at the declaration side) what the default wildcard strategy should be.

For example look at the following code:

    interface Function<contravariant T, covariant R> {
        R apply(T arg);
    
    }
    // other possible syntaxes are Function<-T, +R> or Function<in T, out R>

The compiler can now automatically treat every use of the type e.g., Function<String, Number> as if it had wildcards Function<? super String, ? extends Number>.

On the use side the proposal says:

Rather than making changes to subtyping, we preprocess the source code so that types like Function<String, Number> are implicitly expanded to Function<? super String, ? extends Number>.

This should make it more powerful and just as readable to using wildcards by default without even noticing them.

JEP 301: Enhanced Enums

The next proposal Mark has submitted is about using Enums with Generics. Look at the following example:

enum Pet {

    BELLA(new Dog("Bella")),
    BUDDY(new Dog("Buddy")),
    TIGGER(new Cat("Tigger"));

    Animal animal;

    Pet(Animal animal) {
        this.animal = animal;
    }

    public Animal get() {
        return animal;
    }
}

We have an enum with three pets. These pets have an instance of an animal inside them. And we have a way of retrieving them.

System.out.println( Pet.BELLA.get().getName() ); // prints: "Bella"

But one thing we can’t do it call the method “.bark()” on BELLA, because we don’t know this is a Dog.

The proposal JEP 301 wants to make it possible to correlate a specific type to an enum constant:

enum Pet<A extends Animal> {

    BELLA<Dog>(new Dog("Bella")),
    BUDDY<Dog>(new Dog("Buddy")),
    TIGGER<Cat>(new Cat("Tigger"));

    A animal;

    Pet(A animal) {
        this.animal = animal;
    }

    public A get() {
        return animal;
    }
}

Having coupled the Dog type to enum BELLA it should now we possible to call:

Pet.BELLA.get().bark(); // WOOF!
Pet.TIGGER.get().purr(); // Purrrrrrrrr.....

JEP 302: Lambda Leftovers

This is turning out to be a rather long blogpost but we’ve reached the final proposed JEP of the day: Lambda Leftovers

Accidental ambiguities

One of the problems people are having with the lambdas at the moment, and this JEP wants to improve, are accidental ambiguities.

For example:

private void apply(Predicate<Animal> filter) {
   ...
}

private void apply(Function<Animal, String> function) {
   ...
}

apply(input -> false); // <- compile error

/**
 * Ambiguous method call. Both:
 * apply (Predicate<Animal>)        in classname and
 * apply (Function<Animal, String>) in classname match
 */
    

Why are we having this problem? Both methods are possible candidates of the lambda. If we look further and see the return type ‘boolean’ it should be clear we wanted to call the Predicate method and not the Function (which should return a String). Right now this doesn’t work, but it is something the compiler could figure out for us.

Underscores

Up to Java 8 it was perfectly acceptable to use the underscore character ‘_’ as a variable name. But this has been changed, all leading up to JEP 302. In most languages with lambda’s it is possible to denote certain inputs as unused. This is done using the underscore. In Java this causes problems because it is right now a valid variable name.

Starting with Java 8 the use of an underscore as lambda argument caused a warning and from Java 9 the use of an underscore became an error. This allows future Java versions beyond 9 to be able to use the underscore for other purposes. And one of those purposes is to bring it back as a default variable name. Not causing collisions if used multiple times and it can’t be used as variable by calling _.toString() for example.

// Ignore the second parameter, just use i:
BiFunction<Integer, String, String> biss = (i, _) -> String.valueOf(i);

// Even possible, ignore both:
BiFunction<Integer, String, String> b2 = (_, _) -> "someString";
    

Shadowing of parameters

Another small change that is proposed is allowing to shadow parameters. For example look at the following code:

Map<String, Integer> map = ...
String key = computeSomeKey();

map.computeIfAbsent(key, key -> key.length()) // compile error, key already defined

map.computeIfAbsent(key, _ -> {
    String key = "";  // compile error, can't redefine key inside this scope
    return key.length();
});

In both cases ‘key’ is already defined, can’t be used as a parameter or local variable inside the lambda. The proposal wants to lift this restriction, allowing the use of ‘key’ as a parameter or as a local inside the lambda using so called ‘shadowing’.

One possible drawback is readability, and I too think that this might be a problem. For example:

Map<String, Integer> map = ...
String key = "theInitialKey";

map.computeIfAbsent(key, _ -> {
    String key = "theShadowKey"; // <- delete this
    return key.length();
});

The second variable “theShadowKey” is taking the place of the first “theInitialKey”. This can be quite confusing because if you delete the second declaration nothing would break. The other variable would come from the shadows and take its place. This feels dangerous and confusing to me, not very ‘Java’-like.

Conclusion

Another day, three new JEPs submitted. Java is moving forward and trying to improve the user experience with genetics and lambdas. These proposals look like good, small, low-impact improvements that can really benefit the common programmer.


Excuse me, sorry to interrupt...

Excuse me, sorry to interrupt...

Interruptions are a software developers worst nightmare. This is what you often hear. There is nothing worse than being interrupted while working hard on a problem, while you’re in the zone. You’ll lose your train of thought and the world collapses.

The idea is that in software development you are sometimes very deep into a problem, analysing code:

This orchestrator calls that service, it is managed by this class and talks to that queue. So this generator has these parameters and it all depends on… “hey I still need your time sheet

Rage

Poof… everything gone. Your mind is now filled with rage and lost the entire train of thought. This is the main reason programmers hate interruptions.

Root cause analysis

During the JavaOne 2016 conference I attended a talk by Holly Cummins called “Euphoria Despite the Despair”. In this talk she went in depth into what makes work fun and stressed the point that interruptions should be avoided at all cost.

She even talked about a team that has a dedicated duo that had ‘interruption duty’. A Slack-bot was created so you could ask which colleagues you could interrupt each day.

But… are we judging too quickly here? Are all interruptions bad? I don’t think they are. Time to dig a little bit deeper.

Sync versus async and good versus bad

Interruptions are synchronous and blocking. Someone walks up to you and stands near your desk trying to get your attention. You might have a few milliseconds to finish what you are doing but you’ll need to reply. Other forms of communication are asynchronous, for example mail or chat clients (Slack). Someone asks a question and when you have the time to reply, you reply.

Our team has evolved to use this to our advantage. Some problems ask for direct action, but most can be handled asynchronous. This is something we talk about and discuss.

For example: If my manager wants a time sheet? Ask me asynchronous, it can wait. If a colleague has a question but is able to do other things first? Ask asynchronous, it can wait. If a colleague is stuck and can’t continue to work? I’d be happy to drop what I’m doing and assist! This is what teams do, they work together and communicate!

Don’t throw all interruptions on one big pile and label them as bad, distinguish between the good and bad interruptions.

Mount the headphones, get in the zone

Sometimes, as a programmer, you just want to concentrate and solve some deep problem alone.

In our team this can be done in two ways:

  1. Work at home or in a small dedicated room in our office
  2. Put on your headphones, if they are on, you signal you don’t want to be disturbed

I do this too, mostly using my headphones. Most of the time I don’t even have music playing and I can hear everything the team says (this is important, more on this below!).

In my opinion though we need to rethink this. Is it really the best way to program when you are ‘in the zone’?

I think you are much more likely to solve problems when you openly share and collaborate. Pairing isn’t just for trivial work, instead: the trivial things are things you should do alone! Teams should have no secrets, at each point in time you should have a pretty good idea what each of your team buddies is working on. Actively ask questions, even trivial things.

Near-subliminal team updates

What? “Near-subliminal” team updates? Yes, I’m so sorry, I can’t think of a better name. Can you? Please tell me.

One thing that is very important in software development is the use of what I’ve just called near-subliminal team updates/mumblings. It is the main reason I have headphones on without any music, and why I don’t like working at different locations (at home or in cubicles).

Example

You are working on something and you feel the need to refactor a class. At this moment you say/mumble out loud:

“Hey team, I’m going to refactor classname because reason okay?”

This is what I call a near-subliminal team update, and they are very important. They can solve a lot of problems!

  1. Maybe you don’t agree with reason, this is the perfect time to talk about that. You don’t want to wait until a code review and tell them it was a bad idea later the same day.

  2. Maybe you are also working on something in classname and it might collide with your work. You don’t want to wait until you git pull and need to merge, tackle it right away!

  3. Maybe it isn’t relevant to you at all (which is most of the time)… Well, most likely you don’t even really notice the update. It didn’t contain any trigger words. Terms you are working on or have an opinion about. You aren’t really interrupted and can continue to work.

Conclusion

To summerize:

  1. Don’t treat all interruptions as evil, they are not…
  2. If you are annoyed about interrupts, talk about it
  3. Speak up, mumble, use those near-submliminal team updates!

Did I miss anything? How do you cope or deal with interruptions?

And please: If there is someone with a better name for these short near-subliminal status updates, let me know!


JavaOne 2016, the Future of Java EE

JavaOne 2016, the Future of Java EE

Lately there has been a lot of rumor going around about the future of Java EE. Oracle ex-employees Reza Rahman was one of the first to voice their concern about Java EE. It seemed that all development on the seperate JSRs (Java Specification Requests) that make up Java EE 8 ground to a halt and Oracle was thinking about stopping Java EE development all together.

Oracle finally gave some insight on their proposal of the future of Java EE during JavaOne 2016 (where I am right now).

What is Java EE?

First, lets take a step back and look at what Java EE actually is. If you download Java SDK/JRE you are able to compile classes and run them. In the language (java.* and javax.*) there are a couple of libraries that you can use. For example if you want to compute mathematical equations there are classes to use in the java.math.* package.

Oracle quickly realized it is hard to make larger enterprise applications using just these libraries. That is why they developed the following things:

  1. A set of interfaces (API) for Enterprise Applications (Java EE)
  2. A default server implemention for these API’s (Glassfish)
  3. A licensing structure for vendors that want to implement these API’s

So if you want to make an Java EE application you can use the Java EE API. For example you can define Servlets for web communication. Next when you deploy this application on an official licensed Java EE server it’ll make sure the methods are implemented and called when a URL is invoked.

Java EE at JavaOne 2016

During the keynote Oracle informed the crowd about Java EE 8. Rumor was that Oracle wanted to completely stop developing Java EE because the demand has been decreasing over the years. More and more ‘fat’-jar applications are being deployed on simple web servers that don’t implement the full Java EE specification. Oracle has to think about the return value, is the effort of developing a new Java EE 8 specification worth the effort? They clearly thought it wasn’t.

The problem for Oracle was the big backlash coming from the community. A couple of initiatives were started to create a voice and support for Java EE (for example the Java EE Guardians and EE Central). This put Oracle in a bad position. If they stopped developing Java EE the community would be very dissapointed. The initiatives would demand the rights to the API to keep developing it themselfs. But Oracle can’t do this because they are earning money from selling licenses.

The decision has been made to continue developing Java EE 8. And during the keynote they proposed a release of EE 8 in 2017. Going forward they’re talking about changing the focus to reflect ‘modern’ enterprise development. They want to add support for virtualization (Docker anyone?) and microservices, modernizing Java EE.

My thoughts

Parts of Java EE, for example CDI and JPA are in my opinion very succesful. Java EE looked at the options in the market and they’ve defined a new, clearer, general, evolved API that allows you to change the underlaying technology/vendor. This is very good! It is always valuable when vendors get together and define a shared API together based on the lessons learned from their own implementations.

The problem is that Java EE 8 as a whole is too large, it is a monolith. If I start a new project I’d love to pick some parts from Java EE and just use those. There is no need to have one huge Java EE certified server if instead you can pick one particular CDI and JPA implementation.

The future of Java EE isn’t to continue as one big bundled EE server. We need to break it up. All the parts can have their own lifecycle and seperate implementations. This makes it easier to get smaller certified implementations and doesn’t require large EE servers. This also allows for pruning, if certain parts aren’t relevant anymore, don’t use it and stop developing.

Vendors like Red Hat (owner of WildFly) are already breaking up their Java EE implementation using frameworks like WildFly Swarm. Swarm allows you to package and run just the parts of the specification you’re using. This is, what I think, the real future of enterprise Java.


Job titles when writing code

Job titles when writing code

The company I work for (JPoint) we don’t have work titles. Well, we do, but you’re free to pick one. Some people call themselfs ‘software developer’, some are having more luck as ‘software architect’, others label themselfs as ‘software craftsman’ and there might be a ‘software ninja/rockstar’ hanging around.

But I have a problem with that… all those terms don’t reflect on what we do. Currently I’m sitting in a session at JavaOne and I’m having the feeling people don’t realize what their job actually is.

So, what does a software coder do?

When creating software we instruct a computer what to do.

That is it.

We tell a machine how to respond. We don’t build things (develop), we don’t slay things (ninja!), we don’t rock, we just tell the computer what to do.

That is why a programming language is called… a language. It is a way we, as coders, communicate with the computer.

Is it that simple? Sadly no.

When writing code, we are not alone. There are also other coders that read/write/edit/analyse our code. It isn’t enough that just you and the machine understand, other coders have to understand as well.

We started out programming in binary, but this was way too complicated for humans. So we invented programming languages. First we created assembly. This made it easier for a human to tell the machine what to do. But assembly was still too complicated. Slowly the programming languages became closer and closer to human language.

Alternatives

My job is to write code, code that the machine understands. The code must also be pleasant to read and understand by other humans. Also, in this, I’m putting a lot of creativity.

Maybe you are a software author or software writer:

wri•ter (rahy-ter)

noun
1. a person engaged in writing (books, articles, stories, etc.) as an occupation or profession; an author or journalist.
2. a person who commits his or her thoughts, ideas, etc., to writing

This fits our job much better!

If you want something more exotic, and your code has a good flow and shows creativity, you might call yourself a: software poet:

po•et (ˈpoʊ ɪt)

noun
1. one who writes poetry.
2. one who displays imagination and sensitivity along with eloquent expression.

Saving the world with a code review

Saving the world with a code review

This morning I noticed the following tweet by fellow programmer (and runner) Arun Gupta:

The tweet contained the following cartoon by ‘Oppressive Silence’, check out their website for more laughs!

Oh no the robots (Source of the comic)

Solved by a code review?

The main question I’d like to ask:

Is this really something that you’ll find during a code review?

I think my answer below won’t surprise you, but the reasoning behind it might. First lets look at four reasons this bug should never happen to me (or any other experienced programmer).

1) Static variables/global state

The first obvious problem with the code is the usage of static state. The variable ‘isCrazyMurderingRobot’ is mutable and static, so anywhere in the code the value can be changed. This makes it very hard to reason about the variable and keep track of it. Any programmer can come along and change the value in some method. This is unacceptable, there is almost no reason to use mutable static variables.

Top tip: If you have variables, especially mutable variables, keep their scope as small as possible!

2) Final method arguments

If you solve the global state problem you’ll probably end up with something like this (translated to Java):

    private void interact_with_humans(boolean isCrazyMurderingRobot) {
        if(isCrazyMurderingRobot = true) {
            kill(humans);
        } else {
            be_nice_to(humans);
        }
    }

Whenever an argument is passed to a method I have the habit (and my IDE-settings enforce this for me) to make them final. Method arguments should never change inside a method. It is just strange if you need to do this when you think about it. It probably means the method should have its own (scoped) mutable variable.

In the code the following would happen:

    private void interact_with_humans(final boolean isCrazyMurderingRobot) {
        if(isCrazyMurderingRobot = true) {
        // Compilation error: 'Cannot assign a value to final variable 'isCrazyMurderingRobot'

The code won’t even compile before telling me what is wrong, the world is saved!

3) Static code analysis

Another reason this bug will never happen in my code is because we have static code analysis on all our projects. A program like FindBugs will immediately flag this as a major problem, assigning values inside an if-statement.

Look at this particular check in FindBugs:

QBA: Method assigns boolean literal in boolean expression (QBA_QUESTIONABLE_BOOLEAN_ASSIGNMENT)

This method assigns a literal boolean value (true or false) to a boolean variable inside an if or while expression. Most probably this was supposed to be a boolean comparison using ==, not an assignment using =.

Static code analysis is an essential tool in modern programming, it is just so convenient, never reads over certain bugs like a human would (spoiler: more on that in the final conclusion below).

4) Yoda conditions

The final reason this bug will never happen in my code is: Yoda conditions

A habit I learned a long time ago (in older languages) is writing my if-statements like Yoda. Good it is, mistakes you won’t make. The reason behind doing this is that it’ll prevent exactly the bug in the cartoon.

In the cartoon the if-statement would change from: ‘is crazy murdering robot true?’ to ‘true is crazy murdering robot?’.

If you do this, the following happens:

    private void interact_with_humans(boolean isCrazyMurderingRobot) {
        if(true = isCrazyMurderingRobot) {
        // Compilation error: 'Variable expected'

Conclusion / saving the world

So, do I think Arun is right? Will code reviews find the bug in the cartoon? Yes and no.

Humans are good at reasoning, thinking, being creative, finding bugs, but there is one thing we are horrible at: syntax parsing.

During a code review you are just as likely (maybe even more likely) to read over this typo and don’t notice it. A second pair of eyes won’t save the world here just yet.

But: when reviewing this piece of code, I will complain about the global state! If you start to refactor, encapsulating the logic and remove the mutable static variable the bug will be noticed and solved. So yes, if you do a code review, the code would have be been fixed and humans will be safe for just a little bit longer.


Gender (in-)equality: my honest mistake

Gender (in-)equality: my honest mistake

Gender equality and discrimination in IT is a hot topic. More and more women are (rightfully) opening their mouth and point out problem areas. There are just some men who just don’t get it, those insensitive idiots, they are the reason IT is such a toxic harsh environment for women.

So I thought…

This is a story about when I realized I am (unintentionally) one of those idiots.

Joy of Coding

This friday I spoke at Joy of Coding in Rotterdam. An awesome conference and a real example for other conferences regarding gender equality. The main organizer is female (Hi Felienne!), she’s the face of the conference, presented the opening and announced the speakers on the main stage. They have a very good rule of conduct: Don’t make any assumptions. Also the line-up of speakers was almost 50/50 male and female.

And of all the conferences: This is the conference I made my mistake.

Hilary Parker

The last speaker at the conference was Hilary Parker. She’s a Data Scientist at Stitch Fix and talked about how programming in data science is maturing. No longer are the scientists tweaking Excel sheets, they’ve started to use tools and languages (like R) to do all the analysis.

Hilary Parker talking about The Joy of Analysis Development

I loved the presentation and I also love the fact more and more women are taking the step and talking on stage at conferences. We should totally cherish them! There were however two small things that I noticed though, first: on two occasions her screen went ‘asleep’ and the had to dash to her laptop and wiggle the cursor. The other thing was, Hilary talks with a very obvious ‘Silicon Valley’-accent. She has the habbit of putting ‘like’ multiple times in every sentence as a filler word.

It sounded like this:

“So like, when you like load all the data files, and like you run a tool like R, you like immediately … etc”. This got a little annoying once I noticed it. It kind of takes the focus away from the content.

Twitter

After the conference I didn’t have time to talk to Hilary in person. But I wanted to help her, I want to see more female speakers at conferences. So I went on Twitter, send her a DM (direct message) and gave her some unsolicited feedback in private.

What I said came down to: Have you considered installing ‘caffeine’? It is the perfect tool for public speakers to stop the screensaver from kicking in on OS/X. Also, I’ve noticed you are using the word ‘like’ a lot, up to the point it becomes a distraction. I think you could become an even awesomer speaker if you lessen the usage of the word ‘like’.

Her reply was simple, but blew my mind:

Hilary:

Hey, have you seen this? http://larahogan.me/blog/on-unsolicited-criticism/

Unsolicited criticism

It turns out that unsolicited feedback almost exclusively happens with female speakers. Reading that article I realized that I never have this. People do sometimes come up to me after giving a talk, but only to say ‘nice talk’ or something similar.

This is the moment I realized I’m biased too. I never thought about this being a problem, but I can understand this can be extremely annoying as a female speaker. It was obviously not my intention to be a jerk giving unsolicited advice…

So why did you do it?

So what is the reason I made this mistake? I’ve been thinking about this for a couple of days now. In Lara’s article she mentions some possible reasons it happens, but I have some additional ones:

Cherish female speakers

If you’re reading this you might think I’m just one of those insensitive men at conferences, but trust me, I’m trying not to be! The last couple of years I’ve been actively involved in changing our community to be a better place for everyone. I’ve helped organize and volunteer at various Devoxx4Kids events. I’ve been in CFP committees and have fought for more female speakers there….

One of the reasons I gave my feedback was because I want to see more female speakers. If a men fails, there are dozens of other men waiting to replace him. I thought that with my advice Hilary could become an even better public speaker, increasing her chance to speak at events and being an example to more women.

Women are more affable?

Affable:

pleasantly easy to approach and to talk to; friendly; cordial; warmly polite:

This statement is also gender discrimination, but in a positive way. From my experience women are more affable. They are friendlier, easier to approach and to talk to. Male speakers can have a ‘macho’ attitude, I don’t want to go up to them and give them feedback.

This might also be a big part of why female speakers receive unsolicited feedback and male speakers don’t.

Lessons learned

For me this experience was a real eye-openener, if you’ve made it this far and haven’t read Lara’s post yet, please do!

She writes:

Ask yourself some questions. When’s the right time? Is it constructive? What’s moving you to give feedback to them right now? And is it possible that your brain was itched by them not in a bad way, but in a potentially eye-opening way for you? It may reveal some unconscious biases in yourself that would be worthwhile for you to explore

It is very easy to fall into the gender trap. In my case it was a completely honest mistake, I wanted to help. But Hilary did nothing wrong, she talked the way she always does, with a ‘Valley’ accent… so what? Why was this the time I had to give some feedback?

I never thought that unsolicited feedback would be a problem female speakers have to deal with. I’d like to apologize and thank Hilary, she opened my eyes to this problem and allowed me mention her in this blogpost.

So next time you feel the urge to give some unsolicited feedback, stop and think about it…


Speaking at Joy of Coding 2016

Speaking at Joy of Coding 2016

Most conferences I get to visit are about Java. Java frameworks, techniques, other JVM languages, all of them have pretty much the same focus. However: there is one conference on my agenda that is… different (in a good way!). Joy of Coding is all about (you’ve guessed it) the joy we experience while coding. The topics are very broad, some talks are technical, others are not.

Talking about game theory

At this edition of the Rotterdam-based conference I was invited to talk about game theory and game algorithms, and I explained this by going from a simple game, to noughts and crosses, to chess and finally to Go. From minimax to alpha-beta pruning to neural networks. It is the same talk as I did last week at Devoxx UK, but now I had much more time, 30 minutes. This allowed me to go deeper into the algorithms and for example explain the free optimization you get with alpha-beta pruning.

The absolute best thing about Joy of Coding? The logo/mascot! Just look at this extremely happy cute octopus:

Cutest conference mascot: Joy of Coding Octopus


Speaking at Devoxx UK 2016

Speaking at Devoxx UK 2016

Last week I went to London with my colleague Bert Jan Schrijver for the Devoxx UK 2016 conference. The UK-member of the international Devoxx conference family is smaller than its siblings. The event was three days, with the first two having talks and the last day was filled with hands-on-labs. During the first two days there were four parallel tracks giving the almost 1000 visitors enough content to pick from.

Roy van Rijn speaking at Devoxx UK

The quality of the speakers is very high in London. There are usually a lot of international speakers, probably due to the Devoxx-branding. But also the LJC (London Java Community) has done a lot to encourage their members to do public speaking, it shows!

Day 1

Devoxx UK started with one large keynote. James Veitch (stand-up comedian/nerd) entertained us with his experiences with so called ‘nigerian’ spammers. If you’ve never seen a presentation by him, check out his TED Talk for example right now! He’s amazing.

After the entertaining kick-off Mark Hazell (organizer) took the stage. And during his talk the next Devoxx-sibling was announced: Devoxx US. For the first time Devoxx is going to cross the Atlantic ocean. It will take place 21 to 23 March 2017 (during the Java 9 release?) in San José.

This news was followed by two technical keynotes. The first one was by Hadi Hariri (about the ‘free lunch’ in open source software) anf the second talk was by Mazz Mosley (about her Agile experiences). After this the four parallel tracks started. My colleague Bert Jan immediately took the stage with his talk on microservices in Vert.x.

The first conference day ended with the Ignite sessions (5 minute talks, 20 slides, auto-forwarding slides, fun topics), this is where I talked about the coming of Skynet (from the Terminator movies) and the fact that Skynet will run on the JVM.

The second day of the conference has again four rooms with parallel sessions. And during lunch I had my main talk, a 15 minute quickie about game theory, algorithms and the breakthroughs of Google/DeepMinds AlphaGo. The talk takes you from the most simple game you can imagine to Noughts and Crosses, to Chess and finally to Go. It talks about the algorithms you can use to make a computer play these games and why all those techniques don’t work with Go.

Day 2

The second day ended with the usual Community Keynote. During this keynote some crazy French guy warned us for Brexit, they talked about the problems with Java EE and they did three short interviews, one of them was with me! Martijn and Antonio asked me some questions about Joggling (which I’d done an Ignite talk before) and filming at Devoxx. The most scary part was then Antonio challenged me to juggle three glasses… which I did: (skip to 16:79)

We ended the day like real Londoners do: in the pub. After the last talk we went to ‘DevRoxx’, a party sponsored by Tomitribe, Lightbend, Couchbase and Atlassian.

Impression video

I’m also the ‘official’ Devoxx UK camera man/editor and I’ve created the following movie:


How to become a software architect

How to become a software architect

Yesterday, on the vJUG mailing list, Gilberto Santos asked the following question:

I’m working as Software Engineer and as intend to grow up to architect position, now on I was wondering how to best way to get there , should be :

Java certifications

Masters

Both ?

I replied to him over the email, but it might be something more developers are struggling with, time for a blog post!

Architects should code

There are two types of software architect:

  1. The one that draws Visio® diagrams
  2. The one that develops/codes

The first type of architect likes to talk, have meetings, draw diagrams and give orders. This, to me, is not good.

Architects should write code, they should be part of a team. In fact, everybody that writes code is effectively an architect and should have basic knowledge about architecture principles. For example every programmer should know about the SOLID principles.

Simon Brown has some good presentations on this topic on his website coding the architecture.

Mistakes

The best advice I can give a developer that wants to grow into a senior/architect position is:

Make mistakes, lots of them.

If you want to become a better architect the most important skill to master is the art of making mistakes, noticing them, and not repeating them in the future. Most ‘enterprise’ architects I’ve worked with set up a project and leave before the thing they had designed starts to rot, smell and fall apart. They never experience the flipside of what they set up, you can make everything look good on paper.

As a programmer and architect you need to experience this ‘project rot’. To learn you need to feel the mistakes that are in every system. Once you start seeing problems, admit the things you’ve made aren’t perfect, and start changing them. Try to fix the mistakes.

Matt Damon would say: “I’m going to have to refactor the shit out of this.”

This experience is what makes you a real architect. The best architects I’ve worked with knew instantly what needed to change and which solutions would work better than others. They develop an instinct for this. In Dutch we have a saying ‘they know where the shoe pinches’. Which means: just by looking at it they have a ‘feel’ for what hurts and will cause problems (in the future).

However….

This experience/instinct is what makes you a good architect and a good programmer. But sadly this doesn’t directly get you a better job or position within a company. Managers, recruiters and HR can’t easily test for this instinct. Sadly: the thing they look at most of the time is certifications.

For example, I’ve mentioned the SOLID principles, and they are very important. It takes a maximum of 5 minutes to learn the acronym and use it in job interviews or get a certification. To really understand it though you need to experience SOLID. You need to encounter situations where huge classes have a lot of responsibilities. This is the problem with most certifications: they encourage you to memorize rules and principles, not to understand them. I’d rather have someone in my team that naturely breaks up code into clean interfaces than someone who memorized that the ‘I’ in SOLID stands for the ‘Interface segregation principle’.

Once you developed this ‘architect instinct’, people will notice it. Colleagues will remember and this will help you get better jobs and positions in the future. You’ll need to prove yourself and grow your network. Try to get recommendations from people you’ve worked with and you will become a real senior programmer and architect.


The Prettiest Code

The Prettiest Code

This afternoon I started to wonder…

I’ve been a programmer now for 20+ years, but what is the best piece of code I’ve written in all these years?

The first thing that popped in my mind was this. It is a piece of code that can very quickly, in near linear time, generate de Bruijn sequences. I ‘invented’ it after reading a scientific paper that described how to quickly generate ‘Lyndon words’. I knew with Lyndon words you could easily generate the de Bruijn sequences. So I implemented it and adopted it for de Bruijn. Read more about this here.

Why is this my favourite piece of code? Well, it is small, compact and does something impressive. I couldn’t find a lot of implementations that had the fast runtime my code had. And it wasn’t trivial to implement, I had to do quite a lot of research and it felt like I myself did a little inventing. I probably wasn’t the first to write the algorithm though, but it felt like that for a while.

But is it…?

As a programmer I write code every day. And what I do even more is read code. If I have to guess, for each line I write I’ve read about ten times more. And after more than two decades of programming, I’ve seen my share of source code. This taught me something important. Is the piece of code I mentioned the best code I’ve written? I don’t think so.

What I thought the best code should have:

  • Looks smart
  • Amazes people
  • Jumps out
  • ‘I could have never created that!’
  • It is magical!

The code I picked sure had some of these properties. But is it really the prettiest code I’ve written? No..

When you are working in a large codebase the best (and prettiest) code has the following properties:

  • Doesn’t stand out
  • Looks trivial
  • You don’t notice it’s there
  • You hardly ever need to change it
  • ‘Gah, anyone could have written this’

The best code is code you don’t notice, code that doesn’t stand out, code that looks like anyone could have written it. It doesn’t contain smart things, it looks mundane. This is something we should always strive for… simple code.

So what is the best piece of code I’ve ever written? It is the code that will never be git-blamed, nobody will ask questions about it and nobody will even notice it exists.


Biometric passwords: No!

Biometric passwords: No!

Please sit down, we need to have a talk, programmer to programmer.

Over the last decade we’ve had a lot of problems with authentication. For example, we’ve stored plain text passwords in the database. We’ve learned from this and nobody is doing this anymore right? If you are, please deposit your programming-license in the nearest trash can.

Latest challenge: Biometrics

It is time to talk about the latest problem in IT: biometric data.

Some websites are using biometrics, such as your fingerprint, as your password. This sounds great, very hard to fake, unique to you. But there is a problem… what happens when there is a data leak?

If you store passwords in the database (hashed or not), and they get leaked, it is bad. You need to tell all the users to change their passwords immediately. But what happens when you store biometric data and it gets leaked?

The only way to change your fingerprint is this:

Fingerprint removal tool

Rather painful… and even worse, all devices and websites that use your fingerprint have the same password.

We don’t want to share passwords on multiple websites/devices!

Not a password

There is no real solution, as long as you ensist of using biometric data as a password. Even if you use a nice salted hash, it will eventually be leaked, with big consequences.

A better way to use biometrics in authentication is to treat it as a username. It is a great match, it identifies you. It is not your secret password, it is your username. That means you still need to provide a password, but having the added biometric username does increase security a lot. Of course if there is a database leak, your fingerprint can still be stolen, but that is the entire point. If you touch a glass door you’re also leaving your fingerprint. Using fingerprints as password is like dropping pieces of paper with your secret password all over the place.

Fingerprints (and other biometrics) are not secure, you can never change them once compromised, not suited as passwords. If you really want to use it, use them as usernames.


Deprecating Optional.get()

Deprecating Optional.get()

On the OpenJDK core mailinglist (and Twitter) there is a discussion about Java’s Optional. Before diving into that discussion, lets take a look at what Optional does and how you can use it.

Checking for null

What do you do when your code calls an external service or god forbid a microservice, and the result isn’t always available?

Most of the time the protocol you are using facilitates in the optional part, for example in REST you’ll get a 404 instead of JSON. Getting this 404 forces you to think about this scenario and do something when this happens.

But what do you do when you’re calling a framework (on the boundary of your code) and the value isn’t always known?

You either get the value or the result is a dreaded null. This causes a lot of null checks, or bugs where the code just crashes with a NullPointerException.

Example (old skool, Java 7):

    Order order = Database.readOrder(); //can be null
    if(order != null) {
        ProcessResult result = OrderEngine.process(order);
        if(result != null && result.succeeded()) {
            Database.storeResult(result);
        }
    }

This code is not very pleasant to read. But we Java programmers didn’t have or need anything better… until we started to adopt a more functional style of programming.

java.util.Optional

What happens when you are processing a stream and some values are null? You don’t want null checks inside a stream! This is where Java 8’s Optional comes in. If you’re not (yet!?) using Java 8, there are other implementations as well. For example Google Guava has an Optional as well.

Optional is a class that ‘might’ have a given value in it, or not, it is optional. So how exactly is this helpful? Instead of checking for null this wrapper class can handle some situations for you.

For example:

    Optional<Order> order = Database.readOrder();
    Optional<ProcessResult> result = order.map(OrderEngine::process);
    Optional<ProcessResult> filteredResult = result.filter(ProcessResult::succeeded);

    filteredResult.ifPresent(Database::storeResult);

Or the shorter ‘fluid’ version:

    Database.readOrder()
        .map(OrderEngine::process)
        .filter(ProcessResult::succeeded)
        .ifPresent(Database::storeResult);

Even if the Optional is empty in either reading the order or processing the order… nothing breaks. No NullPointerException, nothing, just no executed lambda storing the result in the end. We’ve eliminated the need for a null check.

As you can see Optional can really clean up your code. You don’t need to worry about null checks anymore.

So what is the problem with Optional.get()?

Optional.get() deprecation discussion

Pretty much out of the blue on the OpenJDK mailinglist an email arrived with a webrev (similar to a patch file) that contained the deprecation of Optional.get().

The get() method is too easy to find, and the name isn’t quite what you’d expect, and the webrev author claims there are a lot of cases online where people made the same mistakes.

Many programmers, when they first encounter Optional, don’t know what to do. They look in their IDE and the first thing that pops up is get().

It is just an easy method to call:

    Order order = Database.readOrder().get();

This works fine! Until there is a situation where the value is not available to the Optional. In that case it will throw an NoSuchElementException. How can we solve this? Well, we could do the following:

    Optional<Order> maybeOrder = Database.readOrder();
    if(maybeOrder.isPresent()) {
        Order order = maybeOrder.get();
    }

This is the ‘safe’ way, but it could just as well have been a null check now. There is likely a much cleaner way to process your Optional.

  • If you want to do something with the result, use filter, map, ifPresent (and many others).
  • If you need to return something, either return an Optional yourself, or get a default value by calling orElse, orElseGet or orElseThrow.

This is all you need, why have a get-method?

The proposal on the mailinglist is to deprecate the get() method and rename it to getWhenPresent(). This name change should warn people that it might not be present and they should check isPresent before calling get().

Instead of embracing this change some people on the mailinglist argue against deprecation, some of their reasons:

  • Renaming will break a LOT of code, well, not really break the code, it will cause deprecation warnings
  • getWhenPresent() instead of get() just adds noise to the code, it doesn’t solve anything
  • People should just read the JavaDoc, it clearly states what get() does and throws
  • Guava’s Optional also has the same get() method, they’ve never heard about the problem

The most honest and one of the more powerful replies in the discussion was from Brian Goetz himself:

As the person who chose the original (terrible) name, let me weigh in…

……

I’d like to see it fixed, and the sooner the better.

He is clearly in favor of deprecation… what is your opinion? Let me know in the comments!