嗨,大家好我有一個非常簡單的問題:switch語句繼續
我有以下代碼:
for (...) { if(something == null) { switch(ENUM_TYPE) { case something: something == new Something(); break; case other: continue; } some instructions that i don't want to execute when other. } }
這是一個好的設計?
嗨,大家好我有一個非常簡單的問題:switch語句繼續
我有以下代碼:
for (...) { if(something == null) { switch(ENUM_TYPE) { case something: something == new Something(); break; case other: continue; } some instructions that i don't want to execute when other. } }
這是一個好的設計?
你可以嘗試在案件內寫下你的「一些Instuctions」代碼:。所以當case是某事時它會被執行:只有。
它是一個設置器,如果案例是其他 – AlexGo 2013-05-01 12:00:14
switch語句的基本思想是有多個可供選擇的選項。
在你的例子中,你只有一個,所以使用switch語句沒有任何意義。
所以從你的例子來看,如果我正確地閱讀它,我會做一些更清晰,更易於閱讀的語句。繼續使用的問題在於它是一種跳躍,所產生的源代碼有點混亂。
for (...) {
if (something1 && something != other) {
if (something == something) {
// do the something stuff
}
// do the stuff that is for everything else
}
}
switch語句有各種限制,以及各種替代方案的樣子可能會降低switch語句的靈活性。
請參閱關於switch語句的討論以及它如何限制爲某些內置類型和枚舉。 Java Switch Statement。
不,原因很簡單,你違反了「做一件事」的原則。相反:
for (...)
{
if(something == null)
{
switch(ENUM_TYPE)
{
case something://I think you have variable overloading here.
methodForSomethingCase();
additionalInstructions();
break;
case other:
//essentially do nothing
break;
default:
additionalInstructions();
}
}
}
通過這種方式可以確保您的附加說明正交什麼需要在這個方法中發生的:這是每次迭代可能的項目之間切換。這使得測試更容易。它可以更容易地更改您的附加說明,或者在每種情況下發生的情況。它使您的代碼更易於閱讀。而當你還有其他一些指令的情況下,它也變得很容易。
請記住:每種方法都應該只做一件事。
而不是使用開關,爲什麼不使用一個sentinel變量來執行代碼? – 2013-05-01 11:51:19
擺脫if(something1)。你爲什麼要這樣做,如果你有切換?您可以始終使用默認情況執行正常流程。 – IndoKnight 2013-05-01 11:51:52
如果沒有上下文,這很難確定。 (數據類型,個案數量等) – Breavyn 2013-05-01 11:52:22