Lazy Operator C # for native data access
I am currently creating a medical schema type application in winforms. I have taken a lazy approach to loading data. I can't use ORM like EF or nHibernate, so I implemented it with my own logic. I have several fields in a class for example. A package that contains navigation properties such as List<Treatment>
which should receive all the processing covered for this package. Is it really bad practice to wrap the whole list is lazy, it gets an instance like this:
Package package = new Package()
{
PackageID = record.GetInt32(0),
Name = record.GetString(1),
CoverageAmount = record.GetDecimal(2),
PackageStatus = (Status)record.GetInt32(3),
AvaliableFrom = record.GetDateTime(4),
AvaliableTo = record.GetDateTime(5),
};
package.Policies = new Lazy<List<Policy>>(() =>
{
return GetPoliciesByPackageID(package.PackageID);
});
package.Treatments = new Lazy<List<Treatment>>(() =>
{
return GetTreatmentsByPackage(package.PackageID);
});
return package;
When I need all the procedures, I have to call the package. Treatment. It means that it is somehow not so. This approach is frowned upon.
source to share
Lazy instance is not a bad practice in and of itself, however, if you expose expensive (in terms of time to get results) values through properties, then it is bad practice. Properties are intended for quick access to part of the object's state. If you purchase data expensively, then output the method.
source to share
The fact that the data is loaded lazily seems to be an implementation detail. This way I would encapsulate it.
public class Package
{
private readonly Lazy<List<Policy>> _lazyPolicies = ...
public List<Policy> Policies
{
get { return _lazyPolicies.Value; }
}
}
If you want to emulate what NHibernate is doing you can use proxy
Here's a simple (insecure) proxy:
public interface IPackage
{
List<Policy> Policies { get; }
}
public class Package
{
public List<Policy> Policies { get ; set; }
}
public class PackageProxy
{
private readonly Package _package;
private readonly Database _db;
public PackageProxy(Package package, Database _db)
{
_package = package;
_db = db;
}
public List<Policy> Policies
{
get
{
if(_package.Policies == null)
_package.Policies = GetPoliciesByPackageID(package.PackageID);
return _package.Policies;
}
}
private List<Policy> GetPoliciesByPackageID(int id)
{
_db...
}
}
// usage
IPackage package = new PackageProxy(new Package(), db) { /** set properties **/ };
source to share