Maybe Data Type

Maybe Data Type

Daily short news for you
  • How I wish I had discovered this repository earlier. github/opensource.guide is a place that guides everyone on everything about Open Source. From how to contribute code, how to start your own open-source project, to the knowledge that anyone should know when stepping into this field 🤓

    Especially, this content is directly from Github.

    » Read more
  • Just the other day, I mentioned dokploy.com and today I came across coolify.io - another open-source project that can replace Heroku/Netlify/Vercel.

    From what I've read, Coolify operates based on Docker deployment, which allows it to run most applications.

    Coolify offers an interface and features that make application deployment simpler and easier.

    Could this be the trend for application deployment in the future? 🤔

    » Read more
  • One of the things I really like about command lines is their 'pipeline' nature. You can imagine each command as a pipe; when connected together, they create a flow of data. The output of one pipe becomes the input of another... and so on.

    In terms of application, there are many examples; you can refer to the article Practical Data Processing Using Commands on MTTQVN Statement File. By combining commands, we turn them into powerful data analysis tools.

    Recently, I combined the wrangler command with jq to make it easier to view logs from the worker. wrangler is Cloudflare's command line interface (CLI) that integrates many features. One of them helps us view logs from Worker using the command:

    $ wrangler tail --config /path/to/wrangler.toml --format json

    However, the logs from the above command contain a lot of extraneous information, spilling over the screen, while we only want to see a few important fields. So, what should we do?

    Let’s combine it with jq. jq is a very powerful JSON processing command. It makes working with JSON data in the terminal much easier. Therefore, to filter information from the logs, it’s quite simple:

    $ wrangler tail --config /path/to/wrangler.toml --format json | jq '{method: .event.request.method, url: .event.request.url, logs }'

    The above command returns structured JSON logs consisting of only 3 fields: method, url, and logs 🔥

    » 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...
Scroll or click to go to the next page