# Trying to define our Code Style

**URL:** https://forums.synfig.org/t/trying-to-define-our-code-style/13097
**Category:** Coding synfig
**Created:** [March 26, 2022, 4:48pm UTC](https://forums.synfig.org/t/trying-to-define-our-code-style/13097 "2022-03-26T16:48:13Z")
**Posts on this page:** 20
**Page:** 1

<div class="post-metadata">

### Author: ![rodolforg](https://forums.synfig.org/letter_avatar_proxy/v4/letter/r/c68b51/32.png) [@rodolforg](https://forums.synfig.org/u/rodolforg)
#### Post date: [March 26, 2022, 4:48pm UTC](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/1 "2022-03-26T16:48:13Z")

</div>

Synfig code was and is written by many hands. To improve readability, maintanance and consistency, we should set our coding style.  
In the old wiki, there is a [short page about it](https://wiki.synfig.org/Dev:Coding_Conventions), written in 2010 by @Genete, but it lacks a lot of info.  
Currently, there are many of Code Styles used by many (modern) C++ projects, like [Coding Guidelines | Haiku Project](https://www.haiku-os.org/development/coding-guidelines), [Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html) and [Code Style Guidelines | WebKit](https://webkit.org/code-style-guidelines).

This topic is about building our own code style or following one of the existent ones to be used on new code contributions/commits and, in a future or hypothetical dream, on the entire Synfig code.

I’ll create here some polls about points the code styles mentioned above handles to we choose what fits better to our taste. The “results” will be compiled in [http://synfig-docs-dev.readthedocs.io/](http://synfig-docs-dev.readthedocs.io/) .

---

<div class="post-metadata">

### Author: ![BobSynfig](https://forums.synfig.org/user_avatar/forums.synfig.org/bobsynfig/32/175_2.png) [@BobSynfig](https://forums.synfig.org/u/BobSynfig)
#### Post date: [March 27, 2022, 10:06am UTC](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/2 "2022-03-27T10:06:31Z")

</div>

Recurrent debate, see argumentation here on the “dangers”

> <https://github.com/synfig/synfig/issues/1690>
>
> \*\*Synfig version & platform\*\*:
> Building from source
> Debian sid
> 
> \*\*Issue desc…ription\*\*:
> Synfig C++ source codes use tabs for indentation and some build scripts use spaces. This is annoying because I've configured my IDE to only insert tabs when tab key is pressed. That also means if I mistakenly use spacebars to indent... the IDE will autocorrect my mistakes.
> 
> Currently, I'm having trouble with existing synfig CMake scripts that are indented using space characters. To add new code I have to use another text editor to launch the script and edit my changes because QtCreator thinks I'm making a mistake unintentionally using spaces for indentation. So it keeps correcting my space characters to tabs.
> 
> I think all synfig text source files must use a uniform whitespace standard. Either tab or space but not a hybrid.

For me the most problematic is a kind of obsession in “optimizing” the source code.  
Complex conditional expressions or constructors as parameters in functions…

Instead it could be decomposed in several lines, introducing temporary variables, to make it more readable and mistakes more obvious.

I used to be an industrial developer having to maintain and adapt neither documented nor commented copy-pasta source with thousands of lines per function that my colleagues didn’t even want to touch, scared to introduce side-effects.  
A clearer code avoids this, indentation and vertical alignment to make look the code like a musical partition.  
It also means avoiding auto-linting 😛

> <https://softwareengineering.stackexchange.com/questions/203684/is-fewer-lines-of-code-always-better/203686#203686>

For example, what about to extract the calculations from this matrix:

> <https://github.com/synfig/synfig/commit/1d1a2ebef9ceec4c67b0d98012445f827dee4d90>

So for me the most important is readability and simplicity.

---

<div class="post-metadata">

### Author: ![rodolforg](https://forums.synfig.org/letter_avatar_proxy/v4/letter/r/c68b51/32.png) [@rodolforg](https://forums.synfig.org/u/rodolforg)
#### Post date: [March 27, 2022, 6:05pm UTC](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/3 "2022-03-27T18:05:20Z")

</div>

Yes, `tab` vs. space promotes wild debates. I won’t go through it. lol Mainly because almost every Synfig file uses `tab`. Only some lines here and there were mixed with spaces. Better leave this discussion for the future, if needed.

Other points I think we don’t need to discuss (at least for now) are file name extensions (.h, .hpp, .cc, .cpp, …) and C++ version, for example.

---

<div class="post-metadata">

### Author: ![rodolforg](https://forums.synfig.org/letter_avatar_proxy/v4/letter/r/c68b51/32.png) [@rodolforg](https://forums.synfig.org/u/rodolforg)
#### Post date: [March 27, 2022, 8:48pm UTC](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/4 "2022-03-27T20:48:49Z")

</div>

**About Header files**

- They must be [idempotents](https://docs.oracle.com/cd/E19059-01/wrkshp50/805-4955/z4000053ad9/index.html), i.e. they must have [include guards](https://en.wikipedia.org/wiki/Include_guard)

- They must be [self-contained](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#sf11-header-files-should-be-self-contained)

- At the same time they must be self-contained, they must `#include` only what is needed to be compiled by itself

- About the include guard: the `#define` symbol must not start with double underscore, as it is reserved [[1]](https://en.cppreference.com/w/cpp/language/identifiers) [[2]](https://www.doc.ic.ac.uk/lab/cplus/c++.rules/chap5.html) [[3]](https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier)

_Poll ([view on site](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/4))_

Other existent problem is that they are not consistent for the `synfig-studio/src/gui` files.

- `ETL` uses ` __ETL__ XXXXX_H`
- `synfig-core` uses `__SYNFIG_XXXXX_H`
- `synfig-studio/src/synfigapp` uses `__SYNFIG_APP_XXXXX_H`
- `synfig-studio/src/gui` mixes ` __SYNFIG_STUDIO_GTKMM_XXXXX_H`, `__ SYNFIG_GTKMM_XXXXX_H` and `__SYNFIG_STUDIO_XXXXX_H`.

Second poll is: **What should be the identifier style used for Synfig Studio GUI?**

_Poll ([view on site](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/4))_

Finally, `#include` order: alphabetically or categorized like [Google Code Style proposes](https://google.github.io/styleguide/cppguide.html#Names_and_Order_of_Includes):

> Include headers in the following order: Related header, C system headers, C++ standard library headers, other libraries’ headers, your project’s headers.

_Poll ([view on site](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/4))_

@ice0 @BobSynfig @KonstantinDmitriev@Keyikedalube @FirasH

---

<div class="post-metadata">

### Author: ![Keyikedalube](https://forums.synfig.org/user_avatar/forums.synfig.org/keyikedalube/32/7725_2.png) [@Keyikedalube](https://forums.synfig.org/u/Keyikedalube)
#### Post date: [March 28, 2022, 6:31am UTC](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/5 "2022-03-28T06:31:29Z")

</div>

> [@rodolforg](#):
>
> Currently, there are many of Code Styles used by many (modern) C++ projects, like [Coding Guidelines | Haiku Project](https://www.haiku-os.org/development/coding-guidelines), [Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html) and [Code Style Guidelines | WebKit](https://webkit.org/code-style-guidelines).
> 
> This topic is about building our own code style or following one of the existent ones to be used on new code contributions/commits and, in a future or hypothetical dream, on the entire Synfig code.

I skimmed through the pages you linked above.

- **Google C++ Style Guide** is comprehensive and a good should-read for C++ devs.
- **Guidelines | Haiku Project** is visually appealing for C++ coders. Readability is prioritized. It is similar to [GTK C Coding Style](https://developer-old.gnome.org/programming-guidelines/stable/c-coding-style.html.en)
- **Code Style Guidelines | WebKit** is the one I am most familiar with. Easy because I’m using most of the default automatic indentation done by my IDE without having to worry too much about maintaining extra column spacings like GTK C or Haiku style.

Based on my experience contributing to Synfig GUI end I think most of the Webkit style can be implemented with a little mix of Haiku for column spacings since GTKMM tend to have lengthy identifier types

```c++
	Gtk::Grid *grid_content;
	Gtk::Grid *grid_canvas;
	Gtk::SpinButton *width;
	Gtk::SpinButton *height;
	Gtk::EventBox *canvas_label;
	Gtk::CheckButton *canvas_only;

```

---

<div class="post-metadata">

### Author: ![rodolforg](https://forums.synfig.org/letter_avatar_proxy/v4/letter/r/c68b51/32.png) [@rodolforg](https://forums.synfig.org/u/rodolforg)
#### Post date: [April 2, 2022, 1:10pm UTC](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/6 "2022-04-02T13:10:49Z")

</div>

Still about header files, Synfig has templates for [header](https://github.com/synfig/synfig/blob/master/synfig-core/src/template.h) and [implementation](https://github.com/synfig/synfig/blob/master/synfig-core/src/template.cpp) files.

They present comment lines to visually help the file ‘sections’ and to guide the contents (like methods/variables/signals) order. Some class header files have more ‘sections’.

```c++
/* === H E A D E R S ======================================================= */

/* === M A C R O S ========================================================= */

/* === T Y P E D E F S ===================================================== */

/* === C L A S S E S & S T R U C T S ======================================= */

```

_Poll ([view on site](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/6))_

# Indentation

Moving to next topic: indentation. I won’t start a discussion about the `TAB` vs. `spaces` (at least for now) XD  
I’ll focus on how to indent stuff:

1. Namespaces and its contents:  
Do not indent. [Google](https://google.github.io/styleguide/cppguide.html#Namespace_Formatting), [Webkit](https://webkit.org/code-style-guidelines/#indentation-namespace) and [Haiku](https://www.haiku-os.org/development/coding-guidelines) follow this rule.  
Good example:

```c++
namespace synfig {

class BLinePoint : public UniqueID
{
};

}

```

Bad example:

```c++
namespace synfig {

	class BLinePoint : public UniqueID
	{
	};

}

```

_Poll ([view on site](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/6))_

1. Regarding **switch** statements, the **case** label should be indented according to [Google](https://google.github.io/styleguide/cppguide.html#Loops_and_Switch_Statements) and Haiku, but not according to [WebKit](https://webkit.org/code-style-guidelines/#indentation-case-label) and [Qt](https://wiki.qt.io/Qt_Coding_Style#Switch_statements).

WebKit and Qt style:

```c++
switch (condition) {
case fooCondition:
case barCondition:
    i++;
    break;
default:
    i--;
}

```

Google and Haiku style:

```c++
switch (condition) {
    case fooCondition:
    case barCondition:
        i++;
        break;
    default:
        i--;
}

```

_Poll ([view on site](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/6))_

Haiku and [WebKit](https://webkit.org/code-style-guidelines/#names-data-members) do not suggest to indent class access modifiers (`public`, `protected` and `private`). Google, however, [explicitly says they should be indented by one single space](https://google.github.io/styleguide/cppguide.html#Class_Format).

_Poll ([view on site](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/6))_

---

<div class="post-metadata">

### Author: ![rodolforg](https://forums.synfig.org/letter_avatar_proxy/v4/letter/r/c68b51/32.png) [@rodolforg](https://forums.synfig.org/u/rodolforg)
#### Post date: [April 9, 2022, 6:22am UTC](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/7 "2022-04-09T06:22:38Z")

</div>

Sorry, but I’ll ping you again XD @ice0 @BobSynfig @KonstantinDmitriev @Keyikedalube @FirasH

---

<div class="post-metadata">

### Author: ![rodolforg](https://forums.synfig.org/letter_avatar_proxy/v4/letter/r/c68b51/32.png) [@rodolforg](https://forums.synfig.org/u/rodolforg)
#### Post date: [April 9, 2022, 12:56pm UTC](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/8 "2022-04-09T12:56:19Z")

</div>

# Spacings

(This post is very inspired from [WebKit docs](https://webkit.org/code-style-guidelines/#spacing)), reusing some texts and examples from them.

### Unary Operators

- Do not place spaces around unary operators ([WebKit](https://webkit.org/code-style-guidelines/#spacing-unary-op), [Google](https://google.github.io/styleguide/cppguide.html#Horizontal_Whitespace), others do not say explicitly):

###### Right:

```auto
i++;
if (!b) {}

```

###### Wrong:

```auto
i ++;
if (! b) {}

```

### Assignment, Binary and Ternary Operators

- Do place spaces around assignment, binary and ternary operators?
  - Always: [WebKit](https://webkit.org/code-style-guidelines/#spacing-binary-ternary-op), [Haiku (`Always separate operators with a space on both sides, and use a space after comma.`)](https://www.haiku-os.org/development/coding-guidelines)

```auto
y = m * x + b;
c = a | b;
return condition ? 1 : 0;

```

- Usually: not mandatory for factors (product and division may be like `a*b`, and not necessarily `a * b`) ([Google](https://google.github.io/styleguide/cppguide.html#Horizontal_Whitespace))

```auto
y = m*x + b;
f(a, b);
c = a | b;
return condition ? 1 : 0;

```

- Never for assignment and binary operators (original Synfig code, but now it’s mixed with previously mentioned styles.)

```auto
y=m*x+b;
c=a|b;
return condition? 1 : 0;

```

_Poll ([view on site](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/8))_

_Poll ([view on site](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/8))_

### Commas and semicolons

- **Do** place space **before** comma and semicolon?
  - Never: [WebKit](https://webkit.org/code-style-guidelines/#spacing-comma-semicolon)

###### Right (WebKit):

```auto
for (int i = 0; i < 10; ++i)
    doSomething();

f(a, b);

```

###### Wrong (WebKit):

```auto
for (int i = 0 ; i < 10 ; ++i)
    doSomething();

f(a , b) ;

```

- Usually not: [Google](https://google.github.io/styleguide/cppguide.html#Horizontal_Whitespace) (see “General” and “Loop and Conditionals” subsections)

```auto
// For loops always have a space after the semicolon. They may have a space
// before the semicolon, but this is rare.
for ( ; i < 5 ; ++i) {
  ...

```

_Poll ([view on site](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/8))_

- **Do** place space **after** comma and semicolon?
  - Mandatory for [WebKit](https://webkit.org/code-style-guidelines/#spacing-comma-semicolon);
  - Haiku only says explicitly for comma;
  - Google incentives it [[1]](https://google.github.io/styleguide/cppguide.html#Conditionals) [[2]](https://google.github.io/styleguide/cppguide.html#Horizontal_Whitespace);
  - In this case, [Qt style](https://wiki.qt.io/Qt_Coding_Style#Whitespace) follows Haiku vagueness.

So I won’t make a poll here.

### Inside Braces and Parenthesis

_Poll ([view on site](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/8))_

_Poll ([view on site](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/8))_

### Lambda functions/expressions

_Poll ([view on site](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/8))_

---

<div class="post-metadata">

### Author: ![ice0](https://forums.synfig.org/user_avatar/forums.synfig.org/ice0/32/4612_2.png) [@ice0](https://forums.synfig.org/u/ice0)
#### Post date: [April 10, 2022, 4:36am UTC](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/9 "2022-04-10T04:36:37Z")

</div>

> [@rodolforg](#):
>
> They present comment lines to visually help the file ‘sections’ and to guide the contents (like methods/variables/signals) order. Some class header files have more ‘sections’.

As you can see (from the vote count), no one knows which is better. Perhaps it’s better to leave it as is. Just like one unique Synfig style feature?

---

<div class="post-metadata">

### Author: ![BobSynfig](https://forums.synfig.org/user_avatar/forums.synfig.org/bobsynfig/32/175_2.png) [@BobSynfig](https://forums.synfig.org/u/BobSynfig)
#### Post date: [April 10, 2022, 6:06am UTC](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/10 "2022-04-10T06:06:41Z")

</div>

To have general rules is not a bad thing but source code is written by humans for humans and need to keep a bit of humanity too.  
It’s not just to set a linter and it has to keep a bit of logic, air and poetry.

For example, here is how I code (yeah, VueJS, but you can catch what I mean)

```auto
this.details.lines.forEach( item => {
  if (!item.editingBarcode) this.$set(item, 'editingBarcode', false )
  if (!item.barcodeModel ) this.$set(item, 'barcodeModel', item.barcode)
  if (!item.editingQty ) this.$set(item, 'editingQty', false )
  if (!item.qtyModel ) this.$set(item, 'qtyModel', item.qty )
  if (!item._showDetails ) this.$set(item, '_showDetails', false )
})

```

Try to set a rule for this 😛

---

<div class="post-metadata">

### Author: ![rodolforg](https://forums.synfig.org/letter_avatar_proxy/v4/letter/r/c68b51/32.png) [@rodolforg](https://forums.synfig.org/u/rodolforg)
#### Post date: [April 21, 2022, 9:24pm UTC](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/11 "2022-04-21T21:24:37Z")

</div>

## Naming

### cases

Current convention on Synfig’s code is:

- classes/structs: CamelCase
- ~~unions: CamelCase~~ (we don’t have any named union)
- enumeration type: CamelCase
- enumeration values: UPPERCASE → snake\_case
- variables/properties: snake\_case
- functions/methods: snake\_case
- constants: UPPERCASE → snake\_case
- macros: UPPERCASE
- ‘templated’ types in ETL templates: snake\_case (e.g. `value_type`)

My suggestion is to change the case of constants and enumeration values to `snake_case`.  
Reasoning: avoid clashes with macros.  
Example: deprecated Gtk::Stock has a value named `DELETE`, but it clashes with a macro defined in MS Windows headers. Solution was a hack:

> <https://github.com/synfig/synfig/blob/05f51084218d75c4317a7c9533dcc0a756b052b7/synfig-studio/src/gui/iconcontroller.cpp#L450-L468>

The usage of lower case is supported by ISO-C++ foundation for [enums](http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Renum-caps) and [constants](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rl-all-caps).

_Poll ([view on site](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/11))_

_Poll ([view on site](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/11))_

### Prefixes/suffixes

#### enum values:

_Poll ([view on site](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/11))_

#### private/protected class variables:

To avoid [shadowing](https://en.wikipedia.org/wiki/Variable_shadowing) and some compiler and logic issues besides worse readability in some cases, sometimes private variables/properties of a class have `m_` as a prefix (e.g. `m_my_var`) or a `_` as a suffix (e.g. `my_var_`) in Synfig code. Sometimes it simply allows variable shadowing (e.g. `my_var`).

Another opensource project written in C++, Godot Engine prefers to solve it by prepending `p_` to method **p** arameter names:

> <https://github.com/godotengine/godot/blob/f4b0c7a1ea8d86c1dfd96478ca12ad1360903d9d/core/io/dir_access.cpp#L131-L135>

_Poll ([view on site](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/11))_

---

<div class="post-metadata">

### Author: ![BobSynfig](https://forums.synfig.org/user_avatar/forums.synfig.org/bobsynfig/32/175_2.png) [@BobSynfig](https://forums.synfig.org/u/BobSynfig)
#### Post date: [April 22, 2022, 12:13am UTC](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/12 "2022-04-22T00:13:46Z")

</div>

I’m not sure that we will get new contributors if they have to assimilate and apply so many rules in addition of learning the global architecture of the application which is, let’s admit it, still poorly documented…

We need diagrams to understand the code, not to scare people 😛

> **[Too many rules will kill creativity and talent](https://www.linkedin.com/pulse/too-many-rules-kill-creativity-talent-paul-takken)**
>
> The reaction from the Dutch F1 driver Max Verstappen after the USGP stating his penalty was killing F1 feels exaggerated and too emotional to many “old and wise” people. In my opinion, the events of last weekend are a clear signal something is...

> **[Secret Productivity Killer: Too Many Rules in the Workplace - TalentCulture](https://talentculture.com/secret-productivity-killer-too-many-rules-in-the-workplace/)**
>
> Workplace rules ensure correct work and proper employee treatment but too many rules make employees feel undervalued. Here are tips for finding a balance.

[![](https://i.imgflip.com/6del2t.jpg) ](https://i.imgflip.com/6del2t.jpg)  
[![](https://i.imgflip.com/6demp1.jpg) ](https://i.imgflip.com/6demp1.jpg)

---

<div class="post-metadata">

### Author: ![rodolforg](https://forums.synfig.org/letter_avatar_proxy/v4/letter/r/c68b51/32.png) [@rodolforg](https://forums.synfig.org/u/rodolforg)
#### Post date: [April 22, 2022, 2:03am UTC](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/13 "2022-04-22T02:03:53Z")

</div>

> [@BobSynfig](#):
>
> I’m not sure that we will get new contributors if they have to assimilate and apply so many rules

Sadly we have so few for years even without any code style actually set.  
Anyway this isn’t the aim on setting our code style.

> [@BobSynfig](#):
>
> apply so many rules

About the number of rules: they are not so many yet. Many of them are well-established in Synfig code.  
Anyway, we can use technology on our side: source code editors have template styles and code refactoring; there are code ‘formatters’ like [ClangFormat](https://clang.llvm.org/docs/ClangFormat.html), and we can use them via git pre-commit hooks, GitHub actions, etc. so we don’t spend too much time on it and still succeed on getting the code easy to read and avoiding some traps.

---

<div class="post-metadata">

### Author: ![rodolforg](https://forums.synfig.org/letter_avatar_proxy/v4/letter/r/c68b51/32.png) [@rodolforg](https://forums.synfig.org/u/rodolforg)
#### Post date: [April 22, 2022, 2:07am UTC](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/14 "2022-04-22T02:07:19Z")

</div>

> [@BobSynfig](#):
>
> the global architecture of the application which is, let’s admit it, still poorly documented…

Yes, it is. Not too difficult to admit it ☹

---

<div class="post-metadata">

### Author: ![BobSynfig](https://forums.synfig.org/user_avatar/forums.synfig.org/bobsynfig/32/175_2.png) [@BobSynfig](https://forums.synfig.org/u/BobSynfig)
#### Post date: [April 22, 2022, 6:29am UTC](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/15 "2022-04-22T06:29:50Z")

</div>

> [@rodolforg](#):
>
> there are code ‘formatters’ like [ClangFormat](https://clang.llvm.org/docs/ClangFormat.html), and we can use them via git pre-commit hooks, GitHub actions, etc.

This is precisely what I am warning about.  
Source code should be self-sufficient and well-structure, not post-processed by automated tools in order to keep the mind and structure of the original creator.  
The only tools we should rely on are the suggestions done by the IDE at write time.

About pre-exiting “style”, well…  
When I contribute, I tend to follow implicitely the conventions existing inside the original code (unless my work is precisely to restructure or refactor old code like I had in some jobs)

We should focus more on tips to newcomers like:

- Don’t make too much long lines, break in several (like in Lottie plugin, where a directive to skip line  
length check is set)
- Should we decompose long instructions into several lines to improve readability and debugging possibilities
- Should we use “Yoda conditions” to avoid to read unneeded parts of the code
- Mark regions as such (with code folding if possible
- Extract code from conditionnal structures and place them in separated functions (readability, debugging)
- Comments, comments, comments…

Too strict code formatting rules bring rigidity and “traditionnal” copy-paste-and-modify-from-StackOverflow-because-it-worked-for-someone-else mistakes.

And if really some contributions are really too badly written, we can still request politely to clean them before PR to be applied, which is great for the developer to learn and improve his skills in writing better code 😉

_P.S.: This reflects my own idea of coding, I am not deciding for the project._

---

<div class="post-metadata">

### Author: ![rodolforg](https://forums.synfig.org/letter_avatar_proxy/v4/letter/r/c68b51/32.png) [@rodolforg](https://forums.synfig.org/u/rodolforg)
#### Post date: [April 22, 2022, 10:10am UTC](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/16 "2022-04-22T10:10:11Z")

</div>

> [@BobSynfig](#):
>
> Source code should be self-sufficient and well-structure, not post-processed by automated tools in order to keep the mind and structure of the original creator.

Hmm… Not everyone writes some way expressing a poetry like you said before, but sometimes in a hurry or just a mess, mixing styles in his/her own code.

When you say “original creator” you mean “project creator”, “file creator” or “that code slice creator”? darco had a style, other contributors mixed when contributed into his files, blackwarthog (and me and others) wrote in other styles when created new files, and others than used another style in their turn.

Some projects use style formatters and they don’t screw the code up and don’t make it a barrier to contributors. Example: Godot Engine.

> [@BobSynfig](#):
>
> The only tools we should rely on are the suggestions done by the IDE at write time.

Some do, some don’t set up the IDE properly. And we would need to set up the IDE style differently depending on the file (or class method) style…

> [@BobSynfig](#):
>
> We should focus more on tips to newcomers like:

Well, like I said in previous post, that is not the reason I’m proposing a code style for this project.  
Some reasons are: consistency, readability, visual comfort, avoiding code mistakes, setting up and using a single style in the IDE/editor, etc.

For that, a minor effort from the contributor (or none) would be needed.

> [@BobSynfig](#):
>
> Comments, comments, comments…

Some many comments usually means the code is bad. 😉 Like you listed before, split into functions/lines and most comments are unneeded.

> [@BobSynfig](#):
>
> _P.S.: This reflects my own idea of coding, I am not deciding for the project._

I’m not deciding anything here 🙂 I’m collecting opinions (almost finishing it) and then I’ll propose a code style. If approved, I’ll write it down in the Dev Docs (focused on examples instead of text), create a CLangFormat style file (and other beautifiers you guys suggest), write a pre-commit git hook and, maybe, a Github action.

---

<div class="post-metadata">

### Author: ![mohamed.Adhamc](https://forums.synfig.org/letter_avatar_proxy/v4/letter/m/a88e4f/32.png) [@mohamed.Adhamc](https://forums.synfig.org/u/mohamed.Adhamc)
#### Post date: [April 22, 2022, 9:07pm UTC](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/17 "2022-04-22T21:07:24Z")

</div>

Hey guys, I’m a new contributor here so I thought I could maybe add some insight on what @BobSynfig mentioned regarding new contributors, and how all this might affect the process of having new contributors integrate into the synfig contribution process.

I personally believe that as long as most of the style stuff is post processed by an automated tool, then this shouldn’t pose any issues that would make it more difficult to get started contributing. The only case that would make it more difficult is if there were many code style practises set in place and have to be followed rigorously and manually, then it might make the process require more work from the contributors part and maybe some contributors don’t have much time or the patience perhaps. However from what it seems this is not the case, so again I don’t see this affecting new contributors in any bad way. Also in many other projects there are coding styles set for everyone to follow so the concept itself shouldn’t be too foreign to anyone new to open-source Dev or Dev in general.

These are my two cents guys, of course not all new contributors may think like this but I believe a good portion might, which is why I shared it. I hope it added something of use to this discussion 😄.

---

<div class="post-metadata">

### Author: ![rodolforg](https://forums.synfig.org/letter_avatar_proxy/v4/letter/r/c68b51/32.png) [@rodolforg](https://forums.synfig.org/u/rodolforg)
#### Post date: [May 1, 2022, 3:38pm UTC](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/18 "2022-05-01T15:38:33Z")

</div>

## Pointers and references

`char* name` or `char *name`?  
`std::string& name` or `std::string &name`?

The `*` and `&` characters must (or should) be next to the type (`char* `) rather than to the variable name (` *name`) according to [Chromium](https://chromium.googlesource.com/chromium/src/+/HEAD/styleguide/c++/c++.md#code-formatting), [C++ Core Guidelines](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#nl18-use-c-style-declarator-layout) and [WebKit](https://webkit.org/code-style-guidelines/#pointers-and-references). [Haiku](https://www.haiku-os.org/development/coding-guidelines/) does not explicitly says so, but all of its examples use this style too.  
However, other C++ coding style require the inverse: [Google coding style](https://google.github.io/styleguide/cppguide.html#Pointer_and_Reference_Expressions) (only?). [Qt](https://wiki.qt.io/Qt_Coding_Style) does not explicitly state anything about it, but its examples use this second style.

So here is the poll, split in two just in case:

_Poll ([view on site](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/18))_

_Poll ([view on site](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/18))_

## The line for Return type of functions and class methods

In Synfig code, the **implementation** files (`*.cpp)` usually (and in their majority) have the return type of functions or class methods in the line before its function/method name and parameter list.  
[Example 1](https://github.com/synfig/synfig/blob/08202f400bffb75031b907c7eab02f517ad99fef/synfig-core/src/synfig/layers/layer_bitmap.cpp#L155-L164):

```auto
Layer::Vocab
Layer_Bitmap::get_param_vocab()const
{
	Layer::Vocab ret(Layer_Composite::get_param_vocab());

	ret.push_back(ParamDesc("tl")
		.set_local_name(_("Top-Left"))
		.set_description(_("Upper left-hand Corner of image"))
		.set_is_distance()
	);

```

[Example 2](https://github.com/synfig/synfig/blob/08202f400bffb75031b907c7eab02f517ad99fef/synfig-core/src/synfig/layers/layer_bitmap.cpp#L211-L224):

```auto
inline
const Color&
synfig::Layer_Bitmap::filter(Color& x)const
{
	Real gamma_adjust(param_gamma_adjust.get(Real()));
	if(gamma_adjust!=1.0)
	{
		x.set_r(powf((float)x.get_r(),gamma_adjust));
		x.set_g(powf((float)x.get_g(),gamma_adjust));
		x.set_b(powf((float)x.get_b(),gamma_adjust));
		x.set_a(powf((float)x.get_a(),gamma_adjust));
	}
	return x;
}

```

I found some reasoning for it in [Stack Exchange](https://softwareengineering.stackexchange.com/questions/200828/reason-for-placing-function-type-and-method-name-on-different-lines-in-c).  
Some Synfig files completely ignore this style.  
What style should we follow?

_Poll ([view on site](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/18))_

## Back to indentation: preprocessor directives

Should we indent them? Like this:

```c++
#ifdef USING_PCH
# include "pch.h"
#else
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#endif

```

[Google coding style](https://google.github.io/styleguide/cppguide.html#Preprocessor_Directives) allows it (it isn’t mandatory). I could not see any other commenting about it.  
Please note it’s not about indenting the hash character (`#`), but what follows it.

_Poll ([view on site](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/18))_

After this post, there are only 3 more topics I’d like to ask about (finally!): braces, documentation and statement styles.

---

<div class="post-metadata">

### Author: ![BobSynfig](https://forums.synfig.org/user_avatar/forums.synfig.org/bobsynfig/32/175_2.png) [@BobSynfig](https://forums.synfig.org/u/BobSynfig)
#### Post date: [May 1, 2022, 5:05pm UTC](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/19 "2022-05-01T17:05:04Z")

</div>

**Return type on previous line** : Clearer and shorter lines  
**Indentation in preprocessor** : I love proper indentation 😛

**Pointers and references** : I always prefered the second form because it looks more “safe”

See [here](https://www.quora.com/What-is-the-difference-between-char*-name-and-char-*name-in-C-programming-language) the comment of Brian Overland

> There is no difference EXCEPT for the following situation. Suppose you are defining multiple pointer variables. Compare and contrast these two lines:
> 
> ```auto
> 1. char *p, *p2, *p3; // This does what you think it does.
> 2. char* p, p2, p3; // This does not do what you think it does.
> 
> ```
> 
> These two lines do very different things. The second line here declares p as a pointer variable, but p2 and p3 are not declared pointers, just ordinary variables of type **char**. This is not technically wrong (other than the fact simple variables of type char are not especially reliable or useful); it is just highly misleading.
> 
> The second style above — to put the \* closer to the type name — appears often in code but has the possibility of creating misleading declarations when declaring multiple pointer vars, as shown above.
> 
> By the way, there is a way to achieve the effect that is probably desired by that second line above. First, use typedef to create a pointer type.
> 
> `1. typedef char *CPTR;`
> 
> Now you can declare multiple pointers more efficiently:
> 
> `1. CPTR p, p2, p3;`

---

<div class="post-metadata">

### Author: ![rodolforg](https://forums.synfig.org/letter_avatar_proxy/v4/letter/r/c68b51/32.png) [@rodolforg](https://forums.synfig.org/u/rodolforg)
#### Post date: [May 1, 2022, 5:33pm UTC](https://forums.synfig.org/t/trying-to-define-our-code-style/13097/20 "2022-05-01T17:33:27Z")

</div>

> [@BobSynfig](#):
>
> `1. char *p, *p2, *p3; // This does what you think it does.`

In that case, I vote for only one variable per line, and preferable with its initialization. Otherwise it is unsafe too. 🙂 Also variable declarations next to their first use helps to avoid the mentioned problem too.

[Next page](https://forums.synfig.org/t/trying-to-define-our-code-style/13097.md?page=2)
