Search code examples
refactoringconventions

Order of Methods within any Class


I'm still very new to programming and I want to write the cleanest code possible.

This may sound like a silly question, but what order should I put my methods in? Functionally of course it doesn't matter, but layout it makes a huge difference. So say we have the following code in one class:

-(void)testCreateProjectWithStartDate {
    [self setUpTestCreateProjectWithStartDate];
    ...
}

-(void)setUpTestCreateProjectWithStartDate {
    testMOC = [self setUpInMemoryStore];
    [self mockOutXMLStoreForInMemoryStore];
}

- (NSManagedObjectContext *)setUpInMemoryStore {
    ...
    NSPersistentStoreCoordinator *coordMock = [self pscMock];
    ...
}

- (NSPersistentStoreCoordinator *)pscMock {
    ...
}

-(void)mockOutXMLStoreForInMemoryStore {
    ...
}

Do I have the methods ordered in the order that they are called? What if a method is called from two places within a class?

This code snippet looks a complete mess to me - it's very confusing to have to skip about as much as this just to figure out what is a very simple flow.

What order of methods would make more sense?


Solution

  • You have multiple options to group your methods:

    • By functionality (i.e. methods which need each other are close together)
    • By visibility (e.g. public methods declared in the interface come first)
    • By name (i.e. methods are just sorted by their name)

    Personally I prefer to group methods by their functionality, so I do not need to jump too far if I trace the flow. With modern IDE's which do the jump for you this is not a big issue any more though.

    In your specific example, you might want to reduce the number of methods to improve readability. If your methods are all very short (2-3 lines) and only get called from one place, you could inline the code and omit some methods.