Author Topic: Programming Style, C#  (Read 5627 times)

0 Members and 1 Guest are viewing this topic.

MP

  • Seagull
  • Posts: 17750
  • Have thousands of dwgs to process? Contact me.
Programming Style, C#
« on: April 12, 2011, 11:26:30 AM »
Hi all -- Long time no see!! Hope everyone is doing well. I've been completely swamped at the new job (started late January) but that's not necessarily a bad thing.

Anyway ...

I've been doing a fair amount of C# programming and I should have asked this simple style question long ago ... do you think it is better to use braces to host child clauses, example an if statement, even if there's only one term? i.e. the braces are superfluous?

Code: [Select]
if ( some_condition )
{
    do_this();
}
else
{
    do_that();    
}
   

versus ...

Code: [Select]
if ( some_condition )
    do_this();
else
    do_that();

I prefer the brevity of the second version and if I were the only one to maintain the code I wouldn't ask but I'll be turning the source code over to others down the road. Would the former version be preferred? Is there an industry norm?

Thanks for your thoughts.

Michael.
Engineering Technologist • CAD Automation Practitioner
Automation ▸ Design ▸ Drafting ▸ Document Control ▸ Client
cadanalyst@gmail.comhttp://cadanalyst.slack.comhttp://linkedin.com/in/cadanalyst

Lee Mac

  • Seagull
  • Posts: 12924
  • London, England
Re: Programming Style, C#
« Reply #1 on: April 12, 2011, 12:00:29 PM »
Nice to hear from you Michael - I hope all is well with you  :-)

FWIW, when studying C, I was taught to leave them out since they weren't needed - but it might've just been a personal preference of my lecturer...

T.Willey

  • Needs a day job
  • Posts: 5251
Re: Programming Style, C#
« Reply #2 on: April 12, 2011, 12:00:47 PM »
I prefer the second.  And if the statement is short, then I'll put them on a single line.  You can do this with ' foreach ' statements also.  Just an FYI.

Code: [Select]
if ( XrLock == null ) XrDb.Dispose();
else XrLock.Dispose();

Code: [Select]
foreach ( KeyValuePair<string, AnnotationScale> kvp in ScDict ) ScCntxCol.RemoveContext( kvp.Key );

Good to hear you are busy with work Michael.
Tim

I don't want to ' end-up ', I want to ' become '. - Me

Please think about donating if this post helped you.

sinc

  • Guest
Re: Programming Style, C#
« Reply #3 on: April 12, 2011, 12:26:27 PM »
I personally think the difference is rather irrelevant, and it's perfectly fine to use whichever one you desire...

JohnK

  • Administrator
  • Seagull
  • Posts: 10657
Re: Programming Style, C#
« Reply #4 on: April 12, 2011, 12:59:36 PM »
I realize this isnt answer isnt C# nor a direct answer but i was reading this doc this morning (I may have to go get those books) and i thought it made some very good points to consider (as well) which could help answer via CODE FLOW solutions.
http://llvm.org/docs/CodingStandards.html#hl_earlyexit

However, to answer the question (directly); I would vote #2 but i dont see any problem with #1 either.
TheSwamp.org (serving the CAD community since 2003)
Member location map - Add yourself

Donate to TheSwamp.org

LE3

  • Guest
Re: Programming Style, C#
« Reply #5 on: April 12, 2011, 01:02:04 PM »
I use both.

But lately started to leave the braces, since end up adding more lines in between, something that can be done very easy later, but also to keep all on the same.

But that's me.

David Hall

  • Automatic Duh Generator
  • King Gator
  • Posts: 4076
Re: Programming Style, C#
« Reply #6 on: April 12, 2011, 02:39:35 PM »
I use #1 all the time, even for 1 liners.  Usually by the time I think to remove the braces, im further down the road and it doesn't matter
Everyone has a photographic memory, Some just don't have film.
They say money can't buy happiness, but it can buy Bacon and that's a close second.
Sometimes the question is more important than the answer. (Thanks Kerry for reminding me)

gile

  • Gator
  • Posts: 2520
  • Marseille, France
Re: Programming Style, C#
« Reply #7 on: April 12, 2011, 04:34:10 PM »
Most of the time I to use #2 (as I don't use a progn in LISP when it's not requiered).

But these days, I tend to replace braces with identation using F#. :evil:
Speaking English as a French Frog

MickD

  • King Gator
  • Posts: 3646
  • (x-in)->[process]->(y-out) ... simples!
Re: Programming Style, C#
« Reply #8 on: April 12, 2011, 06:46:52 PM »
I use both.

But lately started to leave the braces, since end up adding more lines in between, something that can be done very easy later, but also to keep all on the same.

But that's me.

No 1 for the same reasons as Luis, it just becomes habit anyway and if they're not there they are a pain to put in later...but that's just me.
For .net I use BOO as often as I can, no braces required :)
"Programming is really just the mundane aspect of expressing a solution to a problem."
- John Carmack

"Short cuts make long delays,' argued Pippin.”
- J.R.R. Tolkien

It's Alive!

  • Retired
  • Needs a day job
  • Posts: 8785
  • AKA Daniel
Re: Programming Style, C#
« Reply #9 on: April 12, 2011, 06:55:39 PM »
For the most part I don't use the extra braces, however, I keep them symmetrical  I.e.

Code: [Select]
                if (some_condition)
                {
                    do_this();
                    do_this_too();
                }
                else
                {
                    do_that();
                }

over

Code: [Select]
                if (some_condition)
                {
                    do_this();
                    do_this_too();
                }
                else
                    do_that();
« Last Edit: April 12, 2011, 07:05:20 PM by __assume »

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11654
  • class keyThumper<T>:ILazy<T>
Re: Programming Style, C#
« Reply #10 on: April 12, 2011, 08:25:27 PM »
Hello Michael,

personal preference is the decider for me too.

Quote
For the most part I don't use the extra braces, however, I keep them symmetrical  I.e.

Ditto, but different :)

Code: [Select]

        if (some_condition){
            do_this();
            do_this_too();
        }else {
            do_that();
        }


If the conditional action is a simple one liner, I don't use braces.

If there is a chance that I'll need to add statements  I use braces at the outset

Code: [Select]

        BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
        if( !bt.Has(blockName) ) {
            ed.WriteMessage("\nBlock '{0}' is not available in the current drawing.", blockName);
            return;
        }
        PromptPointResult ppr = ed.GetPoint("\nSpecify insertion point: ");
        if( ppr.Status != PromptStatus.OK )
            return;


Code: [Select]

        get { return doc; }
        set
        {
            doc = value;
            if( doc == null ) {
                db = null;
                ed = null;
            } else {
                db = doc.Database;
                ed = doc.Editor;
            }
        }




« Last Edit: April 12, 2011, 08:51:43 PM by Kerry »
kdub, kdub_nz in other timelines.
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

MP

  • Seagull
  • Posts: 17750
  • Have thousands of dwgs to process? Contact me.
Re: Programming Style, C#
« Reply #11 on: April 13, 2011, 08:41:58 AM »
Thanks for the well wishes and feedback folks. I guess personal preference > industry norm. Having said that the minimalist approach in concert with symmetry personally appeals to me the most. Braces and statements on their own lines provide the best clarity to me as well, especially when scanning / perusing pages and pages of code. Thanks for the discussion.
Engineering Technologist • CAD Automation Practitioner
Automation ▸ Design ▸ Drafting ▸ Document Control ▸ Client
cadanalyst@gmail.comhttp://cadanalyst.slack.comhttp://linkedin.com/in/cadanalyst

fixo

  • Guest
Re: Programming Style, C#
« Reply #12 on: April 13, 2011, 01:30:54 PM »
Hi, Michael
I have read in "Best code practice" article , don't remember where is it,
but written by one of the giants  ( I think by Petzold, not sure about )
"Better yet to use the brackets always"

Have a nice all

Oleg

dgorsman

  • Water Moccasin
  • Posts: 2437
Re: Programming Style, C#
« Reply #13 on: April 13, 2011, 02:44:47 PM »
I find when going over code I haven't worked on in a while, its easy to skip right over a single line of unbraced "else" code when there is a large block of "if-positive" code right above it.  For internal consistency I only omit the braces where both are single-statements.  If either require multiple lines they both get braced.
If you are going to fly by the seat of your pants, expect friction burns.

try {GreatPower;}
   catch (notResponsible)
      {NextTime(PlanAhead);}
   finally
      {MasterBasics;}

Glenn R

  • Guest
Re: Programming Style, C#
« Reply #14 on: April 13, 2011, 04:50:06 PM »
I purchased 'The Elements of C# Style' a few years ago and it's an excellent book - I generally live by it when writing C# code.

As far as this discussion is concerned, Rule No. 12 is invoked (this is an extract) - 'Always use Block Statements in Control Flow Constructs' to avoid the 'dangling else' problem:

Code: [Select]
if (x >= 0)
  if (x > 0) PositiveX();
else  // Oops! Matches most recent if!
  NegativeX();

Good to hear from you again MP.

Cheers,
Glenn

MP

  • Seagull
  • Posts: 17750
  • Have thousands of dwgs to process? Contact me.
Re: Programming Style, C#
« Reply #15 on: April 21, 2011, 09:23:50 AM »
I purchased 'The Elements of C# Style' a few years ago and it's an excellent book - I generally live by it when writing C# code.

As far as this discussion is concerned, Rule No. 12 is invoked (this is an extract) - 'Always use Block Statements in Control Flow Constructs' to avoid the 'dangling else' problem ...

I forgot about that book; good example too. Thanks Glenn. :)

I find when going over code I haven't worked on in a while, its easy to skip right over a single line of unbraced "else" code when there is a large block of "if-positive" code right above it.  For internal consistency I only omit the braces where both are single-statements.  If either require multiple lines they both get braced.

Solid approach, thanks dgorsman. :)

Hi, Michael
I have read in "Best code practice" article , don't remember where is it, but written by one of the giants  ( I think by Petzold, not sure about )
"Better yet to use the brackets always"

Following sage Petzold advice could never be a bad thing (very much enjoy his writing too). :)

Bottom line ... whatever scheme one employs ... do it consistently.
Engineering Technologist • CAD Automation Practitioner
Automation ▸ Design ▸ Drafting ▸ Document Control ▸ Client
cadanalyst@gmail.comhttp://cadanalyst.slack.comhttp://linkedin.com/in/cadanalyst