How to use class variables?

Multi tool use
Multi tool use


How to use class variables?



A simple question. If I have class A with methods m1 and m2. Is it a good practice that m1 changes the state of A. And then when m2 is called it relies on A's state being changed by m1. In other words if m2 is dependent on m1 being called before m2 being called. With m1 and m2 being both private. Worded differently is it O.K. for private methods to consider the object state as shared memory? Problem arises when they are called out of order. But with the benefit of not having to copy arguments. Any advice?




1 Answer
1



Your description is not a good design.



Class variables should have class invariants that are true before and after any (and all) method invocations. The order of calls should not matter. The way you described it make is sounds that there will be cases during which this will not be true, for example if m1 is not called yet and m2 is.



Moreover, design wise, classes should encapsulate (hide) internal dependancies. Whoever consumes class services (methods) should not care about the order of invocation, for example.



My advice is that you will state (explicitly as comments) those invariants and then reason about how do you keep them true (the only time they can be false is during a method call). This could help you come up with less dependency on the ordering of calls.



It may lead you to merge some code from the methods or make m2 a helper function that is called from m1 but not callable externally.





Good answer but suppose both of them are helper functions, private, not accessible from the outside, they are helpers to one of my other functions. I sliced it up so the function does not get too large. I read advice to slice larger functions up to smaller pieces so they are easier to understand but if I have to copy the arguments all the time when passing them from one function to the other, I'm afraid that it could visibly decrease the performance. But I guess It's trade-off which depends more or less on what is the actual object one is trying to achieve.
– Kozmonaut
Jul 1 at 15:21





As long as it is not excessive if you design your methods to do something that is "atomic" in nature then longer methods are better than two methods with forced splitting. By atomic I mean something that is complete in some way, is done well, and in a complete manner. It should be clear from the name and parameters what it does.
– Rahav
Jul 1 at 18:53







By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

DdbH9RS Un7F9TIa34AMHPV2KiK13W3Sdsn tzsMsSl937h1p63dhWyPLggfEq
feqnI 8

Popular posts from this blog

Rothschild family

Cinema of Italy