4 ms·
Depends. In complicated code with lots of dependencies, I've always found it easier to understand functions that are written as: function do_task(a, b, c)
by rustybolt 7y ago
Depends. In complicated code with lots of dependencies, I've always found it easier to understand functions that are written as:
function do_task(a, b, c) {
d = subtask1(a, b);
e = subtask2(b, c, d);
f = subtask3(a, d);
}
instead of one long function. Of course, this only makes sense if the subtasks are indeed different conceptual steps in the computation.
As an example, I remember writing finite elements code that was structured something like this:
function solve_fem_problem(problem_description) {
basis_functions = generate_basisfunctions(basisfunctions_type.b_spline);
quadrature_rule = generate_quadrature(quadrature_type.gaussian_quadrature);
A = assemble_matrix(problem_description.differential_equation, basis_functions, quadrature_rule);
b = assemble_righthandside(problem_description.differential_equation, basis_functions, quadrature_rule);
apply_boundary_conditions(problem_description.boundary_conditions, A, b);
solution = linsolve(A, b);
}
which I think is very pleasing to read, and preferable to a single huge function. This also makes it easy to use another linear solver, for example. On the other hand, the functions that are called inside solve_fem_problem are probably larger.
Note: During work, I haven't actually encountered a lot of code that is structured in this way.
- Symbiote 7y agoI'm hijacking this since your function shows the kind of case where I like to make an exception to the line length rule. It looks much better, and is more understandable due to the repeating pattern, as you have it, but some people I've collaborated on open source code with would insist upon this: function solve_fem_problem(problem_description) { basis_functions = generate_basisfunctions(basisfunctions_type.b_spline); quadrature_rule = generate_quadrature(quadrature_type.gaussian_quadrature); A = assemble_matrix(problem_description.differential_equation, basis_functions, quadrature_rule); b = assemble_righthandside(problem_description.differential_equation, basis_functions, quadrature_rule); apply_boundary_conditions(problem_description.boundary_conditions, A, b); solution = linsolve(A, b); } (For this example, I'm assuming an arbitrary maximum line length of between the A = and b = lines.)