Java静态方法pros&缺点 [英] Java static methods pros & cons

查看:111
本文介绍了Java静态方法pros&缺点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之前我没有使用过很多静态方法,但最近我倾向于使用更多静态方法。例如,如果我想在类中设置一个布尔标志,或者在一个类中设置一个布尔标志而不需要通过类传递实际对象。

I havent used a lot of static methods before, but just recently I tend to use more of them. For example if I want to set a boolean flag in a class, or acess one without the need to pass the actual object through classes.

例如:

public class MainLoop
{
    private static volatile boolean finished = false;

    public void run()
    {
        while ( !finished )
        {
            // Do stuff
        }

    }
    // Can be used to shut the application down from other classes, without having the actual object
    public static void endApplication()
    {
        MainLoop.finished = true;
    }

}

这是我应该避免的吗?传递一个对象以便使用对象方法更好吗?布尔完成现在算作全局,还是安全?

Is this something I should avoid? Is it better to pass a object so you can use the objects methods? Does the boolean finished counts as a global now, or is it just as safe?

推荐答案

在这种情况下使用静态变量的一个问题是,如果你创建两个(或更多)MainLoop实例,编写看起来像它的代码只关闭其中一个实例,实际上会关闭两个实例他们:

A problem with using a static variable in this case is that if you create two (or more) instances of MainLoop, writing code that looks like it is shutting down only one of the instances, will actually shut down both of them:

MainLoop mainLoop1 = new MainLoop();
MainLoop mainLoop2 = new MainLoop();

new Thread(mainLoop1).start();
new Thread(mainLoop2).start();

mainLoop1.finished = true; // static variable also shuts down mainLoop2 

这只是其中一个原因(其中很多)选择不使用静态变量。即使你今天的程序只创建了一个MainLoop,但未来你可能有理由创建它们中的许多:用于单元测试,或实现一个很酷的新功能。

This is just one reason (amongst many) for choosing to not use static variables. Even if your program today only creates one MainLoop, it is possible that in the future you may have reason to create many of them: for unit testing, or to implement a cool new feature.

您可能会认为如果发生这种情况,我只会重构程序以使用成员变量而不是静态变量。但是,预先支付成本通常更有效,并且从一开始就将模块化设计融入到程序中。

You may think "if that ever happens, I'll just refactor the program to use member variables instead of static variables." But it's generally more efficient to pay the cost up front, and bake modular design into the program from the start.

毫无疑问,静力学经常会制作一个快速而肮脏的程序更容易写。但是对于您打算在未来几年内测试,维护,增长,共享和使用的重要/复杂代码,通常建议使用静态变量。

There's no question that statics often make a quick and dirty program easier to write. But for important / complex code that you intend to test, maintain, grow, share, and use for years to come, static variables are generally recommended against.

作为其他答案对于这个问题已经注意到,静态变量是一种全局变量。有很多关于为什么(通常)全球 变量 糟糕

As other answers to this question have noted, a static variable is a kind of global variable. And there's lots of information about why (generally) global variables are bad.

这篇关于Java静态方法pros&缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆