-
Notifications
You must be signed in to change notification settings - Fork 165
Code style guide
Since Kod is limited to the Xcode platform and the two compilers GCC and Clang, we prefer the use of #import rather than #include. If you do use #include, make sure to add a header guard in the style described below.
All non-objective-C header files should begin with a #pragma once to prevent multiple inclusion.
Don't use an #import or #include when a forward declaration would suffice.
When you include a header file you introduce a dependency that will cause your code to be recompiled whenever the header file changes. If your header file includes other header files, any change to those files will cause any code that includes your header to be recompiled. Therefore, we prefer to minimize includes, particularly includes of header files in other header files.
You can significantly minimize the number of header files you need to include in your own header files by using forward declarations. For example, if your header file uses the File class in ways that do not require access to the declaration of the File class, your header file can just forward declare class File; instead of having to #import "foo/file.h".
Prefer class member functions to global functions; use completely global functions rarely.
Place a function's variables in the narrowest scope possible, and initialize variables in the declaration.
C and C++ allows you to declare variables anywhere in a function. We encourage you to declare them in as local a scope as possible, and as close to the first use as possible. This makes it easier for the reader to find the declaration and see what type the variable is and what it was initialized to. In particular, initialization should be used instead of declaration and assignment, e.g.
int i;
i = f(); // Bad -- initialization separate from declaration.Instead:
int j = g(); // Good -- declaration has initialization.Note that gcc and clang implements for (int i = 0; i < 10; ++i) correctly (the scope of i is only the scope of the for loop), so you can then reuse i in another for loop in the same scope. It also correctly scopes declarations in if and while statements, e.g.
while (const char* p = strchr(str, '/')) str = p + 1;There is one caveat: if the variable is an object on the stack, its constructor is invoked every time it enters scope and is created, and its destructor is invoked every time it goes out of scope.
// Inefficient implementation:
for (int i = 0; i < 1000000; ++i) {
Foo f; // My ctor and dtor get called 1000000 times each.
f.DoSomething(i);
}