How coupled are your classes ?

October 8, 2014

So, what is, formally, a coupling ? Of course, one will go to Wikipedia's page «Coupling (Computer programming)» to have a first answer. But maybe we can try to search on our own.

For the moment, we will try to modularize on a screen basis, i.e. to move each screen into its own pod. Thus what we want to know is how much "link" there is between a screen and the others modules of the application.

Fortunately, we already have a division of our modules by screen:

Capture d’écran 2014-10-08 à 14.23.01

From the outside, this seems nice and clean but maybe not. So how to measure how entagled our code is. A possible start would be to list all the #import of headers which are not in the same module as the importing file.

Let's try with the HP module. First, we want to find all the #import.:

find . -name ".[hm]" | xargs cat | grep "#import"
Maybe we would like to know which header is the most imported:
find . -name ".[hm]" | xargs cat | grep "#import" | sort | uniq -c | sort
Next, we want only the name of the header (forgive my shell scripting capabilities please), that we will keep in the /tmp/imported.txt file
find . -name ".[hm]" | xargs cat | grep "#import" | sort | uniq | sort | sed 's/#import //' | sed 's/"//g' | sed 's/.\///' | sed 's/>//' | sed 's/<//' | sed 's/ //g' > /tmp/imported.txt
Then, we want all the headers in the module, and we will put them in the /tmp/samemodules.txt:
find . -name ".h" | sed 's/#import //' | sed 's/"//g' | sed 's/.\///' | sed 's/>//' | sed 's/<//' | sed 's/ //g' > /tmp/samemodule.txt
At last, we want all the headers in the /tmp/imported.txt but not in the /tmp/samemodules.txt, which we can write as
comm -2 -3 /tmp/imported.txt /tmp/samemodule.txt > /tmp/extern.txt
So now, a bit of stats:
➜ HP git:(develop) wc -l /tmp/samemodule.txt
 45 /tmp/samemodule.txt
➜ HP git:(develop) wc -l /tmp/imported.txt
 120 /tmp/imported.txt
➜ HP git:(develop) wc -l /tmp/extern.txt
 106 /tmp/extern.txt
So in the HP module, we import 120 headers. 106 of those aren't in the module.

Looks like a lot of fun.