Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

A lot of those if-/case-blocks are precisely where I'd put functions :)

If you changed a bunch of those to separate, pure (i.e. side-effect-free) functions it would if nothing else make unit testing a breeze, and then you'd be free to fix bugs in the logic without fear. As it is, if I had a bug in that huge function I'd be really worried about breaking some edge-condition or implied-state 500 lines up etc.



They can’t be side effect free, that’s the point. The switch statements are mutating the input.


There's a lot that can be, take this for instance (line 3336):

  if (c == '\033')
      term->print_state = 1;
  else if (c == (unsigned char)'\233')
      term->print_state = 2;
  else if (c == '[' && term->print_state == 1)
      term->print_state = 2;
  else if (c == '4' && term->print_state == 2)
      term->print_state = 3;
  else if (c == 'i' && term->print_state == 3)
      term->print_state = 4;
  else
      term->print_state = 0;
This could be turned into a pure function that takes c and print_state as input, and returns a new print_state which the outer function assigns. That's 12 lines turned into 1.

  term->print_state = newState(c, term->print_state);
(I am not a C developer so the sytax could be wrong). Just because the outer function is impure doesn't mean it can't in turn call pure functions.


It's a Mealy state machine, it should be encoded as a state machine!

Why some folks will absolutely insist that a series of manually-written case statements in a single thousand line function is the epitome of style, when there's a pure state machine model inside wishing you would free it from the shackles of if else if else if else....


I have some experience with state machines, and I absolutely hate them. It's so easy to get lost, you never know where a function will go to next.

There's a reason stacks are ubiquitous, they're much easier to fit in your head.


You can still have side-effects in your “big” function, based on the return values of pure functions.


I totally agree. And you can always write mutating “functions” (what get called “algorithms” in the C++ world), like C++’s `std::ranges::sort(range)`.


You can always use return values, and allow the caller to decide how to use them (e.g. caller may mutate other values).

Depending on use and language, this may be "expensive" (e.g. you could be allocating for and then copying some huge data structure only to pass it back where is is simply copied over the top of the input), but this is where discretion comes in and decisions are made on what is appropriate (i.e. is performance critical, or is correctness and maintainability more important?)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: