Search code examples
rubyaccess-specifier

Preferred Ruby-ist way of declaring access controls


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?


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.