Suffering insomnia at 5am & so reading Clean Code (by Robert Martin). This book is often seen as a Bible for coding structure and so I was interested to see he suggests the 'Newspaper' analogy when it comes to ordering methods/functions within classes. The book suggests you order functions by first public method, then related private methods, then second public method, then related private methods (and so on). So a class structure might look like this:
public func openAccount() {
completeNameDetails()
completeAddressDetails()
}
private func completeNameDetails() {
...
}
private func completeAddressDetails() {
...
}
public func closeAccount() {
deleteNameDetails()
deleteAddressDetails()
}
private func deleteNameDetails() {
...
}
private func deleteAddressDetails() {
...
}
From hunting stackoverflow this morning, it seems there is strong support for this method:
Best practice: ordering of public/protected/private within the class definition?
The issue I have with this suggestion, however, is the public methods of the class are scattered throughout the class. Would it not be better to have all the public methods at the top of the class and then the privates below it. Certainly this view also has a strong support from this community:
Order of items in classes: Fields, Properties, Constructors, Methods
So in summary, should public methods all be grouped together above private methods or should public methods be followed by their respective private methods (meaning public and private methods are mixed)?
public functions
first andprivate functions
after those. I mean jumping around the class, find a private method, then jumping back to a public method. Especially when the code is unfamiliar. Now, when the methods are organized by newspaper analogy, there is less context switch. Also, just knowing the private method location, I know right away where that is used. – T.Nylund