lundi 23 septembre 2019

Should literals be replaced by generic interfaces

I'm writing code which is using the strategy pattern however I am unsure if I am going overboard with the amount of abstraction I'm using. I am randomly generating numbers for my application using various probability distributions such as normal distributions or uniform distributions or generating numbers constantly (not randomly at all)

The different algorithms have different literal return types, some return Ints whereas others return Floats and Doubles.

Following the interface segregation principle I created ITYPEValuePicker interfaces which each have the following definition:

public interface ITYPEValuePicker
{
    public TYPE getTYPE();
}

where "TYPE" is a specific data type such as float, int, etc.

Now my random algorithms implement these interfaces and can be used in the code

GaussianValuePicker implements IFloatValuePicker, IDoubleValuePicker

and

UniformValuePicker implements IFloatValuePicker, IDoubleValuePicker, IIntValuePicker

and

ConstantValuePicker implements IIntValuePicker, IFloatValuePicker, IDoubleValuePicker

A significant portion of my code is dependent on randomly selected values and randomly selected algorithms to select those values. My question is: is there a reason why I should not be replacing all magic numbers with these generic "IValuePicker"s and having the actual getting of any value be delegated to the the specific algorithm.

For example:

public class chicken
{
    float height;
    int age;

    public chicken(float height, int age)
    {
        this.height = height;
        this.age = age;
    }

    public boolean isSuperOld()
    {
        if (age > 99) 
        {
            return true;
        }
        return false;
    }
}

vs

public class chicken
{
    IFloatValuePicker height;
    IIntValuePicker age;

    public chicken(IFloatValuePicker height, IIntValuePicker age)
    {
        this.height = height;
        this.age = age;
    }

    public boolean isSuperOld()
    {
        if (age.getInt() > 99) 
        {
            return true;
        }
        return false;
    }
}

sorry for the contrived example, but I hope that it illustrates the delayed, almost (lazy [I'm not sure this is the correct term]?) evaluation of the different values. Is this an example of YAGNI (I understand that whether it's YAGNI or not is pretty context heavy) or is this a valid use of interfaces?

Aucun commentaire:

Enregistrer un commentaire