Search code examples
classlanguage-agnosticfunctionencapsulation

What functions to put inside a class


If I have a function (say messUp that does not need to access any private variables of a class (say room), should I write the function inside the class like room.messUp() or outside of it like messUp(room)? It seems the second version reads better to me.


Solution

  • There's a tradeoff involved here. Using a member function lets you:

    • Override the implementation in derived classes, so that messing up a kitchen could involve trashing the cupboards even if no cupboards are available in a generic room.
    • Decide that you need to access private variables later on, without having to refactor all the code that uses the function.
    • Make the function part of an interface, so that a piece of code may require that its argument be mess-up-able.

    Using an external function lets you:

    • Make that function generic, so that you may apply it to rooms, warehouses and oil rigs equally (if they provide the member functions required for messing up).
    • Keep the class signature small, so that creating mock versions for unit testing (or different implementations) becomes easier.
    • Change the class implementation without having to examine the code for that function.

    There's no real way to have your cake and eat it too, so you have to make choices. A common OO decision is to make everything a method (unless clearly idiotic) and sacrifice the three latter points, but that doesn't mean you should do it in all situations.