I have a philosophical disagreement with one of my co-workers, and I'm trying to get back to basics here. What is the purpose of a method?
In this question, consider this example. I was criticized for writing the following two methods. I would like to give the caveat that this is a boiled down baby-example, that there were other places in my code that were more complicated but similar.
The baby example
class UI: def __init___(self): self.thingsCheckBox = # checkbox widget self.moreThingsCheckBox = # checkbox widget def wantShowThings(self): return self.thingsCheckBox.checkState() def wantShowMoreThings(self): return self.moreThingsCheckBox.checkState()
So, my co-worker questioned me about writing those two methods. Ultimately, I was forced to remove those two methods (as they did not pass his code review). And this ultimately meant...
if ui.wantShowThings(): # do stuff... if ui.wantShowMoreThings(): # do more stuff...
His version (that ultimately won)
if ui.thingsCheckBox.checkState(): # ... if ui.moreThingsCheckBox.checkState(): # ...
What is the purpose of writing those methods?
- reuse: I think we all agree about reusability. If a bit of code is being copy and pasted multiple times, it should be put into a function or method so that if the code ever changes, you only have to change it in one place. My co worker argues that reusability is the only reason to write something into a function. My co-worker said that if a function isn't called more than once, I should "inline" the logic (write it in the place its used) and write a comment. "Short" methods are "useless" and serve to increase the "spaghetti code". "Stop making me jump around to figure out the logic".
I believe that writing functions serves other purposes:
encapsulation: Hide the implementation of your class. This brings your thinking into a higher level and abstracts away the concrete parts of your code. In my above example, it doesn't matter with wantShowThings() whether or not the underlying implementation is a checkbox, radio button, or even a server call. We're thinking more abstractly than a checkbox. We're thinking "if we want to show things".
documentation: I think code itself can serve as documentation. I know there are pretty radical people that think that comments are completely useless. While I'm not quite as extreme, I sympathize with the philosophy. Why write a comment when you can refactor it into a method with a meaningful name? In my example, I don't need a comment
# This returns true if we want to show things, it's in the method name.
I believe that I have a multitude of literature that supports my thinking. "Clean Code", CodingHorror. I took a class with Stanford's David Cheriton that certainly stood on my side as well.