Skip to content

Instantly share code, notes, and snippets.

@thomasjo
Created February 14, 2011 23:39
Show Gist options
  • Select an option

  • Save thomasjo/826817 to your computer and use it in GitHub Desktop.

Select an option

Save thomasjo/826817 to your computer and use it in GitHub Desktop.
Let's improve this code (in two different ways.)
// Original code - let's improve it...
public bool IsTelephoneNumberInUse(int clientId, int telephoneId)
{
ISubscriptionService service = GetService<ISubscriptionService>();
IList<Subscription> subs = service.GetSubscriptions(clientId, false);
bool inUse = false;
foreach (Subscription sub in subs) {
if (sub.ContactPhoneId == telephoneId) {
inUse = true;
break;
}
}
return inUse;
}
// First revision (assuming you don't know about LINQ or can't use it for some reason.)
public bool IsTelephoneNumberInUse(int clientId, int telephoneId)
{
ISubscriptionService service = GetService<ISubscriptionService>();
IList<Subscription> subs = service.GetSubscriptions(clientId, false);
foreach (Subscription sub in subs) {
if (sub.ContactPhoneId == telephoneId) {
return true; // Using a break inside of this block is absolutely pointless, just return instead.
}
}
return false; // By simply returning a default, we can remove the pointless 'inUse' variable.
}
// Second revision - the LINQ approach.
public bool IsTelephoneNumberInUse(int clientId, int telephoneId)
{
ISubscriptionService service = GetService<ISubscriptionService>();
IList<Subscription> subs = service.GetSubscriptions(clientId, false);
return subs.Any(x => x.ContactPhoneId == telephoneId); // Stop being an idiot, and start using System.Linq.EnumerableExtensions!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment