I was just wondering what would be the best approach to refactoring this statement to use less of the condidtions? Im reallt strucggling to clean this statement up without having the same functionality if somone could point me in the right direction i would be very gratefull
try
{
var errorProviders = new List<ErrorProvider>() { epEmail, epAlternative, epMobile, epTown, epLandline, epHouseName, epForeName, epSurname, epPostcode, epCountry, epHouseName, epLocality, epCounty };
foreach (Control c in panel1.Controls)
{
if (c is SpellBox || c is TextBox)
{
if (!string.IsNullOrWhiteSpace(txt_ForeName.Text) | !string.IsNullOrWhiteSpace(txt_SurName.Text))
{
if (cmb_Title.SelectedIndex != -1)
{
if (cmb_PrefConTime.SelectedIndex != -1)
{
if (isPhoneNumber())
{
if (errorProviders.Any(e => e.GetError(c).Length > 0))
{
return false;
}
}
else
{
epPrefConNumber.SetError(cmb_PrefConNumber, "Error");
return false;
}
}
else
{
epPrefConTime.SetError(cmb_PrefConTime, "Error in: prefered contact time feild");
return false;
}
}
else
{
epTitle.SetError(cmb_Title, "Title");
return false;
}
}
else
{
epBothNames.SetError(txt_SurName, "Error:");
epBothNames.SetError(txt_ForeName, "Error:");
return false;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString())+ "Error has occurred, Please cancel and try again!");
}
return true;
If there is a way to use bare minumum conditions to reduce code ?
If you have to check all those conditions then you have to check all those conditions. Your most egregious issues, in my opinion, are the deep nesting and validating fields that are completely unrelated to the control inside your loop. You can fix the nesting by reversing your if conditions and returning early. For the rest, just move the unrelated validation outside the loop.
try
{
var errorProviders = new List<ErrorProvider>() { epEmail, epAlternative, epMobile, epTown, epLandline, epHouseName, epForeName, epSurname, epPostcode, epCountry, epHouseName, epLocality, epCounty };
if (string.IsNullOrWhiteSpace(txt_ForeName.Text) && string.IsNullOrWhiteSpace(txt_SurName.Text))
{
epBothNames.SetError(txt_SurName, "Error:");
epBothNames.SetError(txt_ForeName, "Error:");
return false;
}
if (cmb_Title.SelectedIndex == -1)
{
epTitle.SetError(cmb_Title, "Title");
return false;
}
if (cmb_PrefConTime.SelectedIndex == -1)
{
epPrefConTime.SetError(cmb_PrefConTime, "Error in: prefered contact time feild");
return false;
}
if (!isPhoneNumber())
{
epPrefConNumber.SetError(cmb_PrefConNumber, "Error");
return false;
}
foreach (Control c in panel1.Controls.Where(x => x is SpellBox || x is TextBox))
{
if (!errorProviders.Any(e => e.GetError(c).Length > 0))
{
return false;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString())+ "Error has occurred, Please cancel and try again!");
}
return true;
Related
I have new user data (i want to import/update it). Accounts is finded by user data.
I want to update or create new accounts depended on finded accounts by user data
:
if (accountById != null)
{
if (accountByNumber != null)
{
if (accountById.Id == accountByNumber.Id)
{
if (_isSpecialData)
{
AddUserDataToAccount(userData, accountByNumber);
if (userData.Status == Blocked) return;
}
}
else
{
_log.Error($"Bad");
return;
}
}
else
{
AddUserDataToAccount(userData, accountById);
}
}
else
{
if (accountByNumber != null)
{
if (accountByNumber.RefNo == null)
{
SetAccountAdditionalId(accountByNumber, userData.AdditionalId);
if (_isSpecialData)
{
AddUserDataToAccount(userData, accountByNumber);
if (userData.Status == Blocked) return;
}
}
else
{
_log.Error($"Bad");
return;
}
}
else
{
CreateCardAndProfile2(userData, out createdNewAccount);
CreateNewAccount(userData, out createdNewAccount);
}
}
UpdateAccountData(userData, createdNewAccount);
The above method works, but I would like to know if there is any way to make it more readable, optimized?
You can use the switch operator so you can remove a lot of the if statements. if works like this:
(Note: Make sure you have a default case and a break; at the end of every case)
switch(%a%variable%here%) {
case %variable%value& {
%code%here%;
break;
}
}
I realize this may look like a duplicate question (I've seen many other questions asking about this error), however I cannot find an answer which explains the issue I'm having. The error is provoked by a call to
invList.SelectedItems[0].Text //invList is a ListView
From what I've read, the error when provoked by this instruction is indicative of attempted access to an empty list (or array?) of selected items in the ListView. However, the ListView I am attempting to access is populated with items at the time of the instruction's execution. Here are the methods in which I issue this instruction:
Method #1: deleteItem
public bool deleteItem()
{
if (invList.SelectedItems.Count == 0) //if no item selected...
{
MessageBox.Show("Error: No item selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
else
{
DialogResult dialogResult = MessageBox.Show(
"Are you sure you want to delete item: " + invList.SelectedItems[0].Text + "?",
"Error", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (dialogResult == DialogResult.Yes)
{
for (int i = 0; i < itemRecords.Count; i++)
{
if ((itemRecords[i].id.ToString() == invList.SelectedItems[0].Text) && (itemRecords[i].practice == clinicName))
{
itemRecords.Remove(itemRecords[i]);
listRefresh();
}
}
return true; //return true to indicate that data has been edited
}
return false; // return false to indicate that nothing has changed
}
}
Method #2: updateItem
public bool updateItem()
{
if (invList.SelectedItems.Count == 0) //if no item selected
{
MessageBox.Show("Error: No item selected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return false;
}
else
{
for (int i = 0; i < itemRecords.Count; i++)
{
//if id == the id of the selected item
if((itemRecords[i].id.ToString() == invList.SelectedItems[0].Text) && (itemRecords[i].practice == this.Text))
{
ItemAddition itemAddition = new ItemAddition(itemRecords, itemRecords[i], this);
itemAddition.ShowDialog();
}
}
return true;
}
}
listRefresh:
public void listRefresh()
{
invList.Items.Clear();
loadItems();
}
loadItems:
private void loadItems()
{
foreach (Record r in itemRecords)
{
if (r.practice == clinicName)
invList.Items.Add(r.ToString());
}
}
The error is invoked when the first method is called, but NOT when the second method is called. This inconsistency is the reason for my confusion. Is there some reason this error would only occur in the first method?
Move refreshing method after remove items. If you move item and rebind, then you will lost selection.
for (int i = 0; i < itemRecords.Count; i++)
{
if ((itemRecords[i].id.ToString() == invList.SelectedItems[0].Text) && (itemRecords[i].practice == clinicName))
{
itemRecords.Remove(itemRecords[i]);
//listRefresh();
}
}
listRefresh();
return true;
I have a problem with looping a list of songs. I have a List<String> _songList which contains songs paths (loaded correctly, checked). So I thought that there is an event which will tell me "Ok I stopped playing the song, I'm ready to play the next one". In NAudio it should be StoppedEventArgs added to WaveOutEvent.PlaybackStopped. But in my case it doesn't play another song, neither the same again. Here is my code:
public void Play_List(String _playlistName)
{
try
{
if (_songList.Count > 0)
{
if (!_paused)
{
_currentList = _playlistName;
PrimaryOutputStream =
new MediaFoundationReader(_songList[_songIndex]);
VolumeStream = new WaveChannel32(PrimaryOutputStream);
VolumeStream.PadWithZeroes = false;
Player.Init(VolumeStream);
Player.PlaybackStopped +=
new EventHandler<StoppedEventArgs>(RepeatMode);
}
Player.Play();
_paused = false;
_isPlaying = true;
}
}
catch (Exception e)
{
System.Windows.MessageBox.Show(e.ToString());
}
}
public void RepeatMode(object sender, StoppedEventArgs e)
{
try
{
if (_songList.Count > 0 && _currentSong != null)
{
_paused = false;
switch (_repeatMode)
{
case 1: //Repeat one song
Play_List(_currentList);
break;
case 2: //Repeat whole list
NextSong();
Play_List(_currentList);
MessageBox.Show("Changed song");
break;
default:
break;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Of course I set _repeatMode to 2 for list and 1 for one song.
I was searching the internet for help but found nothing. Anyone?
I do not see anything in your code which sets a value to the _currentSong. Probably, it is coming as null and your code is not getting executed.
if (_songList.Count > 0 && _currentSong != null)
Please find the following code and help me write a better if...else code. I feel this is a very below average way to write else if.
{
Retrieve the number in focus.
string number= getnumber();
string zipcode;
int corporate;
bool bCoverageInBet = false;
try
{
//Get the address and zipcode of the number
GetAddress(number, out address);
if (adress!= null)
{
zipcode = adress.zipcode
//if the following are null means this is first time call
if (!(string.IsNullOrEmpty(_loadedZipcode)) && _address != null)
{
if (zipcode.Equals(_loadedZipcode))
{
if (adress.Equals(_address ))
{
if (focusChanged)
{
return result;
}
}
else
{
if (bCoverageInBet)
{
// case 2: Different address and different coverage which is in between, make a call anf get new valus for result
//return the new result
}
else
{
return //current result value;
}
}
}
}
else
{
_loadedZipcode = zipcode;
_address = adress;
GetResponse( out resp)
{
if ((resp != null))
{
bool isCorporate = false;
corporate = getValues();
if (corporate .Equals(100))
{
result = true;
return result;
}
else if (corporate > 0 && corporate < 100)
{
//Make a call to get corporate
bCoverageInBet = true;
LocationResponse objResults;
if (GetAddressbycorporate(out objResults, out errMsg))
{
if (objResults != null)
{
isCorporate = objResults.located;
if (isCorporate )
{
result = true;
}
}
}
}
return result;
}
return result;
}
else
{
DisplayError("No response ");
return result;
}
}
}
else
{
//To do: What is address comes null
}
}
catch (System.Exception ex)
{
//some ccode
}
return result;
}
Thanks
K
Refactor the method into smaller units as appropriate. Also, return early from the method rather than using else clauses.
E.g. instead of
if (adress!= null)
{
zipcode = adress.zipcode
//if the following are null means this is first time call
if (!(string.IsNullOrEmpty(_loadedZipcode)) && _address != null)
{
}
else
{
return false;
}
}
else
{
return false;
}
Do:
if (adress == null)
{
return false;
}
if (string.IsNullOrEmpty(_loadedZipcode) || _address == null)
{
return false;
}
There are quite a few other problems, but that should make the code cleaner to start with.
I don't think anyone is going to "help" you rewrite this code. However, I can offer some suggestions.
I have found it easier to trace my way down to the inner most if and try to rewrite and work my way backwards (up the chain). Depending on the IF block, it is sometimes easier to break them out into separate methods where appropriate.
Also, don't forget about the conditional operator. It can sometimes be clearer to use that than a whole if else block.
For example, property = (boolean expression) ? (true value) : (false value);
Here is a link to MSDN on it: conditonal operator documentation
I have the following line of code:
public bool dcpl_radar()
{
if (radar == null)
return false;
else
{
if (radar != null)
{
if (radar.InvokeRequired)
radar.BeginInvoke(new MethodInvoker(delegate()
{
radar.Visible = false;
}));
else
this.radar.Visible = false;
radar = null;
}
return true;
}//end of else statement
}
but VStudio keeps throwing an error on the invoke line. I've checked the Debugger and if (radar == null) is true, yet VStudio is trying to evaluate a part of the code it shouldn't be in. Can someone explain why it's doing this please?
Wait a minute... I think we have a race condition.
Lets say you BeginInvoke, almost immediately you set radar = null.
There really is no telling when your anonymous delegate will be executed.
I would imagine this should solve your issue.
public bool dcpl_radar()
{
if (radar != null)
{
if (radar.InvokeRequired)
{
radar.BeginInvoke(new MethodInvoker(HideRadar));
}
else
{
HideRadar();
}
return true;
}
return false;
}
private void HideRadar()
{
this.radar.Visible = false;
this.radar = null;
}
What is happening:
The anonymous delegate is being called after you set the radar to null.
How to fix it
public bool dcpl_radar()
{
if (radar == null)
return false;
else
{
if (radar != null)
{
if (radar.InvokeRequired)
radar.BeginInvoke(new MethodInvoker(delegate()
{
radar.Visible = false;
radar = null;
}));
else {
this.radar.Visible = false;
radar = null;
}
}
return true;
}//end of else statement
}
(Note where I've moved your 'null' assignments).
Though I am a bit worried about the point of setting a variable to null, it's generally a sign of a bad design.