Maybe Data Type

Maybe Data Type

Daily short news for you
  • That's terrifying, grep.app is a website that allows you to search for anything in the public repositories of Github. Just type in a few characters and it will instantly find where that snippet is located. I wonder how much data one has to store to be sufficient 🤔!

    » Read more
  • Good news for those who missed the 5-day online course with Google GenAI last time. Now you can learn by reading and practicing the content. Join us now 🥳

    5-Day Gen AI Intensive Course with Google Learn Guide

    » Read more
  • Everyone check out if the free ChatGPT account has been given access to DALL·E yet. Today I logged in and saw this icon and was able to use OpenAI's image creation tool. However, I only tried creating 3 images and now I have to wait until tomorrow. It seems there's a limit of 3 images per day 😅

    » Read more

The Problem

Promise in JavaScript is certainly familiar to anyone. A Promise represents a "promise" that when a function is called, it will definitely return a value in the future. Whether it is resolved or rejected, we can predict the likelihood of one of the two occurring. And one thing is for sure, both cannot occur at the same time.

database.query('SELECT * ...');
.then(...);
.catch(...);

If you study Promise more closely, you will see that this is a very interesting and special architecture. Because it is not like any primitive data type, and has some special properties as a data structure, inheriting some methods that only it has, such as then and catch. Moreover, if you see a Promise, you can almost certainly understand how to handle it.

In addition to Promise, in many programming languages in general or JavaScript in particular, people always strive to create safer data structures for programming. Among them is the Maybe type. So what is special about this "Maybe" data type, and how does it help in programming? The answer can be found in the article below.

The Maybe Data Type

Maybe is a data structure that represents the presence or absence of a value. The example below is the simplest implementation for Maybe:

class Maybe {
constructor(value) {
this.value = value;
}

isNothing() {
return this.value === null || this.value === undefined;
}

getOrElse(defaultValue) {
return this.isNothing() ? defaultValue : this.value;
}
}

When creating a structure like this:

const name = new Maybe('2coffee');
console.log(name); // Maybe {value: '2coffee'}
// or
const unname = new Maybe(); // Maybe {value: undefined}

Let's go through the methods in Maybe one by one.

First, we see there is an isNothing. This method checks whether a Maybe has a value or not, and it is usually used to see if there is a value, so that appropriate processing can be done.

getOrElse returns the actual value of Maybe or a default value passed in if that Maybe has no value.

Using it is also simple. For example, if you want to extract the value from unname, if there is none, it returns 2coffee.

const unname = new Maybe();
const realName = unname.getOrElse('2coffee'); // 2coffee

name is an instance of Maybe. We know name contains a string 2coffee but cannot apply some usual logic like with a string. For example:

const name = new Maybe('2coffee');
const fullName = name + `.dev`; // [object Object].dev

That's because name is now an implementation of Maybe, it is not a string, so it cannot execute logic like a string. Instead, we should first extract the value from Maybe.

const name = new Maybe('2coffee');
const fullName = name.getOrElse() + '.dev'; // 2coffee.dev

This usage is not safe, because if name does not contain a value, you will get the result undefined.dev. So additional exception handling is needed in case name has no value. Otherwise.

Maybe data types are often implemented with an additional map method. It allows applying a function to the inner value of Maybe without needing to extract the actual value.

class Maybe {
...
static of(value) {
return new Maybe(value);
}

map(fn) {
if (this.isNothing()) {
return this;
}
return Maybe.of(fn(this.value));
}
}

map takes a function to apply that function to the value inside Maybe. static of is to wrap the value into Maybe and return it.

const name = new Maybe('2coffee');
const makeFullName = (name) => name + '.dev'

const fullName = name.map(makeFullName); // Maybe {value: '2coffee.dev'}

A bit confusing, right? So why not just declare name = '2coffee' instead of going through Maybe? Because the reason behind using Maybe brings certain benefits in specific cases.

Practical Benefits

Applying Maybe in programming helps us minimize null and undefined errors. Because when encountering a Maybe value, we are forced to handle data in the Maybe way.

const user = null;
const name = user.name; // TypeError: Cannot read properties of null

// compared to

const user = Maybe.of(null);
const name = user.map((u) => u.name); // Maybe {value: null}

One thing I really like and always want to write programs in a chaining style. Maybe can completely accommodate this without worrying about "breaks" when encountering null or undefined values.

const data = {
user: {
address: {
city: "Hanoi"
}
}
};

const city = Maybe.of(data)
.map((d) => d.user)
.map((user) => user.profile)
.map((address) => address.city);

In the example above, at the second map, clearly user.profile returns undefined but the third map can still execute without causing the "Cannot read properties of undefined" error, because map has handled this exception.

Similarly, Maybe forces us to handle the case of no value. Imagine Maybe is like Promise. Once called, it always returns one of two values: a value or no value, in each case, we must handle it correctly so that the program does not cause errors during execution.

function findUserById(id) {
const user = database.find((u) => u.id === id);
return Maybe.of(user); // Return Maybe instead of null
}

const userName = findUserById(1)
.map((user) => user.name)
.getOrElse("User not found");

Moreover, if applied well, Maybe can make the program cleaner and more concise. Sometimes, there will no longer be messy if-else statements.

Conclusion

Maybe is a data structure that represents the presence or absence of a value. Applying Maybe in programming helps us minimize null and undefined errors, handle chaining, and have to deal with all cases of having or not having returned data... In addition to Maybe, there is another data structure called Either, which adds some properties that Maybe does not have. We will explore this together in the next article!

Premium
Hello

Me & the desire to "play with words"

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member now!

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member now!

View all

Subscribe to receive new article notifications

or
* The summary newsletter is sent every 1-2 weeks, cancel anytime.
Author

Hello, my name is Hoai - a developer who tells stories through writing ✍️ and creating products 🚀. With many years of programming experience, I have contributed to various products that bring value to users at my workplace as well as to myself. My hobbies include reading, writing, and researching... I created this blog with the mission of delivering quality articles to the readers of 2coffee.dev.Follow me through these channels LinkedIn, Facebook, Instagram, Telegram.

Did you find this article helpful?
NoYes

Comments (0)

Leave a comment...