4
Suppose we have the following interface:
public interface ICRUDService<T>
{
T Create(T entity);
}
Abstract implementation:
public abstract class CrudService<T> : ICRUDService<T>
{
IRepository repositorio;
public EntityService(IRepository rep)
{
repositorio= rep;
}
public virtual T Create(T entity)
{
if (entity == null)
{
throw new ArgumentNullException("entity ");
}
repositorio.Add(instance);
return entity;
}
}
For each object in my domain (Ex: Person, Car, Animal) will implement a service:
public class PessoaService :CrudService<Model.Pessoa>{
IRepository repositorio;
public PessoaService (IRepository repo):base(repo)
{
repositorio= repo;
}
public void MetodoPersonalizadoServicoPessoa(){
var oi = "oi";
}
}
public class CarroService :CrudService<Model.Carro>{
IRepository repositorio;
public CarroService (IRepository repo):base(repo)
{
repositorio= repo;
}
public void MetodoPersonalizadoServicoCarro(){
var oi = "oi2";
}
}
-How best to test each Crudservice implementation?
-For each implementation I must repeat the Create method test of the abstract class?
-Is there any way to create a generic Abstract test that automatically tests the Create method in all classes that implement it?
How should I reuse code without using inheritance? Utility classes?
– LeoCBS
@Leocbs Exactly. The simplest form of reuse is to encapsulate the code in an independent class and consume this class. In the case of this question,
CrudService
could be simply a utility class instead of being a parent class. Consumption of it could be more or less like this:CrudService.Create<TipoEntidade>(repo, entidade)
. The names are probably wrong - create doesn’t seem to be creating anything, but that’s another matter.– Caffé
In which cases it is recommended to use inheritance?
– LeoCBS
@Leocbs Hence is an extensive subject. My standard procedure is not to use class inheritance. I avoid using especially when the code deals with business irrigation and am less rigid when it comes to simple and more generic technology accessory solutions. I don’t know if you already have a question like that here in the OS and I don’t even know if it would be off topic, but you can do a search and ask a question if that’s the case.
– Caffé