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
XAMPP Apache not starting on Windows

XAMPP Apache not starting on Windows

In a previous article, we’ve explored the issue of Apache being unable to start on macOS devices. In this article, we will be exploring the same thing, but for the Windows version of XAMPP.

What should you do if XAMPP’s Apache service does not run on your Windows machine? Read on to find out.

Update 6 April 2023: Added some new solutions to the article.

Continue reading

Content begins after the advertisement:


Create a Farming RPG in Unity - Part 13

Creating a Farming RPG (like Harvest Moon) in Unity — Part 13: Title Screen and Obstacle Generation

This article is a part of the series:
Creating a Farming RPG (like Harvest Moon) in Unity

Ever wanted to create a game like Harvest Moon in Unity? Check out Part 13 of our guide here, where we go through how to set up the main menu and generate obstacles. You can also find Part 12 of our guide here, where we went through how to implement the player's sleep feature, as well as saving game data to both JSON and binary files.

A link to a package containing the project files up to Part 13 of this tutorial series can also be found at the end of this article, exclusive to Patreon supporters only.

To view this content, you must be a member of Terresqualls Patreon at $5 or more
Already a qualifying Patreon member? Refresh to access this content.
5 best tools for tutoring Math online

5 best tools for tutoring Math online

Maths is a subject that can be difficult to teach, but with the right tools, it can be made easier. This article will discuss some of the best tools for tutoring math online, and how they can help teachers to improve their student’s skills.

Continue reading
A primer on vertical-align in CSS

How to vertical-align text elements in CSS — the last guide you’ll ever need

Of all the CSS attributes that are available to web developes, the vertical-align attribute is perhaps the most mystifying. At first glance, the attribute seems like the vertical aligning cousin of the text-align attribute, but when you try and use it to vertically-centre your elements, it doesn’t work!

<div style="height:100px;background-color:#eee;">
	<p style="background:#dcc;">Item to be vertically-centred</p>
</div>

Item to be vertically-centred

Continue reading
Creating a Farming RPG in Unity - Part 12: Sleeping and Saving

Creating a Farming RPG (like Harvest Moon) in Unity — Part 12: Sleeping and Saving

This article is a part of the series:
Creating a Farming RPG (like Harvest Moon) in Unity

Ever wanted to create a game like Harvest Moon in Unity? Check out Part 12 of our guide here, where we go through how to implement the player's sleep feature, as well as saving game data to both JSON and binary files. You can also find Part 11 of our guide here, where we went through how to save our farmland's data.

To view this content, you must be a member of Terresqualls Patreon at $5 or more
Already a qualifying Patreon member? Refresh to access this content.

Content begins after the advertisement:


XAMPP Apache not starting on macOS

XAMPP Apache not starting on macOS

XAMPP is a great tool for web developers who need to host websites locally on their own computer. 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 we exploring what you can do if XAMPP’s Apache service does not run on a macOS platform.

We also have a guide if XAMPP Apache isn’t starting on your Windows device.

Continue reading
XAMPP MySQL not starting on macOS

XAMPP MySQL not starting on macOS

XAMPP is a great tool for web developers who need to run or test web applications locally on their own computer. Unfortunately, because it runs applications on the LAMP stack, 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 MySQL service does not run on a macOS platform.

Are you looking at getting XAMPP MySQL to work on Windows instead? I’ve also wrote a guide for getting XAMPP Apache working on macOS. Do click on these aforementioned links if they are what you need instead.

Continue reading