Maybe Data Type

Maybe Data Type

Daily short news for you
  • Thank you to threads.net from Meta for being the inspiration behind this section on my blog. Initially, I was a bit skeptical about whether creating short posts like this would attract users, whether anyone would come back to read day after day, or if it would all just be like building sandcastles by the sea. As I have often mentioned, creating a feature is not difficult, but how to operate it effectively is what truly matters.

    Now, time has proven everything. The Short Posts section consistently ranks in the top 5 most visited pages of the day/week/month. This means that readers have developed a habit of returning more often. How can I be so sure? Because this section is almost completely unoptimized for SEO on search engines like Google.

    Let me take you back a bit. In the beginning, I was very diligent in posting on threads.net in the hope of attracting many followers, so that I could subtly introduce them to become users of my blog. However, as time went on, I increasingly felt "exhausted" because the Threads algorithm became less and less aligned with my direction. In other words, the content created was not popular.

    For example, my posts often lean towards sharing information, news, or personal experiences drawn from learning or doing something. It seems that such posts are not highly regarded and often get buried after just over... 100 views. Hmm... Could the problem be me? Knowing this, why not change the content to be more suitable for the platform?

    I have observed Threads, and the content that spreads the most easily often contains controversial elements or a prejudice about something, sometimes it’s simply stating something "naively" that they know will definitely get interactions. However, I almost do not like directing users towards this kind of content. People might call me stubborn, and I accept that. Everyone has different content directions and audiences; the choice is theirs.

    So, from then on, I mainly write here. Only occasionally, if I find something very interesting, do I go on Threads to "show off." Here, people still come to read daily; no matter who you are, I am sure that you can recognize the message I want to convey through each post. At the very least, we share a common direction regarding content. Sometimes, the scariest thing is not that no one reads what you write, but that they read it and then forget it in an instant. Quantity is important, but quality is what brings us closer together.

    Thank you all 🤓

    » Read more
  • Zed is probably the most user-centric developer community on the planet. Recently, they added an option to disable all AI features in Zed. While many others are looking to integrate deeper and do more with AI Agents. Truly a bold move 🤔

    You Can Now Disable All AI Features in Zed

    » Read more
  • Today I have tried to walk a full 8k steps in one session to show you all. As expected, the time spent walking reached over 1 hour and the distance was around 6km 🤓

    Oh, in a few days it will be the end of the month, which means it will also mark one month since I started the habit of walking every day with the goal of 8k steps. At the beginning of next month, I will summarize and see how it goes.

    » 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

The secret stack of Blog

As a developer, are you curious about the technology secrets or the technical debts of this blog? All secrets will be revealed in the article below. What are you waiting for, click now!

As a developer, are you curious about the technology secrets or the technical debts of this blog? All secrets will be revealed in the article below. What are you waiting for, 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...