One goal we should all strive for is to write code that is clean and simple enough that when we look at it six months or six years from now there’s no issue figuring out what it does. Or, as I like to put it, write your code so that your future self doesn’t invent a time machine to keep you from doing something stupid.
This week Javier from Xojo wrote a blog post at https://blog.xojo.com/2020/06/03/using-class-extensions-to-validate-email-and-url-data/ that shows the simple string extensions IsEmail and IsURL. On their face these are nice examples of using Extension to do something useful in Xojo.
Everything is fine until he says this:
“With using the “ByRef” keyword we are instructing Xojo to give us access to the original data; and in that case we will be able to modify the received data through the given variable name in the Parameters field.”
Again, on its face it’s no big deal but this is exactly what my future self would have a conniption fit about. Why? Because when I see IsEmail and I get a boolean back I will assume (as would most developers) that it’s a simple check to see to see if the string is a valid (or valid enough) email. What I absolutely would not expect is for my source string to get modified.
You see, “IsSomething” means true or false in my book. Not, I’m going to mess with your original data. So when your future self sees that there’s an IsEMail method are you going to go look to see the implementation details? Of course not because IsWhatever that returns a boolean seems pretty straightforward and your boss needed the code yesterday.
If you’re going to create a method that massages the data I wouldn’t use an “Is” prefix. Perhaps an extension method that does this should be named “TestAndReturnEMail” because then you’ll at least look at it and go what the hell was I thinking. But then again, using Extends is probably not idea for testing and modifying a string you think is an email. There’s probably a half dozen ways of doing this better.
My general rule of thumb: if you have to look at the guts of a method to determine what it does you’ve already lost. You really think you’re going to remember that IsEmail six years from now mucks about with your original string? I know I won’t.
In my opinion this is the exact wrong place to use ByRef. Feel free to disagree but if I had one of my developers do this I’d be very disappointed.