开发者

Should I require explicitly all dependencies in every file?

I am asking this for Ruby, but I guess this principle can be applied to every project with multiple files. Say I have a main file e.g. application that requires some other modules model1 and model2. Both those modules need the common module. I've seen many Ruby projects that would require common in application and not in model1 and model2. While this works if you always use application directly, if you require one of the modules from elsewhere, you get a NameError. So maybe this impacts the mod开发者_StackOverflowularity of the project? Should I always prefer requiring explicitly all the dependencies from every file? (By not making any assumption about where the file is required from)


I would always require all dependecies if a module is designed to be loaded from different applications. If model1is only an application specific element, you don't need to load already loaded modules.

But it would take a look, what's really needed. Does model1 and model2 need common or does require the mainfile.rb? (I don't think, that's the case in your specific case) Sometimes you don't need to load all requirements, if one of your requirements (let's call it main-requirment) already loads the other (sub-)requirements.


I place the requires in the very files that are using the things that are being required. This sections off your code into portable modules. You can move files among directories/namespaces, and you can pluck parts out and put them into other repositories/projects, or turn them into gems. The practice of requireing where needed also makes your code more communicative, and therefore easier to understand. A reader is better-informed early on about the area of responsibility of the code in the file.

By putting the requires up in some upper- or top-level file, you are embedding the coupling of the higher-level file with the lower-level one. The higher-level file acquires knowledge about what the lower-level file does and needs. You also obscure where dependencies are actually used. This makes cleanup more challenging, should you desire to remove unused dependencies. You can't tell as easily where and how a given dependency is used. If requires are put where they are used, then you can remove a require from a given file when you remove the dependency usage from that file, and if it happens to be required in another file, your app will not break because of the removal. If you put require in the higher-level file, there is risk that a developer can remove the usage from one file, and then think that the dependency is no longer used, and remove the require from the higher-level file, thereby breaking the code in other files that use it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜