Bad practice to strip all requests into a separate file?

If I have a whole bunch of requests in my main application file:

require 'a'
require 'b'
require 'c'
require 'd'
require 'e'
require 'f'
require 'g'
require 'h'
require 'i'
require 'j'

      

it would be bad practice to lay out the strip that all of these are required from and put them in a separate file that just does whatever is needed - let it " all_requires.rb

" - so I can just say:

require 'all_requires'

      

I've never seen this approach in other people's code, so maybe there is a reason?

+2


source to share


3 answers


There is really nothing wrong with this, but there is generally little use in Ruby. It hides what depends on the file and just adds another layer of indirection. It also doesn't work that well with conditional requirements. This is more common:

DEPENDENCIES = %w(a b c d e f g h i j k)
DEPENDENCIES.each {|f| require f}

      



This way you avoid a huge sequence of strings require

, but keep it localized and declarative.

+6


source


The main reason for explicitly requiring all files is usually to be explicit. This way, it will be easier for someone reading your code (or you, in a few months) to know what's going on.



If your requirements are in other files, it can be quite difficult to know where this is coming from.

+2


source


If you normally require all 10 of these files in multiple files, then yes, it makes sense.

You do one extra file access and parse one extra file that way, but worrying about that is really a micro-optimization. If it makes your code cleaner or just more readable, then go for it. This is far more important than any perceived saved cycles without reading a single file from disk.

If you are using opcode caching (APC, eAccelerator, etc.), even the theoretical differences largely go away as you do unconditional inclusions.

+1


source







All Articles