Where to place private methods in Ruby?

前端 未结 10 1021
故里飘歌
故里飘歌 2021-01-30 00:50

Most of the blogs or tutorials or books have private methods at the bottom of any class/module. Is this the best practice?

I find having private methods as and when nece

相关标签:
10条回答
  • 2021-01-30 01:01

    The best practice in my point of view is to go sequentially and declare your methods without keeping private in point of view.

    At the end, you can make make any method private by just adding: private :xmethod

    Example:

    class Example
     def xmethod
     end
    
     def ymethod
     end
    
     def zmethod 
     end
    
     private :xmethod, :zmethod
    
    end
    

    Does this justify your question?

    0 讨论(0)
  • 2021-01-30 01:02

    I don't like having to specify public or private for each method. Putting all private methods at the bottom lets me have a single instance of "private" per file. I guess it's a matter of taste.

    0 讨论(0)
  • 2021-01-30 01:05

    Dennis had the perfect answer, that is, when using ruby >=2.1, just prefix the def with private (or protected,public)

    But I believe that it's now also possible to use private as a block as in:

    private begin
       def foo
       end
       def bar
       end
    end
    
    def zip
    end
    
    0 讨论(0)
  • 2021-01-30 01:06

    I'm coming from java background and I hate to have to scroll to see method type. I think it's insane that one cannot specify method visibility per method without ugliness. So I ended up putting a comment #private before each suck method and then declaring private :....

    0 讨论(0)
  • 2021-01-30 01:15

    As others have already pointed out the convention is to put private methods at the bottom, under one private class. However, you should probably also know that many programers use a double indented (4 spaces instead of 2) method for this. The reason is that often times you won't see "private" in your text editor and assume they could be public. See below for an illustration:

    class FooBar
    
      def some_public_method
      end
    
      def another_public_method
      end
    
    private
    
        def some_private_method
        end
    
        def another_private method
        end
    
    end
    

    This method should prevent you from having to scroll up and down and will make other programmers more comfortable in your code.

    0 讨论(0)
  • 2021-01-30 01:15

    I generally order my methods as follows:

    1. Constructor
    2. Other public methods, in alphabetical order
    3. private, written only once
    4. Private methods, in alphabetical order

    I use “go to definition” features in my editor so that this doesn’t involve much scrolling, and in any case, if the class is big enough that scrolling becomes problematic, it probably should be broken up into several classes.

    0 讨论(0)
提交回复
热议问题