They're also a method of code organisation and self-documentation. There's a principle in coding that says "never document with comments what can be described in code." E.G. $c = sqrt($a * $a + $b * $b);is a piece of code. Non-mathematicians might not realise what this does, so you could comment it:
Code:
// obtain the hypotenuse given the other two sides.
$c = sqrt($a * $a + $b * $b);
Or, you could write a function:
Code:
function get_hypotenuse($side_a, $side_b) {
return sqrt($side_a * $side_a + $side_b * $side_b);
}
Here there's no need to write a comment because the function explains itself. The function is also completely independent from the rest of the code, so you can move it to another file for organisation purposes and it will still make sense. Plus, there are things that you can do with functions that you simply can't do with flat procedural code. Go and learn a functional programming language (Lisp, Haskell, Erlang, Javascript in some cases) for some examples. The LoC is a pretty useless measure in this case when 1/3 lines contains only a single character :-) In something approaching Lisp style:
Code:
function get_hypotenuse($side_a, $side_b)
{ return sqrt($side_a * $side_a + $side_b * $side_b); }
Bookmarks