I have the following seperation of logic in my application, as you can see I have a class called SimpleController which is what I use to Import and Find SimpleEntities.
I read all the SimpleEntities into memory List cause I search these Entities very often and its a lot faster then reading from the database everytime I want to search for an Entity.
Would it be better to move the logic where I read and store the SimpleEntities into memory into the SimpleLogic class instead of the SimpleController class?
public class SimpleEntity
{
public int SimpleId { get; set; }
public string SimpleName { get; set; }
}
public class SimpleDAL
{
public ICollection<SimpleEntity> GetAllSimpleEntities()
{
//Retrieve SimpleEntities from Database
}
public void InsertSimpleEntity(SimpleEntity simpleEntity)
{
//Insert simple Entity into Database
}
}
public class SimpleLogic
{
private readonly SimpleDAL simpleDAL = new SimpleDAL();
public ICollection<SimpleEntity> GetAllSimpleEntities()
{
return simpleDAL.GetAllSimpleEntities();
}
public void InsertSimpleEntity(SimpleEntity simpleEntity)
{
//Validate simpleEntity before adding to database
if (simpleEntity.SimpleId <= 0)
throw new Exception("Invalid SimpleEntity Id: " + simpleEntity.SimpleId);
if (String.IsNullOrEmpty(simpleEntity.SimpleName))
throw new Exception("SimpleEntity Name cannot be empty or null");
simpleDAL.InsertSimpleEntity(simpleEntity);
}
}
public class SimpleController
{
private readonly SimpleLogic simpleLogic = new SimpleLogic();
private List<SimpleEntity> simpleEntities;
public SimpleController()
{
simpleEntities = simpleLogic.GetAllSimpleEntities().ToList();
}
public int FindSimpleIndex(int simpleId)
{
return simpleEntities.FindIndex(p=> p.SimpleId == simpleId);
}
public void ImportOtherSimpleEntity(OtherSimpleEntity otherSimpleEntity)
{
if (otherSimpleEntity.Operation == "Update")
{
int index = FindSimpleIndex(otherSimpleEntity.OtherSimpleId);
//If entity was found update SimpleEntity
if (index > -1)
{
//Call SimpleLogic.UpdateSimpleEntity(Pass in SimpleEntity);
}
}
}
}
I'd perhaps implement a
SimpleEntityManager
which can be referenced from within the controller, and can operate outside it if necessary. So the controller handles the MVC aspects of the system, and theSimpleEntityManager
manages theSimpleEntities
.As an aside,
InsertSimpleEntity()
appears to be performing validation onSimpleEntity
fields. I would normally rather theSimpleEntity
performs that validation itself (most likely during construction).