1

I came to know that scanf is coupled and it is coupled because it takes different types of inputs like integer, float, char and others.

But cohesion indicates doing a single task and scanf does it(scanning input from stdin).

I agree that although it does the desired task of reading, it lack cohesion in the form reading different types of data.

But how does reading different types of data indicate it is coupled? I saw that coupling is a degree to which a component/module is connected to the other modules or independence of modules. How does reading different types of data make it dependent?

Can anyone explain how can we say a function is coupled or cohesive and is scanf coupled or cohesive?

  • 1
    Coupling and cohesion usually refer to software components on a much larger scale, not the contracts of individual functions. Analyzing scanf this way doesn't contribute much; consider instead how your own classes and modules rely on each other or can perform their tasks in isolation. – derekerdmann Jun 03 '15 at 17:01
  • Detail: `scanf()` normally does not take inputs types like `float` and `char`. It does take input types like `float *` and `char *`. – chux - Reinstate Monica Jun 03 '15 at 17:30

1 Answers1

3

As the word suggests, I would say that you can only discuss coupling if you have at least two elements involved.

Saying that scanf(), by itself, is coupled, does not make much sense to me.

Given two modules (two functions, two classes, ...) they may be more or less "coupled" depending on how much one depends on the other.

For example, they may share a global variable or (a file) so that if one alters it, the other is affected too. Or they must be called in a certain order (or they won't work).

Too tight coupling is a bad thing from a maintenance perspective, you may change something in a module and later discover that you introduced a bug in another module!

From this perspective I can't think of any function in the standard C library on which scanf() may depend. But even if there were one it would be a problem for the standard library mainteners, not for programmers.

Cohesion, instead, refers to the fact that a module (again: a function, a class, ...) performs a single, identified task. The worst you can have is when you have a function that performs two (or more) unrelated tasks just because they can be performed at the same time. For example you have a function that computes the average of a set of numbers and cleans up the directory where you will store the results. This is bad from a clarity point of view (and hence, you are increasing the chance of bugs) and from a reuse point of view (little chance you will ever call that function again in the program).

As far as I can tell, scanf() does a single job (reading a set of values from stdin according a pattern) and does it well.

Remo.D
  • 16,122
  • 6
  • 43
  • 74