Reputation: 487
Hi guys I have a really simple question:
I have the following code :
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. } }
Is this a good design ?
Upvotes: 0
Views: 2733
Reputation: 21220
No, for the simple reason you're violating the 'Do One Thing' principle. Instead:
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();
}
}
}
In this manner you can ensure that your additional instructions are orthogonal to what needs to happen in this method: which is to switch between possible items for each iteration. This makes testing easier. It makes it easier to change your additional instructions, or what happens in each case. It makes your code easier to read. And when you have some other case with yet other instructions, it makes that easy, too.
Remember: each method should do one and only one thing.
Upvotes: 0
Reputation: 17573
The basic idea of a switch statement is to have multiple alternatives from which to choose.
In your example you have only one so using a switch statement does not really make sense.
So from your example, if I am reading it right, I would do something like the following statements which is clearer and easier to read. The problem with using continue is that it is a kind of jump and the resulting source code is a bit confusing.
for (...) {
if (something1 && something != other) {
if (something == something) {
// do the something stuff
}
// do the stuff that is for everything else
}
}
There are limitations on a switch statement and what the various case alternatives can look like which reduces the flexibility of the switch statement.
See this discussion on the switch statement and how it is restricted to some built in types and enumerations. Java Switch Statement.
Upvotes: 1
Reputation: 745
Can you try to write your "Some Instuctions" code inside the case something:. so it will be executed when case is something: only.
Upvotes: 0