I have an if else tree that will grow as I add additional elements to support it, and I'm looking for a better way to write it for support. I start with this code.
private void ControlSelect() { if (PostingType == PostingTypes.Loads && !IsMultiPost) { singleLoadControl.Visible = true; singleTruckControl.Visible = false; multiTruckControl.Visible = false; multiLoadControl.Visible = false; } else if (PostingType == PostingTypes.Trucks && !IsMultiPost) { singleLoadControl.Visible = false; singleTruckControl.Visible = true; multiTruckControl.Visible = false; multiLoadControl.Visible = false; } else if (PostingType == PostingTypes.Loads && IsMultiPost) { singleLoadControl.Visible = false; singleTruckControl.Visible = false; multiTruckControl.Visible = false; multiLoadControl.Visible = true; } else if (PostingType == PostingTypes.Trucks && IsMultiPost) { singleLoadControl.Visible = false; singleTruckControl.Visible = false; multiTruckControl.Visible = true; multiLoadControl.Visible = false; } }
and think about re-factoring it to something like this
private void ControlSelect() { List<UserControl> controlList = GetControlList(); string visableControl = singleLoadControl.ID; if (PostingType == PostingTypes.Loads && !IsMultiPost) { visableControl = singleLoadControl.ID; } else if (PostingType == PostingTypes.Trucks && !IsMultiPost) { visableControl = singleTruckControl.ID; } else if (PostingType == PostingTypes.Loads && IsMultiPost) { visableControl = multiLoadControl.ID; } else if (PostingType == PostingTypes.Trucks && IsMultiPost) { visableControl = multiTruckControl.ID; } foreach (UserControl userControl in controlList) { userControl.Visible = (userControl.ID == visableControl); } } private List<UserControl> GetControlList() { List<UserControl> controlList = new List<UserControl> { singleLoadControl, multiTruckControl, singleTruckControl, multiLoadControl }; return controlList; }
I take a performance hit, but I can control all my controls - this is one place
my other thought was to make each selected control its own method, something like this
private void SetSingleLoadControlAsSelected() { singleLoadControl.Visible = true; singleTruckControl.Visible = false; multiTruckControl.Visible = false; multiLoadControl.Visible = false; }
I do not take a hit in performance, but I support controls in several places
I am inclined to option one only because I like its support aspect.
Bob the janitor
source share