4 ms·
I think the thing that really determines whether I break something into a separate function is state. The more state I have to pass into my function, the more u
by slavik81 10y ago
I think the thing that really determines whether I break something into a separate function is state. The more state I have to pass into my function, the more useful that function has to be to justify its existence.
A good name also helps a lot.
- chillacy 10y agoI think refactoring to create a new class is a good solution to the state problem. That is, if you have code like this: func drive(Engine e, Destination d) func park(Engine e) func start(Engine e) You can create a new class class Car { constructor Car(Engine engine) func drive(Destination d) func park() func start() } Which accepts the shared argument in the constructor. That way within the Car, you should have minimal state, and defining new functions can reuse the shared argument that the Car was constructed with: no more long argument lists. A Car was sort of an obvious example but applying that pattern allows me to see less obvious examples, where a class is some abstract entity that I wasn't aware of before. I think there's still fear of undisciplined state management in large classes, but that can be addressed with good SOLID class organization.
- Veedrac 10y agoMultiple shared parameters up is a strong motivation to create a composite type, yes, but one should not instantly jump to making the functions methods of the class. In your example it makes sense, but there are equally many cases it does not. Shared state and shared behaviour are two entirely independent concerns.
- chillacy 10y agoYes, I was responding to what I assumed was the parent's concern that passing state into a function was a hassle. One of the sources which influenced my tastes is Robert Martin's Clean Code.