I have an interface "IPartyCountService" that counts number of customers and number of suppliers.
The implementation class "PartyCountService" makes use of type checking to check whether the party is a Customer or a Supplier.
Does the implementation class PartyCountService's use of type checking give out code smell?
Any feedback, comment, criticism is appreciated.
public interface IPartyCountService
{
int GetTotalNumberOfCustomers();
int GetTotalNumberOfSuppliers();
}
internal class PartyCountService:IPartyCountService
{
IPartyRepository _partyRepository;
public PartyCountService(IPartyRepository partyRepository)
{
_partyRepository = partyRepository;
}
public int GetTotalNumberOfCustomers()
{
var counter = 0;
foreach(var customer in _partyRepository.GetAll())
{
if (customer is Customer) counter++;
}
return counter;
}
public int GetTotalNumberOfSuppliers()
{
var counter = 0;
foreach (var customer in _partyRepository.GetAll())
{
if (customer is Supplier) counter++;
}
return counter;
}
}
public interface IPartyRepository
{
IList<IParty> GetAll();
}
internal class PartyRepository:IPartyRepository
{
public IList<IParty> GetAll()
{
// put together all parties, including customers and suppliers
return allParties;
}
}
internal class Customer:IParty{}
internal class Supplier:IParty{}
public interface IParty{}
I would use the .OfType<> extension method.
return _partyRepository.GetAll().OfType<Customer>().Count();
EDIT: As stated by SP below, this makes for some cleaner code, but doesn't necessarily fix the smell.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With