Maybe Data Type

Maybe Data Type

Daily short news for you
  • For a long time, I have been thinking about how to increase brand presence, as well as users for the blog. After much contemplation, it seems the only way is to share on social media or hope they seek it out, until...

    Wearing this shirt means no more worries about traffic jams, the more crowded it gets, the more fun it is because hundreds of eyes are watching 🤓

    (It really works, you know 🤭)

    » Read more
  • A cycle of developing many projects is quite interesting. Summarized in 3 steps: See something complex -> Simplify it -> Add features until it becomes complex again... -> Back to a new loop.

    Why is that? Let me give you 2 examples to illustrate.

    Markdown was created with the aim of producing a plain text format that is "easy to write, easy to read, and easy to convert into something like HTML." At that time, no one had the patience to sit and write while also adding formatting for how the text displayed on the web. Yet now, people are "stuffing" or creating variations based on markdown to add so many new formats that… they can’t even remember all the syntax.

    React is also an example. Since the time of PHP, there has been a desire to create something that clearly separates the user interface from the core logic processing of applications into two distinct parts for better readability and writing. The result is that UI/UX libraries have developed very robustly, providing excellent user interaction, while the application logic resides on a separate server. The duo of Front-end and Back-end emerged from this, with the indispensable REST API waiter. Yet now, React doesn’t look much different from PHP, leading to Vue, Svelte... all converging back to a single point.

    However, the loop is not bad; on the contrary, this loop is more about evolution than "regression." Sometimes, it creates something good from something old, and people rely on that goodness to continue the loop. In other words, it’s about distilling the essence little by little 😁

    » Read more
  • Alongside the official projects, I occasionally see "side" projects aimed at optimizing or improving the language in some aspects. For example, nature-lang/nature is a project focused on enhancing Go, introducing some changes to make using Go more user-friendly.

    Looking back, it resembles JavaScript quite a bit 😆

    » 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

5 profound lessons

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? Click now!

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? Click now!

View all

Subscribe to receive new article notifications

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

Comments (0)

Leave a comment...