Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I improve this design?
    primarykey
    data
    text
    <p>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):</p> <pre><code>public abstract class BaseBusinessAction&lt;TActionParameters&gt; : 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() { ... } } </code></pre> <p>Only a concrete implementation of <code>BaseBusinessAction</code> knows how to validate that the parameters passed to it are valid, and therefore the <code>ParametersAreValid</code> 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 <code>ParametersAreValid</code> to the constructor and I throw an exception when the function returns <code>false</code>. So far so good, right? Well, no. Code analysis is telling me to "<a href="http://msdn.microsoft.com/en-us/library/ms182331(VS.100).aspx" rel="nofollow noreferrer">not call overridable methods in constructors</a>" 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 <code>ParametersAreValid</code> method may not have access to some critical member variable that the child class's constructor would set.</p> <p>So the question is this: How do I improve this design? </p> <p>Do I add a <code>Func&lt;bool, TActionParameters&gt;</code> parameter to the base class constructor? If I did:</p> <pre><code>public class MyAction&lt;MyParameters&gt; { public MyAction(MyParameters actionParameters, bool something) : base(actionParameters, ValidateIt) { this.something = something; } private bool something; public static bool ValidateIt() { return something; } } </code></pre> <p>This would work because <code>ValidateIt</code> is static, but I don't know... Is there a better way?</p> <p>Comments are very welcome.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload