How to organize your gradle modules

As your application grows, you hopefully organize your code into several gradle (library) modules. You can do that to isolate/decouple features, or to build common libraries for your code base, etc.

One pain point when starting doing this is that gradle modules tend to like to be in the project root folder, having a structure like the following:

- my-app
  |
  - feature-a
  |
  - feature-b
  |
  - feature-c
  |
  - lib-a
  |
  - lib-b
  |
  - lib-b

This is a very flat structure for my taste, it would be much better if we could organize our gradle modules like the following:

- my-app
  |
  - features
    |
    - feature-a
    |
    - feature-b
    |
    - feature-c
  |
  - libs
    |
    - lib-a
    |
    - lib-b
    |
    - lib-b

How to do it? In the settings.gradle file you can add the following:

// This part will include the modules as usual
include :feature-a
include :feature-b
include :feature-c

include :lib-a
include :lib-b
include :lib-c

// This is the trick, it tells gradle where the modules are located within
// the folder structure
project(:feature-a).projectDir = new File(features/feature-a)
project(:feature-b).projectDir = new File(features/feature-b)
project(:feature-c).projectDir = new File(features/feature-c)

project(:lib-a).projectDir = new File(libs/lib-a)
project(:lib-b).projectDir = new File(libs/lib-b)
project(:lib-c).projectDir = new File(libs/lib-c)

And that is it. Enjoy