Skip to main content

Posts

Clean Code from the Trenches - Writing Executable Specifications with JUnit 5, Mockito, and AssertJ

Executable Specifications are tests that can also serve as design specifications. They enable technical and business teams to get on the same page by enabling the use of a common language (in DDD-world this is also known as Ubiquitous Language). They function as documentations for the future maintainers of the code. In this article we will see an opinionated way of writing automated tests which could also function as Executable Specifications.
Let's start with an example. Suppose we are creating an accounting system for a business. The system will allow its users to record incomes and expenses into different accounts. Before users can start recording incomes and expenses, they should be able to add new accounts into the system. Suppose that the specification for the "Add New Account" use case looks like below - Scenario 1
Given account does not exist
When user adds a new account
Then added account has the given name
Then added account has the given initia…

A Beginner-friendly Introduction to Kubernetes for Developers: What is Kubernetes?

Just a few months ago, I had the chance to get my hands dirty with Kubernetes for the very first time. Up until that point, all I knew about it is that it is something that ensures containerized applications run smoothly in a cluster, nothing else. After finishing my "hello world" and trying out some examples, I have decided to write a series of blog posts in which I will try to summarize all my learning.

A fair warning - I am still a beginner in Kubernetes, so advanced Kubernetes practitioners might find my posts to be too basic. This is also what motivated me to write these posts in the first place. I wanted to write a beginner-friendly series of posts on Kubernetes for developers which could be used as a good first starting point. I have also decided to break down my articles into small chunks of posts so that they are easily digestible by a beginner.
What is Kubernetes? Containers have become the de-facto medium of packaging applications nowadays. More and more applicat…

Different States of Java Threads

Introduction In Java, threads can have States. The Thread.State enum defines the different states that a Java thread can have. This enum defines the following values -
NEWRUNNABLEBLOCKEDWAITINGTIMED_WAITINGTERMINATED In the subsequent sections, I provide a brief overview of these states along with possible transitions between them.

States of a Java Thread NEW This is the default state a thread gets when it is first created.
RUNNABLE As soon as a thread starts executing, it moves to the RUNNABLE state. Note that a thread that is waiting to acquire a CPU for execution is still in this state.
BLOCKED A thread moves to the BLOCKED state as soon as it gets blocked waiting for a monitor lock. This can happen in one of the following two ways - It's waiting to acquire a lock to enter a synchronised block/method.It's waiting to reacquire the monitor lock of an object on which it invoked the Object.wait method.
WAITING A thread moves to this state as a result of invoking one of the follo…

A brief overview of the Fork/Join Framework in Java

Introduction The Fork/Join framework is a framework to solve a problem using a concurrent divide-and-conquer approach. They were introduced to complement the existing concurrency API. Before their introduction, the existing ExecutorService implementations were the popular choice to run asynchronous tasks, but they work best when the tasks are homogenous and independent. Running dependent tasks and combining their results using those implementations were not easy. With the introduction of the Fork/Join framework, an attempt was made to address this shortcoming. In this post, we will take a brief look at the API and solve a couple of simple problems to understand how they work. Solving a non-blocking task Let's jump directly into code. Let's create a task which would return the sum of all elements of a List. The following steps represent our algorithm in pseudo-code:
Find the middle index of the listDivide the list in the middleRecursively create a new task which will compute the …

Java Tips: Creating a Monitoring-friendly ExecutorService

In this article we will be extending an ExecutorService implementation with monitoring capabilities. This monitoring capability will help us to measure a number of pool parameters i.e., active threads, work queue size etc. in a live production environment. It will also enable us to measure task execution time, successful tasks count, and failed tasks count.

Monitoring Library As for the monitoring library we will be using Metrics. For the sake of simplicity we will be using a ConsoleReporter which will report our metrics to the console. For production-grade applications, we should use an advanced reporter (i.e., Graphite reporter). If you are unfamiliar with Metrics, then I recommend you to go through the getting started guide.

Let's get started.

Extending the ThreadPoolExecutor We will be using ThreadPoolExecutor as the base class for our new type. Let's call it MonitoredThreadPoolExecutor. This class will accept a MetricRegistry as one of its constructor parameters -

public …

JPA Tips: Avoiding the N + 1 select problem

Introduction ORM frameworks like JPA simplifies our development process by helping us to avoid lots of boilerplate code during the object <-> relational data mapping. However, they also bring some additional problems to the table, and N + 1 is one of them. In this article we will take a short look at the problem along with some ways to avoid them.

The Problem As an example I will use a simplified version of an online book ordering application. In such application I might create an entity like below to represent a Purchase Order -
@Entity public class PurchaseOrder { @Id private String id; private String customerId; @OneToMany(cascade = ALL, fetch = EAGER) @JoinColumn(name = "purchase_order_id") private List<PurchaseOrderItem> purchaseOrderItems = new ArrayList<>(); }
A purchase order consists of an order id, a customer id, and one or more items that are being bought. The PurchaseOrderItem entity might have the following structure…

Replacing exceptions with error notifications during input validation in Java

In my previous article I wrote about an input validation design which replaces hard-to-maintain-and-test if-else blocks. However, as some readers pointed out, it has a drawback - if the input data has more than one validation errors, then the user will have to submit the request multiple times to find all of them. From a usability perspective this is not a good design.

An alternative to throwing exceptions when we find a validation error is to return a Notification object containing the error(s). This will enable us to run all the validation rules on the user input, and catch all violations at the same time. Martin Fowler wrote an article detailing the approach. I highly recommend you to go ahead and give it a read, if you haven't done so already.

In this article I will refactor my previous implementation to use Error Notification object to validate user inputs.

As a first step, I will create an ErrorNotification object which encapsulates my application errors -
public class Error…