Is Type Checking Code Smell in this code?

I have an IPartyCountService interface that counts the number of customers and the number of providers.

The implementation class "PartyCountService" uses type checking to check whether a party is a Customer or a Supplier.

Does the PartyCountService implementation class produce type checking, does it smell code?

Any feedback, comments, criticism are welcome.

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{}
+3
source share
7 answers

I would use the .OfType <> extension method.

return _partyRepository.GetAll().OfType<Customer>().Count();

EDIT: as stated in SP below, this does for some cleaner code, but does not necessarily capture odor.

+2

, , , .

return _partyRepository.GetAll().Count(p => p is Customer);
+1

, IParty , , ""?

+1

, Customer Supplier API. , ICustomer ISupplier. , (.. API), .

: - . , , . , , LINQ- foreach { }.

+1

, partyRepository? , ; , GetCustomers(), GetSuppliers() Get <T> ().

GetAll() - . (, ), .

+1

, , - ( ). :

  • , ? , , , .
  • , . , , , , .
  • LINQ , .

:

return _partyRepository.GetAll().OfType<Supplier>().Count();
0

, , . , :

  • .
  • , , .

(1) , OO. ( , , .)

(2) , -, , . -, is , . , .

EDIT: , , , . ? , , , , .

0

Source: https://habr.com/ru/post/1768322/


All Articles