Is it possible to define an Interface with optional implementation methods? For example I have the following interface definition as IDataReader in my core library:
public interface IDataReader<T> {
void StartRead(T data);
void Stop();
}
However, in my current implementations, the Stop() method has never been used or implemented. In all my implementation classes, this method has to be implemented with throw NotImplementedExcetion() as default:
class MyDataReader : IDataReader<MyData> {
...
public void Stop()
{
// this none implementaion looks like uncompleted codes
throw NotImplementedException();
}
Of course, I can remove the throw exception code and leave it empty.
When I designed this data reader interface, I thought it should provide a way to stop the reading process. Maybe we will use Stop() sometime in the future.
Anyway, not sure if it is possible to make this Stop() method as an optional implementation method? The only way I can think is to either to define two interfaces one with stop and another without such as IDataReader and IDataReader2. Another option is to break this one into to interfaces like this:
interface IDataReader<T> {
void StartRead(T data);
}
interface IStop {
void Stop();
}
In my implementation cases, I have to cast or use as IStop to check if my implementation supports Stop() method:
reader.StartRead(myData);
....
// some where when I need to stop reader
IStop stoppable = reader as IStop;
if (stoppable != null ) stoppable.Stop();
...
Still I have to write those codes. Any suggestions? Not sure if there is any way to define optional implementation methods in an interface in .Net or C#?
Interesting. I'll have to quote you here:
However, in my current
implementations, the Stop() method has
never been used or implemented. In all
my implementation classes, this method
has to be implemented with throw
NotImplementedExcetion() as default:
If this is the case, then you have two options:
Remove the Stop() method from the interface. If it isn't used by every implementor of the interface, it clearly does not belong there.
Instead of an interface, convert your interface to an abstract base class. This way there is no need to override an empty Stop() method until you need to.
Update The only way I think methods can be made optional is to assign a method to a variable (of a delegate type similar to the method's signature) and then evaluating if the method is null before attempting to call it anywhere.
This is usually done for event handlers, wherein the handler may or may not be present, and can be considered optional.
For info, another approach fairly common in the BCL is Supports* on the same interface, i.e.
bool SupportsStop {get;}
void Stop();
(examples of this, for example, in IBindingList).
I'm not pretending that it is "pure" or anything, but it works - but it means you now have two methods to implement per feature, not one. Separate interfaces (IStoppableReader, for example) may be preferable.
For info, if the implementation is common between all implementations, then you can use extension methods; for a trivial example:
public static void AddRange<T>(this IList<T> list, IEnumerable<T> items) {
foreach(T item in items) list.Add(item);
}
(or the equivalent for your interface). If you provide a more specialized version against the concrete type, then it will take precedence (but only if the caller knows about the variable as the concrete type, not the interface). So with the above, anyone knowingly using a List<T> still uses List<T>'s version of AddRange; but if the have a List<T> but only know about it as IList<T>, it'll use the extension method.
If the method is inappropriate for your implementation, throw InvalidOperationException just like most iterators do when you call Reset on them. An alternative is NotSupportedException which tends to be used by System.IO. The latter is more logical (as it has nothing to do with the current state of the object, just its concrete type) but the former is more commonly used in my experience.
However, it's best to only put things into an interface when you actually need them - if you're still in a position where you can remove Stop, I would do so if I were you.
There's no unified support for optional interface members in the language or the CLR.
If no classes in your code actually implement Stop(), and you don't have definite plans to do so in the future, then you don't need it in your interface. Otherwise, if some but not all of your objects are "stoppable", then the correct approach is indeed to make it a separate interface such as IStoppable, and the clients should then query for it as needed.
If your implementation does not implement the interface method Stop, then it breaks obviousily the contract that comes with your interface. Either you implement the Stop method appropriately (not by throwing an Exception and not by leaving it empty) or you need to redesign your interface (so to change the contract).
Best Regards
C# version 4 (or vNext) is considering default implementation for interfaces - I heard that on channel9 a few months ago ;).
Interfaces with default implementation would behave somewhat like abstract base classes. Now that you can inherit multiple interfaces this could mean that C# might get multiple inheritance in form of interfaces with default implementations.
Until then you might get away with extension methods...
Or your type could make use of the delegates.
interface IOptionalStop
{
Action Stop { get; }
}
public class WithStop : IOptionalStop
{
#region IOptionalStop Members
public Action Stop
{
get;
private set;
}
#endregion
public WithStop()
{
this.Stop =
delegate
{
// we are going to stop, honest!
};
}
}
public class WithoutStop : IOptionalStop
{
#region IOptionalStop Members
public Action Stop
{
get;
private set;
}
#endregion
}
public class Program
{
public static string Text { get; set; }
public static void Main(string[] args)
{
var a = new WithStop();
a.Stop();
var o = new WithoutStop();
// Stop is null and we cannot actually call it
a.Stop();
}
}
Related
New to OOP here. I have defined an interface with one method, and in my derived class I defined another public method. My client code is conditionally instantiating a class of the interface type, and of course the compiler doesn't know about the method in one of the derived classes as it is not part of the underlying interface definition. Here is what I am talking about:
public interface IFileLoader
{
public bool Load();
}
public class FileLoaderA : IFileLoader
{
public bool Load();
//implementation
public void SetStatus(FileLoadStatus status)
{
//implementation
}
}
public class FileLoaderB : IFileLoader
{
public bool Load();
//implementation
//note B does not have a SetStatus method
}
public enum FileLoadStatus
{
Started,
Done,
Error
}
// client code
IFileLoader loader;
if (Config.UseMethodA)
{
loader = new FileLoaderA();
}
else
{
loader = new FileLoaderB();
}
//does not know about this method
loader.SetStatus (FileStatus.Done);
I guess I have two questions:
What should I be doing to find out if the object created at run-time has the method I am trying to use? Or is my approach wrong?
I know people talk of IOC/DI all the time. Being new OOP, what is the advantage of using an IOC in order to say, "when my app asks
for an IFileLoader type, use concrete class x", as opposed to simply
using an App.Config file to get the setting?
Referring to your two questions and your other post I'd recommend the following:
What should I be doing to find out if the object created at run-time has the method I am trying to use? Or is my approach wrong?
You don't necessarily need to find out the concrete implementation at runtime in your client code. Following this approach you kinda foil the crucial purpose of an interface. Hence it's rather useful to just naïvely use the interface and let the concrete logic behind decide what's to do.
So in your case, if one implementation's just able to load a file - fine. If your other implementation is able to the same and a bit more, that's fine, too. But the client code (in your case your console application) shouldn't care about it and just use Load().
Maybe some code says more than thousand words:
public class ThirdPartyLoader : IFileLoader
{
public bool Load(string fileName)
{
// simply acts as a wrapper around your 3rd party tool
}
}
public class SmartLoader : IFileLoader
{
private readonly ICanSetStatus _statusSetter;
public SmartLoader(ICanSetStatus statusSetter)
{
_statusSetter = statusSetter;
}
public bool Load(string fileName)
{
_statusSetter.SetStatus(FileStatus.Started);
// do whatever's necessary to load the file ;)
_statusSetter.SetStatus(FileStatus.Done);
}
}
Note that the SmartLoader does a bit more. But as a matter of separation of concerns its purpose is the loading part. The setting of a status is another class' task:
public interface ICanSetStatus
{
void SetStatus(FileStatus fileStatus);
// maybe add a second parameter with information about the file, so that an
// implementation of this interface knows everything that's needed
}
public class StatusSetter : ICanSetStatus
{
public void SetStatus(FileStatus fileStatus)
{
// do whatever's necessary...
}
}
Finally your client code could look something like the follwing:
static void Main(string[] args)
{
bool useThirdPartyLoader = GetInfoFromConfig();
IFileLoader loader = FileLoaderFactory.Create(useThirdPartyLoader);
var files = GetFilesFromSomewhere();
ProcessFiles(loader, files);
}
public static class FileLoaderFactory
{
public static IFileLoader Create(bool useThirdPartyLoader)
{
if (useThirdPartyLoader)
{
return new ThirdPartyLoader();
}
return new SmartLoader(new StatusSetter());
}
}
Note that this is just one possible way to do what you're looking for without having the necessity to determine IFileLoader's concrete implementation at runtime. There maybe other more elegant ways, which furthermore leads me to your next question.
I know people talk of IOC/DI all the time. Being new OOP, what is the advantage of using an IOC [...], as opposed to simply using an App.Config file to get the setting?
First of all separating of classes' responsibility is always a good idea especially if you want to painlessly unittest your classes. Interfaces are your friends in these moments as you can easily substitute or "mock" instances by e.g. utilizing NSubstitute. Moreover, small classes are generally more easily maintainable.
The attempt above already relies on some sort of inversion of control. The main-method knows barely anything about how to instantiate a Loader (although the factory could do the config lookup as well. Then main wouldn't know anything, it would just use the instance).
Broadly speaking: Instead of writing the boilerplate factory instantiation code, you could use a DI-Framework like Ninject or maybe Castle Windsor which enables you to put the binding logic into configuration files which might best fit your needs.
To make a long story short: You could simply use a boolean appSetting in your app.config that tells your code which implementation to use. But you could use a DI-Framework instead and make use of its features to easily instantiate other classes as well. It may be a bit oversized for this case, but it's definitely worth a look!
Use something like:
if((loader as FileLoaderA) != null)
{
((FileLoaderA)loader).SetStatus(FileStatus.Done);
}
else
{
// Do something with it as FileLoaderB type
}
IoC is normally used in situations where your class depends on another class that needs to be setup first, the IoC container can instantiate/setup an instance of that class for your class to use and inject it into your class usually via the constructor. It then hands you an instance of your class that is setup and ready to go.
EDIT:
I was just trying to keep the code concise and easy to follow. I agree that this is not the most efficient form for this code (it actually performs the cast twice).
For the purpose of determining if a particular cast is valid Microsoft suggests using the following form:
var loaderA = loader as FileLoaderA;
if(loaderA != null)
{
loaderA.SetStatus(FileStatus.Done);
// Do any remaining FileLoaderA stuff
return;
}
var loaderB = loader as FileLoaderB
if(loaderB != null)
{
// Do FileLoaderB stuff
return;
}
I do not agree with using is in the if. The is keyword was designed to determine if an object was instantiated from a class that implements a particular interface, rather than if a cast is viable. I have found it does not always return the expected result (especially if a class implements multiple interfaces through direct implementation or inheritance of a base class).
I have an interface -though it could also be an abstract class- that should allow its implementers to specify whether they support a particular feature and I'm looking for the best way to achieve that.
There are several choices here:
Looking at BCL, I see that the Stream class has properties like CanRead and CanSeek, which can be used to check if a feature is supported and throws a NotSupportedException, if I do something that is not supported.
public interface IHandler
{
bool SupportsA { get; }
bool SupportsB { get; }
void A();
void B();
}
This would be an appropriate approach for me, though I have more than a few features that may or may not be supported and I prefer not to define a "SupportsX" property for each one.
I'm also very fond of bitwise Enum values and I think that another way would be:
[Flags]
public enum HandlerFeature
{
None = 0
A = 1,
B = 2,
C = 4
}
public interface IHandler
{
HandlerFeature Features { get; }
void A();
void B();
void C();
}
And an extension method like this could be written:
bool Supports<T>(this T handler, HandlerFeature feature) where T : IHandler
Which I think would also be much prettier than the other approach but, I couldn't help but think that if every Enum value would correspond a member in the contract, I should be able to mark those members more explicitly. Then I thought about attributes:
public interface IHandler
{
[HandlerRequires(Feature.None)]
HandlerFeature Features { get; }
[HandlerRequires(Feature.A)]
void A();
[HandlerRequires(Feature.B)]
void B();
[HandlerRequires(Feature.A | Feature.B)]
void AB();
[HandlerRequires(Feature.C)]
void C();
}
Although I don't know how to leverage an attribute like this in runtime, it definitely makes the interface definition looks explicit enough.
Is there a best-practice for this?
Or another approach you recommend?
Or anything wrong with the ones I specified?
If you have to build an interface that must use all this stuff, I recommend that you do it with Booleans because the developer has to specify a value for that property when he or she is implementing that interface. Using a flagged enum or attributes can result in classes where e.g. method A is not implemented but the developer simply forgot to set the Attribute or enum correctly. In this case, the compiler would not emit an error.
Anyway, I would advise you to not construct such a "fat" interface. I would encourage you to read about the "Interface Segregation Principle" which is part of the SOLID principles of object-oriented design (Google it, you'll find several articles). It states that clients should not be forced to depend on methods they do not use. The consequence of this is that you use multiple small interfaces instead of one that clasps several aspects. Now I don't know the context your working in but if your interface integrates several cross-cutting concerns like e.g. logging besides its basic business capabilities, I would strongly recommend to throw out logging of the interface and use the Decorator pattern instead (also, Google this if you don't know it :-) ).
Hope this helps.
Sorry if the question sounds confusing. What I mean is that if I have a class that has a method that does a bunch of calculations and then returns a value, I can either make that method public (which gives my other classes access), or I can make it private and make a public get method.
Something like this:
public publicmethod{
return privatemethod();
}
private privatemethod{
//do stuff
return value;
}
Is this a futile exercise or does it provide additional program security?
Well, there is no additional security here. However, such a usage can sometimes make sense.
For example, the private and public method may have different semantics.
// base class
public virtual BuyFood()
{
BuyPizza();
BuyCoke();
}
private void BuyPizza()
{
// ...
}
// derived class
public override void BuyFood()
{
BuyChopSuey();
}
private void BuyChopSuey()
{
// ...
}
So your implementation is just calling to a private method -- but what is important, you expose the semantics: your BuyFood operation is just BuyChopSuey(). Your code says: "in this class, buying food is just buying chop suey" in a clear way. You are able to add BuyTsingtaoBeer() into BuyFood() any time without changing the semantics of the both methods.
It is completely redundant. It does not provide anything except another name for the same thing and another indirection for readers to follow. Simply make a single implementation, and make it public. On the same note, getX() { return x; } setX(T newX) { x = newX; } does not encapsulate anything, at best it's future-proofing.
You may end up implementing a particular function required by an interface in a single line, largely delegating to (possibly private) methods which exist for other good reasons. This is different, and more justified (but again, if it's only return someMethod(); you should probably abolish the private implementation and assume the common name). A particular case if when you need two implement two methods which do the same thing (e.g. from separate interfaces).
I think either way is fine, it's more a matter of style assuming the method doesn't change the state of the class. If you have a class that has a bunch of properties and very few methods, it probably makes more sense to define another property. If you have a lot of methods in the class but few properties, then a method is more consistent with your overall class design.
If the method changes a bunch of other class variables than I'd expose it as a public method instead of a property.
I don't think either way, property or method, is necessarily more secure. It depends on what checks you do - is the caller allowed to perform the calculation? Are all variables used in the calculations within acceptable ranges? Etc. All of these checks can be performed whether you are using a property or a method.
Well, actually the question is What code do I want to be able to call this method?
Any code in general, even from other assemblies? Make the method public.
Any code from the same assembly? Make it internal.
Only code from this class? Make it private.
Having a private method directly aliased to a public method only makes the private method callable from the outside, which contradicts its private status.
If the method only does some calculation and doesn't use or change anything in the object, make it a public static method:
public static CalculationMethod(int input) {
//do stuff
return value;
}
That way any code can use the method without having the create an instance of the class:
int result = ClassName.CalculationMethod(42);
Instead of public consider internal, which would give access only to code in the same assembly.
Working with C# Generics you can have a class like this:
class Foo<T> where T:new() {}
Which means that the type T should have a constructor without parameters. It would be nice if we could have:
class Foo<T> where T : new(string)
{
private T CreateItem()
{
string s="";
return new T(s);
}
}
Is there any reason that Microsoft haven't added this feature to the language?
Is there any reason that Microsoft haven't added this feature to the language?
The feature you describe is a specific case of the of the more general feature "allow a constraint that requires a particular method to exist". For example, you might say:
void M<T>(T t) where T has an accessible method with signature double Foo(int)
{
double x = t.Foo(123);
}
We don't have that feature in C# because features have to be justified by a cost-benefit analysis. That would be a pretty expensive feature from both a design and implementation point of view -- a feature that would drive requirements onto not just C# but every .NET language. What's the compelling benefit that justifies the feature?
Moreover: suppose we did design that feature. How would it be implemented efficiently? The constraints in the generic type system have been carefully designed so that the jitter can generate efficient code once that can then be shared for every reference type. How would we generate efficient code for arbitrary method pattern matching? That sort of efficient dispatch is pretty straightforward when the method's slot can be known at compile time; with this feature we would no longer have that advantage.
The feature you want is the same feature, just with the kind of method restricted to a constructor.
Remember, the purpose of generics is to let you write generically typed code. If you're requiring constraints that are more specific than things that can be captured in the type system then you might be trying to abuse generics.
Rather than try to guess why Microsoft decided on a particular implementation, here's a workaround for you, using the factory pattern
public interface IFactory<T>
{
T CreateItem(string s);
}
class Foo<TFactory,T> where TFactory : IFactory<T>, new()
{
private T CreateItem()
{
var factory = new TFactory();
string s="";
return factory.CreateItem(s);
}
}
Using this pattern, say you have a class Bar which has a constructor taking a single string:
public class Bar
{
public Bar(string laa)
{}
}
You just need a BarFactory which implements IFactory<Bar>
public class BarFactory : IFactory<Bar>
{
public BarFactory () {}
public Bar CreateItem(string s)
{
return new Bar(s);
}
}
Now you can use that factory with Foo
var foo = new Foo<BarFactory,Bar>(); // calls to CreateItem() will construct a Bar
The solution I adopted when I wanted a generic function that invoked a constructor with arguments was to use reflection to find and invoke it.
Given that I had control of both the generic, and all the classes it was implemented over (and this function was the only place those classes were constructed), I think I might have been better to give the classes a default constructor and added an Initialize method in the interface they all implemented.
(A solution that allowed adding static methods in general to an interface would be ideal.)
Let's assume that our system can perform actions, and that an action requires some parameters to do its work.
I have defined the following base class for all actions (simplified for your reading pleasure):
public abstract class BaseBusinessAction<TActionParameters>
: where TActionParameters : IActionParameters
{
protected BaseBusinessAction(TActionParameters actionParameters)
{
if (actionParameters == null)
throw new ArgumentNullException("actionParameters");
this.Parameters = actionParameters;
if (!ParametersAreValid())
throw new ArgumentException("Valid parameters must be supplied", "actionParameters");
}
protected TActionParameters Parameters { get; private set; }
protected abstract bool ParametersAreValid();
public void CommonMethod() { ... }
}
Only a concrete implementation of BaseBusinessAction knows how to validate that the parameters passed to it are valid, and therefore the
ParametersAreValid is an abstract function. However, I want the base class constructor to enforce that the parameters passed are always valid, so I've added a
call to ParametersAreValid to the constructor and I throw an exception when the function returns false. So far so good, right? Well, no.
Code analysis is telling me to "not call overridable methods in constructors" which actually makes a lot of sense because when the base class's constructor is called
the child class's constructor has not yet been called, and therefore the ParametersAreValid method may not have access to some critical member variable that the
child class's constructor would set.
So the question is this: How do I improve this design?
Do I add a Func<bool, TActionParameters> parameter to the base class constructor? If I did:
public class MyAction<MyParameters>
{
public MyAction(MyParameters actionParameters, bool something) : base(actionParameters, ValidateIt)
{
this.something = something;
}
private bool something;
public static bool ValidateIt()
{
return something;
}
}
This would work because ValidateIt is static, but I don't know... Is there a better way?
Comments are very welcome.
This is a common design challenge in an inheritance hierarchy - how to perform class-dependent behavior in the constructor. The reason code analysis tools flag this as a problem is that the constructor of the derived class has not yet had an opportunity to run at this point, and the call to the virtual method may depend on state that has not been initialized.
So you have a few choices here:
Ignore the problem. If you believe that implementers should be able to write a parameter validation method without relying on any runtime state of the class, then document that assumption and stick with your design.
Move validation logic into each derived class constructor, have the base class perform just the most basic, abstract kinds of validations it must (null checks, etc).
Duplicate the logic in each derived class. This kind of code duplication seems unsettling, and it opens the door for derived classes to forget to perform the necessary setup or validation logic.
Provide an Initialize() method of some kind that has to be called by the consumer (or factory for your type) that will ensure that this validation is performed after the type is fully constructed. This may not be desirable, since it requires that anyone who instantiates your class must remember to call the initialization method - which you would think a constructor could perform. Often, a Factory can help avoid this problem - it would be the only one allowed to instantiate your class, and would call the initialization logic before returning the type to the consumer.
If validation does not depend on state, then factor the validator into a separate type, which you could even make part of the generic class signature. You could then instantiate the validator in the constructor, pass the parameters to it. Each derived class could define a nested class with a default constructor, and place all parameter validation logic there. A code example of this pattern is provided below.
When possible, have each constructor perform the validation. But this isn't always desirable. In that case, I personally, prefer the factory pattern because it keeps the implementation straight forward, and it also provides an interception point where other behavior can be added later (logging, caching, etc). However, sometimes factories don't make sense, and in that case I would seriously consider the fourth option of creating a stand-along validator type.
Here's the code example:
public interface IParamValidator<TParams>
where TParams : IActionParameters
{
bool ValidateParameters( TParams parameters );
}
public abstract class BaseBusinessAction<TActionParameters,TParamValidator>
where TActionParameters : IActionParameters
where TParamValidator : IParamValidator<TActionParameters>, new()
{
protected BaseBusinessAction(TActionParameters actionParameters)
{
if (actionParameters == null)
throw new ArgumentNullException("actionParameters");
// delegate detailed validation to the supplied IParamValidator
var paramValidator = new TParamValidator();
// you may want to implement the throw inside the Validator
// so additional detail can be added...
if( !paramValidator.ValidateParameters( actionParameters ) )
throw new ArgumentException("Valid parameters must be supplied", "actionParameters");
this.Parameters = actionParameters;
}
}
public class MyAction : BaseBusinessAction<MyActionParams,MyActionValidator>
{
// nested validator class
private class MyActionValidator : IParamValidator<MyActionParams>
{
public MyActionValidator() {} // default constructor
// implement appropriate validation logic
public bool ValidateParameters( MyActionParams params ) { return true; /*...*/ }
}
}
If you are deferring to the child class to validate the parameters anyway, why not simply do this in the child class constructor? I understand the principle you are striving for, namely, to enforce that any class that derives from your base class validates its parameters. But even then, users of your base class could simply implement a version of ParametersAreValid() that simply returns true, in which case, the class has abided by the letter of the contract, but not the spirit.
For me, I usually put this kind of validation at the beginning of whatever method is being called. For example,
public MyAction(MyParameters actionParameters, bool something)
: base(actionParameters)
{
#region Pre-Conditions
if (actionParameters == null) throw new ArgumentNullException();
// Perform additional validation here...
#endregion Pre-Conditions
this.something = something;
}
I hope this helps.
I would recommend applying the Single Responsibility Principle to the problem. It seems that the Action class should be responsible for one thing; executing the action. Given that, the validation should be moved to a separate object which is responsible only for validation. You could possibly use some generic interface such as this to define the validator:
IParameterValidator<TActionParameters>
{
Validate(TActionParameters parameters);
}
You can then add this to your base constructor, and call the validate method there:
protected BaseBusinessAction(IParameterValidator<TActionParameters> validator, TActionParameters actionParameters)
{
if (actionParameters == null)
throw new ArgumentNullException("actionParameters");
this.Parameters = actionParameters;
if (!validator.Validate(actionParameters))
throw new ArgumentException("Valid parameters must be supplied", "actionParameters");
}
There is a nice hidden benefit to this approach, which is it allows you to more easily re-use validation rules that are common across actions. If your using an IoC container, then you can also easily add binding conventions to automatically bind IParameterValidator implementations appropriately based on the type of TActionParameters
I had a very similar issue in the past and I ended up moving the logic to validate parameters to the appropriate ActionParameters class. This approach would work out of the box if your parameter classes are lined up with BusinessAction classes.
If this is not the case, it gets more painful. You have the following options (I would prefer the first one personally):
Wrap all the parameters in IValidatableParameters. The implementations will be lined up with business actions and will provide validation
Just suppress this warning
Move this check to parent classes, but then you end up with code duplication
Move this check to the method that actually uses the parameters (but then your code fails later)
Why not do something like this:
public abstract class BaseBusinessAction<TActionParameters>
: where TActionParameters : IActionParameters
{
protected abstract TActionParameters Parameters { get; }
protected abstract bool ParametersAreValid();
public void CommonMethod() { ... }
}
Now the concrete class has to worry about the parameters and ensuring their validity. I would just enforce the CommonMethod calling the ParametersAreValid method prior to doing anything else.
How about moving the validation to a more common location in the logic. Instead of running the validation in the constructor, run it on the first (and only the first) call to the method. That way, other developers could construct the object, then change or fix the parameters before executing the action.
You could do this by altering your getter/setter for the Parameters property, so anything that uses the paramters would validate them on the first use.
Where are the parameters anticipated to be used: from within CommonMethod? It is not clear why the parameters must be valid at the time of instantiation instead of at the time of use and thus you might choose to leave it up to the derived class to validate the parameters before use.
EDIT - Given what I know the problem seems to be one of special work needed on construction of the class. That, to me, speaks of a Factory class used to build instances of BaseBusinessAction wherein it would call the virtual Validate() on the instance it builds when it builds it.