Introduction to TDD

When you realize the true power of tests for the first time

Introduction

TDD or Test Driven Development is a development methodology that completely changes the way we develop our code. Although this has drawn some criticism, its still getting more and more popular and TTD is considered as an important skill in many job listings.

TDD forces the developers to write the tests first, even before writing the production code. Wierd, you say. Not really, actually.

Why Tests First?

Why not? I mean, don’t treat your tests as second-class citizens of your project. They are as important as the production code, if not more.

Tests are your weapon, the stronger they are, the more powerful you become. They enable us to understand the code, quickly modify it, and bring down the maintenance cost. Don’t believe me? Take my word for it.

What is the best way to understand any new library or a framework? Even we have well-written docs in good English, what we, as developers, always look for is the “code examples“. This is because we prefer well-written code over well-written sentences.

Our tests are code examples of our production code. The tests tell other developers how to use this code and what scenarios should they consider. This brings down the learning curve.

Test Driven Development

How to do TDD?

In TDD, we start with tests first. Since we are starting with tests, it’s obvious that the test will fail. Then we write the production code just enough to pass the failing test. Once done, write another failing test and the process repeats. This way, we are writing code in very short test/development cycles.

It makes sure that all of our production code is covered with the unit tests, which is a good thing.

Following this process forces the developers to have clear API contracts. They are forced to think how the methods are gonna be used by the outside world. When I say API, I mean any public methods that we expose from our classes.

It automatically makes our code easily testable.

Many would argue against this practice saying that it requires more time, but actually, it doesn’t. Whenever we feel like making any changes to the code, we will be able to do so effortlessly, knowing that the tests have our back. This will save a lot of time. Always remember, the code is going to change, today or tomorrow. And when the time comes, you will bless yourself or the original developer for writing such concrete tests.

Fragile Tests

Ever been in a situation where you modify a small bit of code that results in multiple test failures and you find yourself modifying tiny pieces of code in all the failing tests just to find some other tests failing?

Congratulations, you have discovered fragile tests. Many people find themselves stuck in the loop of fragile tests while following the TDD. But think again, is it really the problem of TDD? Or an advantage of TDD?

Having fragile tests that break every now and then is not the problem with TDD, in fact, its the problem with the tests themselves. TDD or not, bad tests are bad tests. They will keep haunting the developers till they exist.

So how does TDD help in writing effective tests? If you find yourself modifying every test while writing code, it is a signal that our tests need refactoring. It’s better to refactor 10 tests than refactoring 50 tests.

BUT…

But my teammates are not interested in TDD. But my manager doesn’t approve of TDD. But my architect thinks TDD we are not prepared for TDD. But, but, but…

This will never end. Understand that explaining the benefits to the team is our responsibility. We need to make them understand that this is the correct way. Even then if no one listens to you, we can still follow the practice on our own.

It is up to the individual whether to follow TDD. Our managers need not worry about the methodology if your performance is good. It’s an individual’s practice.

The next article/video shows you how to actually write code using TDD methodology. See it in action.

If you are just starting with Java or are confused with terms like Java SE and Core Java, head on to this article to simplify things.

Starting Java Development Career

Starting a Java development career can be a great choice given the number of job openings that pops up day after day. Java has been around for a while and there are a tremendous amount of companies that already have a Java system in place. This only means a lot of development opportunities.

Java is compiled, type-safe, and fast. I mean really fast. I have myself migrated a fairly complex project from Python to Java and another one extremely complex system from .Net to Java. The main reasons were performance improvement and platform independence.

Learning Java in itself is not that difficult, but in order to become job-ready and be able to develop real-world Java applications requires a fair amount of knowledge. In this post, we’re gonna list down the skills required for becoming a job-ready Java developer.

Core Java

Core Java or Java SE is the starting point of your Java development career. Many beginners think that once they learn Java SE, they are ready to develop real-world applications. This is not true. First of all, in order to be a good programmer, learning the syntax is not enough. You should learn how to design an application by using various constructs provided by the programming language. You need to master it by writing a lot of code and developing some projects keeping the design principles in mind.

Next thing is that Java SE itself is not enough. A quite common application would be to develop a command line application which has limited use. To get to the next level, you need to learn Java EE or Advanced Java.

Advanced Java

Java EE or Advanced Java supports the development of server-side backend web applications. While an understanding of Java EE concepts like servlets, JSPs, and EJBs is useful, you need not master this. Just the basic level of knowledge should be sufficient.

The main reason for this is that developing any web application by simply using Java EE is difficult and time-consuming. There are a lot of frameworks available today that help in this development. Some of them are Spring, Spark Java, and Dropwizard.

These frameworks make web application development so easy that you don’t even need to know about JSP and Servlets in order to develop a basic web application.

If you are not sure which framework you should use, go for Spring. Its the most widely used framework and has a very active community.

Testing

Testing is an integral part of Software development. Writing automated unit tests helps developer receive instant feedback on the code. Unfortunately, many developers consider tests as second-class citizens.

The de-facto for unit tests in Java is Junit. Junit is widely used and has a great community out there. I can’t stress less on the importance of tests. You just need to master it.

Tools

Before you start with any framework, you must be familiar with some build tools and IDE that makes your job easy.

Build Tools

A Java application can consist of lots and lots of files and one big project might be divided into smaller modules where one module is dependent on another. Apart from this, your code might be using some popular libraries like apache commons to solve some well-known problems that come with every project.

These dependencies need to be supplied from your development environment to test environment and then to the production. This can become a daunting task if done manually. To solve this problem, we use build tools like Maven or Gradle.

If you are unsure of what to start with, choose Maven. It’s the older among the two, has wide applications, good community support, and easier to begin with.

IDE

An IDE or Integrated Development Environment helps you a lot. It saves you a lot of headache by providing the features like real-time compilation – see the compilation errors as you type, no need to wait till actual compilation happens. An IDE provides type completion among other things.

Code completion
Code completion example

There are a lot of IDEs available but only two of them are really good. My preference is IntelliJ Idea and then Eclipse.

I use Ultimate edition of IntelliJ which is paid, but there is Community edition which is free. Eclipse is also a free IDE. There is another IDE called STS (Spring Tool Suite) which is essentially Eclipse with plugins for Spring development.

Git

Git is a distributed VCS (version control system). Every project uses one or the other VCS for source code management. Git keeps different versions of the source code files as you modify them. Making tracking changes and code history a manageable task.

Server

A web application needs to be deployed on a server. There are several choices like Tomcat, Jetty, GlassFish. A beginner should start with Tomcat. It’s really lightweight and very easy to configure and use. However, if you are going to develop your first web application using Spring Boot, then there is no need to worry about servers for a small project. Spring Boot allows you to use an embedded server.

Conclusion

In essence, if you want to get a job as a Java developer, you need to learn about Java Development along with the most popular frameworks and tools. Using a popular framework will increase your chances of employability as well as it will be easier for you to learn.

So once you get hold of Java SE, develop some small projects to get hold of the language. Then Start learning Spring Boot + Maven and use STS for development. Once you are familiar, develop more and more web applications.

You might want to check out the resume polishing tips before applying for a job. All the best.

Replacing Conditional Getters With Functional Programming in Java

1. Introduction

In this small article, we will have a look at how to efficiently write a code that runs a getter (or any other method) based on some input using functional programming.

2. Problem

Instead of explaining it in words, let me show you the code directly:

private int normalMethod(MyPojo pojo, Actions action) {
    if (action == Actions.ACTION1) {
        return pojo.getActionOne();
    } else if (action == Actions.ACTION2) {
        return pojo.getActionTwo();
    } else if (action == Actions.ACTION3) {
        return pojo.getActionThree();
    } else {
        return pojo.getActionFour();
    }
}

As we can see, we are calling the appropriate getter based on the Action that we get in the input. This seems to be pretty decent at the moment, but as and when there are new actions/getters, we need to modify the code and the chain can grow longer.

3. Solution

One good solution to this is to make use of functional programming in Java. For this, we need to create a mapping of the Actions to method references:

public static final Map<Actions, Function<MyPojo, Integer>> GETTERS_MAP = new HashMap<>();
GETTERS_MAP.put(Actions.ACTION1, MyPojo::getActionOne);
GETTERS_MAP.put(Actions.ACTION2, MyPojo::getActionTwo);
GETTERS_MAP.put(Actions.ACTION3, MyPojo::getActionThree);
GETTERS_MAP.put(Actions.ACTION4, MyPojo::getActionFour);

As we can see, we have mapped every Action to the corresponding getters. Once this is done, our long if-else chain now reduces to only a couple of lines:

private Integer functionalMethod(MyPojo pojo, Actions action) {
    Function<MyPojo, Integer> getter = MyPojo.GETTERS_MAP.get(action);
    return getter.apply(pojo);
}

And that’s it. Even if we need to add another Actions/getters, we just need to add an entry in the Map. The method above doesn’t need to be modified.

4. Conclusion

We have observed that functional programming opens new doors of creativity. Please find the full source code of this article on GitHub.

Actuators in Spring Boot

It is really important to be able to monitor various metrics of a production application. One way to achieve this is to use the Actuators in Spring Boot.

1. Configuration

Like many other things, the configuration of Spring Boot Actuators is really simple. Just add the below dependency in your application.

Gradle

[code language=”sql”]
compile group: ‘org.springframework.boot’, name: ‘spring-boot-starter-actuator’, version: ‘1.5.1.RELEASE’
[/code]

Maven

[code language=”xml”]
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>1.4.2.RELEASE</version>
</dependency>
[/code]
Continue reading “Actuators in Spring Boot”

Creating a strong foundation for a new project using Spring Boot – Part 4

Contents

This post is divided into four parts.

  1. Getting Ready
  2. Unit testing
  3. Integration testing
  4. Launching the app

Launching the app

At this point, our application is complete. You can launch the app by executing the following command.

[code language=”plain”]

gradlew bootRun

[/code]

Make sure you have modified your application.properties according to your DB and that your DB is up and running.

Try our some GET/POST requests. You can use CURL or a GUI based chrome extension Postman. There are similar tools available for other platforms. Make sure to query your DB to check the modifications.

Adding the ability to run anywhere

Making your application flexible enough to be able to run on anywhere could be very useful. Particularly when you have to demonstrate. Continue reading “Creating a strong foundation for a new project using Spring Boot – Part 4”

Creating a strong foundation for a new project using Spring Boot – Part 3

Contents

This post is divided into four parts.

  1. Getting Ready
  2. Unit testing
  3. Integration testing
  4. Launching the app

Integration tests

In integration tests, multiple layers communicate with each other and we test multiple layers of the system in a given test. It’s a good idea to keep your integration tests separate from unit tests. You will run unit tests more often, with every build for example. The integration tests might run with a nightly build.

Create two new source folders src/integrationTest/java and src/integrationTest/resources in your IDE. In eclipse, Right click on project>New>Source folder.

Create a new file application-integrationtest.properties in  src/integrationTest/resources. Continue reading “Creating a strong foundation for a new project using Spring Boot – Part 3”

Creating a strong foundation for a new project using Spring Boot – Part 2

Contents

This post is divided into four parts.

  1. Getting Ready
  2. Unit testing
  3. Integration testing
  4. Launching the app

Unit tests

The “spring-boot-starter-test” is automatically added when you create a new project. If you are familiar with Spring test, you might be aware of @SpringBootTest annotation. But that’s an overkill for a unit test. @SpringBootTest has the power to start an embedded container, which can be useful in integration tests, but more than required while testing the DAO layer. Since we are testing small “units” of the application of the application, we need to be focused on testing more specific “slices” (Controllers, Service layer, DAO layer). Luckily, it’s really easy to do this.

Let’s create our first test.

Testing the DAO layer

I know we have not written any DAO layer code in our application, still we can verify if the repositories are configured properly. Moreover, as the application grows, you might feel the need to have unit tests for the DAO layer. Starting early will help in this case. Continue reading “Creating a strong foundation for a new project using Spring Boot – Part 2”

Creating a strong foundation for a new project using Spring Boot – Part 1

Contents

This post is divided into four parts.

  1. Getting Ready
  2. Unit testing
  3. Integration testing
  4. Launching the app

Creating a strong foundation for any new project is critical for timely delivery as well as maintainability. Frameworks like Spring Boot and tools like Gradle are meant for rapid development. However, if not utilized correctly, these can become a bottleneck and hinder your pace of development.

Let us see how can we create a solid foundation of any new project that provides you high testability as well as portability. This post, by no means, claims to be a perfect example, however, it should provide you a good enough ground to play around.

Not a standard Spring MVC app

We are not going to discuss “How to create a Spring MVC app” here. In fact, the sample app that we will develop will have minimal functionality. Our main focus will be how to set up the project so that it can be developed quickly. We will talk about organizing unit tests, integration tests, while keeping the tests independent such that they can be run on any machine without having any dependency on the infrastructure. Continue reading “Creating a strong foundation for a new project using Spring Boot – Part 1”

Moving on to Assertj assertions – beginner examples

Assertj examples

This post describes the use of a relatively new but a fluent assertion library, Assertj.

1. Introduction

Assertj provides simple yet effective way to assert your tests. It provides a powerful mechanism to make your assertions compact and readable.

2. Dependencies

Add the following dependency to your project.

Gradle:

[code language=”plain”]
testCompile ‘org.assertj:assertj-core:3.5.2’
[/code]

Maven:

[code language=”xml”]
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.5.2</version>
</dependency>
[/code]

3. Getting ready for the examples

We will deal with some real examples in this tutorial. Hence, we need a project setup to work with. Please note that all the source code used in this tutorial can be found on github. Link is at the end of the post.

Continue reading “Moving on to Assertj assertions – beginner examples”

How to add an extra source directory in Maven?

Problem

Sometimes, you might feel the need to add an “extra” source directory in Maven. This becomes tricky specifically when you have already added that extra directory in your favorite IDE. Because of this, you will not see the compiler errors until you build the project using Maven. The need to add the extra source directories becomes more prevalent when you are using some automatic code generation (like Spring query DSL) in your project.

Solution

For the sake of covering a wider range of audience and to make this post more helpful, I will begin by considering that the default Maven configuration (only src/main/java and src/test/java added in your IDE).

Consider the below project structure in which only src/main/java and src/test/java added in source directories in your IDE (eclipse).directory_structure

Please note that there is a directory named “extra” that is not added as a source directory. Now go ahead and add the directory named “extra” as a source directory in eclipse.

Step 1) Right click on your project> Properties > Java Build Path> Add Folder> select “extra”
add_extra_src

Step 2) Once you complete the above step, you should be able to see the recently added directory added as the source directory.
extra_added

Step 3) However, doing so, the compilation errors in eclipse will be kicked out, however, you won’t be able to build this project using Maven. If you try to do so, you’ll get the below error.

[code language=”plain”]
[INFO] 2 errors
[INFO] ————————————————————-
[INFO] ————————————————————————
[INFO] BUILD FAILURE
[INFO] ————————————————————————
[INFO] Total time: 2.321 s
[INFO] Finished at: 2016-10-02T20:14:55+05:30
[INFO] Final Memory: 14M/161M
[INFO] ————————————————————————
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.5.1:compile (default-compile) on project multisrc: Compilation failure: Compilation failure:
[ERROR] /D:/eclipse/Workspaces/luna-ws/websandbox/multisrc/src/main/java/org/websandbox/multisrc/App.java:[3,27] package some.other.packages does not exist
[ERROR] /D:/eclipse/Workspaces/luna-ws/websandbox/multisrc/src/main/java/org/websandbox/multisrc/App.java:[15,9] cannot find symbol
[ERROR] symbol: variable ExtraSourceFile
[ERROR] location: class org.websandbox.multisrc.App
[/code]

Step 4) Add the Maven plugin to include the extra source directory in your build.

[code language=”xml”]
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.12</version>
<executions>
<execution>
<id>add-source</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/extra</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
[/code]

Step 5) Build your project and everything should be fine now. Download this project example from GitHub.

Further reading

You might see the below error in your pom.xml once you add the plugin mentioned above.
m2e-error

Don’t worry, just click “Discover new m2e connectors” and follow the steps.
Read more about the plugin usage here.