DEV Community

Discussion on: Share a code snippet in any programming language and describe what's going on

Collapse
 
maxart2501 profile image
Massimo Artizzu

In JavaScript it's:

String.prototype.like_a_cow = function() {
  return `Moo ${this} mooooo`;
};
"Hello".like_a_cow()
> "Moo Hello mooooo"
Enter fullscreen mode Exit fullscreen mode

I wonder how many languages allow this?

Collapse
 
kenbellows profile image
Ken Bellows

I'll do you one better: if you define a dynamic getter using Object.defineProperty, you can make it look exactly like the Ruby example:

Object.defineProperty(String.prototype, 'likeACow', {
    get() {
        return `Moo ${this} mooooo`
    }
})

'Hello'.likeACow
> 'Moo Hello mooooo'
Enter fullscreen mode Exit fullscreen mode
Collapse
 
arjunsahlot profile image
Arjun

Python:

class str(str):
    def like_a_cow(self):
        return f"Moo {self} mooooo"

str("Hello").like_a_cow()
> "Moo Hello mooooo"
Enter fullscreen mode Exit fullscreen mode

I should add that this is not good practice. str is a built in function and you should not override it.

Collapse
 
ryencode profile image
Ryan Brown • Edited

C# allows this,


    public static class StringExtension
    {
        public static string LikeACow(this string self)
        {
            return $"Moo {self} mooooo";
        }
    }
Enter fullscreen mode Exit fullscreen mode

you can now use this as

Console.WriteLine("Hello".LikeACow());
Enter fullscreen mode Exit fullscreen mode

I use extensions a lot on sealed library classes to add Quality Of Life things. One example is creating cleaner methods for adding parameters to SQLClient ClientCommand objects as one liners instead of multi-command monstrosities. (ok, they aren't that big, but do look unclean)

Thread Thread
 
lionelrowe profile image
lionel-rowe

I think it's different (safer) in C# though, right? Like you need to add using <namespace> for the new methods to be accessible. So it's not true monkey patching, which is generally dangerous and best avoided.

Thread Thread
 
ryencode profile image
Ryan Brown

Indeed you would need to use the containing namespace. And are likely safer as it would be pretty hard to modify the behaviour of code outside of your intended changes. (I think you would have to try very hard to have any affect outside of your explicit calls to the extension methods)

I won't claim to know much about TRUE monkey patching, but wikipedia's Extension Methods and Monkey Patching articles do reference each other in suggestive ways. ;)