Topic: 關于Static

  Print this page

1.關于Static Copy to clipboard
Posted by: skwujinhua
Posted on: 2009-05-07 11:17

跟大家討論個問題﹐在程序中大量使用Static 會有哪些優點和缺點?
我只能想到一點點﹕比如可以減少代碼行﹐但加大內存開支。

大大們你們也發表下﹐謝謝﹗

2.Re:關于Static [Re: skwujinhua] Copy to clipboard
Posted by: junyuo
Posted on: 2009-05-08 10:16

http://www.javaworld.com.tw/jute/post/view?bid=29&id=11490&sty=1&tpg=1&age=-1

3.Re:關于Static [Re: skwujinhua] Copy to clipboard
Posted by: JiafanZhou
Posted on: 2009-05-15 00:20

Hi skwujinhua,

Before talking about the pros and cons of a static member (including static fields and static methods), there is an important Object-Oriented theory you need to understand. Static is subject to the class level, as opposed to individual object instances. Thus, it works like a "global variable" which is shared by all the object instances that belong to the class where the static fields/methods located. It sounds like a very simple idea, but it is extremely important.

Now imagine you are the GOD at the moment, and you decide to use the JAVA programming language to create some sort of Human class. You opened your favourite IDE and write down the code below:

enum Sex
{
Male, Female;
}

class Head
{

}

// ignore other class implementation

class Human
{
private String name;
private Sex sex;
private Head head;
private Body body;
private Arm arm;
private Leg leg;

// getter and setter methods.

// A human can speak
public void speak()
{
}

// A human can walk
public void walk()
{
}

// A human can sleep
public void sleep()
{
}
}


Short and sweet, right? But all of a sudden, you realise that you (the God) want every human being to respect you. At least you don't want them to say you anything bad if you inject too much artificial intelligence. And knowing that you are the only GOD in this universe, and every human should share you as the unique one, hence you added a static field in the Human class as below:

enum Sex
{
Male, Female;
}

class Head
{

}

// ignore other class implementation

class Human
{
private static God god;

private String name;
private Sex sex;
private Head head;
private Body body;
private Arm arm;
private Leg leg;

// getter and setter methods.

// A human can speak
public void speak(String words)
{
if (words.equals("I don't believe in God'"))
{
god.punishHuman(this);
}
}

// A human can eat
public void eat(boolean ifPrayFirst)
{
if (ifPrayFirst)
{
god.giveMoreFood(this);
}
else
{
god.eatMySelf(this);
}
}

// A human can sleep
public void sleep(boolean ifPrayFirst)
{
if (ifPrayFirst)
{
god.letSleepWell(this);
}
else
{
god.giveOneNightmare(this);
}
}
}


In the example above, you added a static God class into the Human class, which now has a object reference to God at the class level. The God class will be created once the first human being is created on the earth. (Adam??) Since then, every human being that you create on the planet will hold a reference to the God class, and receive whatever you want to dole out to them...... In other words, static members are well designed to fit in the OOD world. It can be used to map the scenario in the real world. (Do allow me to say I believe in God and Jesus).

I could say more about static members, but first of all, let me hear back from you to make sure you understand me.

Thanks,
Jiafan

4.Re:關于Static [Re: skwujinhua] Copy to clipboard
Posted by: skwujinhua
Posted on: 2009-05-15 08:50

JiafanZhou﹐Short and sweet, I'm sure! This analogy is very exciting.
But my English is very poor ,so let me speaking Chinese.
我懂你說的意思﹐也知道操作Statis 方法或變量﹐但在程序中如果過多的使用Static﹐會有什么后果或優點呢?

每次發現你在半夜一點或零點回復大家的留言﹐是不是因為美國與中國時差?如果你真在半夜十二點回復大家的留言﹐那我真是太感激你了。

5.Re:關于Static [Re: skwujinhua] Copy to clipboard
Posted by: JiafanZhou
Posted on: 2009-05-18 16:56

skwujinhua wrote:
JiafanZhou﹐Short and sweet, I'm sure! This analogy is very exciting.
But my English is very poor ,so let me speaking Chinese.
我懂你說的意思﹐也知道操作Statis 方法或變量﹐但在程序中如果過多的使用Static﹐會有什么后果或優點呢?

Generally speaking, using static variables will have no difference from using other instance variables. However, the difference is how the variables are initialised. Static variables (class-level) will be initialised only once, conceptually at program invocation time. By contrast, when an instance of a class is created using new, initialization of the class's instance variables (variables unique to each instance) must be done. The difference between these types of initialization is quite important.

Having said that, you will probably have the picture in your mind that static/instance variables have their only usability in the programming. And of course, everything is a double-edge sword, using too many static members will increase the overload at the loading of a particular class, whereas it can significantly improve the performance during the running time. Well, there is one driving guideline here which has been agreed by most programmers: Use Local Variables instead. Local variables are only visible to the local piece of code, e.g. a method or a loop. Their life cycle is much shorter than the global variables regardless it is static or non static. Thus using local variables is much cheaper than global variables. (highly recommended)

Despite of the above reasons, static members have other issues regarding their usage in Java. The following is a pros and cons list that I have promised, I will firstly touch the cons because this is what you care about the most.

Cons:
1. Static fields/methods are not polymorphic.
Believe it or not, even some seasoned programmers will sometimes confuse about this. Yes, static fields/methods are not polymorphic. In others words, we cannot use inheritance to override a static field or static method. This is due to the nature of the static member that it will only be initialised once at the class loading time. Thus, if we designed a field or method to be static, then we lose two of the OOD features, inheritance and polymorphism).

IMO, this is not a problem. Because we can always use the Class.staticField or Class.staticMethod() to get access to the static field.

2. Poorly named static field or methods are incomprehensible.
If naming a static field or method poorly, people will have difficulties or feel weird to understand your code. A very good example is the static factory method. Normally people will use StaticFactory.getInstance() to retrieve the only instance of the factory (if it is designed as a singleton). What if the method is called get()?????. You will have no idea of the purpose of the static factory without reading the comments. Ask yourself, how many time you read the source code and wonder the purpose of a particular static method.

IMO, the name of a static method must be meaningful and understandable.

3. Compromise the thread safety.
Using static improperly or wrongly will greatly compromise the thread safety in the multi-thread programming. Why? Because static fields are only initialised once and are shared by all the instances. If you ever use any static fields in a critical section (an area accessed by multiple threads), then it is fair to say that your program is not thread safe, unless all the static fields are immutable.

IMO, be very cautious using static fields in a multi-threading program.

Pros:
1. You have more control of the code and get flexibility.
A static field can be accessed wherever by using Class.staticField.
A static method can be accessed wherever by using Class.staticMethod().
They look like utilities methods, right. (Yep, in some circumstances static methods are utility methods).

2. Improve the performance.
As the same reason that I have previously explained.

3. Create static factory methods.
Use Class.getInstance() to retrieve a instance of a class. (sometimes it is a singleton)
FYI: Sun use them quite a bit in Java itself.

4. Static factory method can have meaningful names, this can be good
Class.createAllShoppingTrolleys()

Probably said too much, and at some extend, this list is not complete. But I will not lose my sleep if anyone adds another item into the list of the pitfall or tip of using static.

Jiafan


每次發現你在半夜一點或零點回復大家的留言﹐是不是因為美國與中國時差?如果你真在半夜十二點回復大家的留言﹐那我真是太感激你了。

PS: I'm not in the States. I'm working in Ireland. (8 hours behind China in Summer). Smile

6.Re:關于Static [Re: JiafanZhou] Copy to clipboard
Posted by: JiafanZhou
Posted on: 2009-05-18 17:03

Reference this page to http://www.cjsdn.net/post/view?bid=1&id=197805&sty=1&tpg=1&age=0

7.Re:關于Static [Re: skwujinhua] Copy to clipboard
Posted by: skwujinhua
Posted on: 2009-05-19 16:02

我知道你中文也很行的﹐這個我看了半天。學習中﹐給你介紹個地方﹐風景很是不錯。

www.javaworld.com.tw

8.Re:關于Static [Re: skwujinhua] Copy to clipboard
Posted by: JiafanZhou
Posted on: 2009-05-21 17:16

Nail, head, hit Wink

9.Re:關于Static [Re: skwujinhua] Copy to clipboard
Posted by: JiafanZhou
Posted on: 2009-06-06 06:06

Recently I have been preparing for the SCBCD exam, and I found the EJB3.0 specification is very very strict about using the static fields/members for the session and message-driven beans.

It also proves the concept that using static is not thread-safe, I believe this is the reason for the EJB3.0 specification.

Quoted from the EJB 3.0 specification.

A field or method of a bean class may be annotated to request that an entry from the bean's environment be injected. Any of the types of resources or other environment entries described may be injected. Injection may also be requested using entries in the deployment descriptor corresponding to each of these resource types.

The field or method MAY have any access qualifier, but <u>MUST NOT</u> be static.

In other words, EJB experts have the same concerns like me that using static fields could seriously compromise the thread safety.

Regards,
Jiafan

10.Re:關于Static [Re: JiafanZhou] Copy to clipboard
Posted by: ivanna
Posted on: 2009-06-22 12:18

JiafanZhou wrote:
Recently I have been preparing for the SCBCD exam, and I found the EJB3.0 specification is very very strict about using the static fields/members for the session and message-driven beans.

It also proves the concept that using static is not thread-safe, I believe this is the reason for the EJB3.0 specification.

Quoted from the EJB 3.0 specification.

A field or method of a bean class may be annotated to request that an entry from the bean's environment be injected. Any of the types of resources or other environment entries described may be injected. Injection may also be requested using entries in the deployment descriptor corresponding to each of these resource types.

The field or method MAY have any access qualifier, but <u>MUST NOT</u> be static.

In other words, EJB experts have the same concerns like me that using static fields could seriously compromise the thread safety.

Regards,
Jiafan

你要把sun的证考全么。。都卖了!!

11.Re:關于Static [Re: skwujinhua] Copy to clipboard
Posted by: abefirst
Posted on: 2009-06-28 10:38

i could understand .只不过比较慢啊。

12.Re:關于Static [Re: skwujinhua] Copy to clipboard
Posted by: abefirst
Posted on: 2009-06-28 10:52

IMO . you are a kind person


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923