Home > Mobile >  Should require always be at the top of the code (Ruby)?
Should require always be at the top of the code (Ruby)?

Time:01-09

I see lots of Ruby programmers place require at the very first lines and I thought, they do that for a good reason rather than writing readable code! Specifically when they're using more than one...

Now I know requiring more files and libraries will give more load on memory/program, but should one only require something just before when/where it's needed? or does placing require much earlier in the program can have benefits/disadvantages somehow in a long code? or it just depends!

e.g.

require 'open-uri'
require 'rake'
require 'logic.rb'
code 
code...
code..........

or

code
require 'open-uri'
require 'rake'
code...
require 'logic.rb'
code..........

CodePudding user response:

Putting them at the top makes it abundantly clear what dependencies any given file has, though there are occasions when you may want to defer loading something until later.

For example:

  • It's not clear if that import will be used, and that dependency is heavy and could unnecessarily slow down the program.
  • It's not clear if that import could be used, as it might be OS or platform specific and loading it without running some tests would cause problems.
  • There are several mutually exclusive dependencies, and the correct one must be selected and loaded, often depending on environment or configuration details.

Normally it's best to put them all up there for ease of inspection. Finding "surprise" requirements deep down in the code is never fun.

If they're stated clearly, and in a consistent manner, then it's easy to check if you can remove a particular dependency that's no longer necessary. If you leave these hidden in your code you'll have a much harder time doing that, and will be resistant to removing dependencies. Over time that Gemfile can accumulate a lot of junk!

  • Related