In Ruby, methods with side effects or methods that change the object passed as parameters have "!" as a postfix.
For example:
"SomeString".gsub!(/S/, "s")
would be changing the String object, while"SomeString".gsub(/S/, "s")
would work on a copy of the String object, and would not change the state of any objects outside of the method.
I like this convention, and I'd like to use it when programming in other languages, too.
My question:
Bang methods are not intended to mean "changing the receiver".
http://www.wobblini.net/bang.txt
As you can see, Matz intended them to mean "more dangerous than the version without an exclamation mark". Just a general FYI, seeing most of the answers so far mentions changing the receiver.
In Scheme, methods with side effects or methods that change the object passed as parameters have "!" as a postfix. Methods which are predicates have a "?". Other lisps also sometimes use this convention.
In Java, it's common to have the return type void
for a procedure which mutates its receiver, and to return the computed value for a function which does not. ( eg: String.toLowerCase() returns a new string, Collections.sort(List) sorts in place and does not return a value ). However, this isn't a rigorous idiom, as often mutating procedures also need to return a value.
I can only speak about the languages I've used, but... I'm not familiar with any such convention in Python, Perl, Java, PHP, Javascript, or Bash (shell) scripting.
Some programmers might find it useful to put some prefix or postfix on function names to indicate those that mutate their arguments vs. those that create new "versions" of the arguments and return them. If you're one of those people, go right ahead. But again, I'm not aware of anything standard (except for the const
thing Steven mentioned in C and C++).
There is a convention for marking parameters in other languages (C++ specifically). When calling a method, mark parameters that will not be changed with const: e.g.
void doSomething( const int ¶meter )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With