I am updating a class in legacy code and having some issue with my calcPressure
method. I want to make it nice and clean but there is some convolution in the process.
Namely the calcPressure
method I have does this:
- computes a value from existing values
- writes that value into an in-class parameter
- returns the value to the caller
- prints debug output while computing
- prepares output for View (JSON, document...innerHtml)
Issues
In general, the code is all interconnected and it works, so part of me feels "why do I want to mess with it". But part of me feels that Separation of Concerns (SOC) is super-broken. After all, the same internal pressure
parameter that originates inside PHP class goes all the way into JS view, from being computed in PHP, transferred to JS and displayed in the browser. So if I make pressure
private for example, or rename it, my view will become broken, since it depends on having the same parameter name in JS as in PHP for it to work.
More specifically my method seems to do an awful lot. I'm questioning whether I should only have it compute data and return it without assigning the in-class parameter. Or if I should only assign the in-class parameter and not return anything. Right now it does both. I wonder if I should redirect debugging information to be a part of view and not be a part of the method somehow (computation/debug output separation).
Code
class Spec
{
function load()
{
$result = db_query("SELECT * from spec where id = {$this->id}");
$row = db_fetch_array($result);
$this->n = $row['n'];
$this->sg = $row['sg'];
$this->q = $row['q'];
}
/**
* Computes and returns Pressure
* Outputs debug info
* Assigns internal parameter
*
* @return number
*/
function calcPressure()
{
$res = abs($this->n * sqrt($this->q) / 15164.93 * $this->sg);
dump(" *** <u>Pressure</u> = $res");
$this->pressure = $res;
return $res;
}
public $pressure;
public $sg;
public $q;
public $n;
public $id;
}
PHP side
$spec = new Spec();
/*
* Load of static parameters ($q, $sg, $n) from DB omitted for clarity
*/
$spec->id = 5;
$spec->load();
$spec->calcPressure();
$json = json_encode($spec);
JS/View side
<script>
var x = <?=$json?>;
/*
* Populates HTML pages with computed pressure information
*/
document.getElementById('pressure').innerHTML = x.pressure;
</script>
Dump
function dump($sql){print "<pre>";print_r($sql);print"</pre>" . PHP_EOL;}