Search code examples
javapackagehierarchyconventions

Proper Class Organization and File Hierarchy


As a computer programming major, I need to know what the convention is for program development (more specifically with game development) in terms of class organization and file hierarchy. This web page explains naming conventions. I recently sat down to memorize it. So going forward, that is not the kind of organization that I would like help with.

If I were to create a generic platforming game like Super Mario World, how can I organize my packages, classes, etc? What would be overkill in terms of organization of packages and Classes, and what would be considered to be a "big ball of mud" so to speak?

Understandably, this could all be a matter of opinion and perhaps there is another question here on StackOverflow which answers my question, but if anyone can toss in any suggestion of proper conventions that they personally use, that would help hugely.


Solution

  • From a language perspective packages allow to use the same class name in different contexts. You may have multiple classes named SuperMario if you put them in different packages since the package qualifies the class name.

    From an application perspective packages allow you to express the structure of your application. If someone wants to comprehend your source code it will first look at the packages. Therefore any good package design will allow this person to comprehend your code faster. So for a large codebase it is important to have a good, intuitive package structure.

    Here are some principles which I apply to package design:

    1. You don't have to design the perfect package structure upfront as long as your are willing to refactor your packages as your application evolves.

    2. Put classes dealing with the same aspect of your application in the same package.

    com.supermario.gui
    com.supermario.model
    com.supermario.events
    

    3. When you feel that a package contains too much classes and gets crowded then refactor it into subpackages.

    com.supermario.model           95 classes
    

    refactor into

    com.supermario.model.ape       30 classes
    com.supermario.model.stair     40 classes 
    com.supermario.model.ton       25 classes
    

    4. When you feel that an package contains too much subpackages and gets crowded refactor them into subpackges of subpackages, or combine subpackages:

    com.supermario.gui.levela01
    ...
    com.supermario.gui.levelz99
    

    refactor into

    com.supermario.gui.level
    com.supermario.gui.level.a
    com.supermario.gui.level.a.01
    ...
    com.supermario.gui.level.z
    com.supermario.gui.level.z.99
    

    In the end there are no right or wrong designs, but designs and structures which are easy to understand or not.