I am reading a post about mobile web development and ASP.NET MVC here: http://www.hanselman.com/blog/ABetterASPNETMVCMobileDeviceCapabilitiesViewEngine.aspx.
In the article, Scott Hanselman goes through the process of creating his own view engine to render different views based on whether the site is requested from a mobile web browser or not.
In his MobileHelpers class, he has several methods with signatures that are very foreign to me. Here's an example:
public static void AddMobile<T>(this ViewEngineCollection ves, Func<ControllerContext, bool> isTheRightDevice, string pathToSearch)
where T : IViewEngine, new()
{
ves.Add(new CustomMobileViewEngine(isTheRightDevice, pathToSearch, new T()));
}
I've worked a little bit with inline functions like this (I think thats what they're called) but this logic is eluding me. I don't understand the purpose of the where T : ...... line either.
Could you guys help me understand what is happening here?
It would help if you could identify which parts in particular are confusing to you. I've picked the two I think are the most likely based on your question, and explained those. If there is any other syntax that is confusing you, please edit your question to explain which.
Explanation for where T : IViewEngine, new()
C# allows you to place constraints on generic type parameters. You can read more about constraints here.
In your particular case, where T : IViewEngine means that whatever type T is must be a descendant of the IViewEngine type. where T : new() is special syntax that indicates that whatever type T is must have a default constructor.
Explanation for this ViewEngineCollection ves
The keyword this means that the method AddMobile is an extension method to the ViewEngineCollection class. This means that in addition to being called as AddMobile(someViewEngineCollection, ...), it can be called as someViewEngineCollection.AddMobile(...). You can read more about extension methods here.
This is known as an extension method. The this modifier on the first parameter allows the method to be called as if it's an instance method on the type `ViewEngineCollection. For example
ViewEngineCollection col = ...;
col.AddMobile<SomeType>(() => true, "thepath");
The second item you mentioned, where, is known as a generic constraint. It limits the set of types which can be used for T to those which have a public parameterless constructor and derive from IViewEngine
The this is for an extension method. So any reference to a ViewEngineCollection has an extension method called AddMobile. The where T : IViewEngine, new() is called a generic constraint.
Where the calling device contains identification information in its user agent details (this is typically the browser name or something in webapp the method is aiming to match up a custom view engine to the route table for that device.
It's a bit generic and without context can be quite confusing but each device identifies itself in a unique way (well unique by device name at least).
essentially this method is identifying the right veiw engine to use to handle the device information given.
Since everyone else is trying to explain constraints and generics i thought i would leave that to the pros ...
http://msdn.microsoft.com/en-us/library/bb384067.aspx
... best way really ...
Related
Hello denizens of stack overflow, I'm having an issue (perhaps with understanding?) regarding polymorphism and generics. I want to be able to define a "system" that contains a "component". I also want to be able to extend systems and components to be able to have greater functionality.
I currently have two base classes, Component, and I/A_ComponentSystem (For the sake of brevity, I'm not going to be showing any actual code, just definitions):
public abstract class Component { }
public interface IComponentSystem { }
public interface IComponentSystem<TComponent> : IComponentSystem
where TComponent : Component { }
// The following are what should should actually be inherited from
public abstract class AComponentSystem : IComponentSystem { }
public abstract class AComponentSystem<TComponent> : AComponentSystem
where TComponent : Component { }
Below is an example component/system created:
public abstract class ITag : Component { } // This is to allow generating the code in a different binary. Hard to explain in the question, I'll clarify if need be
public class Tag : ITag { }
public abstract class ITagSystem : AComponentSystem<ITag> { }
public class TagSystem : ITagSystem { }
Below are some excerpts of actually trying to use the code/morph between the different objects (please note that the code isn't meant to be used in this way, but I'm writing unit tests to ensure compatibility between layers)
// This is the main system that will be passed around
TagSystem tagSys = new TagSystem();
// This is OK
ITagSystem ITagSys = (ITagSystem)ITagSys;
// This is OK
AComponentSystem A_TagSys = (AComponentSystem)tagSys;
// This is OK
AComponentSystem<ITag> ATag_TagSys = (AComponentSystem<ITag>)tagSys;
// This is OK
IComponentSystem I_TagSys = (IComponentSystem)tagSys;
// This is OK
IComponentSystem<ITag> ITag_TagSys = (IComponentSystem<ITag>)tagSys;
// Even the following is OK (which is why I am confused)
IComponentSystem<Tag> new_ITag_TagSys = (IComponentSystem<Tag>)tagSys;
//***This is where it blows up*** (1)
AComponentSystem<Tag> new_ATag_TagSys = (AComponentSystem<Tag>)tagSys;
I have another interface/class, SystemManager, which is defined thusly:
public interface ISystemManager
{
TComponent AddNewComponentToEntity<TComponent, TComponentSystem>(Entity e) // Please don't ask about Entity, it shouldn't be required for this snippet and I already feel like I've posted a lot)
where TComponent : Component, new() // Required for some reason or I get an error
where TComponentSystem : IComponentSystem<TComponent>;
}
Now, the specific block of code that I have here will throw an error as well:
//*** blows up here as well ***(2)
ISystemManager sysMan = new SystemManager(); // defined elsewhere
sysMan.AddNewComponentToEntity<Tag, ITagSystem>(entity);
As far as the errors that I receive, error (1) is:
Cannot convert type 'TagSystem' to 'AComponentSystem<Tag>'
Error (2) is below:
The type 'ITagSystem' cannot be used as type parameter 'TComponentSystem' in the generic type or method 'ISystemManager.AddNewComponentToEntity<TComponent,TComponentSystem>(Entity)'. There is no implicit reference conversion from 'ITagSystem' to 'IComponentSystem<Tag>'.
Now, as far as my question goes, it is thusly:
Why can I not convert TagSystem to AComponentSystem<Tag>? This seems like a valid morph.
Why is ITagSystem not converting to IComponentSystem<Tag>? It appears that Tag should still conform to ITag, which is supported.
Is there any way I could change my hierarchy while preserving my need for that many layers of abstraction?
Thank you to anyone for reading this and assisting me.
Note: Yes, this is for an EntityFramework driven game engine. I'm building it mainly as an exercise for myself, and so I can quickly spin up 3d projects for myself. Yes, I've built a few game projects before, no I'm not interested in "finishing" a game, I'm just tinkering and having fun.
Without a simpler and yet more-complete code example, it's impossible to provide specific advice in your specific scenario. However, the basic problem is that the types are indeed not convertible, just as the compiler says.
Why can I not convert TagSystem to AComponentSystem<Tag>? This seems like a valid morph.
TagSystem doesn't inherit AComponentSystem<Tag>. It inherits AComponentSystem<ITag>. These two types are not actually the same. Just because Tag inherits/implements ITag, that does not mean that AComponentSystem<Tag> automatically inherits/implements AComponentSystem<ITag>. If it did, then that would mean that a method or property of AComponentSystem<Tag> that normally would return a value of type Tag, could wind up being used in a situation where a Tag value is expected, but some other implementation of ITag is actually returned. This is because you would be able to cast to AComponentSystem<Tag>, and then use that reference to return the non-Tag implementation of ITag, to some code that only wanted Tag.
This is bad for what I hope are obvious reasons, so the compiler doesn't allow you to do that.
Why is ITagSystem not converting to IComponentSystem<Tag>? It appears that Tag should still conform to ITag, which is supported.
Without a good Minimal, Complete, and Verifiable code example, it's difficult to answer this part of your question, as the types you've shown don't appear consistent with the code you've shown. ITagSystem is declared as inheriting AComponentSystem<ITag>, which in turn implements only IComponentSystem, not IComponentSystem<TComponent>.
So based on the code shown, there's no reason even naively to think that the conversion could work. But let's assume for a moment there's a typo in the type declarations you've shown. Then the answer is basically the same as above: implementing IComponentSystem<ITag> is not the same as implementing IComponentSystem<Tag>.
Is there any way I could change my hierarchy while preserving my need for that many layers of abstraction?
Possibly. It depends on what these types actually do. Since C# 4, we've been able to specify generic type parameters on interfaces with covariance and contravariance. With a type parameter thus restricted, and interface members to match, the interface then can support specific casting scenarios like you're trying to do.
But note that this only works when the interface members really are compatible with such conversions. The compiler still won't let you do anything unsafe.
There are a lot of questions on Stack Overflow already discussing this. Technically your question could even be considered a duplicate of those. I hope the above addresses your immediate concerns, and gives you enough information to do more research and see if generic interface variance will work in your situation. If you need more help, I recommend you post a new question and make sure to include a good MCVE that clearly illustrates your question in the simplest way possible.
TagSystem distantly inherits AComponentSystem<ITag>, but you are trying to convert it to AComponentSystem<Tag>. (Note the lack of an "I" in the generic type.) Those two generic types of AComponentSystem<> are completely different, and you cannot freely cast between the two.
Same as point 1, just because Tag is a child of ITag doesn't mean that IComponentSystem<Tag> is a child of IComponentSystem<ITag>.
The answer is almost certainly yes, though exactly how depends entirely on how you are going to use it. You might also want to ask yourself if you really need this many layers of abstraction.
To give a better example of my first point, take for example a common generic type: the List. If generics followed the same inheritance rules as normal classes, then List<Car> would be a subtype of List<Vehicle>. But the difference between the two is that the first list can only hold cars, while the second list can hold any vehicle. So if these lists were parent and child, you would be able to do the following:
List<Car> cars = new List<Car>();
List<Vehicle> vehicles = (List<Vehicle>)cars;
vehicles.Add(new Truck());
You see the problem? The general rules of inheritance just allowed us to add a non-Car object to out list of cars. Or they would, provided that is a legal cast, which it isn't. In reality, List<Car> and List<Vehicle> are not related in any way, but are actually completely separate classes with no direct relation whatsoever.
I'm currently working on DevExpress Report, and I see this kind of syntax everywhere. I wonder what are they? What are they used for? I meant the one within the square bracket []. What do we call it in C#?
[XRDesigner("Rapattoni.ControlLibrary.SFEAmenitiesCtrlTableDesigner," + "Rapattoni.ControlLibrary")] // what is this?
public class SFEAmenitiesCtrl : XRTable
Those are called Attributes.
Attributes can be used to add metadata to your code that can be accessed later via Reflection or, in the case of Aspect Oriented Programming, Attributes can actually modify the execution of code.
The [] syntax above a type or member is called an attribute specification. It allows a developer to apply / associate an attribute with the particular type or member.
It's covered in section 24.2 of the C# language spec
http://www.jaggersoft.com/csharp_standard/24.2.htm
They are called attributes. They are quite useful for providing metadata about the class (data about the data).
They are called Attributes, You can use them to mark classes, methods or properties with some meta-data that you can find by reflection at runtime.
For instance, one common one is Serializable which marks a class as suitable for conversion into an offline form for storage later.
It is called an attribute.
In this case, DevExpress is using custom attributes on their report classes.
If you're interested in why you want to create custom attributes, this article explains it.
Piling on to the previous answers, this is an attribute that takes a string value in its constructor. In this case, the '+' in the middle is a little confusing... it should also work correctly with:
[XRDesigner("Rapattoni.ControlLibrary.SFEAmenitiesCtrlTableDesigner,Rapattoni.ControlLibrary")]
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.
I'm trying to write a strongly typed, localizable DisplayNameAttribute, but I can't get it to even compile. What I'd like to do on my viewmodel properties is something like
[LocalizedDisplayName<HomeResources>(r => r.WelcomeMessage)]
which would basically do the same thing as
[DisplayName("Welcome to my site!")]
except the message is localized. However, I can't get neither the generic constructor working (how do you supply type arguments to a constructor?) nor the choosing of what string to use. The current constructor looks like this
public class LocalizedDisplayNameAttribute<TResource> : DisplayNameAttribute
{
public LocalizedDisplayName(Expression<Func<TResource, string>> resource)
{ // ...
but the compiler complains that the input argument is not a compile time constant, so apparently this way of doing it is not valid.
Is there any way to get a strongly typed, localized attribute for display name? Is there one out there already?
You can't do it via an attribute. Keep in mind that an attribute is purely metadata embedded in an assembly. There's currently no way to embed a code construct such as an expression as metadata.
If you really really wanted to provide a means of specifying this metadata in a strongly typed way, you could write your own ModelMetadataProvider. It's a pretty advanced task, but I'm currently in the middle of a blog post that shows how to write one which I'll post soon hopefully.
Attribute classes cannot be generic.
IMO, the only way you can do that is:
[LocalizedDisplayName("WelcomeMessage")]
In fact framework attributes are not typed (like DefaultPropertyAttribute etc)
Since an attribute can't be generic and its arguments must be constants, you can't do it the way you describe. Anyway, members of the resource classes generated by the designer are static, so you can't access them through a instance.
Another option would be to pass only the name of the resource to the attribute :
[DisplayNameResourceKey("WelcomeMessage")]
When you want to retrieve the actual message, you just call ResourceManager.GetString with the resource key. But of course you lose the strong typing...
I'm looking for a list of reasonable use cases of putting attributes in a parameter.
I can think of some good cases for attributes in a method, but can't seem to see a good usage of a parameter attribute. Please, enlighten me.
And what about attributes on the return type of a method?
A specific case where they are used is in PInvoke. Parameters in PInvoke signatures can be optionally decorated with additional information through the use of attributes so that PInvoke marshalling of individual arguments can be either explicitly specified or have the default marshalling behaviour overriden, e.g.:
[DllImport("yay.dll")]
public static extern int Bling([MarshalAs(UnmanagedType.LPStr)] string woo);
This overrides the default marshalling behaviour for the string argument "woo".
For example, in Vici MVC, a .NET MVC framework, the parameters of a controller's action method can be "mapped" to a parameter with a different name. This is how it's done in in Vici MVC:
public void ActionMethod([Parameter("user")] int userId)
{
}
This will map the parameter "user" from the query string to the parameter userId.
That's just a simple example on how you can use attributes for parameters.
When using reflection, you might want some metadata associated with a property, for example, if you were to perform some code generation based on the properties in a class.
I would say that this question is a little open ended, there will be a time sooner or later that a need will arise and you will be thankful that the language supports it.
In Boo you can add macro attributes. Such as:
def Foo([required]p):
pass
This tells the compiler to transform the Foo method into this:
def Foo(p):
raise ArgumentNullException("p") if p is null
Slightly different than the static examples but interesting nonetheless.
As others have shown, what a thing is good for can be answered by what other people do with it. E.g.in MEF you can use it on the parameter of a constructor to specify that you want to import a dependency with a certain name:
public class Foo {
[ImportingConstructor]
public Foo([Import("main")] Bar bar) {
...
}
}