vendredi 22 mars 2019

Issues with inheritance, do I need extra abstract class [on hold]

Suppose, I have the base abstract class Function that looks like this:

public abstract class Function
{         
   public abstract string Invoke(string[] args);
}

And also I have a child sub-class DeterministicFunction that looks like this:

public abstract class DeterministicFunction : Function
{
    private readonly Dictionary<string[], string> _cache;

    public sealed override string Invoke(string[] args) 
    {
         if (args?.Length > 0) 
         {
             string fnResult;
             if (_cache.TryGetValue(args, out fnResult))
                 return fnResult;

             fnResult = GetResult(args);
             _cache[args] = fnResult;
             return fnResult;
         }

         return GetResult(args);
    }

    protected abstract string GetResult(string[] args);
}

All functions can be either deterministic or non-deterministic. Deterministic function always returns same result for same combination of arguments, so I decided to optimize it by putting result to cache so if expensive function is invoked with already invoked arguments it could cache result and retrieve it faster. I also have a bunch of non-deterministic functions related to date & time. They are non-deterministic cause they return different result with every invocation. My base class for date & time functions:

public abstract class DateTimeFunction : Function 
{
     private CultureInfo _culture;

     protected DateTimeFunction(CultureInfo culture) 
     {
         _culture = culture;
     }

     protected CultureInfo Culture => _culture;
}

public class UtcNowFunction : DateTimeFunction 
{
     // skip constructor code, too long to type  

     public override string Invoke(string[] args) 
     {
         DateTime now = DateTime.NowUtc;
         string result = now.ToString(Culture);

         if (args?.Length > 0) 
         {
            string format = args[0];
            result = now.ToString(format, Culture);    
         }  

         return result;
     }
}

My question is - do I need to create a base class for all non-deterministic functions? For now, I don't see reasons to add a new abstract level, but it would be logical to separate them into two major groups. If I create a new abstract class NonDeterministicFunction - it's going to be empty. What should I do??

Aucun commentaire:

Enregistrer un commentaire