标签云

微信群

扫码加入我们

WeChat QR Code

Say I have the following class:class MyClass{private int memberVar;public MyClass(int passedInVar){memberVar = passedInVar; }}In the constructor you pass in an int and assign it to a private member variable.My question is, is it better to pass that int variable around between private methods of the class, or to not pass the int variable as a parameter and instead have each private method directly access the private membervar?i.e. Is this (Example A):class MyClass{private int memberVar;public MyClass(int passedInVar){memberVar = passedInVar; }public MyPublicMethod(){MyPrivateMethod(memberVar);}public MyPrivateMethod(int variable){// Do something with passed in variable...}}better than this (Example B):class MyClass{private int memberVar;public MyClass(int passedInVar){memberVar = passedInVar; }public MyPublicMethod(){MyPrivateMethod();}public MyPrivateMethod(){// Do something with memberVar...}}The reason I ask is that I find myself switching between the two styles.I find that example the style of example A shows more intent for the code. You can see what is being passed between private methods so it's more obvious what is being affected by that method.Whereas Example B is cleaner because the memberVar isn't being passed between private methods. However the code feels more "side-effecty" because it's not always obvious which private member variables the method is acting on.I'd appreciate your opinions on which approach you consider best.


Why would you've this private variable if you don't use it globally in your class?

2019年04月22日33分54秒

Richard Moore I would choose the second approach as the declaration of memberVar is accessible to all methods so passing the variable would be pointless.

2019年04月22日33分54秒

I would say that it depends on the scenario, perhaps the private method can perform an action on a value supplied, this would make the method more flexible as you wouldn't have to set a field every time you wanted to use the method. I'd say as long as you keep it consistent throughout your application with code standards I don't think either method would be any better than the other, except as said in certain scenarios.

2019年04月22日33分54秒

The way you structure your private attributes and methods is completely up to you, since they are encapsulated within the class. Having said that, option B seems the most sensible to me, given that you're all the time within the same scope.

2019年04月22日33分54秒

In most of the time, I prefer the first approach. I feel that it is a proper function (in and out), and does not have a dependency on the private variable. Functions in mathematics have input and output.

2019年04月22日33分54秒