473,796 Members | 2,765 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Getting rid of / Minimizing a lot of if statements?

I have some code that works fine, except for the fact that it has a lot of
embedded if statements. I don't think that this would be practice code, but I
wanted to tap into the knowledge of this group, and see what is the best way
to handle it. Basically, the if statements are used to check several
conditions of whether something is activated etc., and if it is, it outputs a
small piece of text and redirects the user to a new page. For each of the
conditions, there are 20 if statements. In the below, I am putting 1 piece,
but there are 20 IDENTICAL other lines to these, for each of the the ten
conditions. The first checks whether the condition is active, if the user is
an admin, and displays some text.
if (AdminUser())
{
if (_enableConditi on1 == true)
{
output.Write(@" <img border=""0"" src=""foo""
align=""middle" ">);
output.Write("< b>");
output.Write("f oo" + "<br>");
}
else
{
output.Write("F oo Not Active" + "<br>");
}
}
.......

(then there are 20 more of these!)

then the other type is handled if it is found active:

if (_enableConditi on1 == true)
{
if (foo1 == foo2)
{
fooMethod
}
}

Also 20 of these.

This seems to be inefficient to me. Is there a better way of handling it?
Apr 25 '07 #1
3 3607
XSler wrote:
I have some code that works fine, except for the fact that it has a lot of
embedded if statements. I don't think that this would be practice code, but I
wanted to tap into the knowledge of this group, and see what is the best way
to handle it. Basically, the if statements are used to check several
conditions of whether something is activated etc., and if it is, it outputs a
small piece of text and redirects the user to a new page. For each of the
conditions, there are 20 if statements. In the below, I am putting 1 piece,
but there are 20 IDENTICAL other lines to these, for each of the the ten
conditions. The first checks whether the condition is active, if the user is
an admin, and displays some text.
if (AdminUser())
{
if (_enableConditi on1 == true)
First thing: you never need to compare conditional expressions with
'true', you can just use:

if (_enableConditi on1)
{
output.Write(@" <img border=""0"" src=""foo""
align=""middle" ">);
output.Write("< b>");
output.Write("f oo" + "<br>");
}
else
{
output.Write("F oo Not Active" + "<br>");
}
}
The basic pattern here is to choose to do one thing or another, based on
the truth of a third thing. The problem, the ugliness, is that it's
code. Consider how things would change if these choices were data:

---8<---
using System;
using System.Collecti ons.Generic;

class App
{
delegate bool Predicate();
delegate void Action();

class ConditionalActi on
{
Predicate _pred;
Action _ifTrue;
Action _ifFalse;

public ConditionalActi on(Predicate pred,
Action ifTrue, Action ifFalse)
{
_pred = pred;
_ifTrue = ifTrue;
_ifFalse = ifFalse;
}

public void Execute(/* args maybe */)
{
if (_pred(/* args maybe */))
_ifTrue(/* args maybe */);
else
_ifFalse(/* args maybe */);
}
}

static void Main()
{
List<Actionacti ons = new List<Action>();
actions.Add(new ConditionalActi on(
delegate { return true; },
delegate { Console.WriteLi ne("True"); },
delegate { Console.WriteLi ne("False"); })
.Execute);

foreach (Action action in actions)
action(/* args maybe */);
}
}
--->8---

This makes sense if you can find a way to fill the 'actions' list from
somewhere else, such as a configuration file, or otherwise
*declaratively* specify it.

That might satisfy your thirst for more neatness. However, beware! It
may be too much complexity, more complexity than it's worth.

-- Barry

--
http://barrkel.blogspot.com/
Apr 25 '07 #2


You might consider the "Factory Design Pattern"
public interface IDoSomeWork
void DoWork()

public ConcreteClass1 : IDoSomeWork
void DoWork

public ConcreteClass2 : IDoSomeWork
void DoWork
Then you create a "Factory" . A factory is basically a class, which creates
other classes.
public class WorkFactory
public static GetAWorker( bool someCondition )
{
if (someCondition)
{return new ConcreteClass1( ) );
else
{ return new ConcreteClass2( ) ) ;
}

bool sc = true;
IDoSomeWork idsw = WorkFactory.Get AWorker( sc ) ;
idsw.DoWork();

--------
Real life:
Imagine you need to pay employees. You have salaried and hourly employees.
hourly employees get their hours * wage. salaried people get some fraction
of their yearly income.

instead of this (your issue)

if (isSalaried)
{
//logic to pay a salaried employee
}
else
{
//logic to pay an hourly employee
}
-- BOO !! Hard to maintain code.
Here is the alternative.


public interface IPayEmployee
void PayOut()

public PayHourlyEmploy ee : IPayEmployee
void PayOut ( //take hours * wage and pay employee);

public PaySalariedEmpl oyee : IPayEmployee
void PayOut ( //find yearly salary and divide by 52 (aka , a fixed rate)
;
public class PayFactory
public static GetAPayer( bool isSalaried )
{
if (isSalaried )
{return new PaySalariedEmpl oyee () );
else
{ return new PayHourlyEmploy ee () ) ;
}
bool isSalaried = true;
IPayEmployee ipe = PayFactory.GetA Payer( isSalaried ) ;
ipe.PayOut();
And....when you need a hybrid (an employee who gets paid salaried, but if
goes over 60 hours, gets an hourly rate for example),
you just add a new class, and alter the Factory a little.
www.dofactory.com and look for factory pattern under "free design patterns".

see also:
12/1/2005
Understanding the Simple Factory Pattern
http://sholliday.spaces.live.com/blog/

"XSler" <XS***@discussi ons.microsoft.c omwrote in message
news:A0******** *************** ***********@mic rosoft.com...
I have some code that works fine, except for the fact that it has a lot of
embedded if statements. I don't think that this would be practice code,
but I
wanted to tap into the knowledge of this group, and see what is the best
way
to handle it. Basically, the if statements are used to check several
conditions of whether something is activated etc., and if it is, it
outputs a
small piece of text and redirects the user to a new page. For each of the
conditions, there are 20 if statements. In the below, I am putting 1
piece,
but there are 20 IDENTICAL other lines to these, for each of the the ten
conditions. The first checks whether the condition is active, if the user
is
an admin, and displays some text.
if (AdminUser())
{
if (_enableConditi on1 == true)
{
output.Write(@" <img border=""0"" src=""foo""
align=""middle" ">);
output.Write("< b>");
output.Write("f oo" + "<br>");
}
else
{
output.Write("F oo Not Active" + "<br>");
}
}
......

(then there are 20 more of these!)

then the other type is handled if it is found active:

if (_enableConditi on1 == true)
{
if (foo1 == foo2)
{
fooMethod
}
}

Also 20 of these.

This seems to be inefficient to me. Is there a better way of handling it?

Apr 25 '07 #3
Hello,

In order to minimze the number of IFs multiple IF can be used togather
using AND or OR conditions wherever possible.

if (AdminUser() && _enableConditio n1 == true)
{
{
output.Write(@" <img border=""0"" src=""foo""
align=""middle" ">);
output.Write("< b>");
output.Write("f oo" + "<br>");
}
else
{
output.Write("F oo Not Active" + "<br>");
}
}

You can also exclude the exceptions that come in else in order to
reduce ELSEs in the code using RETURN statments. like

if ( ! AdminUser() OR _enableConditio n1 == false)
return;
output.Write(@" <img border=""0"" src=""foo"" align=""middle" ">);
output.Write("< b>");
output.Write("f oo" + "<br>");
}

HTH.

On Apr 25, 7:50 pm, XSler <X...@discussio ns.microsoft.co mwrote:
I have some code that works fine, except for the fact that it has a lot of
embedded if statements. I don't think that this would be practice code, but I
wanted to tap into the knowledge of this group, and see what is the best way
to handle it. Basically, the if statements are used to check several
conditions of whether something is activated etc., and if it is, it outputs a
small piece of text and redirects the user to a new page. For each of the
conditions, there are 20 if statements. In the below, I am putting 1 piece,
but there are 20 IDENTICAL other lines to these, for each of the the ten
conditions. The first checks whether the condition is active, if the user is
an admin, and displays some text.
if (AdminUser())
{
if (_enableConditi on1 == true)
{
output.Write(@" <img border=""0"" src=""foo""
align=""middle" ">);
output.Write("< b>");
output.Write("f oo" + "<br>");
}
else
{
output.Write("F oo Not Active" + "<br>");
}}

......

(then there are 20 more of these!)

then the other type is handled if it is found active:

if (_enableConditi on1 == true)
{
if (foo1 == foo2)
{
fooMethod
}
}

Also 20 of these.

This seems to be inefficient to me. Is there a better way of handling it?

Apr 26 '07 #4

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

Similar topics

3
2346
by: Del | last post by:
Does anyone know how to minimize all the windows on a desktop, programatically?
3
3094
by: NL | last post by:
Hi, Does anybody know how to turn off the animation Windows does with a window as it's minimized/maximized to the taskbar? I have an app which, when minimized, syncs to any other open instances of the app and tells them to minimize. If I have more than a couple instances open, the user ends up waiting quite a while for all of windows to minimize, since each minimizing animation is done consecutively and not in parallel.
1
1196
by: Jawahar | last post by:
All, I have an ASP.net application from which I allow users to run reports that are crystal reports and exported to PDF format, in addition there are other static documents that users can view in pdf format. Each time a PDF document is opened, it is opened in a new window (this fine) but the windows seems to minimize. Why does this happen, is it code related? This is what I use: With Response
13
1375
by: Nathan | last post by:
Hello again, I have an application with three forms. Frm1 has a button whose click event calls frm2 -- frm2.ShowDialog(). Frm2 has a button that calls frm3 -- frm3.ShowDialog(). When I minimize frm3, I want the other two forms to minimize as well. As I have it now, frm3 minimizes and a small title bar appears at the lower left of my desktop, and frm2 and frm1 remain in the center and I cannot touch them because of ShowDialog. (I...
4
1772
by: Tony Clark | last post by:
Hi, How can i tell when a form is minimizing or closing by use of the button in the top right of the form? thanks in advance
7
9337
by: Lee | last post by:
Hi, How do I detect when a form is minimizing? specifically when a user clicks the show desktop button on the taskbar, rather than the minimize button on a form. thanks in advance
1
1045
by: Zectron | last post by:
I have made my custom application from which i can access all other installed application using Shell function. I need to send this application to system tray upon minimizing. How to do it?? Please help!! -- Regards
0
885
by: =?Utf-8?B?aXdkdTE1?= | last post by:
hi, ive been working on a utility type app that would minimize all windows when the moue stays in a corner of the screen for more than 5 secodns....the only problem is getting all the VIEWABLE windows. i can minimize windows, but unfortunately, i dont know how to tell if they are hidden or not, so it ends up minimizing applications that are gone to the tray, etc. how can i achieve what im looking for? any help would be great....thanks --...
3
1917
by: qazplm114477 | last post by:
Hi, I'm having a tiny problem. I have just started playing around with visual basic a week ago so im fairly new at this. I created a method that saves changes when you click a button, once the button is clicked a message box pops up with a yes/no option. whenever i click any of those buttons the entire window minimizes. Theres no problem with the code it self yet, i just want my window to stop minimizing here is the code: Dim...
0
9535
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,...
1
10200
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9061
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7558
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
6800
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5453
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...
0
5582
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4127
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
3
2931
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.