Exposing only important logic to the user from a method - c#

RsiStrategy is a class that should be modified by the user, so it suits his desires. Having that loop and for ex. if (i < StartupCandleCount - 1) exposed to the user, is not so great, because the user doesn't care about it. What the user cares about, is the indicators population and buy/sell conditions. Could you guys suggest to me a way to deal with that?
public interface IStrategy
{
IReadOnlyList<TradeAdvice> Prepare(IReadOnlyList<Ohlcv> candles);
}
public abstract class StrategyBase : IStrategy
{
public abstract IReadOnlyList<TradeAdvice> Prepare(IReadOnlyList<Ohlcv> candles);
}
public class RsiStrategy : StrategyBase
{
public override IReadOnlyList<TradeAdvice> Prepare(IReadOnlyList<Ohlcv> candles)
{
var result = new List<TradeAdvice>();
var rsiPeriod = 4;
var rsi = candles.Rsi(rsiPeriod);
for (int i = 0; i < candles.Count; i++)
{
if (i < StartupCandleCount - 1)
result.Add(TradeAdvice.WarmupData);
else if (rsi[i] < 45 && rsi[i] > rsi[i - 1])
result.Add(TradeAdvice.Buy);
else if (rsi[i] > 70)
result.Add(TradeAdvice.Sell);
else
result.Add(TradeAdvice.NoAction);
}
return result;
}
}
Expected
I expect something like the following and the logic about if (i < StartupCandleCount - 1) and that loop should probably be moved to the abstract class.
private void PopulateIndicators()
{
var rsi = candles.Rsi(14);
var ema = candles.Ema(6);
// these have to be returned somehow
}
// TODO: I could of course pass current and previous item to the method,
// but I want to be access anything, e.g. rsi[i - 42]. That's basically shifting right
public void BuyCondition()
{
return rsi[i] < 45 && rsi[i] > rsi[i - 1])
}
public void SellCondition()
{
return rsi[i] > 70;
}

One possible solution would be to have all strategies implement an abstract method from StrategyBase, public abstract TradeAdvice Advise(IReadOnlyList<Ohlcv> candles, int index);
StrategyBase would generate the warmup data trade advices, and run the loop for the rest and call Advise for each item. Every strategy would implement just this Advise method, and Prepare should be implemented by StrategyBase only.
With index parameter the strategy knows for which item it is giving the advice.
If there is some preparation required before the loop runs there should be a protected abstract void StrategyBase.Prepare method. But then the method of the interface should be renamed to something like Run or Execute. So:
public interface IStrategy
{
IReadOnlyList<TradeAdvice> Execute(IReadOnlyList<Ohlcv> candles);
}
public abstract class StrategyBase : IStrategy
{
protected abstract void Prepare(IReadOnlyList<Ohlcv> candles);
protected abstract TradeAdvice Advise(int index);
public IReadOnlyList<TradeAdvice> Execute(IReadOnlyList<Ohlcv> candles)
{
// Call Prepare once, fill up WarmupData, call Advise once per the rest of the items
}
}
public class RsiStrategy : StrategyBase
{
protected override void Prepare(IReadOnlyList<Ohlcv> candles)
{
// Calculate rsi and save it and all the rest to class fields
}
protected override TradeAdvice Advise(int index)
{
// return advice using index and class fields
}
}

Related

Moq parent method being called in child class

I have a base class with a protected method that's being called in a public method in the child class I want to test. I'm failing to find a way to moq the base protected method for easier testing in child class.
public class MyBaseClass
{
protected virtual bool MyMethod(int number)
{
return number == 1;
}
}
public class MyChildClass : MyBaseClass
{
public bool DoSomething(int number)
{
return MyMethod(number);
}
}
[TestFixture]
public class MyChildClassTests
{
[Test]
public void Expected_Returns_False_WhenPassed_1()
{
var myChildClass = new MyChildClass();
// How do I mock MyMethod used in myBaseClass here?
// var mock = new Mock<MyBaseClass>();
// mock.Protected().Setup<bool>("MyMethod", ItExpr.IsAny<int>()).Returns(false);
// The above mock is correct, but it's in a different instance object than myBaseClass
var result = myChildClass.DoSomething();
Assert.AreEqual(false, result);
}
}
I can't change the classes to have a better architecture and I must do the best I can to implement unit test for DoSomething(), what I did so far is mock and prepare all the data that method uses, but since it's in another class I'd love my MyChildClassTests to not do all that and just limit to test DoSomething().
I've read about partial mocking and a whole lot of other questions and answers and I can't get it to work right.
I appreciate any suggestions!
Edit: Forgot to put public in all the classes, in my real world case, they are public.
class MyChildClassTests
{
[Test]
public void Expected_Returns_False_WhenPassed_1()
{
var myChildClass = new FakeChildClass();
var result = myChildClass.DoSomething(1);
Assert.AreEqual(false, result);
}
}
public class FakeChildClass: MyChildClass
{
protected override bool MyMethod(int number)
{
return number == 1;
}
}
First of all, ensure your classes are public.
Moq will complain about not being able to proxy into them if they're not.
public class MyBaseClass
{
public virtual bool MyMethod(int number)
{
return number == 1;
}
}
public class MyChildClass : MyBaseClass
{
public bool DoSomething(int number)
{
return MyMethod(number);
}
}
Next, make your base class method public. You won't be able to set it up unless you do.
After that, create a mock of the child object and mock the parent method.
var mockChild = new Mock<MyChildClass>(){CallBase = true};
mockChild.Setup(x => x.MyMethod(It.IsAny<int>())).Returns(false);
Pull your result.... result will return false even though the actual implementation would have returned true with 1 as a parameter.
var result = mockChild.Object.DoSomething(1);
When calling the DoSomething method, you'll actually enter the real implementation of that (put a breakpoint on if you don't believe me!) - but the mocked version of MyMethod will kick in.
Thanks all for your replies, gathering all I was able to get the actual answer to my use case:
Without changing MyBaseClass and MyChildClass:
public class MyBaseClass
{
protected virtual bool MyMethod(int number)
{
return number == 1;
}
}
public class MyChildClass : MyBaseClass
{
public bool DoSomething(int number)
{
return MyMethod(number);
}
}
I was able to mock the protected method and save me a LOT of work and duplicate code (that was in MyBaseClassTests already)
[TestFixture]
public class MyChildClassTests
{
[Test]
public void Expected_Returns_False_WhenPassed_1()
{
var expected = false;
var myChildClass = new Mock<MyChildClass> {CallBase = true};
myChildClass.Protected().Setup<bool>("MyMethod", 1).Returns(expected);
var result = myChildClass.Object.DoSomething(1);
Assert.AreEqual(expected, result);
}
[Test]
public void Expected_Returns_True_WhenPassed_1()
{
var expected = true;
var myChildClass = new Mock<MyChildClass> {CallBase = true};
myChildClass.Protected().Setup<bool>("MyMethod", 1).Returns(expected);
var result = myChildClass.Object.DoSomething(1);
Assert.AreEqual(expected, result);
}
}
Thanks everyone for your help! :)

I'm trying to create unit tests for a private method

I'm trying to create unit tests for the GetOutOfJail method but I can't work out a way of getting to it as it private and apart from testing there is no need for it to be public. I can't change the signature of the LandedOnTile method as it inheriting a the abstract class Tile.
As you probably worked out, it is for a game of Monopoly I'm trying to make as a mini project.
public abstract class Tile
{
public abstract int Location { get;}
public abstract void LandedOnTile(Player player);
}
public class JailTile : Tile
{
public override int Location { get; }
Random dice = new Random();
public JailTile()
{
Location = 3;
}
public override void LandedOnTile(Player player)
{
if (player.inJail)
{
GetOutOfJail(player);
}
else
{
Console.WriteLine(player.name + " is just visiting jail");
}
}
private void GetOutOfJail(Player player)
{
int roll = dice.Next(1, 4);
int turnsInJail = player.timeInJail;
if (turnsInJail == 3)
{
player.inJail = false;
Console.WriteLine(player.name + " has spent 3 turns in jail and is now out");
player.timeInJail = 0;
}
else if (turnsInJail < 3 && roll > 2)
{
player.inJail = false;
Console.WriteLine(player.name + " has rolled a 3 and it out of jail");
player.timeInJail = 0;
}
else
{
Console.WriteLine(player.name + " has rolled a lower than a 3 and is in jail for another turn");
player.timeInJail++;
}
}
}
As mentioned by others, it shouldn't matter what the private method does from the perspective of the unit test. All you care about is that if you poke or prod the object in the right way, it ends up in the right state.
Here is how you could achieve that using interfaces and Moq.
Firstly, extract the interface that represents the properties and methods you require to perform the action. I have abstracted out your Console.WriteLine because it makes testing much easier (and even opens other opportunities for that code to be used in a non-console application). We don't actually need a "dice" per se. What we actually need is an object we can ask to Roll() and get an int. Players probably have their own business rules about them, so extracting to an IPlayer interface allows my tests of JailTile to ignore such things.
public interface ILogger
{
void LogMessage(string message);
}
public interface IDice
{
int Roll();
}
public interface IPlayer
{
string Name
{
get;
}
bool InJail
{
get;
set;
}
int TimeInJail
{
get;
set;
}
}
Secondly, here are the concrete implementations of a Dice and a ConsoleLogger. You would pass in these in your production code rather than the mocks that I use in the test cases
public class ConsoleLogger : ILogger
{
public void LogMessage(string message)
{
Console.WriteLine(message);
}
}
public class Dice : IDice
{
private readonly Random random = new Random();
public int Roll()
{
return this.random.Next(1, 6);
}
}
Thirdly, here are your Tile and JailTile classes slightly modified to use constructor injection
public abstract class Tile
{
protected readonly IDice Dice;
protected readonly ILogger Logger;
protected Tile(ILogger logger, IDice dice)
{
this.Logger = logger;
this.Dice = dice;
}
public abstract int Location
{
get;
}
public abstract void LandedOnTile(IPlayer player);
}
public class JailTile : Tile
{
public JailTile(ILogger logger, IDice dice): base (logger, dice)
{
}
public override int Location => 3;
public override void LandedOnTile(IPlayer player)
{
if (player.InJail)
{
this.GetOutOfJail(player);
}
else
{
this.Logger.LogMessage($"{player.Name} is just visiting jail");
}
}
private void GetOutOfJail(IPlayer player)
{
int roll = this.Dice.Roll();
int turnsInJail = player.TimeInJail;
if (turnsInJail == 3)
{
player.InJail = false;
this.Logger.LogMessage($"{player.Name} has spent 3 turns in jail and is now out");
player.TimeInJail = 0;
}
else if (turnsInJail < 3 && roll > 2)
{
player.InJail = false;
this.Logger.LogMessage($"{player.Name} has rolled a 3 and it out of jail");
player.TimeInJail = 0;
}
else
{
this.Logger.LogMessage($"{player.Name} has rolled a lower than a 3 and is in jail for another turn");
player.TimeInJail++;
}
}
}
Finally, here is a test case to prove that your jailTile.LandedOnTile() method causes the right changes to Player and logs the right message to console given a certain set of preconditions
[Test]
public void ShouldReleaseAfterThreeTurns()
{
// Arrange
Mock<ILogger> loggerMock = new Mock<ILogger>();
Mock<IDice> diceMock = new Mock<IDice>();
diceMock.Setup(s => s.Roll()).Returns(2);
Mock<IPlayer> playerMock = new Mock<IPlayer>();
playerMock.Setup(s => s.Name).Returns("Adam G");
playerMock.Setup(s => s.InJail).Returns(true);
playerMock.Setup(s => s.TimeInJail).Returns(3);
// Act
JailTile jailTile = new JailTile(loggerMock.Object, diceMock.Object);
jailTile.LandedOnTile(playerMock.Object);
// Assert
playerMock.VerifySet(v => v.InJail = false, Times.Once());
playerMock.VerifySet(v => v.TimeInJail = 0, Times.Once());
loggerMock.Verify(v => v.LogMessage("Adam G has spent 3 turns in jail and is now out"), Times.Once());
}
Now you probably want to think a bit more about the design, and whether it is really the tile's responsibility to be updating these properties, or whether it should call something on a jail object that can separately be tested, but this shows how you can use mocks to abstract calls to random etc out of your code to make it testable.

C#: Calling parent (Base) constructor from child's constructor body

I have an abstract class Parent and a derived class Child. I know that I can call Parent's constructor inside Child's constructor in the following way:
abstract class Parent
{
protected int i;
protected Parent(int i)
{
this.i = i;
}
}
class Child : Parent
{
public Child(int i) : base(i)
{
}
}
However, I don't want to pass some parameters to the Parent constructor right away. I would like to perform some calculations and then call Parent's constructor using the result of such calculation as input parameters. The code "would look" something like this:
public class Child : Parent
{
public Child(int i)
{
int calculation = i * 2; // Complicated operation
base(calculation); // This line will break
}
}
The second snippet is not valid C# code. Is there any way of postponing the call to Parent's constructor to mimic the sentiment expressed on the second code snippet?
This would do the same trick assuming u can access the properties directly
abstract class Parent
{
protected int i;
protected Parent()
{
//default constructor
}
}
class Child : Parent
{
public Child(int i)
{
Int calculation = i * 2
base.i = calculation
}
}
however if u cant do that because of restricted access to the properties my personal preference is to outsource the logic of the calculation in separate function and call the base class like following:
abstract class Parent
{
protected int i;
protected Parent(int i)
{
this.i = i;
}
}
class Child : Parent
{
public Child(int i) : base(Child.dosomework(i))
{
}
public static int dosomework(int i){
int calculation = i * 2
return calculation
}
}
abstract class Parent
{
protected int i;
protected Parent(int i)
{
this.i = i;
}
protected Parent(Func<int> param)
{
i = param();
}
}
class Child : Parent
{
public Child(int i) : base(() => i * 2)
{
}
}
Create a static method and use base(MyStaticMethod(params))
If you were allowed to call a base constructor in the child class in that way, you can face weird problems in your programs. Means that you can leave that instance in an inconsistent state because you could make a try-catch to handle some input-parameter errors and bypass the constructor. That is not the idea, imagine if you were allowed to create a Date in that way.
class MyDate : DateTime
{
public int(int year, int month, int day)
{
try
{
base(-1, -1, -1)
}
catch
{
}
}
}
The funny thing is that Java allows that with the super keyword.
The point of a constructor is to construct the instance, i.e. get it into a valid state. It should do that and nothing else. And if your class can exist without having i set already, then the act of setting i is not essential to its validity and therefore doesn't belong in a constructor.
Perhaps you don't want inheritance, you want composition.
class Inner
{
protected readonly int _i;
public Inner(int i)
{
_i = i;
}
}
class Outer
{
protected Inner _inner = null;
public Outer()
{
//Construct
}
public void SetI(int i)
{
_inner = new Inner(i); //Call constructor of Inner
}
}

How to prevent multiple Initialization of property from derived classes

The code below is a short "summary" of my real project that contain only the relevant parts to understand my question. (and don`t want to ruin someones day with the original code).
imagine you have 4 classes: Division, Branch, Department and Team. every class inherits base class in that order.
The final goal: return one division object that holds List of 7 Branches, each Branch holds List of 7 Departments and each Department holds List of 7 Teams.
for example i will be able to reach from outside to every class instance:
division d = new division();
d.CreateDivisionStructure();
int Example = d.ListOfBranches[5].ListOfDepartments[4].ListOfTeam[3].SomeIntegerProperty;
(the original code has that lists, override functions, properties etc..)
the problem: imagine that protected string _myVar in the code below is a Datatable that needs to initialized via myVarproperty with heavy resource consuming SQL query. hence, my wish is to initialize protected string _myVar only one time for all the creation of the "division units structure". in the code below protected string _myVar will be null 64 times and will be initialized 64 times (for my understanding 7 times for each unit and one time for each base() call).
how can i achieve that?
i tried quite a lot other ways but could not solve that. I would appreciate any help, different way of thinking or advice.
class Program
{
static void Main(string[] args)
{
division d = new division();
d.CreateDivisionStructure();
Console.ReadLine();
}
}
class division
{
private static int CountHowManyTimesMyVarWasInitilized = 0;
public division()
{
}
protected string _myVar;
public string myVar
{
get
{
if (_myVar == null)
{
CountHowManyTimesMyVarWasInitilized++;
Console.WriteLine(CountHowManyTimesMyVarWasInitilized);
_myVar = "now myVar is not null";
return _myVar;
}
else
{ return _myVar; }
}
set { _myVar = value; }
}
public void CreateDivisionStructure()
{
Console.WriteLine(myVar);
for (int i = 0; i < 7; i++)
{
Branch b = new Branch(7);
}
}
}
class Branch : division
{
public Branch(bool dImDerivedClass)
{
// constructor for department to prevent recursive stackoverflow if base of department will call the empty constructor
}
public Branch(int NumberOfBranches)
{
Console.WriteLine(myVar);
Department d = new Department(7);
}
}
class Department : Branch
{
public Department(bool ImDerivedClass) : base(true)
{
// constructor for team to prevent recursive stackoverflow if base of Team will call the empty constructor
}
public Department(int numberOfDep) : base(true)
{
for (int i = 0; i < numberOfDep; i++)
{
Console.WriteLine(myVar);
Team t = new Team(7);
}
}
}
class Team : Department
{
public Team(int numberOfTeams) : base(true)
{
for (int i = 0; i < numberOfTeams; i++)
{
Console.WriteLine(myVar);
}
}
}
}
This is likely a good use of the Lazy<T> class, used in a static variable so there is only a single copy for the process. It will run the Func you give it once to initialize during the first access of the variable.
https://msdn.microsoft.com/en-us/library/dd642331(v=vs.110).aspx
However, based on your class structure I'm not sure if it is the best approach. What is the purpose for the hierarchy of Branch : division and Department : Branch. Is the Branch a Division? If you are trying to share common properties as to not code them over again, I would suggest creating a common class that can hold those variables that Branch, Division, and Department can inherit from.
You can use a static variable / static constructor in the lowest class in the hierarchy. The static constructor will only be called once.
A simple solution is to use a "control" variable.
I'm sure you can improve your design and avoid this problem but I don't have time to check it now..
using System;
namespace Program
{
internal class Program
{
private static void Main(string[] args)
{
division d = new division();
d.CreateDivisionStructure();
Console.ReadLine();
}
}
internal class division
{
private static int CountHowManyTimesMyVarWasInitilized = 0;
public division()
{
}
protected string _myVar;
private bool _isReadyForInitialization;
public string myVar
{
get
{
if (!_isReadyForInitialization)
return null;
if (_myVar == null)
{
CountHowManyTimesMyVarWasInitilized++;
Console.WriteLine(CountHowManyTimesMyVarWasInitilized);
_myVar = "now myVar is not null";
return _myVar;
}
else
{ return _myVar; }
}
set { _myVar = value; }
}
public void CreateDivisionStructure()
{
// now _myVar is spposed to be initilized to all dirved clasess isnt is?
Console.WriteLine(myVar);
for (int i = 0; i < 7; i++)
{
Branch b = new Branch(7);
}
_isReadyForInitialization = true;
Console.WriteLine(myVar);
}
}
internal class Branch : division
{
public Branch(bool dImDerivedClass)
{
// constructor for department to prevent recursive stackoverflow if base of department will call the empty constructor
}
public Branch(int NumberOfBranches)
{
Console.WriteLine(myVar);
Department d = new Department(7);
}
}
internal class Department : Branch
{
public Department(bool ImDerivedClass) : base(true)
{
// constructor for team to prevent recursive stackoverflow if base of Team will call the empty constructor
}
public Department(int numberOfDep) : base(true)
{
for (int i = 0; i < numberOfDep; i++)
{
Console.WriteLine(myVar);
Team t = new Team(7);
}
}
}
internal class Team : Department
{
public Team():base(false)
{
}
public Team(int numberOfTeams) : base(true)
{
for (int i = 0; i < numberOfTeams; i++)
{
Console.WriteLine(myVar);
}
}
}
}

Difficulty to combine the use of base constructors and nonstatic fields

I was tackled by this issue for too many times so i decided to share and see what you guys think, lets look at the following (dumb) exemple:
public delegate void ToRun();
class Runner {
ToRun tr;
public Runner(ToRun f) {
tr=f;
}
public void run() {
tr();
}
}
class CountingRunner : Runner {
ToRun tr;
int i;
public CountingRunner(ToRun f) : base(f+=inc) {
i=0;
}
private static void inc() {
i++; //COMPILATION ERROR - i is not (and logically cannot be) static!
}
}
well, what i want to ask is:
Q1: why do base() parms have to be static?
Q2: what if, as in my exemple, we want to combine nonstatic fields or methods with the call to the base constructor? what is the most OOP way to do that?
Note : try not to give bandaid solutions like "just dont use the base c'tor", cause there might be more complex situation where using base is unavoidable, so im looking for a reasonable well designed solution for this.
Thanks!
Update:
my exemple was too easy to crack,therefore i feel like i havent learned enough, so lets try to give another (pretty dumb still) exemple:
public delegate int HashFunc<E>(E e);
public interface HashTable<E> {
void insert(E e);
bool isMember(E e);
}
class HashArray<E> : HashTable<E> where E : IComparable<E> {
private E[] a;
private bool[] taken;
public readonly int n;
public int size {
get { return n; }
}
HashFunc<E> hash;
public HashArray(int m , HashFunc<E> hash ) {
n=2*m;
a=new E[n];
taken=new bool[n];
for (int i=0 ; i<n ; i++) taken[i]=false;
this.hash=hash;
}
public void insert(E e) {
int index=hash(e),i;
for (i=index ; i<n && taken[i]!=false ; ++i) ;
if (i>=n)
for (i=0 ; i<index && taken[i]!=false ; ++i) ;
if (i>=index) return;
taken[i]=true;
a[i]=e;
}
public bool isMember(E e) {
int i=hash(e);
for ( ; i<n && taken[i]!=false && a[i].CompareTo(e)!=0 ; ++i );
if (i>=n || taken[i]==false) return false;
return true;
}
}
class HashArrayInt : HashArray<int> {
public HashArrayInt(int n) : base (n,HashFunc) {
}
public static int HashFunc(int i) {
return (i%n);// n is a non static field, every hash table has its own size!
}
}
in this exemple we are giving some weird implementation for an hash table where the hash function is unknown, and a special class for hash table of ints with predefined hash function, notice that here again we need to combine the non static size of the hashtable n and base c'tor...
Q1: why do base() parms have to be static?
They must be static because the instance hasn't been defined at the time of the constructor call (that definition was "in progress").
Q2: what if, as in my exemple, we want to combine nonstatic fields or methods with the call to the base constructor? what is the most OOP way to do that?
To OOP-way would is just simple method overrides.
class Runner
{
ToRun tr;
public Runner(ToRun f)
{
tr=f;
}
public virtual void Run()
{
tr();
}
}
class CountingRunner : Runner {
int i;
public CountingRunner(ToRun f) : base(f) {
i=0;
}
public override void Run() {
i++;
base.Run();
}
}
This is what you want:
class Runner {
protected event Action _toRun;
public Runner() {
}
public void Run() {
var r = _toRun;
if (r != null)
_toRun();
}
}
class CountingRunner : Runner {
int i;
public CountingRunner(Action f) : base() {
_toRun += f;
}
public void inc() {
i++;
}
}
EDIT
For your particular example with hash tables, this problem is solved by the design of the language. Just call GetHashCode() on the elements of your hashtable to determine their hashcode. You don't need implementations to pass a hashing function.
To answer your more general question of "How should I send functions manipulating instance data to the base class," you should either capture your instance variables in a lambda expression and send that to the base class, or consider a design in which the base class doesn't need access to the instance functions of its derived classes. I would go with the latter :)
One such design would be to have the function a pure virtual call in the base class. That would require derived classes to implement the virtual call in order to be instantiated. So here you would have a abstract int GetHashCode(E item) function in the base class, and just override it in your subclasses. Again, in this specific case the language does this for you with the virtual GetHashCode() function defined for all types.
Here is a non-abstract example (derived classes aren't required to override the hashing function).
class HashArray<E> : HashTable<E> where E : IComparable<E> {
private E[] a;
private bool[] taken;
public readonly int n;
public int size {
get { return n; }
}
public HashArray(int m) {
n=2*m;
a=new E[n];
taken=new bool[n];
for (int i=0 ; i<n ; i++) taken[i]=false;
}
public void insert(E e) {
int index= GetSpecialHashCode(e)%n;
int i;
for (i=index ; i<n && taken[i]!=false ; ++i) ;
if (i>=n)
for (i=0 ; i<index && taken[i]!=false ; ++i) ;
if (i>=index) return;
taken[i]=true;
a[i]=e;
}
public bool isMember(E e) {
int i= GetSpecialHashCode(e)%n;
for ( ; i<n && taken[i]!=false && a[i].CompareTo(e)!=0 ; ++i );
if (i>=n || taken[i]==false) return false;
return true;
}
protected virtual int GetSpecialHashCode(E item) {
return item.GetHashCode();
}
}
So you get a default hashcode generating function, but derived classes are also welcome to supply their own.
Regarding both Q1 and Q2, it's not that the parameters must be static, but rather the parameters must be accessible at the time they are invoked.
And base constructors are invoked prior to the local constructor, which is why you can't use this members as parameter for example, and why you shouldn't invoke virtual calls.
Not totally sure what the ultimate goal of that would be, but it does resemble a Decorator pattern.
For your last example, I think this could work:
class HashArrayInt : HashArray<int> {
public HashArrayInt(int n) : base (n,i => HashFunc(i,n)) {
}
private static int HashFunc(int i, int n) {
return (i%n);// n is a non static field, every hash table has its own size!
}
}
If not, you can do this:
class HashFuncProvider {
private int n;
public HashFuncProvider(int n){
this.n = n;
}
public int HashFunc(int i) {
return (i%n);
}
}
class HashArrayInt : HashArray<int> {
public HashArrayInt(int n) : base (n, new HashFuncProvider(n).HashFunc) {
}
}

Categories