0

Hi, I have 20 strings, each of which will have same package structure except for the class name. These strings need to be passed to method as required. Refer to the code below:

public static final String RECENT_MSG_        = "com.foo.xxs.RecentMessage";
public static final String PROJ_              = "com.foo.xxs.Proj";
public static final String FORECAST           = "com.foo.xxs.Forecase";
public static final String REQUEST            = "com.foo.xxs.Request";
public static final String UNAPPROVED         = "com.foo.xxs.UnApproved";
public static final String UNPOSTED           = "com.foo.xxs.Unposeted";
public static final String VACANT             = "com.foo.xxs.Vacant";
public static final String ORG_VIOL           = "com.foo.xxs.OrgViolation";
public static final String ORG_WARN           = "com.foo.xxs.OrgWarning";
public static final String EMP_VIOL           = "com.foo.xxs.EmpViolation";
public static final String EMP_WARN           = "com.foo.xxs.EmpWarning";    
public static final String TS_WARN            = "com.foo.xxs.TSWarn";
public static final String TS_VIOL            = "com.foo.xxs.TSViolation";
public static final String AGE_GROUP          = "com.foo.xxs.AgeGroup";


private void rescheduleTasks(long _taskType,String value)
{
    if(_taskType == 1000 &&(_sSchedTaskMgr.getInstance().getCurrentScheduledTaskInfo(RECENT_MSG_)==null))
    {

    // do something     
    }

}

This can also be done as follows:

public static final String RECENT_MSG_        = "RecentMessage";
public static final String PACK                       ="com.foo.xxs."

And concatenating the strings like so:

if(_taskType == 1000 &&(_sSchedTaskMgr.getInstance().getCurrentScheduledTaskInfo(PACK+RECENT_MSG_)==null))

Which one would be better?

4

2 に答える 2

2

They will have the same performance - the concatenation will be performed at compile time rather than execution time as both parts are constants. There will be fewer strings in the constant pool in the original version, admittedly - but that's unlikely to make a difference.

Which do you find more readable? I can't say there's much in it for me - I dislike the repetition of the first form, but equally I'm not sure I'd want to concatenate everywhere.

Another alternative is:

public static final String PACK               = "com.foo.xxs."
public static final String RECENT_MSG_        = PACK + "RecentMessage";

etc - so you perform the concatenation at the point of the constant declaration. Then you can just use RECENT_MSG_ in the code, as per the first snippet, but avoid the "com.foo.xxs" duplication as per the second.

EDIT: Another option you may want to consider is using an enum.

于 2010-08-19T06:56:31.987 に答える
1

私は最初のバージョンに行きます。読者が文字列の意味と、参照しているクラスをすぐに確認できるようにするだけです。さらに、別の名前空間からクラスを導入したい場合は、そうすることできます。

対照的に、2 番目のバージョンでは、最初に読者が解釈する必要のあるロジックが導入されています。

2 番目のバージョンを使用する場合は、代わりに Jon の代替案を使用してください。これにより、少なくとも、他の名前空間からクラスを導入するオプションがまだ残っています。

于 2010-08-19T07:03:00.083 に答える