Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any best practices on whether to access class instance members directly or pass state as parameters to a class method?

Tags:

c#

For example:

Foo
{
     private int _instanceData;

    // Do this?
    private void Bar1(int instanceData) { // some work using 'instanceData' }

    // Or this?
    private void Bar1( ) { // some work using '_instanceData' }
}
like image 341
user597934 Avatar asked Feb 01 '11 05:02

user597934


2 Answers

If a method already has access to the relevant information as part of the state of the object - and unambiguously so - then I think it would be highly confusing to also pass it in as an argument to the method.

Most of the point of instance methods is to associate behaviour with the state of the object. If you're passing in the information the method needs, you would be better of making the method itself static to make it clear that you're not using the existing state of the object. I'd probably just make it an instance method in the fist place though.

Why would you want to pass in the information via a parameter, when you already have access to it via the instance state?

like image 112
Jon Skeet Avatar answered Sep 22 '22 23:09

Jon Skeet


If the property or field belongs to the same class and you don't want external data to be passed to the method, then there is no need to request that information from the developer and rather call it inside the class instance itself.

like image 24
Den Delimarsky Avatar answered Sep 22 '22 23:09

Den Delimarsky