c# - Designing database interaction while following Single Responsibility Principle -
i'm trying adhere single responsibility principle better, , i'm having issues grasping how structure general class design communicating database. in simplified version, have database containing:
manufacturer <== probes <==> probesettings
a probe has manufacturer. probe has 1 set of settings. related objects accessed on application, , quite frankly, current implementation mess.
currently, here's general view of how communication , objects implemented:
public class manufacturer { public int id; // primary key, auto-incrementing on insert public string name; } public class probe { public int id; // primary key, auto-incrementing on insert public int manufacturerid; public string name; public int elements; } public class probesettings { public int probeid; // primary key, since unique. public int randomsetting; } // class mess... public static class database { public static string connectionstring; public static void insertmanufacturer(manufacturer manuf); // id ignored here, since it's auto-incrementing. public static void insertprobe(probe probe); // again, id ignored. public static void insertprobesettings(probesettings probeset); public static manufacturer[] getallmanufacturer(); public static probe[] getprobesfrommanufacturer(int manufacturerid); public static probe[] getprobesfrommanufacturer(manufacturer manuf); }
i see many issues here.
database
far much.- these objects can immutable when read really, issue after inserting, i'm not sure id assigned, , inserted object obsolete.
- anytime class needs information
database
, i'd have add method handle specific query.
i'm @ loss here on correct implementation be. real idea improvement kind of base interface database objects, although might inserts...
public interface idatabaseobject { void insert(database db); bool delete(database db); }
what way implement this?
well best solution work db while maintaining srp (or other kind of sane pattern) use kind of orm (for example, nhibernate).
this allow work classes are, instead of manually tossing them from/to db.
for example, nh classes can this:
public class manufacturer { public string name { ... } public ilist<probe> probes { ... } } public class probe { public string name { ... } public int elements { ... } public probesettings settings { ... } } public class probesettings { public int randomsetting; }
as see, not need getprobesfrommanufacturer
since can navigate collection within manufacturer.
also, orm manage object ids , saving you. need small , fixed number of general methods loadbyid/loadall, fit nicely class srp of data access. need class per each complex , configurable query db.
Comments
Post a Comment