I'd like to override the Serialize methods of the ASP.NET JavaScriptSerializer class. Nothing too fancy, I just want to do some additional post processing to the serialized string returned from .NET.
Unfortunately, none of the methods on this class are declared virtual and the class itself does not derive from an interface or abstract class (seems like a strange oversight given how many of the core .NET Framework classes are designed for extensibility).
Based on some reading I've done on the subject, it appears that I have a couple of options to choose from.
Create an extension method. I'm not a huge fan of this option, since it involves creating a new method (compiler won't allow using the same name/signature twice) that class consumers would need to be aware of.
Derive a new class from JavaScriptSerializer that has the exact same signature. Since JavaScriptSerializer has no virtual methods, I would use the "new" keyword in each method/property declaration in order to perform method hiding. I think this option is considered a decorator pattern?
Create a new interface called IJavaScriptSerializer that would have the same signature as JavaScriptSerializer. Remove all references in my code to JavaScriptSerializer and replace with references to the newly created interface.
I'd love to hear about additional approaches and the pros/cons of each approach.
Thanks for taking the time to read.
You're misunderstanding the Decorator Pattern, which refers to an object that inherits a class and wraps another instance of that class. (This is very common for streams). In your case, it's inapplicable.
I would recommend that you make your own replacement (or wrapper, whichever you need) for the JavaScriptSerializer class, without trying to have an identical API. If you need to be able to swap implementations, I would make an interface or base class with the core methods, and have two concrete implementations of it, one wrapping the original and one adding your post-processing.
In general, when designing classes, you should design to meet your needs, not to copy the .Net Framework's built-in classes.
Go to http://json.org and d/l one of the several classes that have source code, for JSON serialization.
Then, put in your post-processing, compile and use in your project.
Ideally, at this point I would create an extension method so I can just do this:
List<MyObject> s = fillObject();
return s.ToJSON();
Related
I'm trying to find out if there's a way to stop functions/methods from being added (EDIT: by other developers) to a class for the case where the object is a Model or DTO which should not contain methods (to prevent 'abuse' of the Models/DTOs by others, who may try and add 'helper' methods etc).
Is there any way to achieve this?
Use reflection and write a unit test that fails if a model-class has methods.
Mark all you model classes with a custom attribute. Then make a unit test that uses reflection to load a given assembly, iterate all classes in that assembly and check that classes marked with the model attribute does not have methods. This should be fairly straight forward using reflection.
I believe you are trying to solve a procedural issue with code where you should be using communication.
Your colleagues (i assume) are operating on the code files with 'full trust' privileges. If they break that privilege you should open a dialogue. Use the change as an opportunity to educate them on the intended design. Perhaps they are correct and you will be educated!
I suggest simply making the intended design obvious in the class name and with a comment stating the intended nature. Perhaps quote the design document(s) that informed the class.
You cannot hinder anyone with full write-access to your code-base to do so. The only two things you may do to avoid it are create some CodeAnalysis-rule for FXCop as mentioned by Christian.K in the comments or by writing your DTO-class so that it is undoubtly a DTO that should not have any methods by using a unambigious name for the class and if this is not enough provide some code-comments that notifies the coder to do not so.
However you may need some kind of method if using collections e.g. where you will need some kind of comparision if two instances of your DTO are equal, so you have to provide at least an Equals- and GetHashCode-method.
You don't need to use a struct to prevent additions to a class. You can use the sealed keyword
public sealed class MyDTOObject { ... }
Now, you can not inherent a class and also prevent inheritance (which is essentially what you're asking). The very fact of inheriting MyDTOObject is creating a new class which is based off of not equal to, or restricted, or defined in any way by the implementation of MyDTOObject.
You can use an abstract class, to force derived classes to implement certain methods, but not the other way around.
If you want to prevent others from deriving from your class and implementing helper methods, you must use the sealed keyword, or mark the class internal.
You may prevent the class being extended or inherited by marking it final that way nobody would be able to extend your class and hence not being able to add any behavior. But stop and ask yourself whether you want to do that or not, because then you'd be signing an invisible contract that everything ever required by the class is written in the class and this class needs no further addition.
To be clear, I was talking in Java context.
I'm working with a third party product which has provided an API. This API works by creating an implementation of a base class, and then in the app.config indicating the implementation that you want to use.
The problem with this is that it's possible to have multiple projects in this third party application. What I would like to do is create a wrapper class which implements the base class. This would look at the parameters and then look up a configuration to determine which other class to pass the processing over to, depending on which project is being used. This way we could add future projects to the system without modifying any of the existing code.
public class MyImplementation : ThirdPartyBaseClass
{
public override OnLoad(ThirdPartyType data)
{
//do stuff
}
public override Process(ThirdPartyType data)
{
//do stuff
}
}
There are about 15 methods that can be overridden. The base class methods appear to be empty because nothing happens if you don't override a method, so I would need my wrapper to be able to handle the situation where the type I need to use for this project might not implement some or all of the methods.
Anybody know of a suitable design pattern for this situation?
As said by Robert in comments, Abstract Factory seems appropriate for this one.
Check this wiki link and this dofactory link for more information on this one.
For a more concrete response, I have a few doubts.
There is an object of the base class which is got from the third party API. Now, when you say that is is possible to have multiple projects in this tool, do I take it to mean that you need to use this base class to create multiple "project" classes as defined by you?
Then, the wrapper class can have an object type of an interface IProject. This should have all the definitoins like OnLoad and Process. Each type of project will have a concrete class with the final implementation depending on the project type.
Hope this helps in giving you a direction!
I would think this would be fairly easy to implement with a good DI container (like Autofac), or even a poor-man's DI. You can choose which service to provide at run-time based on whatever criteria you choose and supply that as the concrete implementation for your implementation of the third-party API class via constructor injection.
The Decorator Pattern might help you here, together with the Abstract Factory pattern. I'd suggest a decorator (the implementation you configure in app.config) that uses a concrete factory (depending on the current configuration) to get an inner for the decorator.
If you'd like to use multiple implementations at once, you may also think of using the Composite Pattern to delegate calls to more than just a single inner.
Why does Microsoft use extension methods for classes that it creates; instead of just adding the methods to the classes, or creating child classes?
There are a number of reason Microsoft did this. The two biggest being:
Extension methods apply to interfaces, not just classes. Had Microsoft simply added the Linq methods directly to IEnumerable, it would have required every concrete implementation of that interface to implement those methods as well. By making them extension methods, written in terms of the existing IEnumerable<> behavior, every IEnumerable<> class gets them automatically.
For the 3.0 and 3.5 Frameworks, the core System.dll is the 2.0 library. Everything new in 3.0 ad 3.5 was added on top of that, in System.Core or other related libraries. The only way to get, for example, a new method in the List<> class that exists in 3.5 but not in 2.0 is to make in an extension method available in a 3.5 library.
IgnoreRoute() on RouteCollection is an extension method because it is intended for use with the MVC framework, rather than a core ASP.NET application. My guess would be that they didn't want to pollute the RouteCollection class with methods that non-MVC applications wouldn't need, while still allowing MVC applications to make use of the class.
I'm not sure this approach necessarily make sense (since, for example, they could have just created a child class); for more general reasons that extension methods might be used, others have answered nicely.
This is an example of the Non-Virtual Interface pattern (similar to Template Method). This is a pattern used in languages with multiple (implementation) inheritance, and the way to do it in C# is to use extension methods.
The basic idea is that you have only non-virtual and pure-virtual (abstract) methods. The implementor of the interface (or inheritor of the class/mixin, in languages with multiple inheritance), implements a small method or set of methods (in this case, GetEnumerator), and in return gets a whole slew of methods that depend on that one abstract method (like Select, Where, Aggregate, etc.)
As Michael Edenfield said in his answer, if we want to implmeent this pattern and we want IEnumerable to be an interface, we need to use extension methods. And making IEnumerable into an abstract class would be bad because its supposed to be a very low-cost, basic interface that should be put on pretty much any collection - implementing IEnumerable should not require rethinking a class hierarchy, it should be almost "for free".
I think the main reason is that it's very easy to extend such methods. For example, if you Linq extension methods you can easily write yout own set of extension methods (maybe foreach or some specific filter) which will work greate with microsoft methods: mylist.Where(...).MyFilter(...).Select(...)
My two cents:
because extension methods were added only in later versions of the .NET framework, they already had .NET Framework 1, 1.1, 2.0 and newer then at some point they added extension methods so they have used them to enrich the feature set on top of existing classes.
Should extension methods only be used on classes whose code you don't have access to?
I'm struggling to come up with a reason to have extension methods versus making it partial and adding the classes in an external file.
My specific scenario is as follows: I have classes that represent entities in a database via EF. I'm debating making the classes it renders partial and adding my own methods. Are extension methods a more valid alternative approach or are they not intended to be used when you have access to the code of the class you are extending?
The canonical counter-example is extension methods on an interface, as even if you control the source, there is no implementation. See: Linq.
But, yes, generally speaking, if you control the source of the concrete class, it is not unreasonable to expect to add the functionality to the class directly rather than using an extension method, if it makes sense for the functionality to actually be part of the class instance.
On the other hand, and coming back to your situation, you might consider neither approach. Your entities are data models, I would not add methods to those models, but rather encapsulate that functionality elsewhere. Those models exist to encapsulate your data, logic that might operate with or against that data might be better served in a different unit. But that really depends upon what your methods are doing, and also assuming they're not something like a trivial wrapper over one or more properties, for example.
Apart from the ability to provide extensions to interfaces, I use extension methods to add 'members' to a class that work using only the class' public interface. So if a method needs access to a private/protected member, it will become a class member, if not an extension method. This keeps the classes themselves small and focused...
No.
You may have a class that works fine in ninety percent of your projects. By adding an extension method you don't 'pollute' the original class but can still leverage it in the other ten percent of your projects.
Should extension methods only be used on classes whose code you don't have a access to?
Not necessarily. There are situations where extension methods can still help. I recently had an issue with the xml serializer where it could serialize an object that had a method that made use of a linq / lamba expression. Moving the method to an extension method resolved that. I like to use extension methods on DTOs also.
You might want to look at How Non-Member Functions Improve Encapsulation. There are some C++ specifics, but main idea applies to other OO languages as well. In short: the less methods you have in a class the easier it is to understand who and how changes private class state.
so in my application I've got several different customers being "serviced". Each customer has their own implementations of various classes that are all based on interfaces.
With the latest customer being added, I've noticed there will be a lot of duplication of code from another customer but the other customer is in no other way related to them.
I've already got a default implementation for several other customers and roll new ones as i need them.
My question is how do i refactor this and still keep the code clean? If i were a dev new to this code base i would want each customer to either use the default or their own implementation of these classes... but that's a lot of duplication.
Consider using an abstract base class with abstract or virtual members. Abstract members are essentially equivalent to interface members (they have no build-in behavior, they only guarantee the method exists) whereas virtual members have a default implementation which can be overridden by derived classes.
Your question is really too vague to answer in full, but here's how you can leverage inheritance.
If you want all classes to use the same implementation of a member then that member can be implemented in the base-class.
If you want each class to have its own implementation of a member then you can either use a base-class with abstract members, or an interface.
If you want some classes to use the same implementations and others to use different implementations then implementing the default behavior in the base-class and override it as needed.
My main point is that OOP there is a spectrum of how much or little functionality is in base/abstract/concrete classes. There's no silver-bullet answer, sometimes your base classes will be skeletons and sometimes they'll be fully fleshed-out; it all depends on the specific problem at hand.
Is there some way that you could create a base class, then a specific implementation for each customer and then using some type of Dependency Injection have that load classes or functionality as needed. You want to really have a DRY system so as to avoid headaches and typos or other similar human mistakes.
You may use either inheritance (put common logic to the base class) or aggregation (spread that logic among other classes and make use them from your customers).
I'd recommend the visitor pattern:
http://en.m.wikipedia.org/wiki/Visitor_pattern
As well as the mediator pattern:
http://en.m.wikipedia.org/wiki/Mediator_pattern
Reason being that it sounds like you may benefit from decoupling, or at least more-loose-coupling, the business logic from your classes, based on what you are saying.
It's a bit difficult to know what to suggest without a better understanding of the code... but some things that have worked for me in similar situations include:
Use a Strategy, for the duplicated code. I've had most success where the strategy is encapsulated within a class implementing a known interface (one class per alternate strategy). Often in such cases I use some form of Dependency Injection framework (typically StructureMap) to pass the appropriate strategy/strategies to the class.
Use some sort of template class (or template methods) for the common item(s).
Use a Decorator to add specific functionality to some basic customer.
STW suggested that I should offer some clarification on what I mean by "Strategy" and how that differs from normal inheritance. I imagine inheritance is something you are very familiar with - something (typically a method - either abstract or virtual) in the base class is replaced by an alternate implementation in the derived class.
A strategy (at least the way I typically use it) is normally implemented by a completely different class. Often all that class will contain is the implementation for a single replaceable operation. For example if the "operation" is to perform some validation, you may have a NullValidationStrategy which does nothing and a ParanoidValidationStrategy which makes sure every McGuffin is the correct height, width and specific shade of blue. The reason I usually implement each strategy in its own class is because I try and follow the Single Responsibility Principle which can make it easier to reuse the code later.
As I mentioned above, I typically use a Dependency Injection (DI) framework to "inject" the appropriate strategy via the class constructor, but a similar results may be obtained via other mechanisms - e.g. having a SetSomeOperationStrategy(ISomeOperation StrategyToUse) method, or a property which holds the strategy reference. If you aren't using DI, and the strategy will always be the same for a given customer type, you could always set the correct choices when the class is constructed. If the strategy won't be the same for each instance of a given customer type, then you probably need some sort of customer factory (often a factory method will be sufficient).
I'd go with the answer of spinon (got my vote at least), but it's to short so let me elaborate:
Use your interfaces for the default implementation and then use dependency injection. Most tools allow you to define a scope or some criteria how to resolve something.
I assume that you do know the client at some early point of the program. So for ninject you just might want to define a "Module" for each client and load that into the kernel, depending on the client.
So I'd create a "no customization" Module and create a "ClientX" Module for every special case that uses ´Bind.To()` instead.
You end up with
a base implementation that is clean/default
a single place change for a new client (got a new one? Great. Either it works with the default or just needs a single Module that maps the interfaces to other classes)
The rest of the code shouldn't mind and get the dependencies via injection (constructor, property, whatever is easiest to go for. Constructor would probably be the nicest way) and has no special treatment at all.
You could even use a conditional binding in Ninject link text to solve the binding issue without different modules at all (although, depending on the number of clients, this might get messy and should better be separated).
I was going to suggest aggregation, as #the_joric suggests, over inheritance, but your description makes it sound like your application is already reasonably well-factored - that there aren't a lot of small classes waiting to be extracted from your existing classes. Assuming that's the case, for any given interface, if you have a perfect class for the new customer already written and ready to go, I would say go ahead and use it. If you're worried about that, for some reason, then take that perfect class, make it abstract, and create empty subclasses for your existing customer and your new customer - and if it's not quite a perfect fit, then that's the way I would go.