Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 951
John Gallagher Avatar asked Nov 06 '25 21:11

John Gallagher


2 Answers

I have found this to be more true of methods than of classes - but I think it's because I'm just not doing it enough: keep it short enough, and questions like these disappear.

So, for methods - there have long been questions about whether to initialize all the variables at the top, or to initialize them near where they're used (the answer is near where they're used, fwiw) - but if you keep your methods short enough, it just doesn't matter. Near where they're used is at the top.

Same goes, at least in theory, for classes: keep them short enough, and the internal organization just doesn't matter (limiting and impossible case: just one method per class; it's automatically in whatever order you declare). If your classes have so many methods that you're wondering how to organize - think about extracting some methods that belong together into their own class. Smaller is better.

like image 141
Carl Manaster Avatar answered Nov 08 '25 10:11

Carl Manaster


There's doesn't seem to me to be a definitive answer to this, unless you have a standard to follow for your project/workplace. Personally, if I'm not following another standard, I put the constructor(s) first, followed by the destructor(s). After that, I just put them in alphabetical order by method name. I'm a bit of a dinosaur (I've been programming since the Carter administration), so I adopted the alphabetical approach for functions before I ever heard of object-oriented programming and just carried it over when I started doing objects.

like image 22
PTBNL Avatar answered Nov 08 '25 10:11

PTBNL