开发者

When not to use a private field?

开发者 https://www.devze.com 2023-01-04 01:38 出处:网络
When should it be considered dangerous to use a private field all over the place in the methods of your class?I mostly just create the variable and set it to a default value like null.Then in my metho

When should it be considered dangerous to use a private field all over the place in the methods of your class? I mostly just create the variable and set it to a default value like null. Then in my methods reference it and set it to an instance of that object type from the methods.

I don't know开发者_StackOverflow if my question makes sense but let me know if it doesn't and I'll clarify.


If you only need the member inside a single call to a method then prefer to make it a local variable instead of a member. The more local your variables, the easier it is to understand the program.

If it's necessary to use the same object across multiple calls, you could consider if the member could be made readonly and set in the constructor.


Generally speaking, if you are going to use a field all over in your class it should be private, but that can often be a code smell signalling state that is being managed in many places.

Not bad in itself, but the complexity can grow quickly in that case.


If the variable holds sensitive Data you should be aware that it is still accessible from outside with reflection.

Otherwise if you can avoid a private field you shouldn't use one. If you can't, there's nothing wrong with a local field if it is used correctly.

This is a bad idea:

public class Calculator()
{
    private int result;

    public int Add(int a, int b)
    {
        result = a + b;
        return result;
    }
}

because you can get a race condition if two threads call the Add() method at the same time and after the first thread sets the result the context is switched to the second thread wich sets the result and both calls return the value from the second one.

Those errors are hard to debug because they are completely random.

0

精彩评论

暂无评论...
验证码 换一张
取 消