Question

This is a simple style question. What is the preferred means for declaring access controls in Ruby code?

Example A:


#!/usr/bin/env ruby

class MyClass
    def method1    # this is public by default
        #...
    end
    protected      # subsequent methods will be protected
        def method2
            #...
        end
    private        # subsequent methods will be private
        def method3
            #...
        end
    public         # subsequent methods will be public
        def method4
            #...
        end
end

or Example B:


#!/usr/bin/env ruby

class MyClass
    def method1
        #...
    end
    def method2
        #...
    end
    def method3
        #...
    end
    def method4
        #...
    end
    public :method1, :method4
    protected :method2
    private :method3
end

Syntactically, I like Example B. A introduces ambiguity between public methods declared after protected/private methods, although I see no reason why you shouldn't just call method1 after specifying it as being public.

This isn't however about what I like. What is the industry defined norm for this?

Was it helpful?

Solution

The only place I've ever seen the second method used is in Ruby books, and only as a "You can also do this" example.

And you very rarely see the use of "public" like in the first method, as it's the default and people just define all their public methods before any protected/private declarations.

OTHER TIPS

I think it really depends on your coding style. If you read "Clean Code" by Uncle Bob, you (which I personally loved), you're encouraged to write methods or functions that are called by each other closely together. In this case, using the visibility of a method as in example B would make sense:

class Foo
  def method1
    method2
  end

  def method2
    ..
  end
  private :method2
end

Uncle Bob actually makes a good case for having methods close together, since this prevents scrolling in your code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top