Global access versus local variables

I have two objects that will be used mainly inside the same class. I will initialize them at the beginning and use them throughout the life of the program. Now, my question is that if I should just create them as global variables and access them anywhere in the code (aside from one class), or I should create them as local variables and pass them as parameters for other functions. I just want to see what the best programming practice will be.

I am using C #.

Thank.

+5
source share
7 answers

, . , .

, only , ( ) . , (IE, private).

Singleton, ( ) .

+5

- , , -.

, .

, , , . , , .

- , .

+2

, . .

private static readonly. , .

, , . , - .

+2

,

static const double PI = 3.14158;
0

(, ) . , .

.

0

, , , . - ( A - , , B - , :

public class A
{
    private B _b;

    public A(B b)
    {
        _b = b;
    }

    public void DoSomething()
    {
        //do something with _b;
    }

    private void DoSomethingElse()
    {
        //do something else with _b;
    }
}

A B ( B A Injection Dependency). A , B.

0

, , . - . , .

Generally, if only a few methods use objects, pass them otherwise, create them as class level variables (possibly using private static readonly, as Jefferey suggests) and use them in the class. Making code more readable should be your goal here.

0
source

All Articles