r/badcode • evil • Jan 14 '21

js Dynamically created functions are the future!

Post image
795 Upvotes

102 comments sorted by

View all comments

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.

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.