Let’s Use Optional to Fix Our Method Contract

A method is a contract; when we define one, we put our thoughts into it. We specify the parameters with their type and also a return type. When we invoke a method, we expect it to behave according to the contract. If it doesn’t, it’s a violation of the contract.

We deal with such a violation all the time. We invoke a method with its proper arguments, and we get a return. However, sometimes we end up getting a null, which is, in fact, a clear violation. We shouldn’t accept such a violation. If a method cannot return the value of the specified type, it should mention that in the method signature, the method may or may not be returning the value you are expecting. If we know it from the method signature, we then write our code accordingly.

Learning the Basics: Methods in Java

Learn everything you need to know about methods in Java.

If you’ve used Java at all, chances are you’ve already used a method. Look no further than the public static void main(String[] args) at the beginning of every Java program.

What’s in a Name: Java Naming Conventions

Imagine a world without names. What would happen if nothing in this world had a name? This article would have been a very different story. Oh sorry, we wouldn’t even be able to tell the story. What about if we had weird names? Then what will aliens think about us? So, basically, everything is in the name, especially when it comes to programming languages.

Programming is a story; every character and scene needs to have a name that properly tells you what it is and what it does. You should be careful while naming things: You don’t want to make your code hard to read or debug. Remember: You are the creator here. You can name anything from babies, stars, trees, and mountains, almost anything (almost). Paying little attention to this feature will make your code more readable, easy-to-debug, and whatnot. And you should be able to look at it after months and be able to understand it without any trouble.

HashMap: get() Vs. getOrDefault()

When a developer is working on a module, they always come across some form of data structure, like set, queue, list, etc. Data structures are used for storing Java objects in a certain fashion so that they are easy to retrieve when needed.

You may also like: How HashMap Works in Java

The right data structure makes functionality more efficient and effective — otherwise, it would be a nightmare as the implementation expands. You can start with a Map of one of the data structures where objects are stored in the key-value format. And with the help of key, we can easily retrieve the value in time complexity of O(1).

A Look at Java Optionals

Optional is a container object that may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

Package : java.util
public final class Optional<T>
extendsObject