this post was submitted on 17 Nov 2024
80 points (100.0% liked)

Programmer Humor

854 readers
9 users here now

Post funny things about programming here! (Or just rant about your favourite programming language.)

Rules:

founded 5 years ago
MODERATORS
 
class BaseFunction {
  static #allowInstantiation = false;

  constructor(...args) {
    if (!BaseFunction.#allowInstantiation) {
      throw new Error(
        "Why are you trying to use 'new'? Classes are so 2015! Use our fancy 'run' method instead!"
      );
    }
    for (const [name, validator] of this.parameters()) {
      this[name] = validator(args.shift());
    }
  }

  parameters() {
    return [];
  }

  body() {
    return undefined;
  }

  static run(...args) {
    BaseFunction.#allowInstantiation = true;
    const instance = new this(...args);
    BaseFunction.#allowInstantiation = false;
    return instance.body();
  }
}

class Add extends BaseFunction {
  parameters() {
    return [
      ["a", (x) => Number(x)],
      ["b", (x) => Number(x)],
    ];
  }

  body() {
    return this.a + this.b;
  }
}

console.log(Add.run(5, 3)); // 8



top 9 comments
sorted by: hot top controversial new old
[–] 30p87@feddit.org 2 points 17 hours ago

"Why are you trying to use 'new'? Classes are so 2015! [...]"

Uses new to throw error

[–] BaumGeist@lemmy.ml 21 points 1 week ago

OP, what's your address? I have a "present" for you

[–] pfm@scribe.disroot.org 17 points 6 days ago

A true FP programmer would make it apply instead of run...

[–] PanArab@lemmy.ml 11 points 6 days ago

This should be programmer horror

[–] bleistift2@sopuli.xyz 11 points 6 days ago

validators is a shitty name for something that actually does type conversion.

[–] navi@lemmy.tespia.org 9 points 6 days ago

Dont look at C++ with std:: function

[–] FiskFisk33@startrek.website 4 points 5 days ago

That'll be fun in a multi threaded setting!

[–] NigelFrobisher@aussie.zone 3 points 5 days ago
[–] CrossbarSwitch@lemm.ee 3 points 5 days ago

I've seen something similar to this at work. Horrible.