This question is related to a previous post of mine Here. Basically, I want to inject a DAO into an entity i.e.
public class User
{
IUserDAO userDAO;
public User()
{
userDAO = IoCContainer.Resolve<IUserDAO>;
}
public User(IUserDAO userDAO)
{
this.userDAO = userDAO;
}
//Wrapped DAO methods i.e
public User Save()
{
return userDAO.Save(this);
}
}
Here if I had a custom methods in my DAO then I basically have to wrap them in the entity object. So if I had a IUserDAO.Register() I would then have to create a User.Register() method to wrap it.
What would be better is to create a proxy object where the methods from the DAO are dynamically assign to the User object. So I may have something that looks like this:
var User = DAOProxyService.Create(new User());
User.Save();
This would mean that I can keep the User entity as a pretty dumb class suitable for data transfer over the wire, but also magically give it a bunch of DAO methods.
This is very much out of my confort zone though, and I wondered what I would need to accomplish this? Could I use Castles Dynamic proxy? Also would the C# compiler be able to cope with this and know about the dynamically added methods?
Feel free to let me know if this is nonsense.
EDIT:
What we need to do it somehow declare DAOProxyService.Create() as returning a User object -- at compile time. This can be done with generics.
This isnt quite true, what I want to return isn't a User object but a User object with dynamically added UserDAO methods. As this class isn't defnied anywhere the compiler will not know what to make of it.
What I am essentially returning is a new object that looks like: User : IUserDAO, so I guess I could cast as required. But this seems messy.
Looks like what I am looking for is similar to this: Mixins
I was initially going to say what you ask cannot work. But with some tweaking, we might be able to get it to work.
var is just a compiler feature. When you say.
var x = GetSomeValue();
the compiler says "'GetSomeValue' is defined as returning a string, so the programmer must of meant to write 'string x = GetSomeValue();'". Note that the compiler says this; this change is done at compile time.
You want to define a class (DAOProxyService) which essentially returns an Object. This will work, but "var User" would be the same as "Object user".
What we need to do it somehow declare DAOProxyService.Create() as returning a User object -- at compile time. This can be done with generics:
class DAOProxyService
{
static DAOProxyService<T> Create<T>(T obj) { ......}
}
It's not entirely automatic, but you might consider using a variation of Oleg Sych's method for generating decorator classes. Whenever IUserDAO changes (new method, etc) just regenerate the file. Better than maintaining it manually :-)
http://www.olegsych.com/2007/12/how-to-use-t4-to-generate-decorator-classes/
Related
I know this may be purely a design preference, but from your perspective:
Should my functions that retrieve items from the database be static or instance based?
What is generally the most preferred method? (And most common)
What are the Pros/Cons of each method?
I have an class which has 3 properties: (No constructor for the object)
ObjectId - string
Name - string
Count - int
Instance Based Example
public async void Get(string objectId) {
// Gets specific item from "Tag" table
ParseQuery<ParseObject> query = ParseObject.GetQuery("Tag");
ParseObject tagObject = await query.GetAsync(objectId);
this.ObjectId = tagObject.ObjectId;
this.Name = tagObject.Get<string>("name");
this.Count = tagObject.Get<int>("count");
}
Setting my object would be done like so:
Tag myTag = new Tag();
await myTag.Get("123456");
// Properties are set and ready to work with
Static Example
public static async Task<Tag> Get(string objectId) {
Tag toReturnTag = new Tag();
// Gets specific item from "Tag" table
ParseQuery<ParseObject> query = ParseObject.GetQuery("Tag");
ParseObject tagObject = await query.GetAsync(objectId);
toReturnTag.ObjectId = tagObject.ObjectId;
toReturnTag.Name = tagObject.Get<string>("name");
toReturnTag.Count = tagObject.Get<int>("count");
return toReturnTag;
}
And would be set as such:
Tag myTag = await Tag.Get("123456");
I don't think there's an explicitly, definitively better way of doing this. This is the kind of thing that, to me, depends on how you best want to associate responsibilities with the objects in your application. As it stands, both of your functions are more or less the same.
Logically, though, do you want "accessing the database" to be something that each Tag object is responsible for? Should they have knowledge of the database, and, in a greater sense, about anything outside themselves? Or should they just be constructed with the all the information they (seem to) need, and not worry about communication?
In your case, it doesn't seem like you accomplish anything from allowing your objects to take on database-accessing responsibility, so it seems to me like you're better off restricting their concerns in favor of the static option. (If you have to choose between those only those two, I mean. I think you could do just as well with a non-static method in your ViewModel which constructs and returns a Tag object. Mostly my feeling here is that Tags should try to restrict their concerns, not static vs. instance.)
Also, in the static case, why no constructor? You're setting all Tag object's properties before it's returned, so unless you have some need to be able to construct a Tag object with some or all of its properties as null, why not have one?
Edit: A few people have pointed out, reasonably, that static methods tend to make unit testing harder. I agree with that in principle, but I think he'd be more okay in this case:
There's not any state being stored or modified by the method. What comes out is the Tag object, and you can test that regardless of whether it came from an instance or static.
It relies on an external data call (GetQuery) that would need to be mocked anyway.
Without knowing enough about ParseObject.GetQuery (I think this might be Xamarin?), though, I'm not really sure whether a static, or this specific construction, would make it more difficult to mock the data source.
My requirement is to download and scrape various HTML pages, extracting lists of Objects from the code on the page depending on what object type we are looking for on that page. Eg one page might contain an embedded list of doctors surgeries, another might contain a list of primary trusts etc. I have to view the pages one by one and end up with lists of the appropriate object types.
The way I have chosen to do this is to have a Generic class called HTMLParser<T> where T : IEntity, new()
IEntity is the interface that all the object types that can be scraped will implement, though I haven't figured out yet what the interface members will be.
So you will effectively be able to say
HTMLParser<Surgery> parser = new HTMLParser<Surgery>(URL, XSD SCHEMA DOC);
IList<Surgery> results = parser.Parse();
Parse() will validate that the HTML string downloaded from the URL contains a block that conforms to the XSD document provided, then will somehow use this template to extract a List<Surgery> of Surgery objects, each one corresponding to an XML block in the HTML string.
The problems I have are
Im not sure how to specify the template for each object type in a nice way, other than HTMLParser<Surgery> parser = new HTMLParser<Surgery>(new URI("...."), Surgery.Template); which is a bit clunky. Can anyone suggest a better way using .NET 3.0/4.0?
Im not sure how in a Generic way I can take the HTML string, take an XSD or XML template document, and return a generic list of constructed objects of the Generic Type. Can anyone suggest on how to do this?
Finally, I'm not convinced generics are the right solution to this problem as it's starting to seem very convoluted. Would you agree with or condemn my choice of solution here and if not, what would you do instead?
I'm not convinced that generics are the right solution, either. I implemented something very similar to this using good old inheritance, and I still think that's the right tool for the job.
Generics are useful when you want to perform the same operations on different types. Collections, for example, are a good example of where generics are very handy.
Inheritance, on the other hand, is useful when you want an object to inherit common functionality, but then extend and/or modify that functionality. Doing that with generics is messy.
My scraper base class looks something like this:
public class ScraperBase
{
// Common methods for making web requests, etc.
// When you want to download and scrape a page, you call this:
public List<string> DownloadAndScrape(string url)
{
// make request and download page.
// Then call Scrape ...
return Scrape(pageText);
}
// And an abstract Scrape method that returns a List<string>
// Inheritors implement this method.
public abstract List<string> Scrape(string pageText);
}
There's some other stuff in there for logging, error reporting, etc., but that's the gist of it.
Now, let's say I have a Wordpress blog scraper:
public class WordpressBlogScraper : ScraperBase
{
// just implement the Scrape method
public override List<string> Scrape(string pageText)
{
// do Wordpress-specific parsing and return data.
}
}
And I can do the same thing to write a Blogspot scraper, or a custom scraper for any page, site, or class of data.
I actually tried to do something similar, but rather than using inheritance I used a scraper callback function. Something like:
public delegate List<string> PageScraperDelegate(string pageText);
public class PageScraper
{
public List<string> DownloadAndScrape(string url, PageScraperDelegate callback)
{
// download data to pageText;
return callback(pageText);
}
}
You can then write:
var myScraper = new PageScraper();
myScraper.DownloadAndScrape("http://example.com/index.html", ScrapeExample);
private List<string> ScrapeExample(string pageText)
{
// do the scraping here and return a List<string>
}
That works reasonably well, and eliminates having to create a new class for every scraper type. However, I found that in my situation it was too limiting. I ended up needing a different class for almost every type of scraper, so I just went ahead and used inheritance.
I would rather focus on your parser/verifier classes, as designing them properly will be cruicial to the ease of future usage. I think it's more important how the mechanism will determine which parser/verifier to use basing on input.
Also, what happens when you're told you need to parse yet another type of website, say for Invoiceentities - will you be able to extend your mechanism in 2 easy steps in order to handle such requirement?
I have a code like that:
// can't make any changes at that class
class MyClass
{
void SomeMethod()
{
// some code ...
var someVar = WebConfigurationManager.AppSettings["SomeProperty"];
// some code ...
}
}
I can't change that code, but I need that WebConfigurationManager.AppSettings["SomeProperty"] return different values depending on some external conditions (for example, depending on user role). So I'm looking for some way to override accessing to that property. In that override method I would check user role and
return appropriate value.
Is there any way to do that?
I found that question: Is there a way to override ConfigurationManager.AppSettings? but it seems that it's not suitable for me, because here value of WebConfigurationManager.AppSettings["SomeProperty"] set once when application starts. And I need to do it dynamically.
In MVC, in order to simplify the testing and mocking, I tend to use customized object for all the common classes, like Request, Session and ConfigManager, referenced through interfaces.
You basically don't need to realize classes from scratch obviously, so your implementation can be a wrapper which is actually using the .net class under the hood, but which gives also the chance to insert some custom logic in the middle, like in your case.
Therefore, you can create a wrapper of the webconfigurationManager, with a method like GetAppConfig(key) containing your own logic.
Playing with the concept of dependency injection is then easy enough having this class available wherever you need it.
Therefore to make a simple example:
//this will be injected
public MyControllerCtor(IConfig cfg)
public interface IConfig
{
string GetAppConfig(string key);
}
public class myConfig:IConfig
{
public string GetAppConfig(string key)
{
//your logic
var someVar = WebConfigurationManager.AppSettings["SomeProperty"];
//your logic
return yourCustomAppSetting;
}
}
Big advantage of this approach is that if you wanted to store your config in a database or a service, and change your code, you simply need to change your interface implementation and the inject the new instance.
If you can't change the code that is reading the AppSettings, then there is no way to do what you want. WebConfigurationManager is not pluggable or replacable externally.
You'll have to change the code.
No, of course not.
If you can't change the class, then you can't change the behavior. There's no general reason why Microsoft would have placed an "override" capability inside of WebApplicationManager. Usually, one is expected to be able to change ones class, or else to design it properly so that it can be overridden the right way.
It sounds like you need to do some logic after retrieving the value from the web.config. If the logic modifies the value itself, you could always store a format string in the web.config instead.
Here's an example using a connection string setting. I'm using a format string to populate the server name at runtime:
<add name="sqlconnection" connectionString="Server={0}\SQLEXPRESS;Database=xxx;Trusted_Connection=True;"/>
And then I'm using this logic:
string connect = ConfigurationManager.ConnectionStrings["sqlconnection"].ConnectionString;
if (!String.IsNullOrEmpty(connect))
{
//check to see if the connection string needs to be set at runtime
if (connect.Contains("{0}"))
connect = String.Format(connect, HttpContext.Current.Server.MachineName);
}
return connect;
EDIT: If you can't edit the class directly, I would consider creating a partial class to implement this.
If you make direct changes to Web.config they will be effective only during the next request, and as I understand, this is not the desired effect.
You can not directly affect WebConfigurationManager.AppSettings["SomeProperty"], and that's the desired behavior, as the AppSettings as configurations are something static.
To achieve an effect close to what you desire, I'd suggest you to use the HttpContext.Current.Items collection, in which you will initialize in Application_BeginRequest to a certain value if conditions are met or default to WebConfigurationManager.AppSettings["SomeProperty"] otherwise.
Than, instead of accessing WebConfigurationManager.AppSettings["SomeProperty"] you will be accessing HttpContext.Current.Items["SomeProperty"].
Let's say I have a long established repository like this:
interface IDonutRepository
{
public IEnumerable<Donut> GetDonuts();
}
It's been around for ages, and the GetDonuts method does what it says. Then one day I need to add a new screen that shows all the donuts in the database, and it turns out that the method has a hidden feature - it filters out all donuts where stale = true. But on my new screen, I want to show all of them, even the stale ones! What is the best approach here?
Assuming that this method is used all over the place, and the default behaviour needs to stay the same, is it best to add a new method called GetAllDonuts that doesn't do the filtering, or should I just add a onlyFresh parameter onto the GetDonuts method?
I'm guessing its just down to judgement, but I'm wondering if there are any more informed answers out there?
I would overload the method creating a new overload that takes the showStale parameter and then modify the old method to use the new overload passing false for the parameter value.
The interface would look like:
interface IDonutRepository
{
public IEnumerable<Donut> GetDonuts();
public IEnumerable<Donut> GetDonuts(bool showStale);
}
Or if you're using .NET 4.0, you can use an optional parameter:
interface IDonutRepository
{
public IEnumerable<Donut> GetDonuts(bool showStale = false);
}
Why not use an optional parameter? This way you don't break existing code:
interface IDonutRepository
{
public IEnumerable<Donut> GetDonuts(bool onlyFresh);
}
Implementation:
public IEnumerable<Donut> GetDonuts(bool onlyFresh = false)
{
if (onlyFresh)
// do stuff
else
// do other stuff
}
This really comes down to personal preference, to some extent...
If you have the ability to change the API, I would (personally) rename the current method in a way that makes it obvious that it is not returning all Donut instances. My expectation would be that a repository's GetDonuts method would get all of the donuts. This could be doing via a parameter, or a different name, at your discretion.
That being said, a method overload taking the extra parameter is probably the best option moving forward, if keeping compatibility is critical. (This depends a lot on who and where this API is used...)
Depending on the circumstancs, one might consider introducing a property for accessing the donuts.
interface IDonutRepository
{
IEnumerable<Donut> Donuts { get; }
.. or ..
IQueryable<Donut> Donuts { get; }
}
It's fairly easy to implement this interface if you're using a Linq-savvy ORM like Entity Framework or NHibernate.
The old GetDonuts method could be renamed GetFreshDonuts(), or you could refactor calls to it into the form:
repository.Donuts.Where(x => !x.Stale)
One of the growing trends in software
design is separating interface from
implementation. The principle is about
separating modules into public and
private parts so that you can change
the private part without coordinating
with other modules. However, there is
a further distinction—the one between
public and published interfaces. This
distinction is important because it
affects how you work with the
interface.
http://www.martinfowler.com/ieeeSoftware/published.pdf
I've just reviewed some code that looked like this before
public class ProductChecker
{
// some std stuff
public ProductChecker(int AccountNumber)
{
var account = new AccountPersonalDetails(AccountNumber);
//Get some info from account and populate class fields
}
public bool ProductACriteriaPassed()
{
//return some criteria based on stuff in account class
//but now accessible in private fields
}
}
There has now been some extra criteria added which needs data not in the AccountPersonalDetails class
the new code looks like this
public class ProductChecker
{
// some std stuff
public ProductChecker(int AccountNumber)
{
var account = new AccountPersonalDetails(AccountNumber);
var otherinfo = getOtherInfo(AccountNumber)
//Get some info from account and populate class fields
}
public bool ProductACriteriaPassed()
{
//return some criteria based on stuff in account class
// but now accessible in private fields and other info
}
public otherinfo getOtherInfo(int AccountNumber)
{
//DIRECT CALL TO DB TO GET OTHERINFO
}
}
I'm bothered by the db part but can people spell out to me why this is wrong? Or is it?
In a layered view of your system, it looks like ProductChecker belongs to the business rules / business logic layer(s), so it shouldn't be "contaminated" with either user interaction functionality (that belongs in the layer(s) above) or -- and that's germane to your case -- storage functionality (that belongs in the layer(s) below).
The "other info" should be encapsulated in its own class for the storage layers, and that class should be the one handling persist/retrieve functionality (just like I imagine AccountPersonalDetails is doing for its own stuff). Whether the "personal details" and "other info" are best kept as separate classes or joined into one I can't tell from the info presented, but the option should be critically considered and carefully weighed.
The rule of thumb of keeping layers separate may feel rigid at times, and it's often tempting to shortcut it to add a feature by miscegenation of the layers -- but to keep your system maintainable and clean as it grows, I do almost invariably argue for layer separation whenever such a design issue arises. In OOP terms, it speaks to "strong cohesion but weak coupling"; but in a sense it's more fundamental than OOP since it also applies to other programming paradigms, and mixes thereof!-)
It seems like the extra data grabbed in getOtherInfo should be encapsulated as part of the AccountPersonalDetails class, and thus already part of your account variable in the constructor when you create a new AccountPersonalDetails object. You pass in AccountNumber to both, so why not make AccountPersonalDetails gather all the info you need? Then you won't have to tack on extra stuff externally, as you're doing now.
It definitely looks like there might be something going haywire with the design of the class...but it's hard to tell without knowing the complete architecture of the application.
First of all, if the OtherInfo object pertains to the Account rather than the Product you're checking on...it's introducing responsibilities to your class that shouldn't be there.
Second of all, if you have a Data Access layer...then the ProductChecker class should be using the Data Access layer to retrieve data from the database rather than making direct calls in to retrieve the data it needs.
Third of all, I'm not sure that the GetOtherInfo method needs to be public. It looks like something that should only be used internally to your class (if, in fact, it actually belongs there to begin with). In that case, you also shouldn't need to pass around the accountId (you class should hold that somewhere already).
But...if OtherInfo pertains to the Product you're checking on AND you have no real Data Access layer then I can see how this might be a valid design.
Still, I'm on your side. I don't like it.
considering that an accountNumber was passed into the constructor you shouldn't have to pass it to another method like that.
A few points
The parameter names are pascal case, instead of camel (this maybe a mistake)
getOtherInfo() looks like it's a responsibility of AccountPersonalDetails and so should be in that class
You may want to use a Façade class or Repository pattern to retrieve your AccountPersonalDetails instead of using a constructor
getOtherInfo() may also be relevant for this refactor, so the database logic isn't embedded inside the domain object, but in a service class (the Façade/Repository)
ProductACriteriaPassed() is in the right place
I would recommend this:
public class AccountPersonalDetails
{
public OtherInfo OtherInfo { get; private set; }
}
public class ProductChecker
{
public ProductChecker(AccountPersonalDetails) {}
}
// and here's the important piece
public class EitherServiceOrRepository
{
public static AccountPersonalDetails GetAccountDetailsByNumber(int accountNumber)
{
// access db here
}
// you may also feel like a bit more convinience via helpers
// this may be inside ProductCheckerService, though
public static ProductChecker GetProductChecker(int accountNumber)
{
return new ProductChecker(GetAccountDetailsByNumber(accountNumber));
}
}
I'm not expert in Domain-Driven Design but I believe this is what DDD is about. You keep your logic clean of DB concerns, moving this to external services/repositories. Will be glad if somebody correct me if I'm wrong.
Whats good. It looks like you have a productChecker with a nice clear purpose. Check products. You'd refactor or alter this because your have a need to. If you don't need to, you wouldn't. Here's what I would probably do.
It "feels" clunky to create a new instance of the class for each account number. A constructor argument should be something required for the class to behave correctly. Its a parameter of the class, not a dependency. It leads to the tempation to do a lot of work in the constructor. Usage of the class should look like this:
result = new ProductChecker().ProductACriteriaPassed(accountNumber)
Which I'd quickly rename to indicate it does work.
result = new ProductChecker().PassesProductACriteria(accountNumber)
A few others have mentioned that you may want to split out the database logic. You'd want to do this if you want unit tests that are fast. Most programs want unit tests (unless you are just playing around), and they are nicer if they are fast. They are fast when you can get the database out of the way.
Let's make a dummy object representing results of the database, and pass it to a method that determines whether the product passes. If not for testibility, this would be a private. Testability wins. Suppose I want to verify a rule such as "the product must be green if the account number is prime." This approach to unit testing works great without fancy infrastructure.
// Maybe this is just a number of items.
DataRequiredToEvaluateProduct data = // Fill in data
// Yes, the next method call could be static.
result = new ProductChecker().CheckCriteria(accountNumber, data)
// Assert result
Now we need to connect the database. The database is a dependency, its required for the class to behave correctly. It should be provided in the constructor.
public class ProductRepository {} // Define data access here.
// Use the ProductChecker as follows.
result = new ProductChecker(new ProductRepository()).CheckCriteria(accountNumber)
If the constructor gets annoyingly lengthy (it probably has to read a config file to find the database), create a factory to sort it out for you.
result = ProductCheckerFactory().GimmeProductChecker().CheckCriteria(accountNumber)
So far, I haven't used any infrastructure code. Typically, we'd make the above easier and prettier with mocks and dependency injection (I use rhinomocks and autofac). I won't go into that. That is only easier if you already have it in place.