Published
Class getters vs methods in vanilla JS
when debugging them
Using class getters is really easy with the help of TypeScript. Kinda makes me feel like I’m writing Ruby!
This example demonstrates a Content instance that has a Title that cannot be changed:
class Content {
get title() {
return 'cannot change';
}
}
const myContent = new Content();
alert(`My title = ${myContent.title}`);
In vanilla js, I find it much easier to debug when using class methods, because it will raise a TypeError
if the method doesn’t exist, instead of returning the undefined
value.
class Content {
getTitle() {
return 'cannot change';
}
}
const myContent = new Content();
alert(`My title = ${myContent.getTitle()}`);
In this small example, my point is useless. But when it comes to writing a complicated set of vanilla JS modules, without tests, I find the raised TypeError
to be much easier to debug: it points me directly to the code I need to fix, whereas an undefined
value can cascade to some other point and either raise an error (good!) or just... make everything not work.
At the moment I’m trying to build my own edit-and-commit-to-github admin for this site, and the code is a mess, which has wasted me quite a bit of time in debugging problems.
Usually I find debugging fun! But right now it’s more fun to do the thing I want to do, not deal with problems I’m causing by not paying attention when I’m doing the thing I want to do, so... 💁♂️