Fluent interface configuration with lambdas in C# - c#

Many open source projects use a Configuration class and lambda's to clarify configuring a complex object. Take Mass Transit for example. A simple configuration would be like so.
Bus.Initialize(sbc =>
{
sbc.UseMsmq();
sbc.VerifyMsmqConfiguration();
sbc.VerifyMsDtcConfiguration();
sbc.UseMulticastSubscriptionClient();
sbc.ReceiveFrom("msmq://localhost/test");
});
When you hover over Initialize in Visual Studio it says the parameter for the method call is Action<ServiceBusConfigurator>. I was wondering if anyone could show a simple example of how to use this pattern on a class. I don't even know what to call this type of pattern and my "GoogleFu" is not working as of yet. In this particular case I realize the method is operating on a singleton pattern. But I am ok with it being an instance method on a class.

An Action<ServiceBusConfigurator> is a method which accepts a single parameter of type ServiceBusConfigurator, does an "action" operating on that instance, and returns nothing (void).
.NET BCL (starting from 3.5) comes with predefined generic delegate signatures: Action<T>, Action<T1, T2> (etc.) for methods which don't return a value, and Func<Tresult>, Func<T, Tresult> (etc.) for methods accepting zero of more parameters and returning a single result instance of type Tresult.
When you create a method which accepts a delegate, you allow callers of your method to pass more than just data parameters - your method actually delegates a part of responsibility to external code. In your case, Bus.Initialize creates an instance of ServiceBusConfigurator (sbc), and then calls the specified action with the sbc instance as the parameter.
This basically lets your method control the lifetime of the configuration class instance. It is up to the caller to fill in the details, but actual instance is provided by your class:
// this is not actual mass transit source code
public class BusCreator
{
public static IBus Initialize(Action<IConfiguration> action)
{
// create the config instance here
IConfiguration config = CreateDefaultConfig();
// let callers modify it
action(config);
// use the final version to build the result
return config.Build()
}
}
The benefit is that your built instance (the imaginary IBus in this case) cannot be modified further. Configuration instance is only created shortly, passed to an external method, and then used to create an immutable final object:
IBus result = BusCreator.Configure(cfg => cfg.BusType = BusType.MSMQ);
Two things to note in the line above:
The code inside the anonymous method is wrapped inside a delegate passed to the method. It is not executed until the Configure method actually calls it.
The cfg parameter is created by the Configure method and passed to the lambda. After the method returns, this object doesn't exist anymore (or is wrapped inside the resulting object).

To add to what others have said, this is an "entry point" into a fluent interface. The approach of using an Action callback to achieve this is a nice way of isolating the fluent interface in a way that is at the same time very extensible.

This resembles the Unit of Work pattern, which is commonly associated with transactions and persistence scenarios, but seems to fit to your example.
The following citation was taken from Martin Fowler's definition of the pattern:
A Unit of Work keeps track of everything you do during a business transaction that can affect the database. When you're done, it figures out everything that needs to be done to alter the database as a result of your work.
If you change business transaction for initialization and database for configuration, you can get a better idea of what's going on. Additionally, think of the action (the delegate in case) as an atomic operation: either the new configuration is fully applied, or the current configuration is kept unchanged.
As noted, the action itself doesn't explicitly touch Bus. Even without knowing the details of the involved classes, we can guess how this interaction occurs:
The ServiceBusConfigurator may be read after the action is invoked, before the Initializa() method returns (most likely);
Bus might implement/extend ServiceBusConfigurator, so that Initialize() can pass this as the argument of the invoked action (less likely);
Bus may be static and visible to ServiceBusConfigurator, which in turn can change the configuration properties of Bus upon a call to ReceiveFrom() (extremely convoluted and, I hope, very unlikely).
These are some strategies that just popped up my mind right now. Many others may be suggested!

Related

When using dependency injection in C#, why does calling an interface method automatically call the implemented class' method?

To clarify my question, suppose I have the following very basic statistics interface and class:
public interface IStatistics
{
void IncrementPacketsDiscovered();
}
public class Statistics : IStatistics
{
private int numberOfPacketsDiscovered = 0;
public void IncrementPacketsDiscovered()
{
numberOfPacketsDiscovered++;
}
}
Then suppose I have the following class that receives the injected IStatistics object:
public class Reporter
{
private IStatistics _statistics;
public Reporter(IStatistics statistics)
{
_statistics = statistics;
_statistics.IncrementPacketsDiscovered();
}
}
Why is it that I am able to call the IStatistics method IncrementPacketsDiscovered() on the IStatistics object and it automatically knows to fetch the method definition that was implemented in the Statistics class?
Any help would be greatly appreciated. Thank you!
TLDR; because the injected object that implements IStatistics is an instance of the Statistics class, and it is this way because somewhere else you told the dependency resolver to use Statistics whenever you mention IStatistics..
Note that Statistics.IncrementPacketsDiscovered being called is nothing to do with DI per se, you could write this:
IStatistics x = new Statistics();
x.IncrementPacketsDiscovered();
On the outside, x looks like an IStatistics. On the inside, it is a Statistics. If Statistics did something else (other than just implement the interface) it would be easier to see. It would also probably be more clear what's going on if you had something else that implemented IStatistics, like some sort of FakeStatistics that you use in a test scenario - testing is one such valid reason where you'd switch your program back and forth between different suites of objects.
You could just conceive that somewhere outside of all your code is the dependency resolver, a thing created by Microsoft*. It did that first line of code above for you, and later when you said you wanted to have a Reporter it looked and saw "the constructor takes a parameter of anything that implements IStatistics, and I just happen to have an instance of Statistics here that fits that requirement, so I'll pass that into the Reporter constructor.." because that is what it is configured to do/that is its job.
If you had a FakeStatistics that you used for testing, and a context where you reconfigured the injector to create and supply fake objects then it suddenly starts to make sense why it's a useful way to engineer - you don't have to have 100 places where you said new Statistics where you go through and change them all to say new FakeStatistics. It's also useful to be writing a class and suddenly realize "this class needs statistics.." you add a single argument IStatistics x to the constructor, hit Ctrl . and pick the option to add a property for it and that class now has access to a suitable implementation of IStatistics, supplied by the resolver. You don't have to chase up through everywhere you said new MyXClass(param1, param2) and change it to say new MyXClass(param1, param2, someStatistics) because the job of newing all your objects is the responsibility of the resolver
By using interfaces and coding up such that "any object that implements this interface can sensibly be used as an input argument to this class" you then open it up to the possibility that a "class instance lookup and provider service" can wire all your app together just by "rummaging around in its currently configured bag of objects for one that will do the job" (and then you change what's in the bag depending on the context)
So where did you put things in the bag? In the part of the program where you configured the resolver, methods like AddScoped, AddTransient, AddSingleton have the dual purpose of mapping a type of class to a type of interface and also configure what sort of lifetime the instance has- resolvers manage instances for you and create/destroy them over the lifetime you specify by which Add* method you use
* With this statement I am, of course, making a gross assumption as to which injector you're using. There are other DI/IoC frameworks available for C#, created by others. The overarching concept remains the same; the more you can get the computer to write your code for you, the quicker, easier and more reliable it can be. Establishing dependenceies between objects in your program is one such place where it can make sense to hand it off to software rather than writing it yourself

Dynamically cast/wrap delegate to signature with interface at runtime

Context
Currently I am creating an Extract, Transform and Load (ETL) application written in C# with .NET Core. The source of the ETL application is a Soap webservice, which contains a multitude of methods. Each entity (Employee, Company, etc) and way of retrieving (ByKey, ByQuery, etc) has its own Soap webservice method. For example if I were to retrieve the entity 'Employee' by executing a query, I would call the GetEmployeeByQuery method. All methods return a string with XML.
Visual Studio generated proxy classes of this webservice by its WSDL file (generated indirectly through dotnet-svcutil). Unfortunately the proxy classes generated for this service seem to be generated according to a message contract pattern. This means that the proxy method GetEmployeeByQuery returns the GetEmployeeByQueryResponse partial class, which has a field Body that contains the GetEmployeesByQueryResponseBody partial class. The actual result is located in a string field on the GetEmployeeByQueryResponseBody that has the name of GetEmployeeByQueryResult.
Ideally the ETL application is able to invoke Soap webservice methods through reflection and on the basis of application configuration. The configuration contains the method and parameters to call, and through some factories this results in a Delegate that will be used as a strategy elsewhere in the application. This delegate should be generic and not tied to any specific entity.
The Problem
Currently I have created a delegate with a signature that solely consists of the concrete type implementations. This is necessary because the Delegate.CreateDelegate method requires this in order to bind the actual method to the delegate. The signature is Func<string, string, string, string, Task<GetEmployeeByQueryResponse>>. This signature however is tied to a specific entity, which is what I am trying to prevent.
Therefore I am trying to cast this delegate to the signature Func<string, string, string, string, Task<IMessageResult<string>>> where the IMessageResult<string> is an interface implemented on the generated proxy code through a partial class.
Method that tries to retrieve more generic delegate
public static TMethodSignatureInterfaced GetMethodDelegate<TMethodSignatureInterfaced>(object classInstance, string methodName, Type methodSignatureTyped)
where TMethodSignatureInterfaced : class
{
//Another way of casting, same result.
//TMethodSignatureInterfaced method = (TMethodSignatureInterfaced)(object)Delegate
// .CreateDelegate(methodSignatureTyped, classInstance, methodName) as TMethodSignatureInterfaced;
TMethodSignatureInterfaced method = Delegate
.CreateDelegate(methodSignatureTyped, classInstance, methodName) as TMethodSignatureInterfaced;
if (method == null)
throw new InvalidCastException($"Method {methodName} could not be cast into a delegate. The given method signature could not be found.");
return method;
}
Unfortunately it seems that casting the delegate to another signature is not possibly dynamically. The code either throws an error (with the first casting technique) or returns null. In other posts I have seen cases where if the interface is specified casting a delegate is possible. I was wondering whether someone would know a way around this.
EDIT
From this Stackoverflow question, I gather that the Task class is invariant. If I have understood it correctly, this makes my goal of casting the Delegate to another signature directly impossible. The workarounds mentioned there do not seem to be relevant for my specific case. I am going to look into this further, any help is still greatly appreciated.

What are the desirable situation (real life example) to create static methods except for creating helper?

I just want to understand the purpose that static method serves and what are the desirable situation where i can create static methods except some would say that static methods are used for creating helper.
Consider i have 1 website that will be used in my company only like Human resource management system like websites.
Now after Admin login in to the system admin will see the list of employees.so the method is simple which does nothing more than fetching all details of employees from employee table and will display them on the web site and this method will be define in business access layer like this in .net:
public class EmployeeBal
{
public List<Employee> GetAllEmployees()
{
return Select * from Employee
}
}
This is how i would call this method from my application.For Eg(.aspx page or mvc controller etc....)
var employeeBal= new EmployeeBal();
employeeBal.GetAllEmployees();
So my question is should i create this method as static method or non static method??
Note:This is just an example of method and this method is in my business access layer.
Consider i have 1 ecommerce website where on the home page i am displaying some list of products and on visit of that website every users can see that list of products.
so my function would be same as above define in Business acess layer:
public class ProductBal
{
public List<Product> DisplayProductonHomePage()
{
return Select * from Products
}
}
So my question would be same like whether to create this method as static method or non-static method and what will happen if more than 10 users at same time simultaneously access this website then what will be the behaviour/implications of this method???
Will this method will serve the purpose of this each user if we declare this method as static??
Can anybody answer this question with briefly explaining every scenario???
A static method makes sense when there’s no state to maintain. What do I mean by state? Well, consider the following: You have two distinct objects, a and b, which are both of type EmployeeBal. Is there ever a case in your program where a.GetAllEmployees() and b.GetAllEmployees() would yield different results?
If not, then why do the objects a and b exist at all? The whole point of having objects is to associate some distinct state with them. If two different objects can never refer to a different state, then they fulfil no purpose.
In fact, in this situation your EmployeeBal would be exactly equivalent to System.Math, and all its methods are “helper methods” (if that’s what you want to call them). In this case, forget about static methods for a minute: your whole class should be static (static class EmployeeBal), and it should not have any constructors; because the concept of an object of type EmployeeBal simply makes no sense. In fact, in other languages EmployeeBal wouldn’t be a class at all; instead, it would be something generally called a module: a unit that logically groups code. C# has no modules, and all code must reside within classes. Classes thus fulfil a dual purpose: they group code, and they generate objects.1
Now consider a less extreme case: EmployeeBal objects actually maintain state, and differ. Yet GetAllEmployees() will still yield the same result, regardless of which object calls the method.
In this case, EmployeeBal obviously cannot be a static class. But GetAllEmployees is still stateless, and thus doesn’t belong to objects of type EmployeeBal. And thus the method should be static.
1 This lack of distinction between two fundamentally distinct concepts (module and class) is actually quite annoying, and the main reason that C# behaves this way is because it was conceived to be similar to Java. It was a mistake in hindsight, but not a serious one.
Is there a reason why the method should be static? If not I'd always side with non-static.
One big reason is being able to write unit tests.
In order to write unit tests you want to be able to isolate the class you're testing from other classes. But if class A contains a reference to static class B, then you can't test A without testing B. Maybe B depends on connection strings or config settings. Maybe B depends on other static classes. Now you can't test A unless B and everything it depends on are in place.
If, on the other hand, class A depends on an interface like IEmployeeProvider that gets provided through its constructor then you can test class A with a mocked implementation of IEmployeeProvider.
If A has IEmployeeProvider as an argument in its constructor then you can tell by looking at the constructor that it depends on IEmployeeProvider. But if it depends on a static EmployeeProvider class somewhere inside a method then the dependency is hidden. You have to read the whole class to know what it depends on.
Also, the static class itself can be harder to test. Unless it's absolutely always going to remain stateless then it's better to have a non-static class that you can unit test.
It's fine to have multiple threads executing the same static method, as long as the method does not access static state such as field or properties. In that case, the shared objects stored in the fields/properties must themselves be thread safe. The data access parts of .Net are not designed to be thread safe.
As soon as you start considering aspects such as managing a database connection that can be reused for several queries during the execution of a single web request, you should consider if static is the best approach. Since you cannot store the connection in a static field as explained above, you will have to pass it as a parameter to each static method. On the other hand, if you pass the connection to a constructor and store it in a (non-static) field, you can access it from multiple non-static methods of that instance, which will IMO be easier to manage.
This is quite a big topic however, and in general the management of class dependencies is quite tricky to get right in OOP. Some programmers prefer to delegate this task to an "Inversion of Control"-library. There are many available for .Net such as Microsoft Unity, StructureMap, AutoFac, etc.
To answer your question:
So my question is should i create this method as static method or non static method??
Note:This is just an example of method and this method is in my business access layer.
I would make those methods static - given what you provided. But I bet that you would have instance variables either declared in your class, or in methods in that class, which then of course that would mean don't make it static.
So a determining factor for me if I decide to use a static method or not has to do with re-use and resources.
If I find myself re-using a method many times over, and I conclude it doesn't need state (kept in memory) - I will make it a static method.
Also I usually will make my methods static if they can be used in other applications or if I think they will be useful down the road.
For example I recently wrote a method that converts a excel file to a flat file. I made this a static method in its own static class (i may put it in a similar utility class down the road) because I will probably end up using it again in another project, so I can now just reference its class without having to instantiate a new object to just call the method. ( I don't need state anyways)
I'm pretty new to programming as well and I hope you found this helpful.
If we are going to talk about static, we need to introduce a dependency. In this case it is a sql client. Here's what the code looks like with that introduced. Since we aren't going to get into the details of a sql client it's used as an interface in the static method.
var client = new SqlClient();
var allEmployeeData = EmployeeBal.GetAllEmployees(client);
class EmployeeBal
{
public static Employee GetAllEmployees(ISqlClient client)
{
return client.Execute("Select * from Employee");
}
}
Dependency injection through an interface changes everything. Now the method is good as being static, because it only deals with an interface and a string. Both of these are stateless. Since all components of the method are stateless they are perfectly safe for a static method which can have only one global state.
As your code was written originally it's not safe as being static, because how can I be assured the sql client is prepared to be used and after I've checked that it's ready it hasn't been altered when I go to run the query? If I can inject the sql client I can manage it since it has a local vs global scope.
A better example would be something like a factory for a sql client. For example with nhibernate there should only be one session factory created. That one thread safe session factory can create multiple non-thread safe sessions for running sql queries. In this case it's appropriate to have the session factory exposed through a static method, because that describes the fact that there is only ever going to be one session factory.
var session = SessionFactory.OpenSession();
Using static methods is equivalent of having a global behaviour. It comes with benefits: ease of access for simple scenarios.
It also comes with all the problems that global data and state have. Among them you cannot substitute an implementation with another (for example for tests). See https://softwareengineering.stackexchange.com/questions/148108/why-is-global-state-so-evil
While you might consider that you don't have a global state ... conceptually you have. You have a unique, predetermined, unconfigurable, hard coded way of accessing some behaviour. You published it and you cannot change it ... ever. You break the open-close principle. You break the liskov substitution principle.
Java has this but scala amended that. More on this here: Why doesn't Scala have static members inside a class?
Use cases for static and non-static methods differ, so you need to create one based on what's the need that they fulfill:
Static method does not participate in inheritance-based polymorphism, while non-static does. In other words, you can't mark static method as virtual or abstract, which means you cannot change its behavior. This also means that caller of the static method knows exactly what this static method is going to do and how exactly. With non-static method, you can be calling it on base class but due to polymorphism you may end up calling the derived class method with overriden behavior.
Both static and non-static methods can be changing a state of something (as opposed to what others claim), but there's a difference. You can design a static class that has all static members (properties, methods, etc.) in it, so the methods can be changing the state of this static class (that said, even though C# allows you doing that, I don't recommend creating such class anyway). With non-static method, you can be changing both static and non-static state of the class. This goes further into the differences between static and non-static classes, which in short means: static class is one concrete instance, while a non-static class can be multiplied and each of them will have its own copy of the state (so why design a static class with the artificial limitation then - this is why I didn't recommend them before).
One more nice usage of static methods is extension methods. These should be defined as static, but you can call them on the instance of the class that they are extending. They still serve as outside shortcuts to the instance, since they can't do anything more than regular static methods (cannot access private or protected members for instance).
And you're right, static class fits well when defining helper methods, because those usually are just shortcuts to some fixed functionality, accessible easily to re-execute it from many places. In Visual Basic, instead of static keyword you would use shared keyword, which nicely explains the purpose of the static method.
Finally, I personally recommend creating static methods as Pure functions, which always produce same output for the same input (no side effects, such as output is different based on time or other implicit factors). You should have a strong reason to design it otherwise (e.g. if you are writing Math.Random()).
Now, to answer the points from your question (I know, finally):
I think business access layer should not be static, because you would most likely need benefits of non-static classes, such as dependency injection and unit-testability.
There is no difference between static and non-static methods from the threading/multithreading standpoint, both of them can be called by multiple threads at the same time and all of them will execute simultaneously (unless using synchronization constructs). However, there is common design recommendation that you should make static methods thread-safe if you expect race conditions. Non-static methods don't have to worry about this, as this would put them into too many assumptions.

Constructing a (somewhat) complex object

When I create classes, simple constructors tend to be the norm. On one of my current projects, a movie library, I have a Movie domain object. It has a number of properties, resulting in a constructor as follows:
public Movie(string title, int year, Genre genre, int length, IEnumerable<string> actors)
{
_title = title;
_year = year;
_genre = genre;
_length = length;
_actors = new List<string>(actors);
}
This isn't terrible, but it's not simple either. Would it be worthwhile to use a factory method (static Movie CreateMovie(...)), or a perhaps an object builder? Is there any typical pattern for instantiating domain classes?
UPDATE: thanks for the responses. I was probably overthinking the matter initially, though I've learned a few things that will be useful in more complex situations. My solution now is to have the title as the only required parameter, and the rest as named/optional parameters. This seems the all round ideal way to construct this domain object.
If you are using .NET 4.0, you can use optional/named parameters to simplify the creation of an object that accepts multiple arguments, some of which are optional. This is helpful when you want to avoid many different overloads to supply the necessary information about the object.
If you're not on .NET 4, you may want to use the Object Builder pattern to assembly your type. Object builder takes a bit of effort to implement, and keep in sync with you type - so whether there's enough value in doing so depends on your situation.
I find the builder pattern to be most effective when assembling hierarchies, rather than a type with a bunch of properties. In the latter case, I generally either overloads or optional/named parameters.
Yes, using a factory method is a typical pattern, but the question is: Why do you need it? This is what Wikipedia says about Factory Methods:
Like other creational patterns, it deals with the problem of creating objects (products) without specifying the exact class of object that will be created. The factory method design pattern handles this problem by defining a separate method for creating the objects, which subclasses can then override to specify the derived type of product that will be created.
So, the factory method pattern would make sense if you want to return subclasses of Movie. If this isn't (and won't be) a requirement, replacing the public constructor with a factory method doesn't really serve any purpose.
For the requirements stated in your question, your solution looks really fine to me: All mandatory fields are passed as parameters to the constructor. If none of your fields are mandatory, you might want to add a default initializer and use the C# object initializer syntax.
It depends.
If that is the only constructor for that class, it means all the properties are required in order to instantiate the object. If that aligns with your business rules, great. If not, it might be a little cumbersome. If, for example, you wanted to seed your system with Movies but didn't always have the Actors, you could find yourself in a pickle.
The CreateMovie() method you mention is another option, in case you have a need to separate the internal constructor from the act of creating a Movie instance.
You have many options available to your for arranging constructors. Use the ones that allow you to design your system with no smells and lots of principles (DRY, YAGNI, SRP.)
I don't see anything wrong with your constructor's interface and don't see what a static method will get you. I will have the exact same parameters, right?
The parameters don't seem optional, so there isn't a way to provide an overload with fewer or
use optional parameters.
From the point-of-view of the caller, it looks something like this:
Movie m = new Movie("Inception", 2010, Genre.Drama, 150, actors);
The purpose of a factory is to provide you a customizable concrete instance of an interface, not just call the constructor for you. The idea is that the exact class is not hard-coded at the point of construction. Is this really better?
Movie m = Movie.Create("Inception", 2010, Genre.Drama, 150, actors);
It seems pretty much the same to me. The only thing better is if Create() returned other concrete classes than Movie.
One thing to think about is how to improve this so that calling code is easy to understand. The most obvious problem to me is that it isn't obvious what the 150 means without looking at the code for Movie. There are a few ways to improve that if you wanted to:
Use a type for movie length and construct that type inline new MovieLength(150)
Use named parameters if you are using .NET 4.0
(see #Heinzi's answer) use Object Initializers
Use a fluent interface
With a fluent interface, your call would look like
Movie m = new Movie("Inception").
MadeIn(2010).
InGenre(Genre.Drama).
WithRuntimeLength(150).
WithActors(actors);
Frankly, all of this seems like overkill for your case. Named parameters are reasonable if you are using .NET 4.0, because they aren't that much more code and would improve the code at the caller.
You gave a good answer to your own question, it's the factory pattern. With the factory pattern you don't need huge constructors for encapsulation, you can set the object's members in your factory function and return that object.
This is perfectly acceptable, IMHO. I know static methods are sometimes frowned upon, but I typically drop that code into a static method that returns an instance of the class. I typically only do that for objects that are permitted to have null values.
If the values of the object can't be null, add them as parameters to the constructor so you don't get any invalid objects floating around.
I see nothing wrong with leaving the public constructor the way it is. Here are some of the rules I tend follow when deciding whether to go with a factory method.
Do use a factory method when initialization requires a complex algorithm.
Do use a factory method when initialization requires an IO bound operation.
Do use a factory method when initialization may throw an exception that cannot be guarded against at development time.
Do use a factory method when extra verbage may be warranted to enhance the readability.
So based on my own personal rules I would leave the constructor the way it is.
If you can distinguish core data members from configuration parameters, make a constructor that takes all of the core data members and nothing else (not even configuration parameters with default values—shoot for readability). Initialize the configuration parameters to sane default values (in the body of the method) and provide setters. At that point, a factory method could buy you something, if there are common configurations of your object that you want.
Better yet, if you find you have an object that takes a huge list of parameters, the object may be too fat. You have smelled the fact that your code may need to be refactored. Consider decomposing your object. The good literature on OO strongly argues for small objects (e.g. Martin Fowler, Refactoring; Bob Martin, Clean Code). Fowler explain how to decompose large objects. For example, the configuration parameters (if any) may indicate the need for more polymorphism, especially if they are booleans or enumerations (refactoring "Convert Conditional to Polymorphism").
I would need to see the way that your object is used before giving more specific advice. Fowler says that variables that are used together should be made into their own object. So, sake of illustration, if you are calculating certain things on the basis of the genre, year and length, but not the other attributes, those together may need to be broken out in to their own object—reducing the number of parameters that must be passed to your constructor.
As for me - all depending on your domain model. If your domain model allows you to create simple objects - you should do it.
But often we have a lot of composite objects and the creation of each individually is too complicated. That's why we`re looking for the best way to encapsulate the logic of composite object creation. Actually, we have only two alternatives described above - "Factory Method" and "Object Builder". Creating object through the static method looks a bit strange because we placing the object creation logic into the object. Object Builder, in turn, looks to complicated.
I think that the answer lies in the unit tests. This is exactly the case when TDD would be quite useful - we make our domain model step-by-step and understand the need of domain model complexity.

DAL Design/Load methods with NHibernate

public MyClass(int someUniqueID)
{
using(//Session logic)
{
var databaseVersionOfMyClass = session.CreateCriteria(/*criteria*/)
.UniqueResult<MyClass>();
//Load logic
}
}
The code sample above is my current direction, although I've reached a point where I need a bit of a sanity check.
With NHibernate(I'm green in this area), is it common or best practice to instantiate an object from a database within the class constructor? The alternative I believe, would be to have a static method that returns the object from the database.
I've also come across a relevent question regarding constructors vs factory methods, however I don't believe this implementation fits the factory methodology.
To add an additional question onto the above, if instantiation within the constructor is the way to go, I've always used some sort of Load() method in the past. Either a specific private method that literally matches properties from the returned db object to the new class, or via a generic reflective method that assumes property names will match up. I'm curious if there is another way to "load" an object that I've missed.
I do not like this approach.
IMHO , it is better to implement some kind of repository which retrieves instances of persisted classes for you.
As an alternative, you could also follow the ActiveRecord approach, where you could have a static 'Load' method inside your class, and an instance method 'Save' for instance. (Take a look at Castle ActiveRecord).
But, for me, I prefer the Repository approach.

Categories