I am pretty much the only person I know who codes in the Allman style. I really, really like the idea of braces on their own lines. To me it's just logical and normal. 99% of the code I see, whether it be online or at work is in K&R style, or some variant.

I know I am in a very, very, small minority. I am the only person at my workplace that codes in this style. Because of this, it is sometimes difficult to read others' code and vice versa. It can also be difficult to read code online, in code snippets, etc. because it's just so different from what I see on a day to day basis.

But it's not just brace placement. Variable and method naming conventions are different, too. I prefer to name my things (variables and methods) in lower_snake_case. In my opinion it is the easiest to read, especially if you get into a situation (albeit sometimes rare) where you have no choice but to use a longer-than-usual name. In my opinion this_awesome_variable_that_is_long is much easier to read than thisAwesomeVariableThatIsLong. I believe it also best reflects "everyday" reading (at least in English) as most everyday text is lowercase and separated by spaces. There is also the debate of when you use an abbreviation or shortform. thisUrl or thisURL? I avoid the debate by making everything lowercase.

On the front-end I make sure my CSS properties are listed in alphabetical order. It takes a couple extra seconds to do it, and when it comes time later to make a change you know exactly where to find the property. Otherwise "display: block;" could be the first property, the last, or somewhere in between. I don't want to waste my time hunting through properties just to make a change (also Firebug lists them in alphabetical order, so making changes is easier since I know the second property is actually the second property). I understand the other side of that argument in that you don't want to have to hunt through properties to know where to add the next one. My counterargument is this allows anyone to jump in immediately, and inevitably when the time comes to go back and make changes you are already equipped with where to make the change. Essentially you can get down to business right away. I always feel it's better to "take the hit now" vs later, because you can plan for it now. There is a plugin for PhpStorm that allows you to automatically sort the properties, though it is a little buggy. In the end though I believe the time saved later more than makes up for the extra time now.

I also like to align assignment operators, colons, etc. Making my code readable (and therefore in my opinion, easy to modify and maintain) is usually my #1 priority.

So why the question? Well we have recently secured quite a large project. Other than it's a social media site, I can't say much more (under an NDA plus I simply haven't been filled in on the details yet 😃). Due to its size there will definitely be multiple developers working on it, sometimes at the same time but also sometimes "switching off". If everyone just "did their thing", than that means there will be a mix of coding conventions/style in the project, which is obviously a poor practice.

I am the senior developer (please stop laughing) so technically I could "set the standard" but I'd rather not be "that guy", directly or indirectly (meaning I bring the issue to management, they side with me, and make everyone do it). It is possible we could set a custom coding standard for the project, but that may be detrimental in the long run when developers (including myself) have to switch onto something else that is another style.

So what would you do? Should I take the plunge and try to code in an alternative style, or just say screw it and everyone does their own thing? Or make everyone do something completely different for this project? I included an "illustration" below of what I mean.

What I would do:

public function has_invoice_requires_sourcer()
{
	if(!count($this->invoices))
	{
		throw new Invalid_Invoice_Exception('The request should have at least one invoice!');
	}

foreach($this->invoices as $invoice)
{
	if($invoice->usd >= SOURCING_MANAGER_THRESHOLD)
	{
		return true;
	}
}

return false;
}

What I usually see:

public function hasInvoiceRequiresSourcer() {
	if(!count($this->invoices)) {
		throw new Invalid_Invoice_Exception('The request should have at least one invoice!');
	}

foreach($this->invoices as $invoice) {
	if($invoice->usd >= SOURCING_MANAGER_THRESHOLD) {
			return true;
	}
}

return false;
}

The lack of white space between lines, which to me are distinct, also throws me off.

Would love to hear comments, suggestions, concerns, even stories. Thanks for reading! 🙂

    Admittedly, I'm not horribly consistent, but....

    While I know many coders who love to throw in empty lines between whatever they think of as logical groups of things. I generally prefer not to, but sometimes make exceptions. The main reason I prefer not to is simply to allow more lines of code in my editor window at any given point, so that I don't have to scroll back and forth as much. If the code is consistently and logically indented, I can see the flow just fine (and another reason why the opening brace can stay on the line with the if/for/whatever). If things are getting so cluttered that you feel the need to add empty lines or to put opening braces on a new line so you can line them up with their closing braces with a straight edge or something ( 😉 ), that becomes a "code smell" to me that you need to refactor things into smaller, more tightly focused methods in the first place, most likely.

    As far as camelCase versus snake_case, I prefer typing camelCase, so tend to use it simply for that reason. As to readability, I'm fine either way.

    My overall recommendation would be getting the team together early on and see what areas of formatting you have a consensus or near-consensus on, and make those your team's standard, but only on things that actually matter to them -- if there are not strong feelings one way or the other, then why worry about that aspect? On any aspect they cannot agree upon but which you feel is important, you have the god-like power to make it the standard. 🆒

    Also, there are some handy stand-alone tools and IDE/editor features that can apply formatting rules, which could allow you and your team to apply your agreed-upon (or dictated) formatting rules before committing code. (E.g., PHPStorm lets you set a lot of that stuff in the config, and then you can use a keyboard shortcut to apply them to a file.)

      PS: If you're using a framework, it might be good to start with whatever standard is used/approved by that framework, and any plug-ins and tools you use with the framework will likely follow that standard in their code or the code they generate.

        I have been following the PSRs since before the FIG existed.

        http://www.php-fig.org/psr/psr-1/
        http://www.php-fig.org/psr/psr-2/

        These are pretty good standards. They're accepted by a lot of open source projects. Based on those standards, your example becomes:

        public function hasInvoiceRequiresSourcer() 
        { 
            if (!count($this->invoices)) { 
                throw new Invalid_Invoice_Exception('The request should have at least one invoice!'); 
            } 
        
        foreach ($this->invoices as $invoice) { 
            if ($invoice->usd >= SOURCING_MANAGER_THRESHOLD) { 
                return true; 
            } 
        } 
        
        return false; 
        }  
          Bonesnap wrote:

          I know I am in a very, very, small minority. I am the only person at my workplace that codes in this style. Because of this, it is sometimes difficult to read others' code and vice versa. It can also be difficult to read code online, in code snippets, etc. because it's just so different from what I see on a day to day basis.

          I use Allman style for C and C++ code, but tend to use K&R for PHP code (and back in school for Java, if I remember correctly), and of course when I code in Python there are no braces to delimit blocks of scope 🙂

          Consequently, I have no problems switching between either, whether for reading or writing, and I try to maintain the style used in code posted when modifying code posted by someone requesting for help.

          Frankly, indentation style is a very small part of coding style. It is what Sutter and Alexandrescu call the "small stuff" in their book on C++ Coding Standards. The important thing is to be consistent, so follow the norm for the given file, or project, or team, or if you have the choice, pick whatever reasonable style you like. Perhaps some deliberate change of style from time to time will help you; not to besmirch your ability or professionalism, but I agree with Sutter and Alexandrescu when they assert that "any professional programmer can easily read and write any of these styles without hardship", and they are referring not only to Allman and K&R, but also to Whitesmiths, which frankly I have never seen in the wild.

            I'm with you on camel case, I hate and detest it - it may be my graphic design background that makes it typographically offensive to me.
            It's underscores for me as you do- but underscore and camel case looks redundant
            Braces : always on the same line for open - new line for close
            White lines : I add more than I used to !

              Derokorian wrote:

              I have been following the PSRs since before the FIG existed.

              I commend you (seriously), for choosing a standard, and sticking to it. I'm beginning to think that I'm schizophrenic.

              cretaceous;11053801 wrote:

              White lines : I add more than I used to !

              Me too, apparently, which on one level I find hilarious as I used to methodically go through old code REMOVING blank newlines to make files as short as possible (where's the study on how much programmer time is wasted on the PgDwn/PgUp keys?)

              I've also taken, recently, to whitespacing method/function parameters (I forget which project does this now, WP, maybe?). My newest stuff generally looks like this...

              if ( $this->foo ) {
              
                 $bar                      = "Please frobnitz the valkerator.";
                 $count                    = $this->someNumberThing( $parameter );
              
              }
              Bonesnap wrote:

              I also like to align assignment operators, colons, etc.

              You'll see that above as well. The only problem I have with this is it makes me feel dirty to use tabs instead of spaces, but it's SO much faster ...

              I currently think it would be interesting to work in an environment where somebody cared about stuff like this, instead of merely "whether it works or not". Of course, the latter is, as we all know, immensely practical to the layman ...

                cretaceous wrote:

                It's underscores for me as you do- but underscore and camel case looks redundant

                If we are talking about using them for the same identifier, I agree: I think such a combination looks ugly. That said, my personal preference is to have class and function names use camel case (capitalised for the former), and use underscores as separators for other names.

                dalecosp wrote:

                You'll see that above as well. The only problem I have with this is it makes me feel dirty to use tabs instead of spaces, but it's SO much faster ...

                That sounds bad to me: if you are using tab characters to align for pretty printing (rather using them to indent for normal indent level, or using the tab key to insert spaces instead of tab characters), then your code might look odd when read with a different tab setting. Maybe your editor can be configured to convert tabs to spaces upon saving, in which case this problem will disappear.

                dalecosp wrote:

                I currently think it would be interesting to work in an environment where somebody cared about stuff like this, instead of merely "whether it works or not". Of course, the latter is, as we all know, immensely practical to the layman ...

                Not really: everyone should care about the code being written in a good style, and that includes these "small stuff" very subjective elements of style. But when you have someone going around caring too much and enforcing the small stuff very strictly, it misses the forest for the trees.

                Coding style is so much more than this, e.g., decisions on whether to use exceptions or return codes, decisions on programming paradigms to choose for various kinds of problems, whether to go for single-entry/single-exit (how about exceptions possibly getting thrown?) or allow for early returns when checking pre-conditions, etc.

                  NogDog;11053785 wrote:

                  While I know many coders who love to throw in empty lines between whatever they think of as logical groups of things. I generally prefer not to, but sometimes make exceptions. The main reason I prefer not to is simply to allow more lines of code in my editor window at any given point, so that I don't have to scroll back and forth as much. If the code is consistently and logically indented, I can see the flow just fine (and another reason why the opening brace can stay on the line with the if/for/whatever).

                  Having more code on the screen is indeed a plus, but the monitors I use at work are 1080p, so it's not a huge burden. Also at home I have a 4K monitor, so it's even nicer (with the ability to rotate 😃). There is also font size and line height to take into consideration which I am sure varies widely among programmers.

                  NogDog;11053785 wrote:

                  If things are getting so cluttered that you feel the need to add empty lines or to put opening braces on a new line so you can line them up with their closing braces with a straight edge or something ( 😉 ), that becomes a "code smell" to me that you need to refactor things into smaller, more tightly focused methods in the first place, most likely.

                  Generally I agree; keeping the code in smaller, more manageable pieces is a focus of mine. But my wanting to line up braces isn't about organization. I am not sure how to explain it other than I just think they should be. I also believe it gives literal meaning to "code block" and to "balancing braces"; it is (in my opinion) much easier to spot a block of code with that style than the common alternative. I am in the minority, however.

                  I also like to place blank lines and group things together because that's just what programmers do. It may be on a much smaller scale than the norm (putting a bunch of logical code together in a method for example), but it feels right.

                  NogDog;11053785 wrote:

                  My overall recommendation would be getting the team together early on and see what areas of formatting you have a consensus or near-consensus on, and make those your team's standard, but only on things that actually matter to them -- if there are not strong feelings one way or the other, then why worry about that aspect? On any aspect they cannot agree upon but which you feel is important, you have the god-like power to make it the standard. 🆒

                  This is good advice and I know the other programmer that will be working on it with me is pretty sharp and most likely open to compromise.

                  NogDog;11053785 wrote:

                  Also, there are some handy stand-alone tools and IDE/editor features that can apply formatting rules, which could allow you and your team to apply your agreed-upon (or dictated) formatting rules before committing code. (E.g., PHPStorm lets you set a lot of that stuff in the config, and then you can use a keyboard shortcut to apply them to a file.)

                  Indeed, I am already using PhpStorm's reformatting feature, just not in a commit-setting. I will be pushing for Git as well, but that is a separate uphill battle, unfortunately.

                  NogDog;11053787 wrote:

                  PS: If you're using a framework, it might be good to start with whatever standard is used/approved by that framework, and any plug-ins and tools you use with the framework will likely follow that standard in their code or the code they generate.

                  No framework, all custom code.

                  Derokorian;11053793 wrote:

                  I have been following the PSRs since before the FIG existed.

                  http://www.php-fig.org/psr/psr-1/
                  http://www.php-fig.org/psr/psr-2/

                  These are pretty good standards. They're accepted by a lot of open source projects. Based on those standards, your example becomes:

                  public function hasInvoiceRequiresSourcer() 
                  { 
                      if (!count($this->invoices)) { 
                          throw new Invalid_Invoice_Exception('The request should have at least one invoice!'); 
                      } 
                  
                  foreach ($this->invoices as $invoice) { 
                      if ($invoice->usd >= SOURCING_MANAGER_THRESHOLD) { 
                          return true; 
                      } 
                  } 
                  
                  return false; 
                  }  

                  This is a really good idea, and provides a great compromise for everyone: use what's already established. I noticed that it intentionally omits rules for naming variables.

                  laserlight;11053795 wrote:

                  Frankly, indentation style is a very small part of coding style. It is what Sutter and Alexandrescu call the "small stuff" in their book on C++ Coding Standards. The important thing is to be consistent, so follow the norm for the given file, or project, or team, or if you have the choice, pick whatever reasonable style you like. Perhaps some deliberate change of style from time to time will help you; not to besmirch your ability or professionalism, but I agree with Sutter and Alexandrescu when they assert that "any professional programmer can easily read and write any of these styles without hardship", and they are referring not only to Allman and K&R, but also to Whitesmiths, which frankly I have never seen in the wild.

                  I definitely strive for being consistent and during the times when I have had to work on others' code, I adapt to the current style so it wouldn't even be immediately noticeable that I worked on it. But I don't think "the important thing is to be consistent" is necessarily correct. If you are consistently doing bad things then you are just doing bad things. It may be predictable, but they're still bad (bad is subjective but you know what I mean).

                  If I wrote an essay in txt spk 4 u, u wud b upset. I doubt you'd commend me on my consistency :p

                  I do agree it could be a nice breath of fresh air for me and expand my horizons. And don't worry, you are not besmirching my abilities :p.

                  dalecosp;11053803 wrote:

                  I've also taken, recently, to whitespacing method/function parameters (I forget which project does this now, WP, maybe?). My newest stuff generally looks like this...

                  if ( $this->foo ) {
                  
                     $bar                      = "Please frobnitz the valkerator.";
                     $count                    = $this->someNumberThing( $parameter );
                  
                  }

                  Yes, WordPress does this, but it does not line up assignment operators. I tend to do that but I let PhpStorm do it for me.

                    laserlight;11053805 wrote:

                    That sounds bad to me: if you are using tab characters to align for pretty printing (rather using them to indent for normal indent level, or using the tab key to insert spaces instead of tab characters), then your code might look odd when read with a different tab setting. Maybe your editor can be configured to convert tabs to spaces upon saving, in which case this problem will disappear.

                    That's dependent on whether I'm in the IDE or just terminalled into the server for a "quick job".

                    Not really: everyone should care about the code being written in a good style, and that includes these "small stuff" very subjective elements of style. But when you have someone going around caring too much and enforcing the small stuff very strictly, it misses the forest for the trees.

                    Coding style is so much more than this, e.g., decisions on whether to use exceptions or return codes, decisions on programming paradigms to choose for various kinds of problems, whether to go for single-entry/single-exit (how about exceptions possibly getting thrown?) or allow for early returns when checking pre-conditions, etc.

                    Yes, yes, but I'm kind of stuck almost like I was when I worked for myself; there's still no one in the shop that knows very much about what I do; the only difference is that someone else handles the marketing, bookkeeping, and money (and writes the paychecks).

                    And while a couple of people, on some esoteric level, could agree that well-written code is important, the ever-present question is "when will $x be done"?

                      While I doubt any PHP team is going to do this, one "easy" way to avoid the curly brace placement question is the alternate syntax option:

                      <?php
                      
                      if(true):
                          foreach($arr as $value):
                              while($counter++ < 10):
                                  echo "$value - $counter\n";
                              endwhile;
                          endforeach;
                      endif;
                      

                      😉

                        Bonesnap wrote:

                        But I don't think "the important thing is to be consistent" is necessarily correct. If you are consistently doing bad things then you are just doing bad things. It may be predictable, but they're still bad (bad is subjective but you know what I mean).

                        Yes, but none of the reasonable options are bad, so arguing that way is just a strawman argument. We're not talking about an indent style where there is consistently no indentation at all, or a naming convention that is consistently random, or consistently having 20 blank lines in between function definitions, etc.

                        Python's PEP 8 expresses another aspect of being reasonably consistent:

                        A Foolish Consistency is the Hobgoblin of Little Minds

                        One of Guido's key insights is that code is read much more often than it is written. The guidelines provided here are intended to improve the readability of code and make it consistent across the wide spectrum of Python code. As PEP 20 says, "Readability counts".

                        A style guide is about consistency. Consistency with this style guide is important. Consistency within a project is more important. Consistency within one module or function is the most important.

                        However, know when to be inconsistent -- sometimes style guide recommendations just aren't applicable. When in doubt, use your best judgment. Look at other examples and decide what looks best. And don't hesitate to ask!

                        In particular: do not break backwards compatibility just to comply with this PEP!

                        Some other good reasons to ignore a particular guideline:

                        • When applying the guideline would make the code less readable, even for someone who is used to reading code that follows this PEP.

                        • To be consistent with surrounding code that also breaks it (maybe for historic reasons) -- although this is also an opportunity to clean up someone else's mess (in true XP style).

                        • Because the code in question predates the introduction of the guideline and there is no other reason to be modifying that code.

                        • When the code needs to remain compatible with older versions of Python that don't support the feature recommended by the style guide.

                          5 days later
                          NogDog;11053813 wrote:

                          While I doubt any PHP team is going to do this, one "easy" way to avoid the curly brace placement question is the alternate syntax option:

                          <?php
                          
                          if(true):
                              foreach($arr as $value):
                                  while($counter++ < 10):
                                      echo "$value - $counter\n";
                                  endwhile;
                              endforeach;
                          endif;
                          

                          😉

                          WordPress does this is some of their default templates and themes. Drives me insane. I have never pressed ctrl+a then delete as fast as when I have to modify one of those files. Now I just make my own templates and themes.

                          if($you_want_to_write_pascal):
                              then_write_pascal_dammit();
                          else
                              then_write_php_dammit();
                          endif;
                          
                          laserlight;11053815 wrote:

                          Yes, but none of the reasonable options are bad, so arguing that way is just a strawman argument. We're not talking about an indent style where there is consistently no indentation at all, or a naming convention that is consistently random, or consistently having 20 blank lines in between function definitions, etc.

                          Python's PEP 8 expresses another aspect of being reasonably consistent:

                          Indeed, I concede that my previous (current) style isn't bad. It just reminds me of something I read while I was learning Dvorak years ago. I'm paraphrasing heavily but the basic idea is that we use the common phrase "Practice makes perfect!" but practice doesn't make perfect. Practicing good habits makes perfect; practicing bad habits simply just builds bad habits. Some circles would argue the habits I have practiced are bad. I don't, but to each their own.

                          On a side note I have increased my font size in PhpStorm by 4px to encourage producing more concise methods. Makes you think about code differently when you have less real estate.

                            NogDog wrote:

                            While I doubt any PHP team is going to do this, one "easy" way to avoid the curly brace placement question is the alternate syntax option

                            I used to use alternative syntax only when I first started with PHP :p

                            Bonesnap wrote:

                            WordPress does this is some of their default templates and themes.

                            It makes sense for templates/themes because it is basically using PHP as a template language, and in this the endif/endfor stuff can help in readability for matching across non-PHP code.

                            Bonesnap wrote:

                            On a side note I have increased my font size in PhpStorm by 4px to encourage producing more concise methods. Makes you think about code differently when you have less real estate.

                            It may also help with your eyesight 😃

                              laserlight;11053861 wrote:

                              It makes sense for templates/themes because it is basically using PHP as a template language, and in this the endif/endfor stuff can help in readability for matching across non-PHP code.

                              I find it to be the complete opposite. Aren't <?php ?> tags good enough? Also there's very little if any IDE support for that type of syntax. IE: There's no matching brace that highlights when I place my cursor next to the opening/closing brace.

                              laserlight;11053861 wrote:

                              It may also help with your eyesight 😃

                              I have already had to increase it a couple years ago. On 1080p monitors I run at 16px but on my 4K monitor at home I'm sitting at 20px.

                              Unrelated question to everyone: what font do you use primarily when programming? I usually use Consolas (Windows font) but I am trying out Source Code Pro lately to see how I like it.

                                Bonesnap;11053877 wrote:

                                Unrelated question to everyone: what font do you use primarily when programming? I usually use Consolas (Windows font) but I am trying out Source Code Pro lately to see how I like it.

                                I am currently use Monospaced at 16 on a 4K

                                  Right now it's DejaVu Mono @ 7pt on a 1080 monitor. Another editor is at 8pt Consolas.

                                    Currently using Menlo 15 (unspecified unit) with 1.5 line-spacing in PHPStorm and RubyMine on my MacBook 15" Retina screen.

                                      Courier New in terminals, 10, 12, 14, 16 pt depending on which monitor, which system, and some other stuff. NetBeans I've not modified AFAIK?

                                        Bonesnap wrote:

                                        I find it to be the complete opposite. Aren't <?php ?> tags good enough? Also there's very little if any IDE support for that type of syntax. IE: There's no matching brace that highlights when I place my cursor next to the opening/closing brace.

                                        Good point about IDE support, but as the term "indent style" implies, brace placement depends on indentation, but when using PHP as a template language, there might not be any indentation in a given context, or there may be competing indentation, i.e., the template code is indented at a different rate from the template content. Hence, the "endX" style as used by some template languages (e.g., Smarty, or in the Python framework world Django's template language and Jinja2 that it inspired) can be an advantage in allowing one to read the control structure context at the closing "tag", something normally visible by indentation alone (as Python shows).

                                        Bonesnap wrote:

                                        Unrelated question to everyone: what font do you use primarily when programming? I usually use Consolas (Windows font) but I am trying out Source Code Pro lately to see how I like it.

                                        DejaVu Sans Mono, or if that is not available, then Bitstream Vera Sans Mono on which it is based. If that is also not available... I'll see if I can get DejaVu Sans Mono installed.