Maybe Data Type

Maybe Data Type

Daily short news for you
  • Manus has officially opened its doors to all users. For those who don't know, this is a reporting tool (making waves) similar to OpenAI's Deep Research. Each day, you get 300 free Credits for research. Each research session consumes Credits depending on the complexity of the request. Oh, and they seem to have a program giving away free Credits. I personally saw 2000 when I logged in.

    I tried it out and compared it with the same command I used before on Deep Research, and the content was completely different. Manus reports more like writing essays compared to OpenAI, which uses bullet points and tables.

    Oh, after signing up, you have to enter your phone number for verification; if there's an error, just wait until the next day and try again.

    » Read more
  • I just found a quite interesting website talking about the memorable milestones in the history of the global Internet: Internet Artifacts

    Just from 1977 - when the Internet was still in the lab - look how much the Internet has developed now 🫣

    » Read more
  • Just thinking that a server "hiding" behind Cloudflare is safe, but that’s not necessarily true; nothing is absolutely safe in this Internet world. I invite you to read the article CloudFlair: Bypassing Cloudflare using Internet-wide scan data to see how the author discovered the IP address of the server that used Cloudflare.

    It's quite impressive, really; no matter what, there will always be those who strive for security and, conversely, those who specialize in exploiting vulnerabilities and... blogging 🤓

    » 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.

Comments (0)

Leave a comment...