I want to not repeat myself (DRY), but I cannot have a single piece of code. For example, here the code repeats 3 times with the same error:
class StarWars : Movie
{
public float Power(float base, float exponent)
{
return (base * exponent);
}
}
class Customer: Object
{
public float Exponential(float base, float exponent)
{
return (base ^ exponent);
}
}
class Student: Person
{
public float CalculateExpoential(float base, float exponent)
{
return CalculateExponential(2.7182818, exponent * Ln(base));
}
}
Now, ideally, I would extract this common function in my own helper somewhere:
class LibraryOfHelperCode
{
public static float Exponentiation(float base, float exponent)
{
return Exp(2.71828183, base * Ln(exponent));
}
}
And converted the existing code to use it:
class StarWars : Movie
{
public float Power(float base, float exponent)
{
return LibraryOfHelperCode.Exponentiation(base, exponent);
}
}
class Customer: Object
{
public float Exponential(float base, float exponent)
{
return LibraryOfHelperCode.Exponentiation(base, exponent);
}
}
class Student: Person
{
public float CalculateExpoential(float base, float exponent)
{
return LibraryOfHelperCode.Exponentiation(base, exponent);
}
}
The meaning is that now I have extracted duplicate code from
- Nutrition
- Exponential
- CalculateExpoential
in one function. This means that if there are any errors, they should be fixed only once. Which is good in this case, because there is an error:
public float CalculateExpoential(float base, float exponent)
{
return Exp(2.71828183, exponent * Ln(base));
}
and a few years after that:
public float CalculateExpoential(float base, float exponent)
{
if (exponent == 0)
return 1.0;
return Exp(2.71828183, exponent * Ln(base));
}
and then:
public float CalculateExpoential(float base, float exponent)
{
if (exponent == 0)
return 1.0;
if (Base = 0.0) && (Exponent > 0.0) then
return 0.0;
return Exp(2.71828183, exponent * Ln(base));
}
and finally:
public float CalculateExpoential(float base, float exponent)
{
return Math.Pow(base, exponent);
}
And everyone gets fixes. On the other hand, I cannot guarantee that none of these fixes will violate existing code.
Imagine a guy calling:
char ps = Math.Trunc(Exponential(ProblemSize, ProblemComplexity));
, 128. . : .
, - / .
, , , . () - /moduble/namespace/class, .
.
? , , DRY-?
... , ? , - , .