I have a Calc class that I think was improperly placed in the codebase I am working with. For the class structure see code below.
Currently
Specclass acts as a storage of data, similar to C structCalcclass is a library of computational functions class that is instantiated as part of other classes, whenever those classes need to do some computation.Calcclass also housesSpecclass, so that it can do computations using variables ofSpec.Plotclass is an example of a business object representing a graph.Businessclass is a business object representing a controller of sorts in my application, where some computations are made and are displayed in text for user page "View", and a graph is also created which is also displayed to the user on the "View" page.
class Spec
{
public $a;
public $b;
public $c;
}
class Calc
{
public $spec;
function __construct()
{
$this->spec = new Spec();
}
function calcParameter()
{
$this->spec->c = $this->spec->a + $this->spec->b;
}
}
class Plot
{
public $calc;
function __construct()
{
$this->calc = new Calc();
}
function calcParameter()
{
$this->spec->c = $this->spec->a + $this->spec->b;
}
}
class Business
{
public $calc;
public $plot;
function __construct()
{
$this->calc = new Calc();
$this->plot = new Plot();
}
function doBusinessLogic()
{
//calc for local
$this->calc->spec->a = 5;
$this->calc->spec->b = 5;
$this->calc->calcParameter();
print "total is {$this->calc->spec->c}\n";
//later this format is used by JS to display computational results
$resultsJSON = json_encode($this->calc);
//calc for plot
$this->plot->calc->spec->a = 1;
$this->plot->calc->spec->b = 2;
$this->plot->calc->calcParameter();
print "total is {$this->plot->calc->spec->c}\n";
//later this format is used by JS to display a plot
$plotJSON = json_encode($this->plot);
}
}
//runs the above
(new Business())->doBusinessLogic();
JS is used like so:
var res = JSON.parse(document.getElementById("res").innerHTML);
alert(res.spec.c);
Question
I am under impression that the Calc class was not correctly placed (not designed properly), and as such, it is injected into various places just to do computations. I am thinking that Calc should be a class with no parameters and that Spec should not be part of Calc. And that Calc must only contain functions that do computations, and callers of Calc will supply their own data and receive results. Thereby Calc will become a static library of functions to be used by others. But then is this the best way?
How can I best refactor this? keeping in mind that JSON format is either to be preserved, or being mindful that any changes may require changes to JS code as well.
And before I go knee-deep refactoring this, the design I have now works. Is there a need to refactor at all? Just checking.
Aucun commentaire:
Enregistrer un commentaire