473,744 Members | 2,260 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Sharing code between cases

I'm wondering what the "best" is way to handle blocks of code that are
shared between two or more cases in a switch statement. Consider the
following code (assuming valid variable and function definitions,
obviously):

switch (a)
{
case 1:
if (x) return false;
y = 6;
foo();
break;

case 2:
if (x) return false;
y = 6;
bar();
break;

case 3:
foo();
break;
}

Of course, this isn't too bad, but when the first two lines turn into a
dozen, or as there are more cases that share common code, the
possibility of a change to one not being reflected to all others
increases. Generally, the solution to common code is to pull it out,
but the ways that I see of doing that here are:

1) Sequential switches
switch (a)
{
case 1:
case 2:
// shared code here
}
switch (a)
{
// unique code here
}
This might also be written like
if (a == 1 || a == 2)
{
// shared code here
}
depending on whether there were multiple different blocks of shared
code.

This method looks potentially confusing, and perhaps causes maintenance
problems.

2) Put the common code in a function that is called from each applicable
case. This would work well in some cases, but not, I think, if there
are multiple possible early return values that might be generated,
multiple variables that may be tested or affected (which now all need to
be parameters to the function), etc.

Exceptions could be a way to solve the "multiple return value" part of
the problem with this solution.
So, are there other methods I've missed that people use in this
situation? Is this perhaps an indication that I'm trying to use one
variable to control two orthogonal values (time to refactor)?

--
Greg Schmidt gr***@trawna.co m
Trawna Publications http://www.trawna.com/
Jul 23 '05 #1
12 1524

"Greg Schmidt" <gr***@trawna.c om> schrieb im Newsbeitrag
news:1o******** *******@trawna. com...
I'm wondering what the "best" is way to handle blocks of code that
are
shared between two or more cases in a switch statement. Consider
the
following code (assuming valid variable and function definitions,
obviously):

switch (a)
{
case 1:
if (x) return false;
y = 6;
foo();
break;

case 2:
if (x) return false;
y = 6;
bar();
break;

case 3:
foo();
break;
}


I do this - and I know this is considered crappy style and everyone
will flame me now - for it's fast to write:

#define DEF1 {if (x) return false; y=6;}

switch(a)
{
case 1: DEF1
foo();
break;
case 2: DEF2
bar();
break;
case 3:
foo();
break;
}

any, yes, I do this for very long blocks as well.
-Gernot


Jul 23 '05 #2
In message <1o************ ***@trawna.com> , Greg Schmidt
<gr***@trawna.c om> writes

[switch() complications snipped]

So, are there other methods I've missed that people use in this
situation? Is this perhaps an indication that I'm trying to use one
variable to control two orthogonal values (time to refactor)?


Maybe, but don't just do the obvious and split it into two values. When
a variable is controlling complex *behaviour*, it looks like a hint that
you need to represent that behaviour by polymorphic classes. Then
instead of

switch(a)
{
/* lots of cases, lots of stuff */
}

you'll have

p->DoStuff();

--
Richard Herring
Jul 23 '05 #3

Greg Schmidt wrote:
Exceptions could be a way to solve the "multiple return value" part of the problem with this solution.


I am really surprised nobody else jumped on this one.

Exceptions are not another way to return values. Exceptions are for
exceptional situations and should not be used for flow control or
returns. That is a misuse of the feature and contains all sorts of
bugbears that love to eat lost programmers.

Jul 23 '05 #4
Greg Schmidt wrote:
I'm wondering what the "best" is way to handle blocks of code that are
shared between two or more cases in a switch statement. Consider the
following code (assuming valid variable and function definitions,
obviously):

switch (a)
{
case 1:
if (x) return false;
y = 6;
foo();
break;

case 2:
if (x) return false;
y = 6;
bar();
break;

case 3:
foo();
break;
}
...
1) Sequential switches
...


Wouldn't nested switches be more elegant than sequential ones?

switch (a)
{
case 1:
case 2:

// Common prologue
if (x) return false;
y = 6;

// Specific code (branched with 'if' or 'switch')
switch (a)
{
case 1: foo(); break;
case 2: bar(); break;
}

// Common epilogue
// ...

break;

case 3:
foo();
break;
}

--
Best regards,
Andrey Tarasevich
Jul 23 '05 #5
On Wed, 9 Feb 2005 16:54:42 +0000, Richard Herring wrote:
In message <1o************ ***@trawna.com> , Greg Schmidt
<gr***@trawna.c om> writes

[switch() complications snipped]

So, are there other methods I've missed that people use in this
situation? Is this perhaps an indication that I'm trying to use one
variable to control two orthogonal values (time to refactor)?


Maybe, but don't just do the obvious and split it into two values. When
a variable is controlling complex *behaviour*, it looks like a hint that
you need to represent that behaviour by polymorphic classes. Then
instead of

switch(a)
{
/* lots of cases, lots of stuff */
}

you'll have

p->DoStuff();


You may be right. The library where I'm currently having this issue
(which I did most of the design for) actually makes extensive use of
polymorphism, but for some reason I had a mental block to seeing that it
might work in this case too.

--
Greg Schmidt gr***@trawna.co m
Trawna Publications http://www.trawna.com/
Jul 23 '05 #6
On 9 Feb 2005 09:12:08 -0800, Noah Roberts wrote:
Greg Schmidt wrote:
Exceptions could be a way to solve the "multiple return value" part

of
the problem with this solution.


I am really surprised nobody else jumped on this one.

Exceptions are not another way to return values. Exceptions are for
exceptional situations and should not be used for flow control or
returns. That is a misuse of the feature and contains all sorts of
bugbears that love to eat lost programmers.


I'm sure if you search the archives, you'll find that this is another
one of the religious issues that comes up from time to time. I think it
depends largely on the situation. When I wrote that, I was thinking
that the multiple return values would actually tend to be codes for
different error situations, in which case an argument can be made that
"error" and "exception" can be (close to) synonymous. Certainly, using
an exception to return the result of, say, a mathematical calculation is
an abuse of the feature.

In my original, hypothetical situation, since the exception would be
thrown from the newly-created "shared code" function, which won't be
useful anywhere except very locally, the switch could be nested inside a
try block, and the catch would be right there to trap the exception and
return a "normal" result back to the caller. No need to worry about the
exception biting the unwary when its use is so limited.

--
Greg Schmidt gr***@trawna.co m
Trawna Publications http://www.trawna.com/
Jul 23 '05 #7
Greg Schmidt wrote:
I'm sure if you search the archives, you'll find that this is another
one of the religious issues that comes up from time to time. I think it
depends largely on the situation. When I wrote that, I was thinking
that the multiple return values would actually tend to be codes for
different error situations, in which case an argument can be made that
"error" and "exception" can be (close to) synonymous. Certainly, using
an exception to return the result of, say, a mathematical calculation is
an abuse of the feature.
In "Thinking in C++" Eckel explains the use of exceptions as to deal
with 'exceptional' situations. In other words, the unexpected. He also
uses them to enforce function contract (or preconditions). So for
instance you wouldn't use an exception upon end of file, because that is
an expected situation, but you would if the file suddenly became
unreadable or disconnected without an eof.

I would say that is a pretty reasonable explaination.

In my original, hypothetical situation, since the exception would be
thrown from the newly-created "shared code" function, which won't be
useful anywhere except very locally, the switch could be nested inside a
try block, and the catch would be right there to trap the exception and
return a "normal" result back to the caller. No need to worry about the
exception biting the unwary when its use is so limited.


Oh I don't think so. I think it poorly advised to allow bad design to
creap into "local" functions that won't be used elsewhere for some
unforseen reason down the road. Simply because those reasons are
unforseen. When you make a function you should always assume you might
use it in ways you are not expecting to right now.
Jul 23 '05 #8
Noah Roberts wrote:
In "Thinking in C++" Eckel explains the use of exceptions as to deal
with 'exceptional' situations. In other words, the unexpected. He also
uses them to enforce function contract (or preconditions). So for
instance you wouldn't use an exception upon end of file, because that is
an expected situation, but you would if the file suddenly became


That depends. If you are reading a text file, the end of file is the normal
condition to mark the end of the text, but if you are reading for example a
file in a format that defines precisely what contains and what are the
lengths of each part, reaching end of file in the middle of a file can be
considered an excpetional condition (file is corrupt or is not in the
required format).

--
Salu2
Jul 23 '05 #9

Julián Albo wrote:
Noah Roberts wrote:
In "Thinking in C++" Eckel explains the use of exceptions as to deal with 'exceptional' situations. In other words, the unexpected. He also uses them to enforce function contract (or preconditions). So for
instance you wouldn't use an exception upon end of file, because that is an expected situation, but you would if the file suddenly became
That depends. If you are reading a text file, the end of file is the

normal condition to mark the end of the text, but if you are reading for example a file in a format that defines precisely what contains and what are the lengths of each part, reaching end of file in the middle of a file can be considered an excpetional condition (file is corrupt or is not in the
required format).


Sure. Good point.

Jul 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

83
4728
by: theodp | last post by:
While Mainframe and Unix users are unlikely to find it novel that Windows XP allows several family members to share a PC while enabling each to have personalized settings and folders, that's not stopping Microsoft from seeking a patent for 'Methods and arrangements for providing multiple concurrent desktops and workspaces in a shared computing environment,' the USPTO disclosed Thursday. --> Link to Microsoft's Patent Application ...
5
8535
by: geoffblanduk_nospam | last post by:
Is it valid to share namespaces across projects in C#? For example, I have a project that contains the code for a core assembly, this builds a DLL. I then have a second project in the same solution that contains test cases for the assembly in the same namespace, this references the first project's DLL and builds a further DLL for testing. All code has the same namespace. The code in the tests needs access to internal methods etc of the...
3
2851
by: Robert W. | last post by:
I'm embarking on a project that will have both a desktop application and a Pocket PC application. It seems logical to have as much code as possible sitting in a shared project, which would be referenced and utilized by both the Windows Forms application and the Mobile Device application. Are there any "gotchas" (ie. warnings) that anyone knows about in following this approach? Robert W. Vancouver, BC
5
10521
by: BPearson | last post by:
Hello I would like to have several sites share a single web.config file. To accomplish this, I would point the root of these sites to the same folder. Is there any reason why I might not want to do this? (IIS 5 or 6 In case you're wondering why I would do this, we have many web sites on a single server, and there are groups of sites that need to share common configuration information. I'd like to ease some administration by having one...
11
2779
by: Nick | last post by:
Hello, Please pardon my ignorance as this is something I should know, but I'm a little unclear. I have an MDI based app. It is setup so the user opens a file and the main child form is created. Once that is opened one (or more) properties forms can be opened. What is the best method for sharing data between the properties forms and the main child form? I need to alert the main child form when a value is modified in a properties form so I...
1
1508
by: Joe | last post by:
While I understand that Server Side Includes still work, I realize it's not the best practice for sharing code such as a common set of includes between screens. In ASP.NET I've already built several User Controls and such for sharing code between screens, but this typically was used things such as menus and headers and footers. What is the best practice in 1.1 for sharing code such as a common set of functions used by multiple screens?
8
4850
by: mc | last post by:
I would like to be able to send from an ASP.NET page an email which when recieved takes the form of a "Sharing Invitation for a RSS Feed" (http://office.microsoft.com/en-us/outlook/HA101595391033.aspx) I've found a MSDN article about it (http://msdn2.microsoft.com/en-us/library/bb176432.aspx) but that example is presented as a vb(a) script from within outlook. Can this functionality be emulated from sending an email from C#? TIA
27
1999
by: Jonathan Wood | last post by:
Greetings, I'd like to write any number of classes and then use those classes from any number of .NET applications. Since we've supposedly left "DLL Hell" and ActiveX objects behind, what has taken it's place. Can anyone point me in the right direction getting started learning the best way to write a library of routines and then being able to access those
8
1337
by: Nathan Sokalski | last post by:
I have a form that contains a number of fields, all of which have validators. There are two submit buttons, one to update a record and one to add a record. Because the only difference in validation is to make sure someone is not using a username that is already in use, I would like to be able to use all the other validators for both the add and update buttons. However, because as far as I know a validator can only be in one...
0
8970
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8795
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9486
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9344
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9214
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6763
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4572
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3286
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2759
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.