簡體   English   中英

嘗試編寫if條件時,我收到死代碼警告

[英]I get a Dead code warning when trying to write an if condition

我收到了代碼的死代碼警告:

Topic topic = findTopicByID(point.getIDTopic());

if (topic != null)
{
   ...
}
else if (topic == null)
{
    // I get Dead code warning for every thing I write here!
}

有時當我收到警告但一切看起來都沒問題時,我重新啟動IDE並且我不再收到警告了! 但這一次......

編輯:

public Topic findTopicByID(int IDTopic) {
    for (Topic topic : topics)
        if (topic.getID() == IDTopic)
            return topic;
    return null;
}

編輯:完整代碼:

Topic topic = Res.getSchedule().getTopicBox().findTopicByID(point.getIDTopic());
            Section section =     topic.findSectionByID(point.getIDSection());

            if (topic != null)
            {
                View rowView = inflater.inflate(R.layout.daily_day_day_row, lLDoneWorks, false);

                TextView tVLabel = (TextView) rowView.findViewById(R.id.daily_day_day_row_label);
                TextView tVNum = (TextView) rowView.findViewById(R.id.daily_day_day_row_num);
                TextView tVTopic = (TextView) rowView.findViewById(R.id.daily_day_day_row_topic);
                TextView tVSection = (TextView) rowView.findViewById(R.id.daily_day_day_row_section);

                int color = topic.getColor();
                tVLabel.setBackgroundColor(color);
                tVNum.setTextColor(color);
                tVTopic.setTextColor(color);
                tVSection.setTextColor(color);

                tVLabel.setText(topic.getName().substring(0,1).toUpperCase(Locale.US));
                tVNum.setText(Integer.toString(point.getCount()));
                tVTopic.setText(topic.getName());
                if (point.getIDSection() != Point.DEFAULT_SECTION)
                    tVSection.setText(section.getName());

                lLDoneWorks.addView(rowView);
            }
            else if (topic == null)
            {
                TopicArchived archivedTopic = Res.getSchedule().getTopicBox()
                            .findArchivedTopicByID(point.getIDTopic());
                    if (archivedTopic == null)
                        removedTopicsPoint += point.getCount();
                    else
                        archivedTopicsPoint += point.getCount();
            }

你可以編碼

if (topic != null)
{
   ...
}
else
{
   ...
} 

代替。

編譯器可能會錯誤解釋條件的目標。 將其重寫為:

if (topic != null) {
   ...
}
else {
    // Code
}

在else條件中, topic在邏輯上保證為null。 如果它不是null, if塊被取消而else不會。

看看你的代碼。

if(topic != null) {
} else { // here topic definitely not null, so the your if is redundant.
}

我想你擁有的是矯枉過正。 為什么不呢:

if (topic != null)
{
    ...
}
else
{
    // It must be null if it gets here
}

這是因為這條線:

Section section =     topic.findSectionByID(point.getIDSection());

如果topic為null,則表示存在NullPointerException,並且未到達其余代碼。 因此,對事后出現的topic空值的每次檢查都是無關緊要的:編譯器知道topic在該行之后不為空。

您應該將該行放在if語句的第一個分支中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM