Is it better for class data to be passed internally or accessed directly?

Posted by AaronSzy on Stack Overflow See other posts from Stack Overflow or by AaronSzy
Published on 2010-04-16T23:26:47Z Indexed on 2010/04/16 23:33 UTC
Read the original article Hit count: 157

Filed under:

Example:

// access fields directly
private void doThis()
{
    return doSomeWork(this.data);
}

// receive data as an argument
private void doThis(data)
{
    return doSomeWork(data);
}

The first option is coupled to the value in this.data while the second option avoids this coupling. I feel like the second option is always better. It promotes loose coupling WITHIN the class. Accessing global class data willy-nilly throughout just seems like a bad idea. Obviously this class data needs to be accessed directly at some point. However, if accesses, to this global class data can be eliminated by parameter passing, it seems that this is always preferable.

The second example has the advantage of working with any data of the proper type, whereas the first is bound to working with the just class data. Even if you don't NEED the additional flexibility, it seems nice to leave it as an option.

I just don't see any advantage in accessing member data directly from private methods as in the first example. Whats the best practice here? I've referenced code complete, but was not able to find anything on this particular issue.

© Stack Overflow or respective owner

Related posts about best-practices