Is it a bad idea to add a new method (that implements a new algorithm) to a clas
ID: 644349 • Letter: I
Question
Is it a bad idea to add a new method (that implements a new algorithm) to a class library for its new version and expose a version option the consumers can select?
It is just for backward compatibility where an old application might need a constant sequence of random numbers for a certain seed number.
The following code might speak my idea much better. Hopefully you get the essence.
//Class Library:
namespace MyGenerator
{
public sealed class MyRandom
{
public enum Version { One, Two }// add more options in the future
private int current;
private Version version;
public MyRandom(int seed, Version version = Version.One)
{
current = seed;
this.version = version;
}
public int Next()
{
switch (version)
{
case Version.One:
AlgorithmOne();
break;
case Version.Two:
AlgorithmTwo();
break;
// add more options in the future
}
return current;
}
private int AlgorithmOne()
{
current = (current * 1234567890 + 987654321) & 0x7FFFFFFF;
return current;
}
private int AlgorithmTwo()
{
current = (current * current + current) & 0x7FFFFFFF;
return current;
}
// add more algorithm in the future
}
}
and
//Console Application (for testing purposes):
using MyGenerator;
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
const int seed = 12345;
MyRandom rnd = new MyRandom(seed, MyRandom.Version.Two);
Console.WriteLine(rnd.Next());
Console.ReadLine();
}
}
}
Explanation / Answer
No, never do this. If you want to design for future versionability then use the object-oriented patterns specifically designed for that. For example, here's how I would solve your problem:
abstract class MyRandom
{
// Ensure that a third party cannot extend the base
// class by making the ctor private.
private MyRandom() {}
public abstract int Next();
private class First : MyRandom
{
// whatever
}
private class Second : MyRandom
{
// whatever
}
// Chef's choice:
public static MyRandom MakeRandom() { return new Second(); }
// Diner's choice:
public static MyRandom MakeFirst() { return new First(); }
public static MyRandom MakeSecond() { return new Second(); }
}
When you want to add a new version, that's a private implementation detail of the class, and you then add a new static factory method. If the caller wants you to choose the best version, they call the method that lets you decide. If they have a specific version they want, they call a method that gives them that.
Some more guidance:
If you believe you will be adding more members to an enum in the future then you are probably doing something wrong. The set of items in an enum should be identical forever.
If you are taking a non-flags enum with n options and doing n different things as a result then just write n methods.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.