Builder pattern VS my implementation - c#

I had to build a logging dll assembly that will use a large amount of optional parameters, around 20 of them. It was written in c#.
What I end up doing was let my logging class to accept an object of type "log". This "log" class contains all the needed parameters and the corresponding properties to Get/Set them.
All of the parameters were of course initiated with default values first.
Once passing the "log" object to my main logging class, it then extract the values from that "log" object and perform the printing to file.
My question is - should I change it now to the builder pattern? (I just now learn it in - "Effective Java 2nd edition" book).
I can see the advantages of this pattern against calling Ctr/Methods with a billion parameters but I also think that passing in a new object that contains all parameters is not bad.
Can you explain if I really should change my design and why?
Since this is a design question I did not provide any code input. If I need to post some code let me know.

There is no compulsary rules for using design pattern. But it makes life simpler if applied to correct usecase.
You can definitely use Builder pattern in your case. Here are some guidelines:
First decide how many of the attributes of the Log object are mandatory (say x number), and how many of the attributes are optional (y).
2.Remove the y attributes from log object and put that in your Builder class through "add" methods.
If x<6 , remove the x attributes from log class, put them in the constructor of your Builder class. Now you can get rid of the Log class itself.
Else, if x>=6, keep them in the log class and pass the class in the constructor of your Builder class. This is also called "Transfer Object".
you can change the deciding number 6 as you wish. Usually a constructor containing 6 or more paramters becomes less readable.

Do you have a constructor with many arguments, where many of them are of the same type? Go Builder.
Do you have many constructors, where the difference between them is minimal? Go Builder.
Do you have a class initialized where one constructor calls another constructor, following a chain-like structure? Go Builder.
Otherwise, do your own thing.

Related

Is there a pattern where you have a class whose job it is to instantiate common implementations of another class?

I want to call it a "Helper" but this seems way too general.
Let's say I have a class called WidgetCranker and WidgetCranker can be set up to crank out widgets of the type Square, Keyhole and GearShape. I can also specify which Color I want my widgets to be and which Label I want stamped on them.
Now, setting up each individual instance of WidgetCranker is fairly involved, the constructor just gives you an empty WidgetCranker and you have to manually set the type and colour of widgets you want to crank.
WidgetCranker keyholeWidget = new WidgetCranker();
keyholeWidget.Type = WidgetTypes.Keyhole;
keyholeWidget.Color = WidgetColors.Red;
keyholeWidget.Label = "ACME Industries Prototype 1";
But I have a class that requires a lot of WidgetCrankers that pretty much all look the same except for the label. I want to make my code more readable and less laborious to maintain, so I create a helper class that does all the lifting for me. So the above now becomes:
WidgetCranker keyholeWidget = WidgetCrankerHelper.RedKeyhole("ACME Industries Prototype 1");
My question is twofold:
Is this an actual design pattern and if so, what do we call it? I want to call it a factory, but it most definitely isn't a factory pattern. We're creating exactly the same kind of object in every case, just instantiating them differently. I know it's a type of "Helper", but I want to be more specific than that if I can. It's a helper that does a very specific thing.
Given that "Helper" is a very generic name, I feel that just naming the method by what it produces isn't enough. I should name it so that it's obvious what it does. So would MakeRedKeyhole be better or BuildRedKeyhole? I don't want to use GetRedKeyhole because that implies we're getting back a reference to an existing instance and not creating a brand new one.
I tend to stay away from the term "Helper" as all classes are supposed to be helpful, right? :)
I think that calling this either Factory or Builder would be acceptable. The point of abstract factory is to encapsulate the construction/instantiation of an object. It could return different types, but it doesn't need to. The type consuming the factory shouldn't care.
I tend to use the "Builder" name when it is doing any complex construction like this.

Selecting constructor with fewer parameters in Unity

I have a 3rd party class library. One of the classes in that library, has a constructor with multiple overrides.
I want to tell Unity to create the class, using a constructor with fewer parameters (by default, it selects the one with the most number of parameters). How can I do this?
I know I can use InjectionFactory, but I prefer to let Unity create the object for me, than writing a delegate for it. Also if I had access to the source I could probably label the desired constructor with InjectionConstructor, but I don't. So what would be my other option?
Since you cannot use InjectionConstructorAttribute (as you mentioned, the library is not yours), you can use the InjectionConstructor class (not an attribute). You will need to call Resolve yourself to make sure Unity builds up the constructor parameters. Something like this:
IUnityContainer c = new UnityContainer()
.RegisterType<IStuff, GoodStuff>()
.RegisterType<StuffUser>(new InjectionConstructor(c.Resolve<IStuff>()));

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.

Best Practices on Code Duplication c#

I am trying to structure my code in such a way to reduce/avoid code duplication and I have encountered an interesting problem. Every time my code invokes a stored proc, I need to pass few variables that are common to the stored proc: such as username, domain, server_ip and client_ip. These all come from either HttpRequest object or a system.environment object.
Since these are passed to every stored proc, my initial thought was to create a utility class that is a database wrapper and will initialize and pass these every time, so I don't have to do it in my code.
The problem is though that c# class (inside App_Code folder) doesn't see Httprequest object. Of course, I could pass this as an argument to the wrapper, but that would defeat the whole purpose of creating the wrapper. Am I missing something here?
I realize it's not such a huge deal to repeat 4 lines of code each time I call a stored proc, but I would rather eliminate the code duplication at the very early stages.
Set up your data layer to inherit from a base class which contains 4 properties for those values. Make the public constructor require those 4 properties.
Then do something similar in the business layer - base class with those 4 properties in the constructor.
Then the UI does new BusObj( Request["username"], ... ).method()
Within the data layer you can have a method that builds a SQLParameter array with those 4 properties, then each method can add additional parameters to the array.
As a general rule regardless of programming language, if you can squint your eyes and the code looks the same you should make a function/method/message out of it and pass the parameters.
Another thing to look at once you have methods that take a large number of parameters (4 is a good rule of thumb, but it is definatly a case-by-case basis) it is time to make that method take an object as a parameter instead of individual parameters. 99.99999999999999999999% of the time such an object should be immutable (no writeable instance variables).
HttpContext.Current has similar information to what you find in HttpRequest and more importantly is available inside App_Code.
Here's a weird idea you may or may not like: define a 'profile' class and a function that expands the profile into the arguments of functions taking the common arguments.
class P {
readonly string name;
readonly string domain;
public P(string name, string domain) {
this.name = name; this.domain = domain;
}
public void inject(Action<string, string> f) {
f(p.arg1, p.arg2);
}
public T inject<T>(Func<string, string, T> f) {
return f(p.arg1, p.arg2);
}
}
It might work better in VB.net where you have the AddressOf operator. I would be really cautious using this type of thing, because you could easily damage readability and encapsulation.
I would keep it the way you have it now. It's cleaner, easier to extend/modify, and easier to unit test.
As for using HttpContext instead as some others have suggested, I would say that it is a bad idea. Once you start introduce dependencies in your domain on HttpContext, it's very difficult to take it out. What if later on you wanted to use your module without an HttpContext? What about unit testing it?
Try System.Web.HttpContext.Current.Request to get the current request.
You are possibly headed down a slippery slope. The point to DRY is to not repeat business logic in multiple places where a change in requirement creates the need to change code in multiple similar places. You don't necessarily refactor just because 4 lines are the same if those 4 lines are context dependent. You have also broken encapsulation by referencing the httprequest in that you are using a global variable. As a consumer of you class I would have to know the implementation detail that I could only call you from a web application.
That being said, if you take that into account and still want to proceed, here is another option for information like this. Create a custom SecurityPrincipal (Implement IPrincipal) that contains the properties you need and attach it to the thread. Fill them when the user logs in and then you can access it anywhere during the request. Your caller would still need to make sure this was done but at least it isn't platform specific.
Otherwise for the best encapsulation, pass in a class with the properties you need into the constructor for each object that needs to consume those properties.

Categories