Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Type Checking a Code Smell in this code? [closed]

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{}
like image 633
SP. Avatar asked Apr 09 '26 10:04

SP.


1 Answers

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.

like image 191
Chris Missal Avatar answered Apr 10 '26 23:04

Chris Missal