Created
February 14, 2011 23:39
-
-
Save thomasjo/826817 to your computer and use it in GitHub Desktop.
Let's improve this code (in two different ways.)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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