Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent to exclamation mark for method names from ruby in other languages

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:

  • Do real Ruby programmers (I'm not one;-)) actually use this convention? If not, why not?
  • Are there equivalent conventions for naming methods in Java, PHP, Perl, Cobol...?
  • like image 242
    panschk Avatar asked Mar 17 '09 08:03

    panschk


    4 Answers

    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.

    like image 101
    August Lilleaas Avatar answered Nov 13 '22 11:11

    August Lilleaas


    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.

    like image 39
    Pete Kirkham Avatar answered Nov 13 '22 13:11

    Pete Kirkham


    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++).

    like image 2
    David Z Avatar answered Nov 13 '22 13:11

    David Z


    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 &parameter )
    
    like image 1
    Steven Oxley Avatar answered Nov 13 '22 11:11

    Steven Oxley