00:00
00:00
Newgrounds Background Image Theme

Our goal is for Newgrounds to be ad free for everyone! Become a Supporter today and help make this dream a reality!

Coding Style - unnecessary spaces

1,210 Views | 18 Replies
New Topic

Coding Style - unnecessary spaces 2020-06-26 01:46:43


Why do people sometimes write code like this


myfunction (parameter)


instead of this?


myfunction(parameter)


It's a bit of a peeve and it's applicable to many programming languages as both tend to be valid from a compiler or interpreter's point of view in many cases and for most languages (though specifics do depend on specific language and compiler/interpreter in question, of course).


The thing is, it doesn't add anything useful. Does it make the program easier to understand? No. Does it make the source code easier to read? No. Does it add any benefit to the resulting executable? No. So why even do it? It's not wrong, but why?


If you have multiple parameters, one could make a case that


myfunction(parm1, parm2, parm3)


looks better than


myfunction(parm1,parm2,parm3)


Though both are usually equivalent. So okay, in the parameter list, optionally include a space between them if you like, or don't, fine, just be consistent.


But why would you do this?


myfunction (parm1, parm2, parm3)


or worse


myfunction (parm1,parm2,parm3)


or even worse


myfunction (parm1,parm2, parm3)


(Insert picture of Jackie Chan making that "But why?" face)

Response to Coding Style - unnecessary spaces 2020-06-29 00:16:20


#python3

print(                                                                            'IT'                   ,                             'IS'                    ,             'THE'                  ,                 'ONLY'             ,            'WAY'                 ,              'I'                           ,                       'KNOW'                     ,                'HOW'                                            )

Response to Coding Style - unnecessary spaces 2020-06-29 01:06:53


At 6/29/20 12:16 AM, EternalJudge wrote: #python3
print(                                                                            'IT'                   ,                             'IS'                    ,             'THE'                  ,                 'ONLY'             ,            'WAY'                 ,              'I'                           ,                       'KNOW'                     ,                'HOW'                                            )


Do people actually code like this? Outside of some "Intentionally code badly" competition or something?

Response to Coding Style - unnecessary spaces 2020-06-29 14:44:29


I put space after a comma for the same reason I put space after comma in plain text, around operators, in comments.

int a = 1 + 2 + calculate(numberA, numberB); // more readable

Maybe not always, if it's more readable without the space.

list = [1,2,3,4,5];


Before function parenthesis it definitely looks weird, but I'd accept it if it was justified in some way.


For example, in Ruby, you can write arguments without parentheses (and it's the recommended way).

puts "Hello world!"
puts "Bankrupt" unless balance > 0.0

But you can also feed an entire block to a function, and I'd use a space there (and inside the block).

('a'..'z').each { |letter| puts letter }


In functional programming, you pass functions to functions, "chain" them, use them as operators, so it makes a lot of sense to always use space, because a function can be used without its arguments.

map (negate . abs) [5,-3,-6,7,-3,2,-19,24]  # use 'abs', then 'negate' on each element of the list
>> [-5,-3,-6,-7,-3,-2,-19,-24]


In "regular" iterative languages, the reason for extra space might be for better layout, e.g. C#'s Linq:

people.First()
      .Select(p => p.children)
      .Where(ch => ch != 0 && ch.Length > 0)
      .ToList()
      .ForEach(Console.WriteLine); // Display the names of children of the first person in the list

Still, a space before function parenthesis would look weird, but I guess it's a question of style.

Response to Coding Style - unnecessary spaces 2020-06-29 21:23:12


At 6/29/20 02:44 PM, RaIix wrote: I put space after a comma for the same reason I put space after comma in plain text, around operators, in comments.
Maybe not always, if it's more readable without the space.


I usually do too. That said, don't mix and match. If you're going to put spaces after commas, put them after every comma. Otherwise don't use them at all.


Before function parenthesis it definitely looks weird, but I'd accept it if it was justified in some way.


Well this one is the biggie. It's not incorrect from a compiler's perspective, but it just is completely unnecessary and looks bad. It is definitely a style thing. But, for example, perusing through various C and C++ code, and I'm occasionally finding it.


I just don't understand why you would do "function ();" instead of "function();" and likewise if it had variables and so forth.


There are also various style guidelines as far as braces go, but I usually find that people are pretty consistent with that. They'll pick something and stick with it for everything.


I prefer the version that's like

int function(){

//stuff

}


but if you prefer


int function()

{

//stuff

}


that's also fine.


It uses up too much vertical screen space is why I don't do it that way, but some people do. If you only or primarily use a code-folding IDE or such, then it probably doesn't matter as much. I primarily do things from the command line.


For example, in Ruby, you can write arguments without parentheses (and it's the recommended way).
But you can also feed an entire block to a function, and I'd use a space there (and inside the block).


The puts examples look fine.

For the other one, why wouldn't you do

('a'..'z').each{|letter| puts letter}

?


In functional programming, you pass functions to functions, "chain" them, use them as operators, so it makes a lot of sense to always use space, because a function can be used without its arguments.


Again, why would you not do it like

map(negate . abs)[5,-3,-6,7,-3,2,-19,24]

?


In "regular" iterative languages, the reason for extra space might be for better layout, e.g. C#'s Linq:


Well yeah. If, when written out horizontally, it becomes too cumbersome, then it makes sense to break it up into additional lines. But that is more adding linebreaks, as-needed, rather than spaces. I'd probably do it as you wrote as well.


Still, a space before function parenthesis would look weird, but I guess it's a question of style.


It is definitely a question of style. And, again, adding extra space isn't wrong (unless whatever compiler you use complains), but it's more like just why do it?


Also, very impressive reply by the way. You went into a lot of depth.

Response to Coding Style - unnecessary spaces 2020-06-30 00:39:13


I'll admit, I spend much less time on "proper style" and more time on "does my Jerry-rigged poorly thought out contraption work." You guys are blowing my mind here with the spaces.

The space thing doesn't really bother me, actually when I was younger I didn't understand what my teachers meant by "double spaced papers" because I think single spaced looks better, so I ended up putting two spaces between every word, or manually line breaking after every line of text, etc. It was literally a year before I figured out what they meant, because no one actually explained, and I'm pretty sure no one noticed. Everyone had different requirements for format, computers were still a "new thing", the mice all had filthy balls in them, typewriters were considered sexy...


And no one seems to remember our librarian, who was the tech guru at the time. Dude completely disappeared.


I have encountered spacing issues, mostly in older python code, where the spacing actually mattered, and very often in code golf. Many of the issues are linked to trying to execute python 2 as python 3 and vice versa. A common one is when putting parameters in functions:


function(d=13, a=42, v=126, e=80) #this will work


but


function(d = 13, a = 42, v = 126, e = 80) #this will NOT work... SOMETIMES.


And I have no idea why the second arrangement won't work... sometimes. If it's *supposed* to work, I swear I've had this issue. Now I write everything the first way to avoid the issue.


The worst ones are the ones that demand something like func(parm='thingy') and sometimes 'thingy' is a number but not always and why does =None work but ='None' not always work and I can't even wrap my head around the weird stuff NumPy asks for and spits out.


I also occasionally miss commas.


I once/twice tried to read through the PEP documentation but I fell asleep.


(I pretty much only work in Python and dabble in other languages when I'm looking at other people's work, yes, I know that makes me a weak programmer, I should be perfectly fluent in C#, C++, and Java, but I'm not.)


Now that you mention it, it looks like I've been using spaces between "if" keywords and their conditions, but don't generally do that with most other functions so I've been inconsistent. And that's only the tip of the iceberg when it comes to unnecessary whitespace. Am I evil for using unnecessary space in things like

  // LevelNumber                             [ 0,  1,  2,  3]
  public static var levelTime:Array<Float> = [ 0, 30,  0,  0];
  public static var levelBoss:Array<Int> =   [ 0,  0,  1,  0];
  public static var mob1time:Array<Float> =  [ 0,  0,  0,  3];

and

        if (((thisUnlock.unlockName == "decel")     && (SaveHandler.publicSaveData.unlockedDecel     == false)) ||
            ((thisUnlock.unlockName == "phase")     && (SaveHandler.publicSaveData.unlockedPhase     == false)) ||
            ((thisUnlock.unlockName == "sharpturn") && (SaveHandler.publicSaveData.unlockedSharpturn == false)) ||
            ((thisUnlock.unlockName == "turret")    && (SaveHandler.publicSaveData.unlockedTurret    == false))) {
          unlocks.add(thisUnlock);
        }

and heaven forbid

      if (FlxG.keys.anyPressed([NUMPADFOUR,  A])) {FlxG.camera.scroll.add(   -elapsed * CAMERA_SPEED, 0);}
      if (FlxG.keys.anyPressed([NUMPADSIX,   D])) {FlxG.camera.scroll.add(    elapsed * CAMERA_SPEED, 0);}
      if (FlxG.keys.anyPressed([NUMPADEIGHT, W])) {FlxG.camera.scroll.add(0, -elapsed * CAMERA_SPEED   );}
      if (FlxG.keys.anyPressed([NUMPADTWO,   S])) {FlxG.camera.scroll.add(0,  elapsed * CAMERA_SPEED   );}


If so I'll switch to JavaScript and start writing all my code minified from the outset :3


As for why I do it... I only just now noticed that I've been doing it with if statements when I saw this, so not even intentional really.

Response to Coding Style - unnecessary spaces 2020-08-05 01:15:05


At 8/5/20 12:49 AM, 3p0ch wrote: Now that you mention it, it looks like I've been using spaces between "if" keywords and their conditions, but don't generally do that with most other functions so I've been inconsistent. And that's only the tip of the iceberg when it comes to unnecessary whitespace. Am I evil for using unnecessary space in things like
and
and heaven forbid

If so I'll switch to JavaScript and start writing all my code minified from the outset :3

As for why I do it... I only just now noticed that I've been doing it with if statements when I saw this, so not even intentional really.


Why do you have a space after the [ in each array assignment? And if you're going to "line up" the array declarations like that, which it doesn't even look like there's a good reason to as they don't even appear to be related data, then why on earth wouldn't you also "line up" those equals signs for aesthetic reasons?


And you would probably be better off using switch statements instead of most of those if statements, unless the language you're using is dumb and doesn't even have a switch statement. Python, for example. (But what you wrote isn't Python and looks like ActionScript). Does ActionScript not provide a switch statement? Most languages do.


I mean, as long as the code works, it's not "wrong" per-se, but it could probably be done better.


If you have good reasons for including extra spacing, then go ahead and do it, as long as you're consistent. If it is actually easier to read, fine. In most cases it's not, though.

Response to Coding Style - unnecessary spaces 2020-08-05 11:14:24


At 8/5/20 01:15 AM, NeonSpider wrote:
At 8/5/20 12:49 AM, 3p0ch wrote: Now that you mention it, it looks like I've been using spaces between "if" keywords and their conditions, but don't generally do that with most other functions so I've been inconsistent. And that's only the tip of the iceberg when it comes to unnecessary whitespace. Am I evil for using unnecessary space in things like
and
and heaven forbid

If so I'll switch to JavaScript and start writing all my code minified from the outset :3

As for why I do it... I only just now noticed that I've been doing it with if statements when I saw this, so not even intentional really.
Why do you have a space after the [ in each array assignment? And if you're going to "line up" the array declarations like that, which it doesn't even look like there's a good reason to as they don't even appear to be related data, then why on earth wouldn't you also "line up" those equals signs for aesthetic reasons?

And you would probably be better off using switch statements instead of most of those if statements, unless the language you're using is dumb and doesn't even have a switch statement. Python, for example. (But what you wrote isn't Python and looks like ActionScript). Does ActionScript not provide a switch statement? Most languages do.

I mean, as long as the code works, it's not "wrong" per-se, but it could probably be done better.

If you have good reasons for including extra spacing, then go ahead and do it, as long as you're consistent. If it is actually easier to read, fine. In most cases it's not, though.


First one's mostly functionality -- the arrays have parameters for each level of a game where index #n of each array is the parameter for the nth level, so they're sort of related data, and you can read a column with the level number in the top commented line and see the parameters for that level. Spaces after the opening [ were originally in case I ever decide to add any parameters where level 0 would have a two-digit value, although later I decided to have the first level be 1 and not have a level 0 so level numbering for humans would match level numbering in code, and I never bothered to remove those spaces when I decommissioned level 0. I didn't line up the equals because it didn't serve that functionality, although now that you mention it maybe it would be prettier if I did.


None of these specific sections with if's seem like they could be replaced with switch-case; the second section is a single if statement, and the cases aren't all mutually exclusive in the third (the player could be pressing both up and right simultaneously). But even if they were switch-case-able, I admit I have a pet peeve against using switch-case. IDK exactly why but I always felt like switch statement syntax was gross, partially because they don't have their cases' code in curly braced blocks, but even if they did it still seems icky for some reason.


But I don't program professionally, just as a hobby, so I don't have to worry about sticking to conventions or anyone else being able to read it or wanting it compact or easy for them to modify in the future (although I'm getting better about structuring things to make it it easy for myself to make sometimes large changes). I mostly just do whatever seems like I'll be able to understand easily if I get tied up with IRL and come back a month or so later with it no longer fresh in memory. Maybe if I were a pro and had to read and edit other people's code all the time I would get a better sense of what makes for good style.


Anditlookslikemycodefallsintheevilcategory,soit'sminifiedJavaScriptformefromhereonout!Whee!

Response to Coding Style - unnecessary spaces 2020-08-05 13:48:07


At 8/5/20 11:14 AM, 3p0ch wrote: First one's mostly functionality -- the arrays have parameters for each level of a game where index #n of each array is the parameter for the nth level, so they're sort of related data, and you can read a column with the level number in the top commented line and see the parameters for that level.


Awkward. And just "LevelNumber" really isn't good enough documentation for what you're doing there. You may come back to that years later and have no clue what you did. You're probably better to make these private variables within a class than to make them global array variables where you add one more array element for each new level. This way also you have no limit to how many levels you can make, and just allow the instance of the level or stage class object itself handle things like private internal variables.


None of these specific sections with if's seem like they could be replaced with switch-case; the second section is a single if statement


You couldn't throw a switch on thisUnlock.unlockName and then do the check for the SaveHandler.publicSaveData part in the case statements?


And is there a reason you did essentially if(variable == false) rather than if(!variable) ? I mean I don't use ActionScript. Maybe there's a difference. But they'd be equivalent in most languages. And the second form is shorter and compacts your code more, meaning you can read more of your code on screen at one time.


and the cases aren't all mutually exclusive in the third (the player could be pressing both up and right simultaneously).


Yes I suppose that's true.


But even if they were switch-case-able, I admit I have a pet peeve against using switch-case. IDK exactly why but I always felt like switch statement syntax was gross, partially because they don't have their cases' code in curly braced blocks, but even if they did it still seems icky for some reason.


Generally the reason to use switch statements is because it's more compact and "leaner" than a bunch of if statements. They do the same thing though. The more compact your code, the more of it you can read at a time on your screen.


Just make sure you know how switch works in whatever language you're using. It works properly in C, C++, Java, C#. Some newer languages put an implicit break after each case, so if you rely on case fallthrough behavior, your code may not behave as expected on such implicit break type languages. Haxe for example. IMO this newer behavior is broken. If you want the fallthrough behavior you may need to forego the switch statement and just stick with if statements in such broken switch languages.


One or two small if statements? Leave them as is. A bunch of if statements or some unwieldly if statement? Consider if a switch statement wouldn't be more appropriate. (Unless using a language that doesn't have switch statements, such as Python)


But I don't program professionally, just as a hobby, so I don't have to worry about sticking to conventions or anyone else being able to read it or wanting it compact or easy for them to modify in the future (although I'm getting better about structuring things to make it it easy for myself to make sometimes large changes). I mostly just do whatever seems like I'll be able to understand easily if I get tied up with IRL and come back a month or so later with it no longer fresh in memory. Maybe if I were a pro and had to read and edit other people's code all the time I would get a better sense of what makes for good style.


That's fine and nothing wrong with that. And by all means continue to do so and have fun with it, if that's what you enjoy doing.


Your code isn't wrong, as long as it works, and is bug-free. How well it runs and how the computer actually handles it should be the ultimate test. And getting something to run well is better than having pretty code. That said, oftentimes elegant code does run better as well.


There are tradeoffs. If you make your code extremely terse (and therefore also extremely compact), you may find it performs better. But many people find terse code difficult to read.


Ultimately, whatever works for you, or for whatever coding standards you're going with.


Anditlookslikemycodefallsintheevilcategory,soit'sminifiedJavaScriptformefromhereonout!Whee!


If that's what you want to do.

Response to Coding Style - unnecessary spaces 2020-08-05 14:14:33


My bad. The C# switch statement is kind of broken https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/switch


It still doesn't insert implicit break statements like Haxe does, but neither will it let you use the normal fallthrough behavior like C, C++, Java, or JavaScript either.


So yeah. Important to know how switch behaves in whatever language you're using.


Response to Coding Style - unnecessary spaces 2020-08-11 06:27:17


@3p0ch your use of spaces is beautiful. In your given examples, they are all used in a logical fashion to better visualize your code. Just by reading the first line of your blocks of codes I instantaniauslly knew what was happening in the whole block without even needing to read them whole. I don't have to read the whole line from left to right to know where I would need to modify a variable, because it's all structured so well. I feel like you're using the spaces correctly by increasing readibility for future maintainers (or your future self).

Response to Coding Style - unnecessary spaces 2020-10-24 12:28:24


Oh my God...

Back in the day, you poast some stupid shit like this, you'll get flamed by at least 10 people (hilariously, mind you), then your topic would get locked with a witty mod message. Then, you'd be banned.

Spaces are necessary, you twit!

Response to Coding Style - unnecessary spaces 2020-10-24 17:30:27


At 10/24/20 12:28 PM, Seth wrote: Oh my God...
Back in the day, you poast some stupid shit like this, you'll get flamed by at least 10 people (hilariously, mind you), then your topic would get locked with a witty mod message. Then, you'd be banned.
Spaces are necessary, you twit!


Flamebait much?


Triggered much?


Called you out on your own bad coding practices? A bit of a n00b there are you? The only one who would be banned would be people who are flaming, like you, right now. Maybe calm down a bit. Maybe learn some things.


Yes, if you code like this you are in a very literal sense "doing it wrong". As long as the compiler accepts it, your program should still work, but it's going to be a pain in the butt for anyone else to work with and it's aesthetically ugly besides.


Also, if your coding style is bad, there's a pretty good chance (though not certain) your actual code quality itself is also bad. You can have pretty code that doesn't work, and ugly code that runs smoothly, but there's greater than average chance ugly code also runs like crap, if it runs at all. And most companies have coding style guidelines *for a reason*!


Maybe think before you post next time and don't get all butthurt just because someone called out a flaw that happens to fit yourself, and maybe take the time to improve yourself instead. Would be different if I personally called you out (or anyone in particular), but I didn't, so there was really no excuse for this emotional outburst from you.


At 10/24/20 05:30 PM, NeonSpider wrote:
At 10/24/20 12:28 PM, Seth wrote: Oh my God...
Back in the day, you poast some stupid shit like this, you'll get flamed by at least 10 people (hilariously, mind you), then your topic would get locked with a witty mod message. Then, you'd be banned.
Spaces are necessary, you twit!
Flamebait much?

Triggered much?

Called you out on your own bad coding practices? A bit of a n00b there are you? The only one who would be banned would be people who are flaming, like you, right now. Maybe calm down a bit. Maybe learn some things.

Yes, if you code like this you are in a very literal sense "doing it wrong". As long as the compiler accepts it, your program should still work, but it's going to be a pain in the butt for anyone else to work with and it's aesthetically ugly besides.

Also, if your coding style is bad, there's a pretty good chance (though not certain) your actual code quality itself is also bad. You can have pretty code that doesn't work, and ugly code that runs smoothly, but there's greater than average chance ugly code also runs like crap, if it runs at all. And most companies have coding style guidelines *for a reason*!

Maybe think before you post next time and don't get all butthurt just because someone called out a flaw that happens to fit yourself, and maybe take the time to improve yourself instead. Would be different if I personally called you out (or anyone in particular), but I didn't, so there was really no excuse for this emotional outburst from you.

Well now, someone's feefees got hurt. I made a troll response to what is obviously a troll poast. I mean, OP is clearly trying to provoke a reaction from people. And he got one. But, you know, whatever helps you sleep at night.

Response to Coding Style - unnecessary spaces 2020-10-25 02:06:53


At 10/24/20 10:03 PM, Seth wrote: Well now, someone's feefees got hurt. I made a troll response to what is obviously a troll poast. I mean, OP is clearly trying to provoke a reaction from people. And he got one. But, you know, whatever helps you sleep at night.


You know, generally it's a good idea not to respond to topics if you don't know what you're talking about and you're not well-versed in the subject matter at hand.


And for most topics, people tend to follow this advice, but for whatever reason on the Internet, everyone thinks they're an expert when it comes to computer topics, when greater than 99% of them aren't even close.


What is it you do that makes you think you're qualified to post here? Built some gaming rig? Watched some Youtube videos? Played a lot of Call of Duty? This is a programming board, so unless you've done actual computer programming, you're in the wrong place. And if you have done programming (or are interested in it), you're still in the wrong because you should be learning rather than trolling, especially when you're a beginner and you still have a lot to learn.


Go ahead and tell me why you think anything you've thus posted to this thread is helpful or relevant in the slightest.


At 10/25/20 02:06 AM, NeonSpider wrote:
At 10/24/20 10:03 PM, Seth wrote: Well now, someone's feefees got hurt. I made a troll response to what is obviously a troll poast. I mean, OP is clearly trying to provoke a reaction from people. And he got one. But, you know, whatever helps you sleep at night.
You know, generally it's a good idea not to respond to topics if you don't know what you're talking about and you're not well-versed in the subject matter at hand.

And for most topics, people tend to follow this advice, but for whatever reason on the Internet, everyone thinks they're an expert when it comes to computer topics, when greater than 99% of them aren't even close.

What is it you do that makes you think you're qualified to post here? Built some gaming rig? Watched some Youtube videos? Played a lot of Call of Duty? This is a programming board, so unless you've done actual computer programming, you're in the wrong place. And if you have done programming (or are interested in it), you're still in the wrong because you should be learning rather than trolling, especially when you're a beginner and you still have a lot to learn.

Go ahead and tell me why you think anything you've thus posted to this thread is helpful or relevant in the slightest.

Wow, another wall of text I can't be bothered to read. I thought you, since you're "so smart," would gather that I didn't read your wall of text before. I said my piece, moved on. You feel the need to "correct" me despite the fact that I already explained my case. Fuck off, you cunt.


IDK why people are flaming, bad code is funny.


var nums[
  "1", "2", "3", "4", "5", "6"...
]

function calc(number_one, number_two){
  if(number_one == nums[0] && number_two == nums[0]){
    return "two!";
  }else if((number_one == nums[0] && number_two == nums[1]) || (number_one == nums[1] && number_two == nums[0])){
    return "three!";
  }else if((number_one == nums[1] && number_two == nums[1]) || (number_one == nums[0] && number_two == nums[2]) || (number_one == nums[2] && number_two == nums[0])){
    return "four!";
  }else if(........)
...
}

Response to Coding Style - unnecessary spaces 2020-11-07 15:00:59


At 11/5/20 04:47 AM, MilanaBezi wrote: Help fix coding errors on my site. I understand absolutely nothing in coding. Pages take a very long time to load, acquaintances told me that it was due to coding errors.


I found a site that checks HTML code for errors: https://validator.w3.org/nu


BBS Signature