panschk
panschk

Reputation: 3272

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...?

    Upvotes: 9

    Views: 2114

  • Answers (4)

    August Lilleaas
    August Lilleaas

    Reputation: 54593

    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.

    Upvotes: 7

    Pete Kirkham
    Pete Kirkham

    Reputation: 49311

    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.

    Upvotes: 3

    David Z
    David Z

    Reputation: 131600

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

    Upvotes: 2

    Steven Oxley
    Steven Oxley

    Reputation: 6723

    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 )
    

    Upvotes: 1

    Related Questions