• Stars
    star
    1,343
  • Rank 33,689 (Top 0.7 %)
  • Language
    Python
  • Created over 13 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Graph the import dependancies in an Objective-C project

License

BSD 3-Clause License

Copyright (c) 2012-2013, Nicolas Seriot All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of the Nicolas Seriot nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Refactoring by graphing class dependencies

Code design and loose coupling

As developers, we all love clean code, but the fact is that most of the time we're dealing with bad code. It may be recent or legacy code, written by ourselves or by other developers. We can recognize bad code because code smells. In other words, some heuristics raise questions about code quality. Among thoses we can name dead code, which I already wrote about here and here, and tight coupling.

Tight coupling describes a system where many components depend on many other components. A tightly coupled code base stinks, the coupling points out that some classes assume too many responsibilities or that a responsibility is spread over several classes, rather than having its own class. The opposite, loose coupling, shows a better design which promotes single-responsibility and separation of concerns. Loose coupling makes the code easier to test and maintain.

In Objective-C, reducing coupling generally involves delegates and notifications.

Graphing class dependencies

So how do we achieve loose coupling in our own code? Well, at first, we need to get a better idea on the current coupling. Let us define class dependency: class A depends on B if class A imports class B header. With such a definition, we can draw a graph of dependencies between classes by considering the Objective-C #import directives in each class. We assume here that the files are named according to the classes they contain.

I wrote objc_dep.py, a Python script which extracts imports from Objective-C source code. The output can then be displayed in GraphViz or OmniGraffle. You can then see an oriented graph of dependencies between classes. Note that we could also compute metrics on coupling, but it's not the point here.

Sample usage

How do we get from the dependencies graph to a better design? There's no determinist algorithm and it depends on your project. Let us apply the script on FSWalker, a small iPhone file browser I wrote a long time ago.

1. Generate the graph

$ python objc_dep.py /path/to/FSWalker > fswalker.dot

2. Open it in OmniGraffle

At this point, we see classes as nodes and dependencies as directed edges.

3. Remove categories

We can safely remove Objective-C categories from the graph, since referencing categories from many places is not an issue from a design point of view.

4. Group related classes

Next, we can move the vertices around, try to group classes with a common responsibility into clusters.

5. Study strange dependencies

The graph now gives a pretty good overview of the overall code structure. The controller objects have been colored in pink, the model objects in yellow and the network part in blue. The graph allows to sport strange dependencies and question the code design. We can see at first glance that FSWalkerAppDelegate has too many dependencies. Specifically we consider:

a) unreferenced classes or clusters

This is probably dead code, which can be removed.

Ok, there are no unreferenced classes here, although you will probably find some in bigger projects.

b) two-ways references

Maybe one class should not reference another directly, but reference a protocol implemented by the other class instead.

We have two examples of two-ways references here, between HTTPServer and HTTPConnection, and also between RootViewController and FSWalkerAppDelegate. The former is part of CocoaHTTPServer and is not a design issue in our project. However, the latter is an issue. By looking at the code, we will notice that RootViewController doesn't actually use FSWalkerAppDelegate. The import can thus be safely removed.

c) weird references

Some of the import directives may simply be unnecessary, or reveal design issues.

There is no good reason why FSWalkerAppDelegate would reference FSItem, nor InfoPanelController. Code inspection will reveal that DetailViewController and InfoPanelController should not be referenced by FSWalkerAppDelegate but RootViewController instead. So, here is the final graph. The architecture of FSWalker may still be improved, but you get the idea...

Real world usage

Here is the kind of chart you can expect with a 100 classes project.

Using options

% python objc_dep.py /path/to/repo -x "(^Internal|secret)" -i subdir1 subdir2 > graph.dot

Will exclude files with names that begin with "Internal", or contain the word "secret". Additionally all files in folders named subdir1 and subdir2 are ignored.

Possible improvements

The Cocoa framework enforces the MVC paradigm, which states (to be short) that model objects and graphical objects should be clearly separated by controller objects. The script could probably be improved by drawing classes which depend on Foundation and classes which depend on AppKit/UIKit with different colors.

Conclusion

I have found objc_dep.py to be definitely useful on small projects as well as bigger ones. It helped me in getting a clear view of code base structure. Spotting strange dependencies allowed me to ask good questions which led to design simplifications. Such a tool could even be integrated into Apple development tools.

Interestingly, the last chart is quite close to the mental representation I have of the code architecture. It reminds me a discussion I had 15 years ago with a friend who was a champion chess player who could play several "blind" chess games simultaneously. He explained then that he saw a blurry chessboard in his head and could move around the pieces as with a small 3D camera. Focusing on a specific piece would then raise awareness of opportunities and risks - dependencies - for this piece. As a side effect, writing this script made me realize that software engineering is pretty similar to chess in this way.

More Repositories

1

iOS-Runtime-Headers

iOS Objective-C headers as derived from runtime introspection
Objective-C
7,919
star
2

RuntimeBrowser

Objective-C Runtime Browser, for Mac OS X and iOS
Objective-C
3,507
star
3

STTwitter

A stable, mature and comprehensive Objective-C library for Twitter REST API 1.1
Objective-C
1,000
star
4

STHTTPRequest

Obj-C / Cocoa HTTP requests for humans
Objective-C
827
star
5

JSONTestSuite

A comprehensive test suite for RFC 8259 compliant JSON parsers
C++
826
star
6

objc_cover

Quick Python script over otool to help spotting potentially unused methods in Objective-C Mach-O executable files
Python
448
star
7

SpyPhone

This project shows the kind of data a rogue iPhone application can collect.
Objective-C
310
star
8

objc_strings

Helps in localizing Cocoa applications by showing unused/missing keys in Localizable.strings.
Python
191
star
9

BitmapCanvas

Bitmap offscreen drawing in Swift for OS X
Swift
121
star
10

BatteryChart

Drawing iPhone Battery Charge / Discharge
C
102
star
11

gmap_tiles

Download and merge Google Maps tiles
Python
96
star
12

UniBinary

Encodes data into printable Unicode characters.
JavaScript
90
star
13

nsarray-functional

Objective-C category to add Python-like map, filter and reduce methods to Cocoa NSArray.
Objective-C
83
star
14

ScreenTime

create movies from periodic screenshots
Swift
74
star
15

MobileSignal

Map and chart the signal type and strength on your iOS device
Objective-C
69
star
16

STJSON

A JSON Parser in Swift 3 compliant with RFC 7159
Swift
68
star
17

BinUtils

Swift functions to ease working with binary formats
Swift
68
star
18

SQRiskCursor

Custom UIControl using CoreAnimation
Objective-C
59
star
19

CocoaSlideShow

Simple Image Browser for Mac OS X
Objective-C
52
star
20

SEVerticalTabBar

A vertical tab bar implementation for iPad
41
star
21

UTIsExplorer

Find OS X UTIs, build up the inheritance tree, save it as a Graphviz graph.
Objective-C
40
star
22

bfps

A Brainfuck interpreter written in PostScript
PostScript
35
star
23

ShapefileReader

A shapefile reader in Swift
Swift
34
star
24

FSWalker

A File System Browser for iOS
Objective-C
30
star
25

iCalReport

iCalReport reads iCal events and reports the time you spend on projects.
Python
25
star
26

UnicodePoster

Unicode Poster
Objective-C
25
star
27

CrashReports

Symbolicate iOS crash reports
Perl
23
star
28

filters

Apply filters on iOS Camera.app JPG files imported with Image Capture.
Python
21
star
29

osx_frameworks

Generate a .dot file of OS X frameworks dependencies
Python
21
star
30

Quickies

Simple PHP/MySQL application to share notes organized by category.
PHP
19
star
31

TwitHunter

Cocoa Twitter client with scoring
Objective-C
18
star
32

Brainfuck

A flexible Brainfuck / Brainloller / Braincopter interpreter in Swift 3.1.
Swift
15
star
33

Wireworld

A simple Wireworld cellular automaton explorer in Swift
Swift
13
star
34

draw_bytes

draw any file as a picture
Python
13
star
35

PulsarRuns

Pulsar-plot of Strava runs in Swift 3
Swift
12
star
36

DevTeamActivity

Generates a picture summarising the activity of a dev team on one or several repositories
Swift
11
star
37

Home-Made-Maps

Home Made Maps
11
star
38

SwissSMS

Mac OS X SMS sender
Objective-C
11
star
39

ECAExplorer

A simple and interactive tool to explore Elementary Cellular Automata, in Swift
Swift
10
star
40

Intertwined

Draw intertwined threads, knots and knitting figures with PyCairo
Python
9
star
41

efx-backtest

Simple tool to backtest eForex strategies
Python
9
star
42

EasterEggs

A social game that consists in catching QR-codes
Python
9
star
43

SwiftDrawing

Drawing in Swift
Swift
9
star
44

STMovingImages

Create .MOV and .GIF from NSImages in Swift 3
Swift
8
star
45

Twitter-Saver

Save your Twitter statuses in CSV format.
Python
7
star
46

deprecated-fb_albums

Download photos from Facebook photo albums.
Python
6
star
47

Isometric

Isometric screensaver for macOS, written in Swift
Swift
6
star
48

PyCairoVisualDoc

Turns PyCairo snippets into HTML
Python
6
star
49

AntennasAssignment

A combinatorial optimisation problem
Objective-C
5
star
50

HTTPRequests

NSURLRequest extensions in Swift
Swift
4
star
51

pmlogs_to_ical

Create a calendar of wake-sleep sessions based on power management logs.
4
star
52

IsoRenderer

A 2D isometric renderer in Python 3 based on PyCairo
Python
3
star
53

JavaDoc

Legacy OS X Dashboard widget to access Java documentation
Objective-C
3
star
54

Boggle

Python
2
star
55

WangTilesTuringMachines

Simulating Wang Tiles with Turing Machines
Python
2
star
56

matplotlib_experiments

Matplotlib experiments
2
star
57

MNIST

Measuring the accuracy of a trivial approach to the MNIST digits classification problem
Python
2
star
58

newsmemory

Django web application to crawl, store and browse pieces of news
Python
2
star
59

AVS

encrypt / decrypt Swiss AVS IDs
Python
1
star
60

HEIG-VD

A few projects from my time at Engineering School HEIG-VD
C
1
star
61

phpMyFlatSite

Minimal framework to run a classic, single user, dynamic web site.
PHP
1
star
62

Mowgli

Generate a static website from Markdown files with <150 lines of Python
CSS
1
star
63

PyGame

Experiments with PyGame
Python
1
star
64

STStrava

Experimental visualisation of runs using Swift and Strava API
Swift
1
star