java 静态变量:好还是坏?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12492969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 09:08:16  来源:igfitidea点击:

Static Variables : Good or Bad?

javastatic

提问by Swayam

Possible Duplicate:
Why are static variables considered evil?

可能的重复:
为什么静态变量被认为是邪恶的?

I have the habit of using static variablesextensively in all my programs, especially when I am working with Android. I tend to use them because sometimes it feels so cumbersome to send 10 or more values via Intents. So, I just declare them as staticvariables and access them in the other classes easily by using the "dot" operator. Another reason for using static variables is when I am making a Utility classto be used throughout my application. Like the code I have given below helps me to use the variables in different activities.

我有在所有程序中广泛使用静态变量的习惯,尤其是当我使用 Android 时。我倾向于使用它们,因为有时通过 Intents 发送 10 个或更多值感觉很麻烦。所以,我只是将它们声明为静态变量,并通过使用“点”运算符轻松地在其他类中访问它们。使用静态变量的另一个原因是当我制作一个在整个应用程序中使用的Utility 类时。就像我在下面给出的代码一样,可以帮助我在不同的活动中使用变量

Utility.java

实用程序.java

public class Utility {
public static Facebook fb;
public static AsyncFacebookRunner fbAsyncRunner;
public static String[] fbPermissions = {"email", "read_stream", "user_birthday"};
public static final String PREF_UTILITY_FILE_NAME = "PrefUtilityFile";
public static SharedPreferences prefs;
public static Editor editor;
public static String access_token;
public static long expires;
}

I searched online for similar questions and came across thisand this, but they do not seem to give a final answer to the issue. And in most of the places, I see conflicting opinions and hence am totally confused.

我在网上搜索了类似的问题并遇到了这个这个,但他们似乎没有给出这个问题的最终答案。在大多数地方,我看到了相互矛盾的意见,因此完全困惑。

Is it a good programming practice or bad ?Should I be using it or not ?

这是一个好的编程习惯还是坏的?我应该使用它还是不使用它?

回答by Peter Lawrey

You can replace all you static fields with a "Context" object which you can pass around or make a Singleton. It is possible to remove almost all your static fields away. Whether this is a good idea or not is up to you, but I wouldn't assume that it has to be much harder to use instance fields.

您可以用“上下文”对象替换所有静态字段,您可以传递或创建单例对象。可以移除几乎所有的静态字段。这是否是一个好主意取决于您,但我不会认为使用实例字段会更加困难。

BTW: I would suggest

BTW:我建议

  • placing static fields/constant with the class or package which uses them
  • treat static arrays as immutable if possible making them finalas well.
  • 将静态字段/常量与使用它们的类或包放置在一起
  • 如果可能final,也将静态数组视为不可变的。


You can use a non-static Context with

您可以使用非静态上下文

public class Context {
    public static final String PREF_UTILITY_FILE_NAME = "PrefUtilityFile";

    public Facebook fb;
    public AsyncFacebookRunner fbAsyncRunner;
    public String[] fbPermissions = {"email", "read_stream", "user_birthday"};
    public SharedPreferences prefs;
    public Editor editor;
    public String access_token;
    public long expires;
}

// pass to constructor as required
class UsesContext {
    final Context context;
    public UsesContext(Context context) {
        this.context = context;
    }

    public void method() {
        // can use context
    }
}

This allows you to create unit tests with multiple Contexts.

这允许您创建具有多个上下文的单元测试。

The only thing I would leave static are constants.

我唯一要保持静态的是常量。

回答by Tschallacka

I am all for static variables if you keep using them regularly and the values never change if you make them final.

如果你经常使用静态变量,我完全支持静态变量,如果你把它们设为最终值,它们就永远不会改变。

Why do things the difficult way?

为什么事情要困难重重?

That is what static variables are all for.

这就是静态变量的全部用途。

Basically what they do is provide a generic access point you can access from any context(static, program flow, external).

基本上他们所做的是提供一个通用访问点,您可以从任何上下文(静态、程序流、外部)访问。

You are basically stating the front door is here and it's yellow. Someone peeking from the outside will see the door which is yellow. Someone on the inside walking will see the door and that it's yellow. Someone in a room can look into the hallway and see that it's yellow.

你基本上是在说前门在这里,它是黄色的。从外面偷看的人会看到黄色的门。走在里面的人会看到门,而且门是黄色的。房间里的人可以看着走廊,看到它是黄色的。

And if you paint it red, it will be clearly visible to everyone.

如果你把它涂成红色,每个人都会清楚地看到它。

Also, there will always be 1 instance throughout the ENTIRE program with the same value. which saves memory.

此外,在整个 ENTIRE 程序中总会有 1 个具有相同值的实例。这节省了内存。

take for example

class test {
public int ten = 10;
   public test() {
   }
}

Every time you make a new test()an integer memory space will be assigned for the ten variable. So if you have 10 test instances you will have 10 seperate integers all holding the same value.

每次做一个new test()整数内存空间都会分配给十个变量。因此,如果您有 10 个测试实例,您将有 10 个单独的整数,所有整数都具有相同的值。

if you have this

如果你有这个

class test {
public static int ten = 10;
   public test() {
   }
}

and you have ten test instances, you will only have oneinteger instance ten. This saves memory assignment, garbage collection. Although I only advice this for persistent lists/variables that do not change and you can afford to keep in memory indefenately. Don't do this with every variable. Do this for large things like an image that you re-use over and over. No use to keep the same image in memory multiple times.

并且您有十个测试实例,您将只有一个整数实例十。这节省了内存分配,垃圾收集。尽管我只建议不更改的持久列表/变量使用此方法,并且您可以无限期地保留在内存中。不要对每个变量都这样做。对于像您反复重复使用的图像之类的大型事物,请执行此操作。多次在内存中保存相同的图像没有用。

When I originally wrote my answer I didn't know how static variables really worked. I got static finaland staticmixed up. On static variables you can assign new values. static final are immutable. those can't be changed.

当我最初写我的答案时,我不知道静态变量是如何真正工作的。我static finalstatic混淆。在静态变量上,您可以分配新值。静态最终是不可变的。那些不能改变。

回答by gexicide

This programming practice is bad in purely object oriented languages (like Java) because it undermines the object oriented programming paradigm. They work, but once you realize you DO need more than one version of them, you will need a lot of refactoring to achieve that.

这种编程实践在纯面向对象的语言(如 Java)中很糟糕,因为它破坏了面向对象的编程范式。它们可以工作,但是一旦您意识到确实需要多个版本的它们,您将需要进行大量重构才能实现这一目标。

If you think that handing too many parameters via method calls is cumbersome. Simply create an object that holds all of them (see Peter Lawrey's answer, "Context" object) and pass only this object. Then you can again use your "simple dot notation" on that object.

如果您认为通过方法调用处理太多参数很麻烦。只需创建一个包含所有这些的对象(请参阅 Peter Lawrey 的回答,“上下文”对象)并仅传递此对象。然后您可以再次在该对象上使用“简单点符号”。

Next point: Testing. If you need to replace some static fields with proxy or other testing stuff for unit tests, you are basically screwed. With a context object, you can simply hand a different context object into the unit tests.

下一点:测试。如果您需要用代理或其他测试内容替换一些静态字段以进行单元测试,那么您基本上就搞砸了。使用上下文对象,您可以简单地将不同的上下文对象传递到单元测试中。

The Utilityclass you mentioned is basically a good candidate for such context object. Simply make all its fields non-static and hand in an object of that class to code that needs it.

Utility您提到的类基本上是此类上下文对象的良好候选者。只需将其所有字段设为非静态并将该类的对象交给需要它的代码即可。

I can tell you about one example where I got screwed by using statics: I once wrote a compiler. And since I thought that during a compilation run, there are many context things that are only necessary once (the symbol table, for example), I added them all as static variables. Later I decided to allow multi-threaded compilation and a "server" mode where the compiler runs all the time in idle mode until a client sends a compile request (this saves Java's long startup time). Now I was screwed. Now there was more than one concurrent context (concurrent compiler threads), but all context was shared via static variables. I needed around one week to replace all statics by context objects and introduced numerous bugs.

我可以告诉你一个例子,我在使用静态时被搞砸了:我曾经写过一个编译器。因为我认为在编译运行期间,有很多上下文事物只需要一次(例如符号表),所以我将它们全部添加为静态变量。后来我决定允许多线程编译和“服务器”模式,编译器一直在空闲模式下运行,直到客户端发送编译请求(这样可以节省 Java 的长时间启动时间)。现在我被搞砸了。现在有不止一个并发上下文(并发编译器线程),但所有上下文都是通过静态变量共享的。我需要大约一周的时间用上下文对象替换所有静态,并引入了许多错误。

回答by Alexei Kaigorodov

Bad. See Cutting out Static.

坏的。请参阅消除静电

In my opinion, static variables comprise one or more objects, but that objects are ill-formed: not organized in classes (no type hierarchy), bad encapsulation, limited to single instance (this may cause trouble when in future, multiple instances required).

在我看来,静态变量包含一个或多个对象,但这些对象格式不正确:未按类组织(没有类型层次结构)、封装不好、仅限于单个实例(这在将来需要多个实例时可能会造成麻烦) .

回答by Shashwat

Variables that are declared static stays in the memory till the program executes thus taking extra space.

声明为静态的变量会留在内存中,直到程序执行为止,从而占用额外的空间。

The use of static may be beneficial if you want to use/retain a value for a long period of time, however declaring all variables as static is not recommended and is not a good practice . If you make a habit of declaring all value as static your program will eat unnecessary memory.

如果您想长时间使用/保留一个值,则使用 static 可能是有益的,但是不建议将所有变量声明为 static 并且不是一个好习惯。如果您养成将所有值声明为静态的习惯,您的程序将消耗不必要的内存。

Other than that static variable doesn't comply with OOPS concept where scopes, abstraction and encapsulation are defined along with the effervescence object. Through which you can call and delete variables at will.

除此之外,静态变量不符合 OOPS 概念,其中范围、抽象和封装与泡腾对象一起定义。通过它你可以随意调用和删除变量。

The biggest disadvantage of using static variables will appear if you are working in limited memory space (such as mobile applications) in that case you application will crash if it is overhogged by variables and less memory space.

如果您在有限的内存空间(例如移动应用程序)中工作,则会出现使用静态变量的最大缺点,在这种情况下,如果应用程序被变量和更少的内存空间占用过多,则会崩溃。

If you want to store a value permanently there are other ways around like database, files etc makes the job easier and cleaner. Just my 2 cents.

如果您想永久存储一个值,还有其他方法,例如数据库、文件等,使工作更轻松、更干净。只有我的 2 美分。