xdtTransform
xdtTransform

Reputation: 2057

Force the usage of a Method, by the interface

Given an interface, that should be Init to Run. Initialisation code must be run.
Initialisation is two part: one that depend of the configuration, one that do not.

The configurable one must be calling the other one if he does not want to duplicate that code.

public interface IProcess
{
    bool Init(out string error);
    bool Init(ProcessConfiguration processConf, out string error);
    bool Run(object message, out ErrorCode errorCode);
    // ...
}

And it's correct implementation :

public class ProcessGood : IProcess
{
       public bool Init(out string error){
              // Important Code   
              return true;
       }
       
       public bool Init(ProcessConfiguration processConf, out string error){              
              Init(out erreur);    
              // things about processConf    
              return true;
       }

My issue is due to the existence of 2 init method, the need for one to call the other as default behavior is not well followed.
Is there a way using Interface/ Virtual / etc to force one Init to call the other?

Example of one incorrect implementation:

public class ProcessBad : IProcess
{
       public bool Init(out string error){
              // Important Code   
              return true;
       }
       
       public bool Init(ProcessConfiguration processConf, out string error){              
              // Init(out erreur);    // some one forgot to type this. 
              // things about processConf    
              return true;
       }

Upvotes: 0

Views: 219

Answers (2)

Fildor
Fildor

Reputation: 16168

If it is feasable to use abstract classes, then I could imagine a solution like this:

public interface IProcess
{
    bool Init(ProcessConfiguration processConf);
    // ...
}

abstract class ProcessBase : IProcess
{

    public bool IProcess.Init(ProcessConfiguration processConf)
    {
     if ( !InitInternal() ) return false;
     return InitInternal(ProcessConfiguration processConf);
    }
    
    protected abstract bool InitInternal();
    protected abstract bool InitInternal(ProcessConfiguration processConf);

}

Here, you force a specific implementation of the init process (in that both sub processes must be called) while leaving the concrete implementation of each part to the child.

Upvotes: 3

Roman Ryzhiy
Roman Ryzhiy

Reputation: 1656

Are you sure your code is C#? As in C# it should look something like this:

public class ProcessBad : IProcess
{
    public ProcessBad(string error) 
    {
        // Important Code   
    }

    public ProcessBad(ProcessConfiguration processConf, string error) : this(error) // will be called ANYWAY
    {
        // things about processConf    
    }
}

Upvotes: 0

Related Questions