A tour of C++ in 15 minutes

C++ can be defined as a general-purpose, imperative, object-oriented programming language, that allows for low-level memory management. It also has generic programming capabilities.

Primitive data types

Boolean: bool
Character: char
Integer: int
Floating point: float
Double floating point: double
Valueless: void
Wide character: wchar_t

Numeric data types can also be:

signed
unsigned
short
long

Literal Values

C++ allows for different types of literals. It is useful to remember them since using them leads to a more fine-grained control over data stored in variables. Some literal examples are:

Integer: 212, 215u, 0xFeeL
Float: 3.14159, 314159E-5L, 210f

Comments

C++ supports inline and multi-line comments.

// In line comment!

/* In line comment! */

/* Multi-line
* comments!
*/

Hello World Program

All C++ programs have the basic syntax of the program bellow. There can only be one main() function in a C++ program, although a C++ program can have multiple files with many functions.

#include <iostream> //Library needed for std::cout
using namespace std; //Using this we can type “cout” instead of “std::cout”

// All C++ programs start in main()

int main() {
cout << “Hello, World!”; //Prints Hello World to the console
return 0;
}

Operators

C++ offers many operators. Operators can be divided in the categories bellow:

Arithmetic Operators: + – * / % ++

Relational Operators: == != > < >= <=

Logical Operators: || && !

Bitwise Operators: & | ~ ^ << >>

Assignment Operators: = += -= *= /= %= <<= >>= &= ^= |=

Some operators have a higher precedence compared to others. For instance, multiplication has a higher precedence then addition. Some have equal precedence such as addition and subtraction.

Arrays

In order to store data in a sequential fashion: arrays. Arrays are a collection of items of equal type. It allows you to create one variable that points to more than one value. The array variable actually points to the first element of a list of elements of the same type.

An array is declared the following manner:

type arrayName [ size ];

For instance, double numbers[5] creates an array called “numbers” that holds up to 5 double values. The code bellow populates the numbers array with 5 double values:

#include <iostream>
using namespace std;

int main () {

double numbers[ 5];

for ( int i = 0; i < 5; i++ ) {
numbers[i] = i * 2.3d;
}

}

C-String

We covered several data types so far, but we have not mentioned an essential data type that requires more detailed explanation right from the start: The C-Style Character String or C-String. The C-String as the name implies is the C programming language C. The C-String is a sequence of characters terminated by a special character called the null character. The null character is represented by ‘\0’. A C-String would then be created the following manner:

char hello[6] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’};

The cstring library contains a number of functions that manipulate c-strings. These functions are the following:

strcpy(s1, s2); //Copies string s2 into string s1.
strcat(s1, s2); //Concatenates string s2 onto the end of string s1.
strlen(s1); //Returns the length of string s1.
strcmp(s1, s2); //Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
strchr(s1, ch); //Returns a pointer to the first occurrence of character ch in string s1.
strstr(s1, s2); //Returns a pointer to the first occurrence of string s2 in string s1.

 

Loop Control Structures

When creating a program you will often want to perform an action repeatedly. That’s what loop structures are for. C++ offers several types of loop structures. Each can be used in slightly different scenarios:

while loop: Repeats the logic while a given condition is true. It tests the condition before executing the logic every time.

for loop: Repeats the logic up to a certain number of times.

do…while loop: Similar to while, but check the condition after executing the logic in the loop body.
The example bellow populates the numbers array in 3 different ways:

#include <iostream>
using namespace std;

#include <iomanip>
using std::setw;

int main () {

double numbers[ 5];

for ( int i = 0; i < 5; i++ ) {
numbers[i] = i * 2.3d;
}

int i = 0;

while(i < 5) {
numbers[i] = i * 2.3d;
i++;
}

i = 0;

do {
numbers[i] = i * 2.3d;
i++;
} while (i < 5);

}

There’s a lot more to C++. In the next article will cover more aspects of the language, such as, control structures, pointers and more.

The Relevance of Design Patterns

The Gang of Four book, Design Patterns: Elements of Reusable Object-Oriented Software, describes essential design patterns and gives valued advice about software engineering practices. When I first read that book I was amazed about how much I had to learn to improve my approach to developing software. It is not a book one should simply read from cover to cover, but it should rather be carefully studied over the course of one’s software engineering career.

It is common hearing someone ask if the design patterns described on the Gang of For book are still relevant. From my experience, I would say that the content of the book is relevant and will continue relevant for many years ahead. Those design patterns were devised with the purpose of solving specific issues software architects and developers face. The specific issues they address can be tackled by programming language features, however, no programming language until now has managed to provide solutions for all the issues those patterns cover. Hence, the need to study them carefully. No matter how cutting edge your programming language and frameworks are, learn the Gang of Four patterns or end up, as the adage says, “reinventing the wheel” (and probably one of much lower quality).

Here are some strategies I came up with in order to understand design patters well:

  1. Understand how patterns are grouped: Creational, Structural and Behavioral
  2. Focus your study on patterns of a single group so you can study with a specific objective in mind (Improve how I deal with object creation in my code, for instance).
  3. Study the applicability, advantages and disadvantages of the pattern.

By doing that, you will be able to retain deep knowledge of the pattern without simply knowing that it exits. One easy way to spot if a developer has solid understanding of design patterns one can check if he/she knows the disadvantages of that pattern. Most developers learn what a pattern is good for, but not its weaknesses.

Finally, the whole point of studying the Gang of Four book is not to simply go through the daunting task of learning all 23 patterns down to the detail. The true goal is to be able to exercise your mind to apply correct design solutions and think in a more abstract and mature way as a software engineer.

Is REST Dead?

REST Architecture

REST was devised by Roy Fielding in 2000. Rest leverages the existing features of the HTTP protocol in order to provide interoperability between systems. REST makes use of the HTTP verbs to exchange data between servers. The HTTP methods, GET, POST, PUT, DELETE and PATCH, for instance, are used to perform CRUD operations on a entity. REST manipulates resources via these methods combined with a URI (Uniform Resource Identifier), more commonly found as URLs. The following are examples of REST method calls:

GET customers //Retrieves a list of customers

GET customers/1234 //Retrieves customer with ID 1234

The acronym REST stands for Representational State Transfer. The name comes from the idea that we manipulate representations of a resource. REST is a client-server based architecture. Since the HTTP protocol is stateless REST is also stateless. Another key aspect of REST, which is easily noticed, is the uniformity of its interface. Since the interface is decoupled from the actual implementation of the resource, applications rely on formats such as XML or JSON to transfer data.

Is Rest Dead?

There has been much discussion on the internet about REST longevity. Some say that it is dead. Technologies always become obsolete over time, but REST is not dead yet. It is very important to learn it and there’s so much developed with REST that it is unlikely that it will go away any time soon. However, it is worth learning the alternatives to REST. Reactive architecture seems to be the biggest competitor to REST at the moment. I would say that learning Reactive architecture is a must.

A fundamental difference between REST and Reactive Architecture is the fact that REST is synchronous and Reactive asynchronous. That is a huge paradigm shift.

Check out the Reactive Manifesto and sign it, if you agree with it. I would say it is hard not to agree with that at least in theory. Let’s see if the implementations live up to those principles.

Spark – Web applications with minimum effort

The Spark framework was designed with high developer productivity in mind. It aids in the development of web applications by leveraging the JVM itself to offer the infrastructural functionality a web application needs. Spark is pure Java.

The best way to present the advantages of using Spark is by analyzing an example web app buit with spark. Look at the sample code bellow and contrast it with other web frameworks. Think of how simple it is to expose a rest endpoint with Spark:


import static spark.Spark.*;

public class MyApp {
    public static void main(String[] args) {
        get(&quot;/about&quot;, (req, res) -&amp;gt; &quot;My App v1.0 - Built with Spark&quot;);
    }
}

Once you run the app above access the endpoint the following way:

http://localhost:4567/about

Project Setup

Creating the app above is very simple. If you are familiar with maven simply create a maven project and add the following dependency to its pom file:

<dependency>
    <groupId>com.sparkjava</groupId>
    <artifactId>spark-core</artifactId>
    <version>2.5</version>
</dependency>

If you would like to see more logging (and I am sure you eventually will) add the following dependency:

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.7.21</version>
</dependency>

Once you add the dependency above Spark will stop showing the following message:

SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”.
Due to its simplicity Spark is excellent for microservices. As the example above shows Spark is ready to expose REST endpoints and serve JSON with minimum effort.

Micro Services

Due to its simplicity Spark is excellent for micro services. As the example above shows Spark is ready to expose REST endpoints and serve JSON with minimum effort. Successful micro services architecture implementations have already been leveraging the Java Virtual Machine capabilities in order to manage micro services. OSGI is a great example of it. The Eclipse IDE makes extensive use of OSGI, for instance. Netflix is a great example that is currently mentioned when one talks about micro services advantages.

The Spark framework comes in very handy when it comes to micro services due to its pure java implementation and simplicity. It is a very lightweight framework that can be used to expose REST endpoints that serve as means of communication between services of a micro service architecture. Spark can obviously be used to serve static content as any web framework, but it does shine compared to other web frameworks as far as micro services are concerned. Check out its documentation for more details about the power and simplicity of this framework.

 

What about Dependency Injection?

What about dependency injection?

It was once said that “Programmers know the benefit of everything, but the trade-offs of nothing.”. The Spring lightweight container popularized the use of dependency injection tremendously. Mastering the Spring framework dependency injection capabilities became a must have tool in the Java developer toolbox.

Understanding how a specific framework implement dependency injection is a good thing. However, as the quotation above says in a rather ironic way, programmers focus too much on how to use the tools available to them and the advantages they gain by using such tools. Unfortunately, few research the downside of those tools including dependency injection.

Disadvantages of Dependency Injection

Dependency injection does have its disadvantages as any solution does. Here are some of them:

  • DI make code harder to read. Understanding of the code requires understanding how the dependency injection is handled by the lightweight container that provides it. Can you be sure without reading the documentation of that lightweight container that it your injected services will be singleton by the default?
  • DI adds configuration overhead. Spring allow XML and Annotation configuration. Android Roboguice makes use of module classes where interface and implementation classes are associated in code.
  • DI can create a strong dependency of your application to the lightweight container.
  • Alternative to Dependency Injection

So what is the alternative to dependency injection? An alternative is a Service Locator. A Service Locator is an object that knows how to retrieve a reference to the service a client code needs. The client needs to know only about the service interface and how to ask the Service Locator for that service. To get a reference to an EncryptionService we could do the following:

EncryptionService encryptionService = ServiceLocator.encryptionService();

If implemented correctly we can get rid of the disadvantages that DI imposes. A software solution always present advantages and disadvantages. Of course a Service Locator also has its disadvantages. Chances are you will have to implement your own Service Locator whereas reliable DI lightweight containers are already available and free to use. It is up to you to weight the advantages and trade-offs of both options.

Is Clean Code Necessary? – Part II

Clean code is about clarity. In this part I will present some techniques which are easy to apply if a developer takes the time to study them and commit to use them on a daily basis. For those who do not use these techniques yet, the greatest obstacle is a shift in mindset when it comes to structuring code. A developer should strive to turn these techniques into second nature in order to excel in producing high quality code. As I mentioned in part I of this article, these techniques are a summary of the ones presented in the book Clean Code.

Functions

The first one I would like to talk about deals with functions. Functions are one of most the fundamental building blocks of our code. Functions are supposed to be small. Read the previous sentence again and remember it daily. A function should do only one thing and the words used in it should have a clear meaning. Let’s refactor a function that is clearly too long:

public void marshal(File file, Student student) {

try {

JAXBContext jaxbContext = JAXBContext.newInstance(Student.class);

Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

jaxbMarshaller.marshal(student, file);

} catch (JAXBException e) {

LOGGER.error(&quot;An error occurred when trying to marshal object&quot;, e);

}

}

This function has several problems. First you have to read lots of implementation details and several lines to be sure about what it does. Second, the variable names have redundant prefixes (jaxb). The prefixes could be useful in case of conflict which is not the case. We could also improve it by making it generic, but that’s not the point at the moment. Let’s just assume that we will make it generic at some point in the future. Since it will only work with Student Objects, let’s change the function name too. Also, as it is, the caller of that function cannot know if something went wrong. Here, is the improved version:

public void marshalStudent(Student student, File file) throws JAXBException {

Marshaller marshaller = createMarshaller();

marshaller.marshal(file, student);

}

private Marshaller createMarshaller() throws JAXBException {

JAXBContext context = createContext();

Marshaller marshaller = context.createMarshaller();

return marshaller;

}

private JAXBContext createContext() throws JAXBException {

return JAXBContext.newInstance(Student.class);

}

This improvement says much about clean code. How difficult is it to know what the function does with a quick glance over it? The name says it all: “It marshals a Student object”. The body of the marshalStudent function is closer to a prose style rather than presenting implementation fuss as the first version does. Its body tells a story: “I will create a marshaller and marshal the Student object.” Contrast it with the first version that says: “I will create Jaxb Context, then I will create a Jaxb Marshaller with the Jaxb Context that I created. Then I will use the jaxb Marshaller to marshal the Student Object. By the way, if something goes wrong I will catch the exception, print an error message and exit silently.” Which of these two would you rather read? The function was split into top level layer and lower level ones. Why should the top level know how a JaxbContext is created? It does not need to know at all. So that’s buried deep in a lower level function. The revised version of the function has a drawback: The JAXBException thrown to the client of the marshalStudent function exposes the fact that the function uses JAXB. The client does not need that information.

Code Formatting and Comments

Formatting is a key aspect to code readability. Comments can be used to share information about the code. That information can true or false. Comments can inform something that I was true when the code was implemented, but is not true anymore. Let’s refer back to a worse version of the function discussed above. Now with worse formatting and comments:

/**

* This function marshals a Student object to a file using JAXB.

*

* @param File the file

* @param Student the student

*/

public void marshal(File file, Student student) {

try {

//Create the JAXBContext and JAXB Marshaller. Marshal Student object to file.

* Note: The directory of this file should exist. The JAXB Marshaller

* will not create directory path.

*/

JAXBContext.newInstance(Student.class).createMarshaller().marshal(student, file);

} catch (JAXBException e) {

LOGGER.error(&quot;An error occurred when trying to marshal object&quot;, e);

}

}

The code above is far from professional work. In his book, Robert C. Martin, explains in detail how code should be vertically and horizontally formatted. Some developers believe that chaining calls makes the code small and consequently easier to read, but it actually does not. Turning a vertical mess into a horizontal one does not make it less of a mess. Do not use comments to compensate for the lack of clarity in badly-written code. Do not use comments to explain what the code already states that it does.

These are some of the techniques the Clean Code book and that I have come across in numerous hours reading code talks about. For a detailed explanation of these techniques check out that highly acclaimed book.

Is Clean Code Necessary? – Part I

Anyone who has taken the time to read the famous Clean Code, by Robert C. Martin will come to the conclusion that clean code is definitely necessary. The author starts the discussion by mentioning a few quotes by famous experts in software engineering. Among those quotations my favorite one is the following by Grady Booch, author of Object-Oriented Analysis and Design with Applications:

“Clean code is simple and direct. Clean code reads like well-written prose. Clean code never obscures the designers’ intent but rather is full of crisp abstractions and straightforward lines of control.” (Clean Code, Robet C. Martin, p. 8)

Unfortunately even experienced developers often seem not to grasp the principles that quote describes. I have had discussions with developers with different experience levels and I would say that many can not be easily convinced of the critical impact of clean code. For many,  clean code is simply “nice to have”. I ascribe this mentality towards clean code to lack of delving into and applying  the techniques presented in the Clean Code book. Developers who possess a sound understanding of computer science concepts already have the foundation to master the art of producing clean code. I believe that anyone who develops software professionally can take their skills to a higher level of expertise if they commit to produce clean code. However, many fail to do so and stagnate at a certain programming skill level.

The Clean Code book focuses on OOP and the examples are in Java. In the OOD world I have noticed that if software developers focus on the basic principles of this paradigm they will be able to create better code. This sounds obvious, but it is surprising the number of Java developers, for instance, whose knowledge about OOD goes as far as encapsulation and programming to interfaces. If these are the only two OOD concepts that cross through your mind while programming, you definitely need to re-study OOD principles. Study them and re-study them until you can explain to someone any time you are asked to. Once you reach that level of awareness of OOD principles your code will become better and better.

As a reminder the following are the basic OOD principles you should have in mind while programming. The acronym is SOLID:

  • Single-Responsibility: A class should have one responsibility
  • Open-Closed: A class should be open for extension, but close to modification
  • Liskov Substitution: An object can be replaced by a subtype without breaking the program
  • Interface Segregation: Many client specific interfaces are better than a general purpose one
  • Dependency Inversion: Depend on abstractions, not on implementations.

As a test, think about these principles. Do you understand them? If you do, do you think about them while programming? Would you be able to explain that without difficulty to another developer? If your answer is “no” to any of these questions, you have found the reason why you have not considered clean code essential yet.

If you have not read the Clean Code go ahead and start reading it. Chapter 1 has a very catchy sub-heading called “The Total Cost of Owning a Mess”. That section can jump-start your desire to produce clean code, if you do not have that desire yet. In part 2 of this article, I will cover some other principles and techniques described in that book.

Finally free from the final keyword

Throughout my 12 years of experience with the Java programming language and almost 20 years of experience with coding with various programming language I have come to realize that the mastery of software engineering has one key skill as its foundation: the ability to understand advantages and trade-offs.

Technologies come and go nowadays. Developers strive to learn the best techniques in order to use them in the most effective way. This is something we should all do frequently if we want to stay relevant and competitive in this market of constant change and improvement.

Learning best practices and techniques is important, but experience and wisdom show that simply applying them by the letter do not make a software engineer great.

There are two principles I keep in mind when coding: Testability and Readability. These are my top priorities. In that order. With the later extremely close to the other.

For years I have used the final keyword in my Java code diligently. I followed the strict rule of declaring the following “final”:

  • Constants
  • Most Instance variables
  • Method arguments
  • Local Variables

After using the final keyword extensively I realized that it had become a burden. This excessive use of the final keyword protects your code from an issue while promoting greater damage:

On one hand it prevents unwanted reassignment of variables (a not so common error among experienced developers) and on the other it drastically decreases code readability! Let’s take the following code sprinkled with the final keyword as an example:

public class SalaryCalculatorImpl implements SalaryCalculator {

	private final CommissionService commissionService;

	private final TaxService taxService;

	public SalaryCalculatorImpl(final CommissionService commissionService, final TaxService taxService) {
		this.commissionService = commissionService;
		this.taxService = taxService;
	}

	public BigDecimal calculateSalary(final long employeeId, final Date closingDate) {
		final BigDecimal commission = commissionService.getComission(employeeId);
		final List&lt;Tax&gt; taxes = taxService.getTaxes(employeeId);
		BigDecimal totalTax = new BigDecimal(&quot;0&quot;);
		for (final Tax tax : taxes) {
			totalTax = totalTax.add(tax.getAmount());
		}
		final BigDecimal salary = calculate(commission, totalTax);
		return salary;
	}

	private BigDecimal calculate(final BigDecimal commission, final BigDecimal totalTax) {
		...
		...
		...
	}
}

Code like the one above is not uncommon. Some developers are tempted to follow strict guidelines to ensure the quality of their work. I have worked in projects in which these guidelines had to be followed by the letter. As one develops his expertise in software engineering he/she will realize that “best practices” always come with an expiration date. Nowadays, thanks to better testings tools and techniques, the code can be tested so thoroughly. The errors that the final keyword tries to prevent would be easily caught with automated tests.

Consider the same code without the final keywork “noise”. Pay particular attention to how much easier it is to read the calculateSalary method implementation bellow:

public class SalaryCalculatorImpl implements SalaryCalculator {

	private CommissionService commissionService;

	private TaxService taxService;

	public SalaryCalculatorImpl(CommissionService commissionService, TaxService taxService) {
		this.commissionService = commissionService;
		this.taxService = taxService;
	}

	public BigDecimal calculateSalary(long employeeId, Date closingDate) {
		BigDecimal commission = commissionService.getComission(employeeId);
		List&lt;Tax&gt; taxes = taxService.getTaxes(employeeId);
		BigDecimal totalTax = new BigDecimal(&quot;0&quot;);
		for (Tax tax : taxes) {
			totalTax = totalTax.add(tax.getAmount());
		}
		BigDecimal salary = calculate(commission, totalTax);
		return salary;
	}

	private BigDecimal calculate(BigDecimal commission, BigDecimal totalTax) {
		...
		...
		...
	}
}

The final keyword should obviously be used, but in specific cases, such as in pre-Java 8 anonymous classes and constant variables. However, as the example above shows, the excessive use of it leads to visible loss of readability at little to no gain. So let’s continue pushing forward towards more readable Java code, finally free from the excessive use of the final keyword.