[Cse461] style: "::" and "."

From: Evan Martin (martine_at_danga.com)
Date: Tue Jan 13 2004 - 14:12:35 PST

  • Next message: Jeff Tyrrill: "[Cse461] When to use BroadcastAddress?"

    This question was asked directly once, and I've seen some student code
    that looked a bit questionable to me, so I'm sending this to the list,
    and elaborating on it a bit.

    :: is for "scope resolution", and it's in C++ if not Java. It's
    typically used in Ruby for namespaces--- that is, separating code into
    different packages to keep names from conflicting. For example,
    Fishnet::BroadcastAddress refers to the constant "BroadcastAddress" in
    the "Fishnet" namespace, which is a different variable than, say,
    Foo:BroadcastAddress.

    Most of the Fishnet code is within the Fishnet namespace. This is
    considered good style because there's no possibility of your code
    conflicting if you happened to pick the same name. For example, you
    could have your own class called, uh, "Topology", and it wouldn't
    conflict with the Fishnet one because that one's full name is
    "Fishnet::Topology".

    You'll notice the "::" operator is quite similar to the "." operator;
    a::b and a.b both mean "the thing called [b] contained within [a]".
    Typically, the latter form is for referring to something contained
    within an object (this is the form you're familiar with) and the :: form
    is for something contained within a namespace. That's a fuzzy
    distinction and I believe in Ruby it's more of a style question than
    anything technical.

    A good rule is this: use "." anywhere you are pulling something out of
    an object. Use :: anywhere you are pulling something out of a class or
    a namespace (which is also called a "module" in Ruby).

    class Foo
      FullName = "The Foo Class" # this is a class constant;
                                  # like, um, public static const in Java.
      def initialize(name)
        @name = name # this is a member variable
      end
      attr_reader :name
    end

    myfoo = Foo.new("my foo object")
    puts Foo::FullName # print out the FullName of the Foo class
                         # because we aren't talking about a particular
                         # Foo, use the :: operator.

    puts myfoo.name # print out the name of my particular object

    -- 
    Evan Martin
    martine_at_danga.com
    http://neugierig.org
    ----- End forwarded message -----
    -- 
    Evan Martin
    martine_at_danga.com
    http://neugierig.org
    _______________________________________________
    Cse461 mailing list
    Cse461_at_cs.washington.edu
    http://mailman.cs.washington.edu/mailman/listinfo/cse461
    

  • Next message: Jeff Tyrrill: "[Cse461] When to use BroadcastAddress?"

    This archive was generated by hypermail 2.1.6 : Tue Jan 13 2004 - 14:12:43 PST