Tuesday, October 26, 2010

Better way of refactoring this ?

Programmer Question

I have the following classes:



public abstract class BaseClass
{
private readonly double cachedValue;

public BaseClass()
{
cachedValue = ComputeValue();
}

protected abstract double ComputeValue()
}


public class ClassA : BaseClass
{
protected override double ComputeValue() { ... }
}

public class ClassB : BaseClass
{
protected override double ComputeValue() { ... }
}


where ComputeValue() is a time consuming computation.



Problem is, there are other methods in the ClassA and ClassB which require the value returned from ComputeValue(). I was thinking of adding a protected property named 'CachedValue' in BaseClass but I find this approach to be redundant and confusing to other programmers who might not be aware of its existence, and might call ComputeValue() directly.



The second option is to use nullable type at the derived class level as I don't necessarily require the computation to be done in the constructor in BaseClass, lazy computation might be a better option:



protected override double ComputeValue()  
{
if(cachedValue.HasValue)
{
return (double) cachedValue;
}

// Do computation
cachedValue = ...

return cachedValue;
}


but I feel I could do better.



What are your thoughts on this ?



Thank you.



Edit: Just to clarify, I'm trying to prevent ComputeValue() from getting called more than once by enforcing the use of 'cachedValue'.



Find the answer here

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails