Sunday 25 August 2013

Folder Structure of a Java Project

My favourite way of structuring a Java project is into the following folders (in eclipse: File > New Folder. For the two folders calls 'Java' you should also right click on the folder after it has been created, go to 'Build Path' and choose 'Use as source folder'):

-- src
        -- main
                -- java
                -- resources
        -- test
                -- java
                -- resources

This is basically the maven way of organising projects (if you haven't heard of maven then don't worry about that right now).

What goes where? 

  • src/main/java
    • This is where your Java code will live.  It will be nicely arranged into packages (which I will discuss shortly)
  • src/main/resources
    • As you many have guessed, this is where any files other than .java files can go.  For example, if you are using properties files to configure parameters in your application, you might have a file 'src/main/resources/properties/my-awesome-properties-file.properties'.  
  • src/test/java
    • This is where your tests will go. I usually have the structure of this folder mirroring the structure of src/main/java. For example if you have a class 'Circle.java' in the package 'com.ojha.shapes' in src/main/java, then I would have a corresponding package 'com.ojha.shapes' in src/test/java with a class 'CircleTest.java'. 
  • src/test/resources
    • If, for example, you are writing tests to check you can read in a file correctly or something then you might put sample files for your tests in this folder. Another very popular use case is if you are using Spring and want to separate your test configuration from your application configuration. 
Why should I do this?

- You test code should have nothing to do with your application code and you are reflecting this separation by physically putting the code and resources in separate location. 

- Your tests can mirror the package and class structure of the main code which makes it easier to structure tests logically.

- It is a commonly used pattern in Java projects.  Being a Software Engineer isn't just about making code work but also producing clean, logical, intuitively-understood code bases.


Note that if you create folders and organise your files within eclipse, the same folder structure is reflected in the filesystem. This is not the case in Visual Studio where you can arrange your classes nicely into folders within your IDE, but then they end up in different places on disk (this confused me a lot when I first moved to C#!) 





No comments:

Post a Comment

Scala with Cats: Answers to revision questions

I'm studying the 'Scala with Cats' book. I want the information to stick so I am applying a technique from 'Ultralearning&#...