• Hey Guest! Ever feel like entering a Game Jam, but the time limit is always too much pressure? We get it... You lead a hectic life and dedicating 3 whole days to make a game just doesn't work for you! So, why not enter the GMC SLOW JAM? Take your time! Kick back and make your game over 4 months! Interested? Then just click here!

Coding Style

ophelius

Member
Hi,
I was just curious, looking at all the examples in GM's help file and also seeing people's code on this forum, I was wondering if the over-use and overly spaced-out distribution of curly brackets is a personal choice or a matter of not understanding that you don't always need them and they can be much more compact.

Example, I see a lot of these types of monsters:

Code:
if(x == 1)
{
   y += 1;
}
else
{
   y -= 1;
}
In case you don't know, and in case you want to have more compact code, this is all you need:

Code:
if(x == 1) y += 1;
else y -= 1;
That's 8 lines compacted into 2.

Or this for improved readibility(my prefered style):
Code:
if(x == 1)
    y += 1;
else
    y -= 1;
I mean you could even have it on 1 line:
if(x == 1) y += 1; else y -= 1;

It's only if you have more than 1 statement that you must use curly brackets to combine them all into a block of statements.

Even then I see:

Code:
if(x == 1)
{
    //multiple
    //statements
}
else
{
    //multiple
    //statements
}
You can start the curly bracket after the 'if' statement, and put the 'else' after the 'if' closing-bracket, and start the 'else' start-bracket right after
(my prefered style):
Code:
if(x == 1){
    //multiple
    //statements
}else{
    //multiple
    //statements
}
10 lines reduced to 7.

What are your thoughts? Do some people actually prefer overly spaced-out code? Is it because people assume that's how it has to be formatted to work because of the examples in the help file? Is it easier on the eyes for some?

Anyways, thanks, just wanted to share some thoughts
 
Last edited:

ophelius

Member
Option number one for readability, every day of the week for me.

Are you really that hard pressed for RAM that you need to compact it down to one line?
It's not a question of ram at all, I'm just curious if people who write it so expanded know about the alternatives. When you have a lot of code to write, it unnecessarily increases the length of your code that you have to manage/browse through. I never see code written by expert programmers like in example 1.
 
I never see code written by expert programmers like in example 1.
How about John Carmack? https://github.com/id-Software/Quake

Slapfights over coding style are ridiculous since you'll find excellent coders that use whatever style they're comfortable with. Allman (braces on separate line) and K&R (braces on same line) are far from the only coding styles. Readability is largely subjective, anyway. What is important is consistency. Don't take it from me, take it from Brian Kernighan and Dennis Ritchie, the creators of the C programming language:
The C Programming Language said:
The position of braces is less important, although people hold passionate beliefs. [...] Pick a style that suits you, then use it consistently.
 
Last edited:

FrostyCat

Redemption Seeker
The spaced-out style actually has a name, and it is pretty broadly used and not only by novices. In fact, a lot of programmers of various skill levels get quite fundamentalist about this style. Read the Wikipedia article I cited and you'll see why.

For the information, I use K&R, not Allman, so it's not like I'm trying to preach my side here.
 

ophelius

Member
How about John Carmack? https://github.com/id-Software/Quake

Slapfights over coding style are ridiculous since you'll find excellent coders that use whatever style they're comfortable with. Allman (braces on separate line) and K&R (braces on same line) are far from the only coding styles. Readability is largely subjective, anyway. What is important is consistency. Don't take it from my, take it from Brian Kernighan and Dennis Ritchie, the creators of the C programming language:
I agree with what you're saying, it's just when I see example 1 for such small lines of code taking up so much space, I just wonder if it's style or lack of understanding how the braces work. I have a very consistent style, which I stated above from the examples.
 

Evanski

Raccoon Lord
Forum Staff
Moderator
I personally use the Allman style, but lately I have seen that it takes up a lot of space and makes the code hard to read even though its spaced out to try and improve readability. But I think im going to try to transfer over to K&R, to save a few extra lines and condense them down. I've also thought about making a batch program to read through my .gml files and auto condense them down. ( i'd use that for a release and keep the source code the normal style I code in )
 
S

Sybok

Guest
Hash out some code and tell me which one makes more sense visually?



In option 1, without even knowing what the code does, you can clearly see the program flow, what sections are scope etc..
Option 2 doesn't tell you anything.
 

ophelius

Member
Hash out some code and tell me which one makes more sense visually?



In option 1, without even knowing what the code does, you can clearly see the program flow, what sections are scope etc..
Option 2 doesn't tell you anything.
Geez, of course option 1 is prefered, I wasn't stating that you should compress everything into a single line like in your 2nd example, I'm just curious why for simple cases like my example 1 people use all those lines.
My prefered style is:
Code:
if(x == 1){
    //multiple
    //statements
}else{
    //multiple
    //statements
}
 
S

Sybok

Guest
For single line comparisons, This is the way I prefer.

Code:
if(something)
     Yolo();
Other than that, option 1 all the way for me.

I'll some times even live right on the edge and put two lines between logical sections of code. :eek:
 
Last edited by a moderator:

Felbar

Member
When I am coding examples for newbies i always use the first, long form, its just easier for them to read i think.
If i am coding on a team, well usually long form unless they have a strict coding style ( they almost never do)
My own stuff , yeah i like to be as brief as possible
 

Sabnock

Member
I use this Style. It just seems to read better to me.

GML:
if (spd < 0.1 && _move == 0) {
    hspd = 0;
    vspd = 0;
} else {
    hspd +=  dcos(_reverse_dir) * deceleration_amount;
    vspd += -dsin(_reverse_dir) * deceleration_amount;
}
I also am a bit fussy how my code looks and space it out.


GML:
    // convert vertex offsets to real x,y coords and apply scale
    var _x1 = _origin_x + _vec_array[_line_array[_l    ], 0] * _scale;
    var _y1 = _origin_y + _vec_array[_line_array[_l    ], 1] * _scale;
    var _x2 = _origin_x + _vec_array[_line_array[_l + 1], 0] * _scale;
    var _y2 = _origin_y + _vec_array[_line_array[_l + 1], 1] * _scale;
But that is just becasue i am mad :)
 
Last edited:

saffeine

Member
I use K&R Style. It just seems to read better to me.

GML:
if (spd < 0.1 && _move == 0) {
    hspd = 0;
    vspd = 0;
} else {
    hspd +=  dcos(_reverse_dir) * deceleration_amount;
    vspd += -dsin(_reverse_dir) * deceleration_amount;
}
I also am a bit fussy how my code looks and space it out.


GML:
    // convert vertex offsets to real x,y coords and apply scale
    var _x1 = _origin_x + _vec_array[_line_array[_l    ], 0] * _scale;
    var _y1 = _origin_y + _vec_array[_line_array[_l    ], 1] * _scale;
    var _x2 = _origin_x + _vec_array[_line_array[_l + 1], 0] * _scale;
    var _y2 = _origin_y + _vec_array[_line_array[_l + 1], 1] * _scale;
But that is just becasue i am mad :)
also the style that i use because i like to keep things compact but still very much organised.
i also do use compact code if something uses up an insignificant number of lines that could all fit on just one:

( prepping for 2.3, hence the miscoloured keywords ;^) i can imagine this won't work immediaterly but hey, not the point here. i'll figure it out when i get there. )

it definitely does make the code longer, but i don't think people use longer code because they don't realise they can compact it, so much as they keep it long for the sake of clarity and form.
those big blocks of code can look daunting at first, but at the end of the day you can see where each block ( and the blocks nested inside ) start and end, along with the fact that you can troubleshoot a little bit faster when an IDE tells you that the error in question is on line 17 and all you have on line 17 is vsp = "12"; which is expected to be a number, not a string for example.

ultimately for me it's a question of keeping things neat and tidy, not compact.
 
Last edited:

Alice

Darts addict
Forum Staff
Moderator
I use whatever code style - K&R or Allman. Which is not to say that I'm inconsistent, but rather that different languages have different typical conventions associated with them. So I end up doing C# code in Allman style in one moment, then type some stuff in K&R style in some piece of JavaScript/TypeScript I need to modify. All this switching almost makes me dizzy. Almost.

When it comes to GML, I think I tend to use K&R, though I might end up occasionally using Allman as well. Maybe it depends on whichever language I coded a lot in recently...?

I am pretty consistent when it comes to keeping the block statement header (if/while/with/etc.) separate from the subsequent inner statement, even if the inner statement is a short one-liner. That way I won't miss the statement as easily as I otherwise would, and also I don't need to glance further to the right just to read what happens inside the block. But that's me.
 

Sabnock

Member
I break long function code down over several lines as well. It just makes it so much more readable and when it is all compiled the compiler deals with and removes all of the spaces and carriage returns anyway. I can't get away from the (good imo) practice of ending lines, or paragraphs of code with a semicolon though. Even though GML lets you get away with it think it is still good for the soul. I still see people missing them off and it makes my OCD twitch lol.
 
Last edited:

Yal

🐧 *penguin noises*
GMC Elder
I've seen production bugs - in code made by a boring app code company with bald old men making most of the code, not some GM "copy Shaun's tutorials indiscriminately" hobbyist project run by people that got their GM licenses the same week, mind - caused by someone indenting but not bracing a line and then someone else sneaking in another statement without adding braces, and you'd be surprised how much time it takes to find one of these issues if the compiler thinks it's valid and reasonable. Do yourself a favor and always use braces, even if you don't need them. It also has the benefit that you don't need to think about whether you need the braces or not, cuz you're always gonna; letting you spend that brainpower on, you know, not having bugs in the first place.
 
S

Sybok

Guest
I do the same thing actually. I don't think I've ever used 'else if' in my life.
 

Nocturne

Friendly Tyrant
Forum Staff
Admin
This makes me feel good knowing that a revered programmer uses the same style I do... :p

Is it because people assume that's how it has to be formatted to work because of the examples in the help file?
Having seen some of the shockingly formatted code people post here on the forum, I don't think the manual influences things very much at all! I should note too that the Whitesmith style was chosen for the manual specifically because of the clarity that it gives when it comes to visualising code flow and structure. It's also the style that I personally prefer as I like to be able to see the code "pattern" from just glancing at a code block and know pretty much immediately how things flow without actually getting into the specifics of the code. It's like it has more "breathing room", and also makes it easier to edit if you need to go back and add stuff later (imho).
 
Z

zendraw

Guest
i dont really see coding as style, just whats better, to look at and convinient. sometimes a more compact code is more convenient, sometimes a more spaced code is more convenient. if instance in a switch i wuld generally go for more compact code, in a nested if, i wuld go for readability. but it aways varies, nothing is written on stone. good practice is to be flexible and not just enforce a certain type of coding just for the sake of it. this aint street racing.
 

samspade

Member
As most people have said, consistency is much more important than any given style, though I would recommend picking a style that is in common use rather than trying to come up with your own from scratch. I'd also recommend using different styles if you are just starting. Use a different style in each project for awhile. You'll learn interesting things.

Like for example, the reason I don't use Allman is that while it looks and reads really nice if you have a lot of indented lines, if you only have one line after an if statement your code gets cluttered really fast (in my opinion). Personally, I really like the way the lisp style looks in theory, but I tried using it in a project and kept making mistakes with brackets and was annoyed every time I tried go back and edit code and had to count how many brackets were at the end of indents. And whitesmiths just looks ugly to me (no offense to the manual).

If you really want to go down a rabbit hole, go to YouTube and search for code style videos. Or do the same on Google. You can find all sorts of fun arguments about the one to way to write code and why everyone else is insane and crazy.
 
This makes me feel good knowing that a revered programmer uses the same style I do... :p
*used 😉

Also goes to show that your style will change over the years. If you make too many negative comments about x style, you'll just make yourself look like a complete fool later down the line when you're using it 😉
 
Well seeing as I'm still new here I'll contribute what I do at the moment as I tend to try and write in my own way than just be a spoon fed copy and paste kinda coder.

GML:
///@desc Pandemic

// Hungry 
with (McDonald's) {
     if (is_closed) {
        buyburgers = true;
        Dir = point_direction(x,y,o_supermarket);
        Money = whatever_you_have;
        Go_There = (Dir + buyburgers) div Money;
       }
      if (!is_closed) {
        buyburgers = false;
        buyMcFlurry = true;
        Dir = point_directiom(x,y,o_McDonald's);
        Money = CreditCard1;
        Go_There = (Dir + buyMcFlurry) div Money;
        }
}

If Money = 0 { instance_destroy(); }
 

kburkhart84

Firehammer Games
Carrmack and I agree pretty much. The one thing I see Carmack doing that I don't typically do is tabbing over on variable declaration lists to even up the names, and the same on #defines.

Code:
int      a;
float    b;
I would just put the single space and not let things line up. I also see on if statements with single-lines Carmack doesn't seem to use curly braces, but of course has to on multiple lines. I do the same thing.

In general, I prefer my code nice and spaced out(except that making names line up on tab-stops seems more extreme than what I need). I have no issue with it being more lengthy, etc... I AM a fan of "early-outs" though, which can make things easier.

Code:
if(some_condition)
    return value;
//keep going
Since the function returns right there anytime that condition is true, there is no need for an else statement, curly braces, etc...
 

Yal

🐧 *penguin noises*
GMC Elder
Carrmack and I agree pretty much. The one thing I see Carmack doing that I don't typically do is tabbing over on variable declaration lists to even up the names, and the same on #defines.
Add me onto the list as well, I'm incredibly particular about lining everything up neatly with tabs. Even with SublimeText's multi-line editing support, any sort of batch change on a whole block of similar code gets a million times easier if it's neatly lined up... and it gets easier to read as well, which means it's easier not just to find bugs, but also not create them in the first place.

I usually even introduce extra spaces mid-code as well if it lets me align things more neatly, as you can see in this code from my current project:

1590270752361.png

Also you wouldn't believe how smug I am about that comment just happening to line up perfectly with the code as well x3
 

kburkhart84

Firehammer Games
Yeah, I line up "scopes" as far as inside and outside nestings of curly braces...but when I coded in C++ where you declare variables by types I never messed with lining the names of those onto tab stops. It would be similar to doing the following in GML.

Code:
value =     5;
value2 =    6;
val =       7;
I think that's a little more extreme than I care for. But as far as lining up groups of code statements evenly inside their brackets, and having each nested bracket set be tabbed over one stop, always.

Code:
if(something)
    doSomething();
if(somethingElse)
{
    doSomeMore();
    etc();
    if(lastCondition)
    {
        doTheseThings();
        doThoseThings();
    }
}
 

Khao

Member
Hello, I'm messy.

Code:
if input_check_pressed(global.player_controller[player],"ultimate") && ((global.ult_power[player]>=100*global.rule_ultimate_cost && global.rule_ultimate_method="meter") || (global.energy[player]>=100*global.rule_ultimate_cost && global.rule_ultimate_method="energy")) && hurt=0 {ult=1}
        if ult=1
        {
            scr_player_stat_gain(player,Stats.UltimatesUsed,1)
            with obj_player_dash_afterimage{instance_destroy()}
            scr_play_sound_gain(sfx_ultimate_cast,10,0)
            hzpeed=0
            vzpeed=0
            global.time_shift=0.1*global.rule_game_speed
            global.time_shift_length=70
            with obj_camera
            {
                x_goal=other.x
                y_goal=other.y
                scale_goal=0.5
                reset=70
                focus=80
            }
            instance_create_depth(x,y,depth+5,obj_darken)
            global.ult_power[player]-=100*global.rule_ultimate_cost
            if global.rule_ultimate_method="energy"{global.energy[player]-=100*global.rule_ultimate_cost}
            ult=2
            enough_to_ult=0
            press_dash=0
            press_shoot=0
   
            dash=0
   
            shooting=500
   
            attacking=0
            sprite_index=ultimate_sprite
            image_index=0
            charge_level=0
        }
This is probably the worst example, but I mix styles on the same block. I don't tab. I don't even put spaces after commas or other types of symbols. I have humongous conditions in a single line. I use more variables than I probably need and place them like anywhere I don't need to order them go away. Also what the hell is a semicolon.

I'll make things prettier if I know someone I'm working with is going to modify it sometime. But otherwise I just do whatever, hahaha. I honestly can't imagine staying consistent with a single style through an entire freaking project.

And hey, in my defense, I'm kinda not a programmer. I've just been using game maker for a long time, hahaha.
 

gkri

Member
I omit ( ) if possible, also I like "not" instead of "!", "or" instead of "||" and "and" instead of &&

GML:
if a == b  do_something();
 else  do_something_else();

if not instance_exists(o_obj)  do_something();
Speaking of code formating, is there an external code editor suitable for GMS2 that worth checking out?
 

Cpaz

Member
Working with C++ and Java has hardened me to conform with some fairly standard syntax and formatting standards.

GML:
var thingIsTrue = false
Var DoThing = function() {};
DoOtherThing = function () {};

if (thingIsTrue) {
    DoThing();
} else {
    DoOtherThing();
}
Speaking of code formating, is there an external code editor suitable for GMS2 that worth checking out?
I think the only thing remotely close at the moment is GMEDIT: https://yellowafterlife.itch.io/gmedit
 

curato

Member
When I went to school, pascal was a thing so I Allman is what looks natural to me. Something about how the brackets line up with the statement above to contain the code that I find satisfying.
 

Simon Gust

Member
I like to keep lines the same length if possible
GML:
if (variable == 0) 
{
    text = "var = 0";
}
else
{
    if (variable > 0) text = "var > 0";
    else
    if (variable < 0) text = "var < 0";
}
And keep similar kinds of lines in the same depth
GML:
for (var i = x1; i < x2; i++) {
for (var j = y1; j < y2; j++) {
    if (abs(i-X) + abs(j-Y) < radius) 
    {
        // and so on
    }
}}
 

Rob

Member
I'm perfectly fine with using as few lines as possible for code but not if it sacrifices readability, so I'll always use variables for drawing coordinates, for example.
 

Tony Brice

Member
I use this Style. It just seems to read better to me.

GML:
if (spd < 0.1 && _move == 0) {
    hspd = 0;
    vspd = 0;
} else {
    hspd +=  dcos(_reverse_dir) * deceleration_amount;
    vspd += -dsin(_reverse_dir) * deceleration_amount;
}
I also am a bit fussy how my code looks and space it out.


GML:
    // convert vertex offsets to real x,y coords and apply scale
    var _x1 = _origin_x + _vec_array[_line_array[_l    ], 0] * _scale;
    var _y1 = _origin_y + _vec_array[_line_array[_l    ], 1] * _scale;
    var _x2 = _origin_x + _vec_array[_line_array[_l + 1], 0] * _scale;
    var _y2 = _origin_y + _vec_array[_line_array[_l + 1], 1] * _scale;
But that is just becasue i am mad :)
Well, I'm mad too then. As is my buddy who's coding style I adapted to so we could work together better.

I'm not so liberal with the spacing but the brackets use is definitely my preference. This code style is very readable to me.
 

poliver

Member
I stick with Allman when working in GameMaker or C type language, single action ifs split on two lines. and if multiple variables are declared I like to 'group' the declaration and assignment parts separately.
4 space indents (no tabs)
It just looks cleanest and easiest to scan the code though it takes up much more space then K&R. I prefer camelCase over GameMaker common underscore 'obj_name' type of naming.
I also always indent inner blocks equally with no compromises.


GML:
//Allman Indentation
while (x == y)
{
    something();
    somethingelse();
}

//simple ifs like this
if (something)
    doThis();

//or like this if there's a cluster of semantically similar statements (ignore dots, can't type spaces here for some reason)
if (somesdf <= sda) doThis();
if (sod == ba)..... doThis();

//regular if/else
if (smtn)
{
    doThis();
}
else
{
    doThis();
}

//variable declarations (ignore dots, can't type spaces here for some reason)
var232... = 'some value';
dsadkj454 = 2343;
sdad344.. = 43;
As I said this is my preferred way of working in GameMaker or C++

when it comes to javascript I tend to stick to K&R and camelCase cause that's how everyone does it. That's what all the documentations are like etc. and it looks similar to cascading markup nature of html/xml.
I don't like it in gamemaker cause it makes it look to labyrinthian and harder to scan at a glance.

Code:
if (something) {
    doThis();
}
else {
    doElse();
}
what I vehemently dislike is how in most Gamemaker documentation they use Whitsmiths?

Code:
if (x == y)
    {
    something();
    somethingelse();
    }
this indent style just triggers me for some reason, lol
I can kinda see how it makes for better readability, but it's just so uncommon that it feels very weird

i remember when I had just started with Gamemaker i used to do something like this

Code:
if (x == y)
    {
        something();
        somethingelse();
    }
 
Last edited:
Top