r/badcode • evil • Jan 14 '21

js Dynamically created functions are the future!

Post image
795 Upvotes

102 comments sorted by

74

u/[deleted] Jan 14 '21

In Ruby you can do this in a nice and useful way.

60

u/NotSteve_ evil Jan 14 '21

Haha seriously? What possible use could writing functions in strings have

77

u/[deleted] Jan 14 '21 edited Jan 14 '21

You can dynamically create methods. It's useful for reducing boilerplate. Sometimes you find yourself just having to implement almost identical methods. That's when it's useful to reach for Ruby's metaprogramming.

I've found it useful when doing Ruby and missed it using other languages that don't have it.

Not something you would use very often though.

34

u/NotSteve_ evil Jan 14 '21

Oh looking into it a bit that does seem neat and useful. I wouldn't mind maintaining that kind of code, unlike the code in the OP...

17

u/[deleted] Jan 14 '21

Yeah dude. I miss Ruby. Such a great language, and such a pity it's fallen out of use. There's Elixir as well, that has gained a bit popularity recently. But still, nothing mainstream.

-3

u/TigreDeLosLlanos Jan 15 '21

When did it was used outside some scripting?

9

u/wilwizard Jan 15 '21

Ruby on Rails was a massively popular backend framework

5

u/NotSteve_ evil Jan 15 '21

Yeah Shopify is built nearly entirely with it from what I remember

7

u/[deleted] Jan 15 '21

and Github is build on Ruby on Rails.

10

u/fun_egg Jan 15 '21

Ruby on Rails was is a massively popular backend framework

2

u/[deleted] Jan 15 '21

Rails was one of the top frameworks for the past 10 years or so, where have you been?

10

u/Isvara Jan 14 '21

Sometimes you find yourself just having to implement almost identical methods.

What are some cases where parametrization isn't sufficient for that?

2

u/[deleted] Jan 16 '21

What do you mean? In Ruby you can do this:

  ["frontend", "backend"].each do |method|
    define_method "coding_#{method}" do
      p "writing " + method.to_s
    end
  end

2

u/Isvara Jan 16 '21

That's pretty ugly. Why would you need to give those closures names?

And why call to_s on a string? And why do you use interpolation in one case and concatenation in the other?

So many curiosities.

2

u/[deleted] Jan 16 '21

I haven't used Ruby in years. I just quickly grabbed that from a Google search just to give you a simple example. You still haven't answered my question.

1

u/AutoModerator Jan 16 '21

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

/u/danklasson, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

0

u/JuhaJGam3R Jan 15 '21 edited Jan 15 '21

This is in fact just parametrization but made really hard. I tried to read about it and it's just about incomprehensible with highly unintuitive syntax. Figures though, metaprogramming isn't the most common feature so I guess it makes sense for it to have obscure syntax.

8

u/Willinton06 Jan 14 '21 edited Jan 14 '21

Is that like manual generic semantics or something?

1

u/[deleted] Jan 14 '21

I don't understand what you mean.

11

u/Willinton06 Jan 14 '21

Like generics in C# or Java where you make a function work with multiple types thus saving you a lot of boilerplate, if the functions are nearly identical then I assume they do the same to a different type or something, maybe they return a different number type or a slightly different class, for those kinds of things we use generics in C#, those are runtime generated functions and methods just like the ones you’re talking about, it also avoids boxing and unboxing because there’s no casting involved, I don’t know if they’re generated at runtime in Java, they could be generated at compile time, but you get my point

0

u/[deleted] Jan 14 '21

Yeah, like that. But way better.

14

u/Willinton06 Jan 14 '21

What makes it better tho

2

u/KernowRoger Jan 15 '21

Ruby's meta programming is amazing. It's kind of hard to explain quickly but stuff like this:

class Developer

    ["frontend", "backend"].each do |method|
        define_method "coding_#{method}" do
            p "writing " + method.to_s
        end
    end
end

From this article https://www.toptal.com/ruby/ruby-metaprogramming-cooler-than-it-sounds. Ruby is a really cool language and allows a huge amount a flexibility.

4

u/Igotbored112 Jan 14 '21

I haven’t ever used Ruby before. Today I wrote 5 functions in C++ which all printed out an array, but they were each specialized for a specific primitive data type that the array might be holding. The functions all have the same name and are used identically by the library user because they’re specialized template functions. But they’re also virtually identical. It had to be this way because primitive types don’t really have special tostring functions in C++ (Well, they do if you use wrappers and the std::iostream class I think but I use printf because it’s way more readable and easy to use.)

In any case, do you think Ruby’s meta programming would have made that easier?

3

u/blueshiftlabs Jan 15 '21

1

u/Igotbored112 Jan 15 '21

Oh boy is it time for me to finally stop using char pointers everywhere?

1

u/[deleted] Jan 14 '21

Well, if you had them in the same class then yes. But then you wouldn't be able to name them the same thing. But other than that, you define the method, and then you can do whatever operations you want inside that method. Including printing or returning different things depending on values within a specific array.

2

u/xigoi Jan 15 '21

I find that too dirty compared to AST-based macros.

1

u/JuhaJGam3R Jan 15 '21 edited Jan 15 '21

Isn't this the point of functions though? I don't see how anyone would ever have to write the same function multiple times if there's only a minor difference. Just write everything once and pass whatever minor thing changes as an argument.

I personally quite dislike metaprogramming in general as it often introduces problems which you can't easily visualize in your head and is generally very good at introducing undebuggable bugs as the lines of code being executed don't exist until they are being executed.

1

u/[deleted] Jan 16 '21

That is true. So you search for a method and you don't find it because it's metaprogramming. That is a huge downside. But sometimes it can be useful. But, like I said, it's something you want to use sparingly.

But Ruby has a lot of these things. Like automatically just adding getters and setters. It's always a trade off. There's no magic bullet. But once you know it's part of the language it's easier for you conceptualize.

In either case, I personally prefer that to having to write tons of boilerplate.

I'm doing a lot of JS and Typescript right now. And I miss the world of Ruby and Python where ideally there would only be one way to do something. In the JS worlds there are hundreds of different libraries and no cohesiveness,

1

u/JuhaJGam3R Jan 16 '21

aren't getters and setters seen as an antipattern nowadays though? nevertheless, having a feature to be able to generate then probably doesn't hurt in itself. I've also been coding in js recently, i feel you. i guess you pretty much have to select a set of libraries and stick with them or you have to overmodularize your code to the point where it isn't even funny anymore, it's just torture.

1

u/[deleted] Jan 16 '21

aren't getters and setters seen as an antipattern

I would hope so. Not sure about Java but in JS you have some, albeit shitty, way of dealing with those now.

1

u/[deleted] Jan 14 '21

Strings are mutable in Ruby too so it isn’t wasting all that memory to construct a string. Shame Ruby isn’t used more.

4

u/hekkonaay Jan 14 '21

Functions from strings are javascript's metaprogramming system, and it's extremely powerful. It's not as easily maintainable as plain code, but it can be a great optimization for a hotpath.

8

u/NotSteve_ evil Jan 14 '21

I know for a fact that's not what this guy was going for at least. This was written by a guy who had just graduated into a team led by a person who had no CS background (biology major) and only knew Perl. The whole codebase is a disaster that I'm slowly rewriting mostly alone.

1

u/SarahTheBlue_ Jan 18 '21

is this written in JS?

1

u/triggerhappy899 Jan 15 '21

You should also check out "source generators" in dotnet 5. Basically allows you to have code that writes code, then during the build process, it generates that code and makes it available for you to use elsewhere.

1

u/cajuncoding Jan 15 '21

In many enterprise platforms that offer developers capability to integrate code by uploading plugins via assemblies, etc its common to see them wrap the plug-in up dynamically like this and then compile it for performance....but Roslyn for C# has made it much easier and more elegant.

In my own experience we needed a dynamic rules engine that could be used with C# syntax where Roslyn compiled expressions from strings was awesome.

In other languages like XSLT where you can extend it with powerful C# functions right there in the source of the XSLT they are using capabilities such as dynamic compilation to enable this....

Sure it’s rare for the average developer to need this at all, and should really question it if they think they do....but there are some very valid use cases for having this capability, so much so that Roslyn was developed ;-) ...

And as someone else mentioned Microsoft is now moving into source generators which will be powerful tools that many underlying frameworks will take advantage of.

1

u/MustachioedMan Jan 15 '21

Roslyn sounds really neat. I implemented a rules engine a while ago in c# using expression trees and it was a real pain

1

u/cajuncoding Jan 16 '21

Yeah with Roslyn it was really a breeze (comparatively speaking as dynamic rules engines go)...here’s an article that helps juxtapose the two approaches

https://www.strathweb.com/2018/01/easy-way-to-create-a-c-lambda-expression-from-a-string-with-roslyn/

1

u/[deleted] Jan 15 '21

I've said the same thing about gigantic libraries that fart out ugly looking SQL monoliths (Wordpress and many other PHP frameworks).

At that point people need to go ORM or sproc. Having disparate pieces of SQL in thousands of files is one of the worst kinds of technical debt.

7

u/KlaireOverwood Jan 14 '21

You can in JavaScript too.

2

u/[deleted] Jan 14 '21

Like what OP posted?

8

u/KlaireOverwood Jan 14 '21

No, in a nice way.

1

u/Perdouille Jan 15 '21

You can in PHP too, I had one case where it was useful but it's nice to have haha

1

u/[deleted] Jan 16 '21

I started my career doing PHP and a hate it with a passion. And I strongly doubt your assertion. But I'm gonna keep an open mind and let you prove it....

1

u/Perdouille Jan 16 '21

If you started your career a long time ago, PHP changed a lot. It's a good language now

And I can't prove the way I used it because it's been a long time ago haha

1

u/[deleted] Jan 16 '21

No, it still sucks monkey balls. I just had an open mind whether what you said was true or not. But you were clearly talking out of your...

1

u/Perdouille Jan 16 '21

Dude what the fuck, fuck off

Keep hating a language for no reason I don't care. You must not be a good dev if you can't use the right language for the right task.

Check out Symfony if you still think PHP "sucks monkey balls" and tell me why you still hate it.

1

u/[deleted] Jan 16 '21

Yeah dude. Been there done that. Symfony 1 and 2. One day, you'll come to the same conclusion.

1

u/Perdouille Jan 16 '21 edited Jan 16 '21

Symfony 1 and 2 my dude. It's been a while.

I use other languages (JS, C#, ...) and I still like PHP. It's a pleasure to use if the codebase is well made.

But continue thinking the language powering most of the web is awful

1

u/[deleted] Jan 16 '21

Well, considering the fact that JS and HTML is what is powering the web....

Which we don't have that much power over. But when it comes to picking PHP. Yeah, that would make no sense whatsoever.

1

u/Perdouille Jan 16 '21

I'm just going to stop answering you. You're talking about a language you clearly haven't used recently, nothing I could say would make you change your mind about it.

→ More replies (0)

1

u/[deleted] Jan 17 '21

You can kinda do this in rust at compile time with procedural macros

20

u/[deleted] Jan 14 '21

Probably fun to write code like this. A nightmare if you inherit it to maintain.

17

u/NotSteve_ evil Jan 14 '21

It's so bad. The previous developers are all long gone too since they almost bankrupted the company and got themselves laid off in the process. There's no documentation either and the codebase is massive. Now I'm in charge of keeping it running. At least the pay is good...

12

u/[deleted] Jan 15 '21

Often, programmers will do things not because it's a good idea, but because they can.

7

u/Tomekske Jan 14 '21

Please, stay on full stack. It should be forbidden for you to program a microcontroller for humanity's sake

17

u/NotSteve_ evil Jan 14 '21

Please don't think I made this atrocity. I just have to maintain it

13

u/Niosus Jan 15 '21

Hahahhaahaha. I've seen and worked on code that ships in cars. Thousands upon thousands upon thousands of lines of C code. Not a unit test in sight. Functions being executed multiple times in a row as workarounds for race conditions. "Tactical" void pointers. And of course, it wouldn't be a proper C program without storing all the state in a global context.

Luckily that code was only used for the infotainment system. But honestly, I don't think the safety critical code is going to be that much better. The only reason we managed to ship relatively bug-free code is because the QA team was really good at their job and found most of the bad stuff before it reached the customers...

Humanity is screwed.

6

u/TigreDeLosLlanos Jan 15 '21

I think I now understand why QA is so well paid.

5

u/GuinnessDraught Jan 15 '21

Same, but airplanes.

2

u/pwnedgiraffe Jan 15 '21

Dude I am scared of flying as it is, I don’t want to know.

2

u/GuinnessDraught Jan 15 '21 edited Jan 15 '21

The saving grace is that aerospace still invests in massive QA operations and exhaustive testing. You can thank the FAA for that, though they have some serious egg on their face with the 737-MAX debacle. But it's a constant battle.

Unlike most other software shops that have just rolled QA into developer responsibilities and decimated QA departments.

Granted, they could probably save a boatload on QA if the developer quality was better instead of contracting and outsourcing so much of it. The result of massive QA of bad code is even worse code, but at least for known cases it is reliable to an outside observer.

4

u/b1ackcat Jan 15 '21

But honestly, I don't think the safety critical code is going to be that much better.

Also worked on code that shipped in cars. The safety critical stuff is definitely better than what you described. Mainly because every single bit and execution flow is accounted for. The systems are designed to work with a very specific set of constraints and they are absolutely purpose built for a given set of features and never anything more. And yes, QA qa's the everloving shit out of it too.

I know what you mean about infotainment systems, though. I worked with those. non software development engineers should not be writing that kind of code lol

189

u/lor_louis Jan 14 '21

I heard you liked JIT so I added JIT to your JIT

95

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jan 14 '21

Image Transcription: Code


// this is the compile function that will become our dimension list;
let compileDimensionList = function (properties) {
    let dimensionFunStr = '(function (d) {\n';
    let dimString = '';
    for (var i = 0, len = properties.length; i < len; i++) {
        if (i === (len-1)) { // end of the list
            dimString += 'd.'+properties[i];
        } else { // every otther item
            dimString += 'd.'+properties[i]+' + ';
        }
    }
    dimensionFunStr += 'if (typeof timeLookup['+dimString+'] === "undefined") {\n';
        dimensionFunStr += 'timeLookup['+dimString+'] = d.time;\n';
    dimensionFunStr += '}\n';
    dimensionFunStr += 'if (d.time > timeLookup['+dimString+']) {\n';
        dimensionFunStr += 'timeLookup['+dimString+'] = d.time;\n';
    dimensionFunStr += '} else {\n';
    dimensionFunStr += 'd.time = timeLookup['+dimString+']\n';
    dimensionFunStr += '}\n';
    dimensionFunStr += 'return '+dimString+';\n';
    dimensionFunStr += '})';
    return eval(dimensionFunStr);
}
let dimensionList = compileDimensionList(groupby); // compile dimension functions

I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!

22

u/fukitol- Jan 15 '21

You wonderful masochist bastard

5

u/TheOnlyTails Jan 15 '21

Yo! Murdo does it again!

4

u/[deleted] Jan 15 '21

[removed] — view removed comment

4

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jan 15 '21

Unfortunately, OCR isn't currently at a stage where it can be used for this purposes.

We actually have a bot that attempts to transcribe posts. It's pretty much the best OCR not behind an expensive paywall, and while it does mostly okay with simple posts that are basically just text, it's easily messed up by anything from different fonts to weird formatting.

One of the ones it has the biggest problem with is code like this. For some reason it just always messes up all of the formatting, and skips over many lines and characters. Some people use its attempts as a basis they correct, but I find to be quicker to just transcribe the post from scratch.

I agree; it would be great if an advancement could be made in the field, but currently, the technology's not at a stage where it can be putting out official transcriptions that haven't at least been vetted by a human, and in the case of code it is, as I've said, useless.

Hope that clears it up! If you have any further questions I can do my best to answer them!

4

u/[deleted] Jan 14 '21

Oh god I can hear the memory screaming from here

4

u/Promant Jan 14 '21

C#'s source generators: let me please introduce ourselfs.

Jokes aside, code like this is actually pretty useful, but only if the compiler itself supports it (so it gets build once, not every time the method is called).

3

u/jarfil Jan 14 '21 edited Dec 02 '23

CENSORED

2

u/[deleted] Jan 15 '21

Isn't this just template

Exactly. C++ devs around the world do that exact thing with templates since decades. With templates it looks a little bit nicer, but it actually is not 😅

2

u/dasbodmeister Jan 14 '21

Oof, when you haven't learned about upvalues yet

7

u/[deleted] Jan 14 '21

What is upvalues 😅

3

u/Isvara Jan 14 '21

What closures close over.

1

u/Unpredictabru Jan 17 '21

Nothing much, what’s up with you?

2

u/frenchy641 Jan 15 '21

This doesn't look secure if the property can be entered by the user

2

u/Martyn_X_86 Jan 15 '21

Ewww, it reminds me of dynamic SQL, which when done correctly can be powerful, but most examples I've seen in the wild are at best very difficult to maintain, and at worst, are a SQL injection attack waiting to happen.

2

u/Duuqnd Jan 15 '21

"We have metaprogramming at home."

1

u/[deleted] Jan 14 '21

You basicaly made a code bloat 😅

1

u/TheTrueSwishyFishy Jan 15 '21

So compile time generics without the compile time

1

u/acomagu Jan 15 '21

I think the author is Lisper.

1

u/Kyn21kx Jan 15 '21

When you want to recreate C++'s templates....

1

u/[deleted] Jan 15 '21

Could the function just be defined, and dimString passed as an argument? Well, I guess dimString is a local value, so maybe not. At the very least, you could define a separate function that takes a string parameter, and then use this same method to call the function in a string and use dimString as the parameter. Or maybe there's a really easy solution, and I'm just overthinking it

1

u/Unpredictabru Jan 17 '21

You could do something like this:

function compileDimensionList(properties) {
    let dimString = ...;
    return function () {
        // you can access dimString here
        ...
    }
}

1

u/[deleted] Jan 17 '21

Oh, that's a way better solution lol

1

u/shizzy0 Jan 15 '21

Shit, people, get a Lisp!

1

u/MegaIng Jan 15 '21

While the exact implementation might need a bit of an improvement (e.g. templates, sanitization, etc.). I really support the core idea. Python as examples uses it in multiple places in its stdlib (namedtuple, dataclass, and (maybe) enum).

1

u/colorpulse6 Jan 15 '21

Oh hell yes

1

u/[deleted] Jan 15 '21

He needs to just learn functional programming this is an atrocity

1

u/Yserbius Jan 15 '21

This reminds me of the last time I had to debug a JSP page with embedded JS. bbrrrrr

1

u/Bowuigi06 Jan 15 '21

Actually with smilebasic you can read and write programs via code so this is possible lol

1

u/not_arch_linux_user Jan 15 '21

truly sadistic. I love it

0

u/[deleted] Jan 14 '21

[deleted]

6

u/ethanjf99 Jan 15 '21

Huh. That is fascinating

4

u/egrgssdfgsarg Jan 15 '21 edited Jan 15 '21

I just tested this, it's only faster if your getClassProperties function is very slow. (In my test I made it some arbitrary function that enumerated all the keys. I had to add a sleep of 100ms to get the string compiled function to be faster.)

And there's a simple optimization for that. You call getClassProperties only once for a schema otherwise you look it up. Essentially, there's a better way to write it than both of the options in the post.

My version of the function (ends up being faster than both versions, under slow and fast circumstances for getClassProperties):

const valuesCache = schema.getClassProperties().values();
function simpleCached(last, current) {
  const changed = {};
  for (const property of valuesCache ) {
    if (last[property.name] !== current[property.name]) {
      changed[property.name] = true;
    }
  }
  return changed;
}

There might be some specific circumstances it's faster to write a function with a string, but 99.99% of the time this is the wrong way to do something.

2

u/Mr2-1782Man Jan 15 '21

Sounds like a problem with the engine.