GraphQL Kotlin Postgres and Vert.x Video

Video continues from last time but this time around covers Postgres reading and writing of data using the Vert.x reactive-pg-client and Kotlin idiomatic syntax using coroutines.

Learn Vert.x And Build Ultra High Performance Servers With The Language You Want

Vert.x Provides Top Tier Performance and Allows You To Use Almost Any Major Language Out There

Connection network in dark servers data center room storage systems 3D rendering

Vert.x is one of the top performing server frameworks on Techempower. Most benchmarks have it within roughly 20% or less of the top performer, which is usually Rust Actix. Realistically that difference is nothing. It is also orders of magnitude faster than Node and Python related frameworks. On top of all this performance goodness, Vert.x is Polyglot. Since Vert.x uses the GraalVM runtime it supports the use of multiple languages including JavaScript, Kotlin, Scala, Java, Groovy, and Ruby.

If you prefer video learning

Where To Start

Let’s start at a high level in understanding Vert.x. Vert.x at its core is not a server framework. It’s more like a set of components for building event driven high performance applications. In other words Vert.x provides base level components that allow you to go off and build almost anything that requires very high performance. The main feature that allows this is the event loop (they also use the label Reactor Pattern).

If you’re a node developer you’ve probably already heard of the event loop concept. The event loop is an iteration looping mechanism that allows code to run asynchronously without using threads. In other words the system depends on callbacks instead of threads to scale. For programming old timers this may seem strange. But the reality is that threads do not scale. Although threads are generally tiny they still take up memory and require management by the operating system, not to mention having contention issues for shared memory. This ultimately limits their maximum scalability. You can see this is true because most thread based servers on Techempower don’t even make it to the top twenty.

So then why does asynchronous IO work better than threads. Because scalability for services is about simultaneous connections, more than CPU brute force. In other words it is an inherently IO bound activity. Threads on the other hand perform better for CPU bound activity. Note I’ll start writing vertx as the name to make it easier to type.

Verticle, The Core of Vert.x

So what else is there to know about Vert.x? Vertx at its core is made up of several sub components. Foremost is the verticle. A verticle is the minimum possible structure needed to create a vertx application. So you can think of it as a parent or container object, even though it’s possible to have more than one. All other components within a vertx application need to be initiated and setup from a verticle.

Inside every verticle is at least one event loop inside of a thread. Event loops live inside a thread because it is possible to have more than one event loop per verticle instance. Therefore having threads allows more cpu cores to be used to enhance scalability. There is an event loop thread pool from which verticle instances can get their event loops. As mentioned the event loop is the main “engine” that does the work of iterating in a loop. Each iteration will execute some action, for example accepting and then handling some request. Note the event loop itself is not inherently asynchronous. It’s only a mechanism to execute tasks in an iteration loop. So it is important not to have blocking code running in your event loop. There are several ways to avoid this which we’ll get into in a later article.

Next is something called the Context. The Context, as the name implies, is where data is shared within an event loop thread or worker thread. You can think of it as a simple session state for sharing data. According to the docs a context object is associated to a single event loop thread. Now because event loops exist inside a thread pool and can be shared among several vertx instances its not clear to me how constraining data to a specific set of services might work. I suppose you could simply add a prefix to your data keys to indicate some sort of grouping. But since the docs don’t comment I think this is a case specific implementation detail you’re going to need to work out. If you need to share data at a higher level, between verticles or vertx cluster nodes you can use the SharedData API.

EventBus, Vert.x Central Nervous System

In vertx it is possible to have multiple verticle instances. For example if you have a web server you might create a verticle handling http requests. Since a typical http server has numerous routes and some of them have complex handler logic it is possible that you might create a separate verticle for each route, both for logical structure and performance. Additionally, because vertx is Polyglot, you might write the http verticle in Java and some of the route handler verticles in JavaScript, in order to take advantage of language features or dependencies specific to that verticle business logic. So now you have multiple verticles that are distinct but need to communicate with each other. The EventBus allows this communication. It’s more complex than this simple explanation of course, and the docs say so as well, but I like to think of it as basically a pub/sub system for sending messages. By the way the default message passing format is JSON.

Simple Starter App

To get started let’s create a new project. One easy way to create a new project is to use the project creator on the website. Go to the url and select the following settings as displayed in the following.

Let’s take this project and open it with VSCode. Once you have downloaded it and opened it you should see a folder structure like this

Every vertx project will use a project and package manager. In our case we selected Maven. The pom.xml file will store our dependencies and list our basic configuration information for the app like the name and the main launching class name. In this case MainVerticle. We also selected Java as the main language, but in a later article I’ll show you how you can also create verticles using JavaScript.

Let’s start writing code. Open the file and add this code.

package com.example.starter;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.Vertx;

public class MainVerticle extends AbstractVerticle {

  public void start(Promise<Void> start) throws Exception {
  public static void main(String[] args){ 
    Vertx.vertx().deployVerticle(new MainVerticle());

As you can see a verticle must inherit from the base AbstractVerticle interface. Now normally you do not need to create a main method, because the pom.xml file is already telling the project which class to run on load. However if you want to use the VSCode debugger you do need this method as the debugger looks for it. So then let’s setup debugging for this project. Go to the debugger section and select the create launch configuration link. It will create a file for you and pre-populate it. Your’s should look like this.

    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit:
    "version": "0.2.0",
    "configurations": [
            "type": "java",
            "name": "Debug (Launch)-MainVerticle<starter>",
            "request": "launch",
            "mainClass": "com.example.starter.MainVerticle",
            "projectName": "starter",
            "cwd": "${workspaceFolder}/src"

Notice the cwd variable. Any source files should go there, like our, and also any config files should also go there. Now going back to the code if you look at the method main you will see that vertx is being instantiated there by calling deployVerticle and instantiating itself with new MainVerticle. Place a break point on that line and run the debugger we just created previously. It should break on that break point.

Now let’s update our start function and startup an http server. Add this code to

  public void start(Future<Void> startFuture) throws Exception {
    vertx.createHttpServer().requestHandler(req -> {
        .putHeader("content-type", "text/plain")
        .end("Hello from Vert.x!");
    }).listen(8888, http -> {
      if (http.succeeded()) {
        System.out.println("HTTP server started on port 8888");

If you run this code with the debugger it will go to the main method first and then run start. Start is the function that is supposed to initialize anything inside of your verticle. In this case we are enabling http services with the call to createHttpServer. However we could also use deployVerticle to create other verticles that are specialized to do specific tasks for our app. For example the route handling that I mentioned previously. Once you run this code you should see this on the terminal and browser.

In this article we covered the conceptual details of how Vert,x works and showed a simple example of how to get a base project started. In the next article I’ll show how to create route handlers for the http server. And how to deploy additional verticles.

More TypeScript Types You Need To Know … Better

You probably know at least some of these types already, but you might be surprised at some of the nuance of using them

Having static types in JavaScript is enormously valuable, but knowing how to use them appropriately can also be difficult. I think you might be surprised by some of the details of these types.

Null and Undefined Types Are More Than You Think

In JavaScript running typeof on null returns ‘object’. Some devs might have thought its type is null, since undefined’s type is undefined. Now to make things more confusing however, in TypeScript null’s type is null. Don’t believe me? Here’s a sample.

console.log(typeof null);
console.log(typeof undefined);
let val1: null = null;console.log(val1);
let val2: undefined = undefined;console.log(val2);

If you run this code you get this

So this detail is definitely something to be aware of when using these types. Here’s another question did you know that by default you can assign null and undefined to any object type? If this is not your experience it would be because your tsconfig.json file uses either strict: true or strictNullChecks: true. If you are using strict, which you should, then this behavior is not allowed without using a union. Here’s an example in non-strict and strict mode.

// non-strict this works
let val: number = undefined;// strict this works
let val: number | undefined = undefined;

Also note even if you have strict turned on null and undefined can still be set to an any variable, which does make sense. But is also another good reason not to use the any type.

Never Type

If you read my previous article on this topic, you’ve seen the any alternative called unknown. The never type is also a lesser known type. This type is a bit strange in that it attempts to describe the scenario where nothing is returned from a function, not even void. Huh? So then when can one return “never”. Here are some examples

function error(): never {     
    throw Error("failed!");
function neverFinish(): never {     
    while(true) {}

So now you’re like well that’s utterly useless. Actually not at all. Let’s give another example that’s a little more realistic.

function processSomeString(msg: string): string | never {    
    if(msg) {        
        // do some string work here        
        return "I finished processing your string.";    
    throw Error("no message given error!");

If you run this code you will get an exception of course, but here’s the thing as TypeScript developers we know the value of static typing. It’s more than just having compiler help. It’s also about explicitness and communication. When we annotate with types we’re not just telling the compiler what we intend, but we’re also letting other devs know what we’re up to.

Therefore having something like never is an explicit way of giving other developers, not just the compiler, notice that something unusual could occur. To me I’ve always felt that functions that could throw an exception should indicate that in their signature. And using never is an easy clean way of doing that. In Swift programming you can indicate that a function can throw an exception in the function signature like this.

func canThrowErrors() throws -> String

I think both languages allowing for explicitness in communicating the possibility of unexpected situations is a very useful feature.

That’s it. Happy coding.

Here’s part one of this series.

As always if you like helping other devs try this

OOP Is Still The Best Software Design Method Ever Created. Period.

Using OOP Language Features, Does Not Mean A Project Is Using OOP Correctly. The Principles Come First.

As a famous dude once said, “the rumors of my demise have been greatly exaggerated.” I think the same holds true for OOP. Developers are piling on in their disdain for OOP. OOP is a giant mistake! Paradigm X is better. So here’s a mixed list of facts and nonsense claims about OOP.

You Don’t Know OOP

When OOP is taught it usually starts with conceptual and abstract explanations. OOP is an extremely complex topic so starting with the technical details or code samples would be hard for anyone to digest. The problem is that since we are humans we can make all sorts of assumptions or draw incorrect conclusions based on high level explanations.

This is one of the most digestible technically accurate explanations of OOP I’ve ever seen, I won’t even attempt to do it better because I cannot. Please review even if you think you know OOP.

The reason I’m suggesting you review it is because I recently watched a Youtuber video, with over a million views, and was surprised to see their explanation for Encapsulation. Basically this Youtuber explained Encapsulation’s main purpose as being the grouping of related object data. This is unfortunately not correct. Encapsulation’s main purpose is access control of member data. That is to hide member data so that it is strictly under the control of the class that it belongs to.

My point is this, there is a lot of incorrectly implemented OOP code out there, because developers misunderstand it. Just like there’s a lot of incorrectly implemented code in Functional Programming and just about any other major paradigm. OOP is an easy target because it is so ubiquitous, not because its bad.

Your Language Actually Does Not Do OOP

Let me lay it out flatly if you’re dissatisfied with the results of OOP, it may be that your chosen language does not really support it. Doh! I’ll say it another way if your language does not support static typing, access modifiers, and interfaces (or abstract classes), it can only mimic OOP and does not truly support it.

If you read through the link I had provided explaining OOP, you will see that without the core features I mentioned you simply cannot fully achieve most of the principles of OOP design. Some JavaScript people may believe that you can. For example it is possible to attain some Encapsulation, by embedding functions inside of constructor functions, to create member privacy and not expose them outside of the class. But so what? This is not a language feature, this is a work around for a missing feature that adds more code and more complexity. Developers have to know how to do it and other developers have to understand what this code means and so on. Is it a wonder that OOP is seen as too complex? But wait ECMAScript 2020 will soon allow for private fields. OK then what about more subtle access modifiers like protected and internal? I guess we can wait another 10 years for those.

For the other main principles of OOP it’s pretty much the same story. Abstraction requires a way to separate code interfaces from implementations. This is how we are able to dumb down a complex object so that we can hide its implementation and loosely couple our code. This is how dependency injection and true test mocking work. JavaScript and other dynamically typed languages again do not support interfaces or abstract classes. Sure it’s possible to simulate Abstraction. Maybe you use a facade pattern or adapter to mimic a reduced interface so that the internal complexity of an object can be hidden, but once again it’s not fluid and the direct language facilities are missing.

So then in the end what do you get? A lot of very clever complex code that may achieve some adherence to OOP principles but at what cost?

OOP Is Too Hard

My programming language supports OOP but it’s too hard. News flash programming is hard. It’s really really hard to do well. But that’s why we get paid the big bucks. Going to work every morning is hard. Working out is hard. But they all have their benefits when done properly. Trying to do anything well is hard. Don’t conflate poor OOP implementations with the idea that OOP sucks.

In my last job I would be the guy to interview candidates on their JavaScript skills. It always surprised me how many candidates had little understanding of some of the fundamental concepts of JavaScript. Prototypes, what this means under certain contexts, scoping rules (pre ES6), etc.

If you don’t know the tool you’re using you will use it poorly. This is just as true for programming paradigms as it is for languages.

There’s lots of different programming paradigms. For example I find Rust’s Trait based programming to be quite promising. It’s not at all OOP in my opinion. But having said that it has huge potential, both the language and the design style. As Rust develops further and more software is built using it, this style of programming may become the preferred way of coding large apps. However as of right now OOP is still king. It has the sophisticated tooling, the language support, and the developer mind share and experience. I suspect OOP will continue to be used for decades to come.

As always if you like helping other devs try

%d bloggers like this: