HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Handling Enum flags for a copy operation

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
handlingenumoperationforflagscopy

Problem

I've just set up a bit of code to try and make things neater, but all I've really done, is add a whole bunch of nested if statements:

```
public void Copy(Copy copyType)
{
FrmProjectChooser frm = null;
if (copyType.HasFlag(Copy.Single))
{
if (copyType.HasFlag(Copy.Estimations) && copyType.HasFlag(Copy.SubItems))
{
// Single item, with sub items and estimations
List items = new List { (WB)treeWBS.GetDataRecordByNode(treeWBS.FocusedNode) };
items.AddRange(_WBSManager.GetAllChildren(items[0].idWBS));
List estimations = new List();
foreach (WB wbs in items)
estimations.AddRange(CTREstimationsManager.Instance.GetEstimationsForWBS(wbs.idWBS));
frm = new FrmProjectChooser(items, estimations);
}
else if (copyType.HasFlag(Copy.Estimations))
{
// Single item, with estimations.
WB wbsItem = treeWBS.GetDataRecordByNode(treeWBS.FocusedNode) as WB;
if (wbsItem != null)
frm = new FrmProjectChooser(new List { wbsItem },
CTREstimationsManager.Instance.GetEstimationsForWBS(wbsItem.idWBS));
}
else if (copyType.HasFlag(Copy.SubItems))
{
// Single item, with sub items
List items = new List { (WB)treeWBS.GetDataRecordByNode(treeWBS.FocusedNode) };
items.AddRange(_WBSManager.GetAllChildren(items[0].idWBS));
frm = new FrmProjectChooser(items);
}
else
{
// Single item
WB wbsItem = treeWBS.GetDataRecordByNode(treeWBS.FocusedNode) as WB;
if (wbsItem != null)
frm = new FrmProjectChooser(new List {wbsItem});
}
}
else if (copyType.HasFlag(Copy.All))
{
if (copyType.HasFlag(Copy.Estimations))
{
// All items, with estimations.
List wbsItems = _WBSManager.GetWBSForProject(CurrentP

Solution

For an aesthetic point of view, you could define some constants:

AllEstimations = Copy.All | Copy.Estimations
SingleEstimations = Copy.Single | Copy.Estimations
etc.


You could then check the value against these constants and create a single level if statement:

if (copyType == SingleEstimationsSubItems)
{}
elseif (copyType == SingleEstimations)
{}
elseif (....


I'm not claiming this will improve performance, but it will make the code more readable.

Code Snippets

AllEstimations = Copy.All | Copy.Estimations
SingleEstimations = Copy.Single | Copy.Estimations
etc.
if (copyType == SingleEstimationsSubItems)
{}
elseif (copyType == SingleEstimations)
{}
elseif (....

Context

StackExchange Code Review Q#105978, answer score: 7

Revisions (0)

No revisions yet.