Why is calling setters in Java constructors discouraged?

Why is calling setters from constructors discouraged in Java?

In Java, coders are discouraged from calling setter functions in class constructors. Even though doing so can sometimes reduce the amount of repeated code.

Consider the following class:

Unit.java

public class Unit {
	protected int health;

	public Unit(int hp) {
		// Prevents health for being set to 0 or less.
		if(hp <= 0)
			throw new IllegalArgumentException("Health must be more than 0.");
		health = hp;
	}

	public void setHealth(int hp) {
		// Prevents health for being set to 0 or less.
		// Repeat of the code in the constructor.
		if(hp <= 0)
			throw new IllegalArgumentException("Health must be more than 0.");

		health = hp;
	}

}

Instead of doing the check twice across 2 functions to ensure the incoming hp value is correct, it might occur to some coders that we can call the setter within the constructor instead, to reduce the amount of repeated code:

Unit.java

public class Unit {
	protected int health;

	public Unit(int hp) {
		// Prevents health for being set to 0 or less.
		if(hp <= 0)
			throw new IllegalArgumentException("Health must be more than 0.");
		health = hp;
		setHealth(hp);
	}

	public void setHealth(int hp) {
		// Prevents health for being set to 0 or less.
		// Repeat of the code in the constructor.
		if(hp <= 0)
			throw new IllegalArgumentException("Health must be more than 0.");

		health = hp;
	}
}

This, however, is discouraged, because (according to textbooks) setters like setHealth() can be overriden by child classes, creating unexpected or buggy behaviour in these child classes.

Continue reading
Java's Scanner.nextLine() is being skipped

Java’s Scanner nextLine() call is being skipped (i.e. not waiting for input)

As a programming language with its fair share of quirks, one of the many things a new Java programmer will run into is the issue of their Scanner.nextLine() calls being ignored. Consider the following Java code:

JavaNextLineProblem.java

import java.util.Scanner;
public class JavaNextLineProblem {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);

		// Prompt the user to enter their name.
		System.out.print("Enter your name: ");
		String name = input.nextLine();

		// Prompt the user to enter their age.
		System.out.print("Enter your age: ");
		int age = input.nextInt();

		// Prompt the user to enter a description.
		System.out.print("Describe yourself in a sentence: ");
		String description = input.nextLine();

		// Prompt the user to enter a message.
		System.out.print("Enter a message: ");
		String message = input.nextLine();
	}
}

This is the desired result (user input coloured in green):

Enter your name: John
Enter your age: 21
Describe yourself in a sentence: I am awesome.
Enter a message: Hello world!

However, this is what you actually get:

Enter your name: John
Enter your age: 21
Describe yourself in a sentence: Enter a message: Hello world!

The program skips over the collection of input for the Describe yourself in a sentence prompt, and goes straight into collecting the input for the Enter a message prompt. What’s going on?

Continue reading
XAMPP MySQL not starting on Windows

XAMPP MySQL not starting on Windows

XAMPP is a great tool for web developers who need to host websites locally on their own computers. Unfortunately, because it uses ports and services that are commonly used by other applications, conflicts can happen, causing certain applications on XAMPP to be unable to run.

In this article, we will be exploring what you can do if XAMPP’s Apache service does not run on Windows.

Continue reading
What to do when gitignore doesn't work

How to fix .gitignore not working on your repository

If you’re using a Git-based source control, you might be familiar with the use of a .gitignore file to list files which Git is supposed to ignore when tracking files and making commits. This can be particularly useful when using Git (if you’re using GitHub Desktop, you’re also using Git) as a source control tool for projects that generate temporary or user-specific files at every run, such as Unity, as these files cannot be shared across different users of the project.

User-generated files in Unity
User-generated files in Unity that don’t need to be tracked by Git.

Sometimes, when setting up the repository, because of a .gitignore that is not properly set up, files that you intend to be ignored can actually get committed into the repository. If that happens, retroactively applying the .gitignore list will not help.

Continue reading
A primer on Base 64 strings — Part 1

A primer on Base 64 strings — Part 1: Introduction

If you have been around the web for awhile, you will notice that sometimes, you will find a series of gibberish alphabets appearing, most often in your browser address bar as part of a website’s URL:

The blue highlighted portions in the GIF above are the aforementioned gibberish alphabets.

These are Base 64 characters, and a large portion of the web uses these characters for a multitude of purposes.

Continue reading
Setting up a virtual Postfix mail server — Part 3

Setting up a virtual Postfix mail server — Part 3: Implementing DKIM, DMARC and rDNS

In the previous part of this tutorial series, we set up a mail server that could accept connections from mail clients like Gmail. This allowed us to send out domain emails using a mail client, instead of having to implement a mailbox on our server.

With our mail server’s basic functionality properly set up, we can now turn our attention to another problem — email deliverability. Spam email is a really big problem online, so many email providers have some kind of system in place to assess whether an incoming email is spam and either flag it, or reject it. Hence, after setting up our mail server, one thing we need to do is to ensure that our mail server conforms to certain email security standards, policies and protocols. This goes a long way to help us communicate to other mail servers that we are trustworthy, so that our emails will be deliverable.

Continue reading
Setting up a virtual Postfix mail server — Part 2

Setting up a virtual Postfix mail server — Part 2: Sending emails with SASL

In the first part of this series, we set up a basic virtual mail server with Postfix that received emails for our domain and forwarded it to a mailbox of our choice. To round off the basic set of features for our mail server, we will be setting up Simple Authentication and Security Layer (SASL) to work with Postfix, so that we can access our mail server with a mailbox client (like Gmail) and send out emails from our domain.

Continue reading
Setting up a virtual Postfix mail server — Part 1

Setting up a virtual Postfix mail server — Part 1: Receiving emails with mail forwarding

If you own a domain, and are looking to set up email hosting for it, you have a couple of options. You can either:

  1. Get a generic web hosting service that comes with a cPanel-based email hosting service, or;
  2. Use services like Google Workspace or Microsoft’s Enterprise Email Service.

The former option is cheap, but can be clunky to use and ineffective with blocking spam. The latter option — being specialised services — are generally much more accessible and effective with spam, but cost more.

There’s actually also a third option, and that is:

  1. Running your own mail server on a cloud server.

This means that you have to set up the server and maintain it, but it also means that you can have a cheap and effective mail server, instead of having to choose between one or the other.

In this series of articles, we are going to explore how we can set up a virtual mail server using a Mail Transfer Agent (MTA) called Postfix. This will be a fully-featured mail server, meaning that over the course of these articles, we will be building a mail server that can:

  1. Send and receive emails,
  2. Filter incoming emails for spam, and;
  3. Pass email policy checks, so that the emails it sends out are not flagged as spam.
Continue reading
Animator does not contain a definition for SetBool

Unity C# error: Animator does not contain a definition for ‘SetBool’

Recently, I came across an error that was quite the head-scratcher while grading some Unity scripts. Here’s what the error says:

Animator does not contain a defintion for 'SetBool'
The myAnim variable was set with myAnim = GetComponent<Animator>() earlier on.

But SetBool() is a valid method in the Animator component from Unity, so what exactly is going on here?

Continue reading