0

For a class project in Introduction to Object Orientated Programming, we are creating a simple game.

This game has two main menus. I was just wondering what the best practice for organizing these are. Should I have these functions in a separate object or should I keep these as separate methods?

To me it makes more sense to create separate methods for each and call it in the main like this

public static void main(String[] args)
{
    // call sub module and create objects
}

Any help on this? I figure it will be coming up a lot throughout programming so I want to know the best practices for handling this.

0

1 Answer 1

2

I would suggest storing your menu structure in some hierarchical data structure:

//C# sample
//You can replace the object initializers with constructors in the class,
//In C# 6.0, you can also create an Add extension method taking three parameters, for use with the collection initializer
//    https://github.com/dotnet/roslyn/wiki/New-Language-Features-in-C%23-6#extension-add-methods-in-collection-initializers

class MenuEntry {
    public string Title {get;set;}
    public Action Action {get;set;}
    public List<MenuEntry> Subentries {get;set;}
}

var entries = new List<MenuEntry> {
    new MenuEntry() {Title = "TopLevel1", Subentries = new List<MenuEntry>() {
        new MenuEntry() {Title = "SecondLevel1", Action = () => SecondLevel1()},
        new MenuEntry() {Title = "SecondLevel2", Action = () => SecondLevel2()}
    },
    new MenuEntry() {Title = "TopLevel2", Subentries = new List<MenuEntry>() {
        new MenuEntry() {Title = "SecondLevel3", Action = () => SecondLevel3()},
        new MenuEntry() {Title = "SecondLevel4", Action = () => SecondLevel4()}
    }
}

Then all you need is a single recursive function to render each MenuEntry to the corresponding UI element, and connect the Action to that element.

All else being equal, it is simplest to group the called methods (SecondLevel1, SecondLevel2) together, either in the same class as the main method, or in a separate static class for all these methods. However, it may be more appropriate to keep some or all individual methods together with the appropriate parts of the application: e.g. a StartNewGame method might belong with the Game class.

Not the answer you're looking for? Browse other questions tagged or ask your own question.