Page 1 of 1

Merge Functions Advice

Posted: Tue Jul 05, 2005 9:43 am
by facets
The following two functions almost do the same job, can anyone see a way to merge them?
I was thinking perhaps an If statement like

[psuedocode]if (!stockId > 0) do (listFaceStock function) else (fnListFaceStock function)

Any ideas? tia, will

Code: Select all

function  listFaceStock() {
	$sql_query = mysql_query("SELECT stockDescription, stockId FROM austock");
	$output = "<select name=\"stockId\">\n";
        $output .= "<option value=\"\">-- Select Option --</option>\n";    
    	while(list($stockname, $stockId)=mysql_fetch_array($sql_query)) {
		$stockname = stripslashes($stockname);
		$output .= "<option value=\"$stockId\">$stockname</option>\n";
	}
	$output .= "</select>";
	mysql_free_result($sql_query);
	return $output;
}

function  fnListFaceStock($stockId) {
	$sql = mysql_query("SELECT stockDescription, stockId FROM austock WHERE stockId = $stockId");
	$query_data = mysql_fetch_array($sql);
	$result = $query_data["stockDescription"];
	$sql_query = mysql_query("SELECT stockDescription, stockId FROM austock");
	$output = "<select name=\"stockId\">\n";
        $output .= "<option value=\"\">$result</option>\n";    
    	while(list($stockDescription, $stockId)=mysql_fetch_array($sql_query)) {
		$stockDescription = stripslashes($stockDescription);
		$output .= "<option value=\"$stockId\">$stockDescription</option>\n";
	}
	$output .= "</select>";
	mysql_free_result($sql_query);
	return $output;
}

Posted: Tue Jul 05, 2005 9:56 am
by djot
perhaps you should try yourself before asking such a question...

Posted: Tue Jul 05, 2005 10:03 am
by facets
sure.. your right..
I guess the question was - is it worth doing this kind of merging?
Or at the end of the day, 50 extra lines of code doesn't really effect anything?

Posted: Tue Jul 05, 2005 10:19 am
by djot
-
If you have these two function working, you gain nothing by merging them except perhaps some easier editing when changing anything inside your query or DB later.

There is no general answer to this. Sometimes it's better to have a function that is used for exactly one purpose. Sometimes you may have some arguments, that might change the behaviour of a function depending on the arguments to not have redundant code parts.

djot
-

Posted: Tue Jul 05, 2005 12:07 pm
by timvw
If you invest a little time in seeing where things are different... and where they are the same... you could generate a generic function....

And reuse it in your following lists...