Ciao a tutti,
sono un programmatore (vecchia scuola) e mi sto addentrando nella programmazione ad oggetti. Sto leggendo molti testi e forum compreso il vostro che ritengo tra i più validi. Non so se è cosa comune ma quando si leggono gli esempi dei libri sembra tutto chiaro, mentre andando a realizzare delle applicazioni reali la poca chiarezza iniziale diventa "poche idee ben sparse e confuse". Mi piacerebbe avere i vostri suggerimenti su come implementare correttamente l'esempio riportato:
codice:
public class Company
{
public Company()
{
Name = null;
Email = null;
}
public long Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
public class Unit
{
public long Id { get; set; }
public long CompanyId { get; set; }
public string Address { get; set; }
}
In un altro file .cs:
codice:
public class db
{
public static List<Unit> GetUnitByCompanyID(long id)
{
SqlCommand myCommand = new SqlCommand("SELECT * FROM Unit WHERE companyid = @CID");
SqlParameter myParam = new SqlParameter("@CID", SqlDbType.BigInt);
myParam.Value = id;
myCommand.Parameters.Add(myParam);
List<Unit> myListUnit = new List<Unit>();
using (DataTable dt = SQLProvider.GetDataTable(myCommand))
{
foreach(DataRow dr in dt.Rows)
{
Unit myUnit=new Unit();
myUnit.Id = (Int64)dr["id"];
myUnit.CompanyId = (Int64)dr["companyid"];
myUnit.Address = dr["address"].ToString();
myListUnit.Add(myUnit);
}
}
return myListUnit;
}
return null;
}
public static Unit GetUnitByID(long id)
{
// indentica a GetUnitByCompanyID cambia solo la query
}
public static Unit GetUnitbyAddress(string address)
{
// indentica a GetUnitByCompanyID cambia solo la query
}
Quale sarebbe il modo corretto di implementare questo comune problema? In particolare come posso evitare di riscrivere sempre lo stesso codice visto che cambia solo la query? Devo utilizzare costruttori, overloading e interfacce?
Ringrazio chi avrà la pazienza di rispondermi.
Ciao, Luca.