Help refactoring with attention to SRP and OCP
public interface iload function load() as integer end interface public enum databasetype mysql mssql end enum public class loadfactory private _load as iload public sub new (databasetype as enum .databasetype, connectionstring as string ) select case databasetype case databasetype.mysql _load = new mysqlload(connectionstring) case databasetype.mssql _load = new mssqlload(connectionstring) end select end sub public function getinstance() as iload return _load end function end class public class users 'collection code here 'implement iload interface private _load as iload public function load() as integer 'to do: load factory constructor values global variables dim loadfactory as new loadfactory(databasetype.mysql, "myconnectionstring" ) _load = loadfactory.getinstance return _load.load() end function end class
when need load data users collection use:
dim users new users
users.load()
however, later on decide add more load functionality. specifically, want execute this:
dim users new users
users.load("select * users office = 2")
way accomplish adding functionality load interface, so?
public interface iload<br/> function load() as integer <br/> function load(byval selectstatement as string )<br/> function loadall() as integer <br/> end interface
in design users class instantiates new loadfactory. that’s not srp nor ocp.
the example below (c#) uses datamapper pattern. might want decouple dal implementations packaging them in separate assemblies , inject them using di framework (for example unity). allows add new databases without need recompile project.
ps: might want take @ object-relational mapping tools.
srp:
the userscollection class represents collection of users.
the mysqldal class retrieves data mysql database.
the mssqldal class retrieves data form sql server database.
the usermapper class moves data between database , user object.
ocp:
the idal interface defines contract data access components implement.
idal {
datatable getallusers();
datatable getusers(string statement);
datatable getbyid(int id);
};
usermapper {
public usermapper(idal dal) {
this.userdal = dal;
}
userscollection getallusers() {
userscollection result = new userscollection();
datatable userstable = dal.getallusers();
foreach(datarow[] userrow in userstable.rows) {
result.add(new user(userrow[0], .., .., ..));
}
}
};
mysqldal : idal {
..
};
mssqldal : idal {
..
};
http://www.paulgielens.com
Architecture > Architecture General
Comments
Post a Comment