Which is the more testable C function implementation? [closed]

  softwareengineering

I write code in C. I have been striving to write more testable code but I am a little
confused on deciding between writing pure functions that are really good for testing
but require smaller functions and hurt readability in my opinion and writing functions
that do modify some internal state.

For example (all state variables are declared static and hence are “private” to my module):

Which of this is more testable in your opinion:

int outer_API_bar()
{
   // Modify internal state
   internal_foo()
}

int internal_foo()
{
  // Do stuff

  if (internal_state_variable)
  {
     // Do some more stuff
     internal_state_variable = false;
  }
}

OR

int outer_API_bar()
{
   // Modify internal state

   internal_foo(internal_state_variable)

   // This could be another function if repeated many
   // times in the module
   if (internal_state_variable)
   {
      internal_state_variable = false;
   }
}

int internal_foo(bool arg)
{
  // Do stuff

  if (arg)
  {
     // Do some more stuff
  }
}

Although second implementation is more testable wrt to internal_foo as it has no sideeffects but it makes bar uglier and requires smaller functions that make it hard for the reader to even follow small snippets as he has to constantly shift attention to different functions.

Which one do you think is better ? Compare this to writing OOPS code, the private functions most of the time use internal state and are not pure. Testing is done by setting up internal state on a mock object instance and testing the private function. I am getting a little confused on whether to use or whether to pass in internal state to private functions for the sake of “testability”

0

The second is better, but

int internal_foo(bool *arg); // modifies argument

keeps it testable while fixing your tiny function tradeoff, and

bool internal_foo(bool arg); // returns new value

is even better if you don’t use the existing return value.

Note that in general though, having lots of little functions isn’t necessarily a problem. If it makes your code less readable, you might just need to give them better names and/or re-work your logic.

The best and most general solution would be to remove your globals entirely, and have the caller pass an opaque API context into your outer function. This might be overkill in your case though, I can’t tell from the code shown.

2

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website Kho Theme wordpress Kho Theme WP Theme WP

LEAVE A COMMENT