I'm trying to refactor some code that is passing different combinations of parameters depending on the type of configuration an object needs. For example:
public MyWidget(string server, string port)
{
...
}
public MyWidget(string server)
{
...
}
public MyWidget(bool createAThing,
string nameOfThingToBeCreated,
string server,
string port)
{
...
}
public MyWidget(bool createAThing, string nameOfThingToBeCreated)
{
...
}
...etc
I don't want to use properties, because it feels like it's hiding some possible dependencies e.g. the object might require the server to be passed in if there's the port property has been assigned. Don't get hung up on the example params, this is just something I'm pulling out of the air.
I looked at the Builder pattern, but it's not quite what I need. Any suggestions would be great!
I'm using .NET 2.0
You could use a configuration object and pass that to your constructor.
Something like this:
public class WidgetOptions
{
public string Server { get; set; }
public string Port { get; set; }
...
}
public class MyWidget
{
public MyWidget(WidgetOptions options)
{
Server = options.Server;
Port = options.Port;
...
}
}
Actually, if the intent is to always create a "valid" object such that the object is not ever in a half-configured state, then the Builder pattern is appropriate. The builder holds the data points until they are all assigned and can then create a completely configured object in one go.
But it sounds like you don't trust your developers to read the documentation to know what to configure...you do provide documentation, right ;)
In that case, perhaps provide a set of builders that each only exposes the properties that relate to the "mode" your final object needs.
So something like this (pseudo code and made up, since you didn't provide any hinst about what you are really trying to model)
WidgetBuilder
+ whatever properties are common to all widget creation
+ MakeWidget
VectorWidgetBuilder : WidgetBuilder
+ get/set Lines
+ MakeWidget
BitmapWidgetBuilder : WidgetBuilder
+ get/set Image
+ MakeWidget
AnimatedWidgetBuilder : WidgetBuilder
+ get/set Images
+ get/set FrameRate
+ MakeWidget
A variation of this would be to define these permutations as various WidgetOptions, as Master Morality called them, but each distint set of options is its own class. So you might have VectorWidgetOptions, BitmapWidgetOptions, and AnimatedWidgetOptions that just exposes the related set of properties.
Related
Please feel free to modify the title, I couldn't come up with any better one =\
Given the following example class
public class Person
{
public string Name;
public int ID;
public string City;
}
I need to create another mirror class, where every field is actually a wrapper of the original class:
public class PersonMirror
{
public FieldWrapper<string> Name;
public FieldWrapper<int> ID;
public FieldWrapper<string> City;
}
public class FieldWrapper<T>
{
public T Value;
public bool someBool;
public int someCounter;
// ..whatever
}
The thing is, I have many classes to mirror, and some of them have many fields! Moreover, the original class may be changed from time to time (add / remove / rename field), and every change must be applied to the mirrored class - not a good practice for maintainability.
My question is - is there a type safe way automate the decleration (rather then creation, such as generated code) of such mirrored classes?
EDIT:
Let's start from the beginning. In our SOA system, there is a resource access service (serviceX) responsible for updating items in the DB. Other services send it the modifications they would like to perform - in json that would be something like: {ID: 123, name : "myNewName"}. serviceX would then build an update query to send to the DB. However, there is a requirement that serviceX will expose a POCO interface, so that the interface will be language independent, so expressions such as (p=> p.name, "MyNewName") are not allowed. Another requirement is type safety, so json is not allowed either. Currently, the above solution is the best one we came up to answer all the requirements. Any better solutions are more then welcome!
IMO, there's no way to do what you want, except code generation.
Approaches for code generation could differ (this maybe source code generation + compilation, emitting IL code, either your own or existing one), but this is the only way.
use T4 to autogenerate your "WrapperClass".
Below, a proposition of how you could implement your FieldWrapper.
public class FieldWrapper<T, O>
{
private T _item;
private O _owner;
private PropertyInfo _setter;
public T Value
{
get { return _item; }
set {
if (!EqualityComparer<T>.Default.Equal(_item, value))
{
_item = value;
// do some personal check
_setter.SetValue(_owner, value);
}
}
}
public bool someBool;
public int someCounter;
// ..whatever
// CTOR
public FieldWrapper(O owner, Expression<Func<T, O>> propertyExpressionInTheOwner)
{
_owner = owner;
propertyName = (propertyExpressionInTheOwner.body as MemberExpression).Member.Name;
// get PropertyInfo using the owner and propertyName
}
}
Using the expression behavior permits you to create your fieldWrapper this way.
var p = new Person();
new FieldWrapper(p, (pers) => pers.Name);
The good point with this technique it is that if you person class change you will directly receive a compilation error.
With T4 the must is to load the assembly where all you class are, tag you class model with a specific attribute. Look into the assembly to found every class that have this attribute and generate the wrapper class associate.
You would have to run it after every code change, but you could create a code parsing application.
List desired keywords to substitute, such as " string ", " int ". Read the file, line by line. Find definition of classes (line contains "class"), then replace every instance of any given keyword in it with:
"FieldWrapper<" + keyword + ">"
You might want to drop keyword substitution inside methods (and perhaps in the method signatures / return types themselves) of by checking for "(" and ")", and the opening curly brace. Resume operation when you reach the closing curly brace. You can achieve that by storing the nesting level in an integer, incrementing it when hitting '{' and decrementing it when reaching '}'.
We're using durandal to convert C# models to Knockout viewmodels for rendering. I'm wondering if there's a way I can set up a C# model with properties that have a set method or something so that the bindings and dependencies are already present when I get the Knockout viewmodel.
I'd like a scenario like this to happen.
public class MyObject{
public string FirstName{get; set;}
public string LastName {get; set}
private string fullName{get; set;}
public FullName{
get{return fullName;}
set{fullName = FirstName +" "+LastName}
}
I've used the prime example Knockout uses when explaining computed observables. I understand how to achieve this in purely JS viewmodel. However, I'd like to set up my C# model similar to what I have above (I don't think this actually works) in order to get back a computed that already has it's dependencies.
I'm not entirely sure it's possible, but it sure would be nice.
Max Brodin mentions KnockoutMVC which is a huge antipattern and you lose almost all benefits with Knockout since it creates server callbacks for almost everything you do.
A better option is to use for example DuoCode or Open source alternative WootzJs
These tools will compile C# code to Javascript, I have only tested DuoCode but it was farily easy to create a Knockout binding for it. After that its easy to create ViewModels like
using Knockout;
namespace ViewModels
{
public class FooViewModel
{
private readonly Observable<string> bar;
private readonly Observable<string> computed;
public FooViewModel()
{
bar = Global.Observable("HelloWorld"); //Translates to ko.observable("HelloWorld") on client
computed = Global.Computed(() => bar.Get() + "COMPUTED");
}
public Observable<string> Bar { get { return bar; } }
public Observable<string> Computed { get { return computed; } }
}
}
I have also created bindings for ko.mapping like
Mapping.Map(new { bar = "DataFromserver" }, null, this); which translates to
ko.mapping.fromJS({ bar = "DataFromserver" }, null, this); on client
The idea is good, but it's not going to work in the real world projects. Your C# code need to be translated to javascript and it could work for simple cases like yours. But if you change your computed property to more something complicated you will have problems.
There is a knockoutmvc project that provides such functionality. They have hello world sample which looks like something you can use as a start. You just need to mark your property with attributes
public class HelloWorldModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
[Computed]
[ScriptIgnore]
[JsonIgnore]
public string FullName
{
get { return FirstName + " " + LastName; }
}
}
And in razor view you should call:
#{
var ko = Html.CreateKnockoutContext();
}
#ko.Apply(Model)
You seem to want auto-translation of computed properties. That's a big ask for a small convenience. I think I could do it for trivial expressions, but how would you map .NET library methods like string.Format to javascript? You would need a client side library replicating the semantics. Big job, not worth the effort.
I've got a Global Resource file with many values
Currently in code I call the value like this
TxtSuccess.Text = (string) GetGlobalResourceObject("GlobalResource", "msgSuccess");
But if later in the design we needed to rename variables then maintaining will be a pain.
would it be better to do something like this?
public class AppGlobalConstants
{
public string MsgSuccess{ get; private set; }
public AppGlobalConstants()
{
MsgSuccess= (string) GetGlobalResourceObject("GlobalResource", "msgSuccess");
}
}
Then if later on the team wanted to change the name of some of these global resources they could do so without having to modify any pages which used these resources.
We want to use globals as there are plans for our web application (asp.net web forms 4.5) to be available to additional countries and languages in the future.
I would rather do something like this:
public static class AppGlobalConstants
{
public static string MsgSuccess
{
get
{
return (string) GetGlobalResourceObject("GlobalResource", "msgSuccess");
}
}
}
This way, the values are static. In case the name changes, you simply modify the strings in this class. Because everything is static in this class, you could do something like this:
Console.WriteLine(AppGlobalConstants.MsgSuccess);
If you want, you could also add a set accessor to the properties. Because everything is static, there's no need to create instances of this class.
I'm trying to find a design pattern or a best practice, or some other solution for a problem with keeping back versions of business logic within my application. Specifically, I am looking to find a way to determine which logic was used to issue an insurance policy.
I currently have code which looks like this:
public double FixedDeductibleSurchageAmount()
{
double percent = FixedDeductibleSurchargePercent();
double base_premium = CollisionPremium() + TheftPremium();
return (base_premium * percent);
}
I am needing to make a change to the business logic so that this function looks more like:
public double FixedDeductibleSurchageAmount()
{
double percent = FixedDeductibleSurchargePercent();
double base_premium = CollisionPremium() + TheftPremium() + MedicalPremium();
return (base_premium * percent);
}
Where I run into trouble is that existing policies should rate with the previous logic. Is there a design pattern for this? If not, are there any good ways to implement it?
Strategy pattern sounds most applicable. Probably you'd need a factory method or some such that takes in a date to return the appropriate strategy.
You're going to have to use additional data of some form to keep track of precisely what algorithm was used to obtain your data; you'll probably need to change your persistence representation to maintain versioning information about the algorithm used to derive your results.
BTW, you might consider making things like MedicalPremium or TheftPremium a Get-only property, rather than a parameterless function. They fit that paradigm very well.
There are any number of ways you can solve this problem. Some examples:
1) Switch to the new code and add a flag to the user data so that MedicalPremium automatically returns 0 for old users. This is particularly easy if you stored your data in XML; the old data just won't have the flag, and it won't affect your deserialization of the data because XML is flexible.
2) Make the class that contains your function MedicalPremium a base class, and make MedicalPremium virtual. Override it in the derived class, which is your new version. Newer users are the derived class. Old users are created as the base class. For the old users, it always returns 0. Properties can also be virtual just as functions can.
If you have a chance to look at Martin Fowler's Patterns of Enterprise Architecture he talks about individual instance methods, which isn't entirely the same as what you have, but is very similar. It's a great book in any case.
In the meantime, I think you might have to start considering your functions as also being data, and store in your database which function was used. You don't need (but may want) to store the function text, but you do need enough information to determine at run time which method to call. You asked about patterns, and obviously you have a strategy pattern going on here, which you could reference, but I don't know if it will be especially helpful.
Yes there is: the Decorator Pattern. You can use this to extend the behavior of a class with additional wrapper classes. In the example below I combine this with the Template Method Pattern to achieve what I believe you are looking for.
public class BaseSurchargePolicy {
protected abstract double BasePremium { get; }
protected abstract double FixedDeductibleSurchargePercent { get; }
public double FixedDeductibleSurchageAmount{
get
{
return (BasePremium * FixedDeductibleSurchargePercent);
}
}
protected ICollection<string> _ProcessorsUsed;
public IEnumerable<string> ProcessorsUsed
{
get { return ProcessorsUsed; }
}
}
public class OldSurchargePolicy : BaseSurchargePolicy
{
protected double BasePremium
{
_ProcessorsUsed.Add(GetType().Name);
return CollisionPremium + TheftPremium;
}
protected double FixedDeductibleSurchargePercent { get; set; }
public double CollisionPremium { get; set; }
public double TheftPremium { get; set; }
}
public class MedicalSurchargeDecorator: BaseSurchargePolicy
{
private BaseSurchargePolicy _wrapped;
private double _medicalPremium;
public MedicalSurchargeDecorator(BaseSurchargePolicy wrapped, double medicalPremium)
{
_wrapped = wrapped;
_medicalPremium = medicalPremium;
}
protected double BasePremium
{
get
{
_ProcessorsUsed.Add(GetType().Name);
return _wrapped.BasePremium + _medicalPremium;
}
}
protected double FixedDeductibleSurchargePercent {
get { return _wrapped.FixedDeductibleSurchargePercent }
}
}
I'm working on a system monitoring application similar to Nagios in C#. I have a plugin interface defined as:
public interface IPlugin
{
PluginResult Execute();
}
Each plugin, depending on its functionality, will have a variable number of arguments. As an example, a ping plugin might take a hostname, # of packets, timeout value, etc. I want the user to be able to define these arguments per service in my user interface, but obviously these arguments won't be known until the application discovers which plugins are available. I'm curious as to how others might design a plugin such that these variable arguments would be discoverable by the application.
Right now, as an example, I've got a ping plugin:
public class PingPlugin : IPlugin
{
private const string RESULT_MESSAGE = "Average ms: {0}; Packet loss: {1}";
private string _hostname;
private int _packets;
private int _timeout;
private int _warningTimeThreshold;
private int _warningLossThreshold;
private int _errorTimeThreshold;
private int _errorLossThreshold;
public PingPlugin(
string hostname,
int packets,
int timeout,
int warningTimeThreshold,
int warningLossThreshold,
int errorTimeThreshold,
int errorLossThreshold)
{
_hostname = hostname;
_packets = packets;
_timeout = timeout;
_warningTimeThreshold = warningTimeThreshold;
_warningLossThreshold = warningLossThreshold;
_errorTimeThreshold = errorTimeThreshold;
_errorLossThreshold = errorLossThreshold;
}
public PluginResult Execute()
{
// execute the plugin
}
}
I thought I might be able to discover the constructor parameters using reflection and present the user with a property grid to allow the configuration of the plugin, but I'm not sure the best way to provide a set of default values with this design. What might some alternatives be?
Have you considered looking at the Managed Extensibility Framework?
Rather than have a Plugin constructor determine the parameters, you might consider something like this:
public interface IPlugin
{
PluginResult Execute(Object parameters);
}
public class PingParameters
{
//Various parameters here, including [Description] and [DisplayName] attributes if you wish
}
public class ParametersTypeAttribute : Attribute
{
public Type Type { get; private set; }
public ParametersTypeAttribute(Type type)
{
Type = type;
}
}
[ParametersType(typeof(PingParameters))]
public class PingPlugin : IPlugin
{
public PluginResult Execute(Object parameters)
{
return Execute((PingParameters) parameters);
}
private PluginResult Execute(PingParameters parameters)
{
//Your execution code here
}
}
This gives you more flexibility for the parameters, as you can add attributes, provide setter validation and even specify designer/converter integration for the property grid. The property grid hooks up directly to the parameters object.
You can apply the [DefaultValue] attribute to the parameters.
In C# for, you can use new syntax for this: int warningLossThreshold = 30,
I voted +1 for the MEF answer too, it will solve many of your problems.
However, if you want to do it without MEF, it seems to me that you are missing some way to have the plugins tell your application via metadata, about the parameters it require.
One possible design could be this: Have an IPluginProvider interface, which your application can discover. This should have a parameterless constructor, so you can easily new up an instance. It should then have methods that return whatever metadata is needed (such as "pretty names" for the parameters, which are required, what are some sensible defaults, and so on). It should then include CreateInstance method, which takes the actual parameters as IDictionary<string,object> and returns the actual IPlugin instance.
I haven't looked at the MEF (will do now).
I had a problem almost identical to yours, I solved it with Attributes.
I have a UI which (calls BL which) uses reflection to show all the available "services" (nothing more than appropriately decorated classes).
When the user selects a "service" further attributes drive the UI. The attribute "schema" is fairly straight forward, and allows for any number of parameters with any name. By introducing constants (with the attribute definition) you can standardise common things like "name" so that your services are consistent.
All the data is then stored in a Key-Value pair table.
The great thing about this is that you can just dump new / modified "service" assemblies in teh bin dir - no extra work required. The only dependency is the attribute definitions assembly - so keep this lean.
Source code is at CodePlex if you want to "steal" some :)