Why is this bad practice

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • philipl@vistatec.ie

    #1

    Why is this bad practice

    hi,

    while reading .net framework sdk, it says that the following is bad
    practice, then it goes on to give an example with the very same
    instance of this 'bad practice'. Can someone comment on this, is it
    good or bad?

    //msdn
    public int Number
    {
    get
    {
    return number++; // Don't do this
    }
    }


    then further on.....

    Example 2
    In this example, two classes, Cube and Square, implement an abstract
    class, Shape, and override its abstract Area property. Note the use of
    the override modifier on the properties. The program accepts the side
    as an input and calculates the areas for the square and cube. It also
    accepts the area as an input and calculates the corresponding side for
    the square and cube.

    // overridding_pro perties.cs
    // Overriding properties
    using System;
    abstract class Shape
    {
    public abstract double Area
    {
    get;
    set;
    }
    }

    class Square: Shape
    {
    public double side;

    // Constructor:
    public Square(double s)
    {
    side = s;
    }

    // The Area property
    public override double Area
    {
    get
    {
    return side*side ;
    }
    set
    {
    // Given the area, compute the side
    side = Math.Sqrt(value );
    }
    }
    }

    class Cube: Shape
    {
    public double side;

    // Constructor:
    public Cube(double s)
    {
    side = s;
    }

    // The Area property
    public override double Area
    {
    get
    {
    return 6*side*side;
    }
    set
    {
    // Given the area, compute the side
    side = Math.Sqrt(value/6);
    }
    }
    }

    public class MainClass
    {
    public static void Main()
    {
    // Input the side:
    Console.Write(" Enter the side: ");
    string sideString = Console.ReadLin e();
    double side = double.Parse(si deString);

    // Compute areas:
    Square s = new Square(side);
    Cube c = new Cube(side);

    // Display results:
    Console.WriteLi ne("Area of a square = {0:F2}",s.Area) ;
    Console.WriteLi ne("Area of a cube = {0:F2}", c.Area);

    // Input the area:
    Console.Write(" Enter the area: ");
    string areaString = Console.ReadLin e();
    double area = double.Parse(ar eaString);

    // Compute sides:
    s.Area = area;
    c.Area = area;

    // Display results:
    Console.WriteLi ne("Side of a square = {0:F2}", s.side);
    Console.WriteLi ne("Side of a cube = {0:F2}", c.side);
    }
    }
    Input
    4
    24
    Sample Output
    Enter the side: 4
    Area of a square = 16.00
    Area of a cube = 96.00
    Enter the area: 24
    Side of a square = 4.90
    Side of a cube = 2.00
  • Jon Skeet [C# MVP]

    #2
    Re: Why is this bad practice

    philipl@vistate c.ie <philipl@vistat ec.ie> wrote:[color=blue]
    > while reading .net framework sdk, it says that the following is bad
    > practice, then it goes on to give an example with the very same
    > instance of this 'bad practice'. Can someone comment on this, is it
    > good or bad?
    >
    > //msdn
    > public int Number
    > {
    > get
    > {
    > return number++; // Don't do this
    > }
    > }[/color]

    Where exactly does that occur in the example that follows? Note that
    the bad practice here is that fetching the Number also *changes* it -
    something that I can't see happening in the example you gave.

    --
    Jon Skeet - <skeet@pobox.co m>
    Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

    If replying to the group, please do not mail me too

    Comment

    • Vincent Lascaux

      #3
      Re: Why is this bad practice

      > //msdn[color=blue]
      > public int Number
      > {
      > get
      > {
      > return number++; // Don't do this
      > }
      > }[/color]

      Here you wont get the same answer every time you read the Number property...
      It's bad : I expect that x.Number + x.Number == 2*x.Number, but it's not the
      case. You should not modify any variable within the get member of a
      property...
      [color=blue]
      > // The Area property
      > public override double Area
      > {
      > get
      > {
      > return side*side ;
      > }[/color]

      That's ok : I'll get the same answer every time I read the Area property
      (provided 'side' doesnt change)...


      Comment

      • Joe Kasta

        #4
        One other reason.

        I"m not sure how it's implemented in the .NET framework, but ++number is
        usually preferred to number++.

        Why? Some implementations I"ve seen use this to mean number++

        {
        int temp = number;
        number = number + 1;
        return temp;
        }
        Note, the number is incremented an another object is allocated. But in
        ++number,

        {
        number = number + 1;
        return number;
        }

        No extra step or allocation. Not sure of .NET does it this way, but it's
        good practice to use, where you can.

        =J

        <philipl@vistat ec.ie> wrote in message
        news:a3f6c32f.0 310080211.a0887 85@posting.goog le.com...[color=blue]
        > hi,
        >
        > while reading .net framework sdk, it says that the following is bad
        > practice, then it goes on to give an example with the very same
        > instance of this 'bad practice'. Can someone comment on this, is it
        > good or bad?
        >
        > //msdn[/color]
        [color=blue]
        >
        >
        > then further on.....
        >
        > Example 2
        > In this example, two classes, Cube and Square, implement an abstract
        > class, Shape, and override its abstract Area property. Note the use of
        > the override modifier on the properties. The program accepts the side
        > as an input and calculates the areas for the square and cube. It also
        > accepts the area as an input and calculates the corresponding side for
        > the square and cube.
        >
        > // overridding_pro perties.cs
        > // Overriding properties
        > using System;
        > abstract class Shape
        > {
        > public abstract double Area
        > {
        > get;
        > set;
        > }
        > }
        >
        > class Square: Shape
        > {
        > public double side;
        >
        > // Constructor:
        > public Square(double s)
        > {
        > side = s;
        > }
        >
        > // The Area property
        > public override double Area
        > {
        > get
        > {
        > return side*side ;
        > }
        > set
        > {
        > // Given the area, compute the side
        > side = Math.Sqrt(value );
        > }
        > }
        > }
        >
        > class Cube: Shape
        > {
        > public double side;
        >
        > // Constructor:
        > public Cube(double s)
        > {
        > side = s;
        > }
        >
        > // The Area property
        > public override double Area
        > {
        > get
        > {
        > return 6*side*side;
        > }
        > set
        > {
        > // Given the area, compute the side
        > side = Math.Sqrt(value/6);
        > }
        > }
        > }
        >
        > public class MainClass
        > {
        > public static void Main()
        > {
        > // Input the side:
        > Console.Write(" Enter the side: ");
        > string sideString = Console.ReadLin e();
        > double side = double.Parse(si deString);
        >
        > // Compute areas:
        > Square s = new Square(side);
        > Cube c = new Cube(side);
        >
        > // Display results:
        > Console.WriteLi ne("Area of a square = {0:F2}",s.Area) ;
        > Console.WriteLi ne("Area of a cube = {0:F2}", c.Area);
        >
        > // Input the area:
        > Console.Write(" Enter the area: ");
        > string areaString = Console.ReadLin e();
        > double area = double.Parse(ar eaString);
        >
        > // Compute sides:
        > s.Area = area;
        > c.Area = area;
        >
        > // Display results:
        > Console.WriteLi ne("Side of a square = {0:F2}", s.side);
        > Console.WriteLi ne("Side of a cube = {0:F2}", c.side);
        > }
        > }
        > Input
        > 4
        > 24
        > Sample Output
        > Enter the side: 4
        > Area of a square = 16.00
        > Area of a cube = 96.00
        > Enter the area: 24
        > Side of a square = 4.90
        > Side of a cube = 2.00[/color]


        Comment

        • Jon Skeet [C# MVP]

          #5
          Re: One other reason.

          Joe Kasta <J@microkroff.c om> wrote:[color=blue]
          > I"m not sure how it's implemented in the .NET framework, but ++number is
          > usually preferred to number++.[/color]

          That may be true in some particualr languages, but generalising it to
          "usually" strikes me as a bad idea.
          [color=blue]
          > Why? Some implementations I"ve seen use this to mean number++
          >
          > {
          > int temp = number;
          > number = number + 1;
          > return temp;
          > }
          > Note, the number is incremented an another object is allocated.[/color]

          Where's the object here? In this case it's just integers, so no objects
          are being allocated at all. In the case where objects *are* allocated,
          a new object should be allocated in either way, rather than updating
          the current one. The only difference is that the stack needs to be one
          bit larger - and then only if it's actually being used in the middle of
          an expression, in which case the difference is semantically important
          anyway. I trust the JIT to optimise the two equally when they're
          statements on their own.

          <snip>
          [color=blue]
          > No extra step or allocation. Not sure of .NET does it this way, but it's
          > good practice to use, where you can.[/color]

          I disagree with the idea that one should take idioms from one
          language/platform and apply them indiscriminatel y to others. I
          personally find number++; more readable, and will continue to do so
          until I've seen some evidence that shows it makes any difference in the
          actual context in which I'm using it.

          --
          Jon Skeet - <skeet@pobox.co m>
          Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

          If replying to the group, please do not mail me too

          Comment

          • Stu Banter

            #6
            Re: One other reason.


            "Joe Kasta" <J@microkroff.c om> wrote in message
            news:OeiW0YdjDH A.3504@TK2MSFTN GP11.phx.gbl...[color=blue]
            > I"m not sure how it's implemented in the .NET framework, but ++number is
            > usually preferred to number++.
            >[/color]

            I think your statement holds little truth. Whether I choose prefix or
            postfix operators depends entirely on the situation at hand. I wouldn't like
            to see this in a program a lot:

            for (int i = 0 ; i < MaxValue; ++i)
            {
            myArray [i-1] = (i-1) * (i-1); // or whatever you want to do with it....
            }


            Besides, I think the point of the OP's example of bad practise is a
            different one altogether, and prefixed the idea would be as bad a practice
            as any other example in which a var gets altered in a get accessor.

            The idea of a get accessor is the var is now available to the outside world
            like it would be a public var, so I'd EXPECT its behaviour to be similar,
            and not have any modifying actions performed on it. get & set were not meant
            to be just another method. I'd have expected it to be illegal even to modify
            the key value in the get accessor...


            Comment

            • Vincent Lascaux

              #7
              Re: One other reason.

              > I think your statement holds little truth. Whether I choose prefix or[color=blue]
              > postfix operators depends entirely on the situation at hand. I wouldn't[/color]
              like[color=blue]
              > to see this in a program a lot:
              >
              > for (int i = 0 ; i < MaxValue; ++i)
              > {
              > myArray [i-1] = (i-1) * (i-1); // or whatever you want to do with[/color]
              it....[color=blue]
              > }[/color]

              Would you definitly prefer this ?
              for(int i = 0; i < MaxValue; i++)
              {
              myArray [i-1] = (i-1) * (i-1); // or whatever you want to do with it....
              }
              In this example, ++i and i++ are interchangeable because their value is not
              read (the value of 'i' is read, but after ++i or i++, i has the same value)

              ++i is, IMHO, far more intuitive than i++. I think ++i should be used every
              where, but when i++ is what you mean (and it's rare to need to use i++).


              Comment

              • Jon Skeet [C# MVP]

                #8
                Re: One other reason.

                Vincent Lascaux <nospam@nospam. org> wrote:

                <snip>
                [color=blue]
                > ++i is, IMHO, far more intuitive than i++. I think ++i should be used every
                > where, but when i++ is what you mean (and it's rare to need to use i++).[/color]

                And that's fine for you, but I suspect (given the balance of code that
                I've read) that most other people prefer i++; when it's the same as
                ++i; - I know I do. (I like to read what I'm incrementing before I see
                that I'm going to increment it.)

                This is one of the issues which I believe is down to pure personal
                taste.

                --
                Jon Skeet - <skeet@pobox.co m>
                Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

                If replying to the group, please do not mail me too

                Comment

                • Vincent Lascaux

                  #9
                  Re: One other reason.

                  > And that's fine for you, but I suspect (given the balance of code that[color=blue]
                  > I've read) that most other people prefer i++[/color]

                  I suspect that most teacher teach i++ rather than ++i (I don't know why :
                  ++i is easier to teach and more performant than i++).
                  [color=blue]
                  > I like to read what I'm incrementing before I see
                  > that I'm going to increment it.[/color]

                  I agree with that point : i++ is more readable (provided you dont need to
                  understand what it does ;))


                  Comment

                  • Jon Skeet [C# MVP]

                    #10
                    Re: One other reason.

                    Vincent Lascaux <nospam@nospam. org> wrote:[color=blue][color=green]
                    > > And that's fine for you, but I suspect (given the balance of code that
                    > > I've read) that most other people prefer i++[/color]
                    >
                    > I suspect that most teacher teach i++ rather than ++i (I don't know why :
                    > ++i is easier to teach and more performant than i++).[/color]

                    Ah - now you're making measurable claims. Do you have any evidence that
                    ++i performs better in C#/.NET than ++i does? A quick test of:

                    static void Foo()
                    {
                    int i=0;
                    i++;
                    Console.WriteLi ne (i);
                    }

                    static void Bar()
                    {
                    int i=0;
                    ++i;
                    Console.WriteLi ne (i);
                    }

                    shows the same IL being generated for both.
                    [color=blue][color=green]
                    > > I like to read what I'm incrementing before I see
                    > > that I'm going to increment it.[/color]
                    >
                    > I agree with that point : i++ is more readable (provided you dont need to
                    > understand what it does ;))[/color]

                    I'd say that even if you *do* know what it does, it's more readable.

                    --
                    Jon Skeet - <skeet@pobox.co m>
                    Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

                    If replying to the group, please do not mail me too

                    Comment

                    • Vincent Lascaux

                      #11
                      Re: One other reason.

                      > shows the same IL being generated for both.

                      How do you see the generated IL ?
                      [color=blue][color=green]
                      > > I agree with that point : i++ is more readable (provided you dont need[/color][/color]
                      to[color=blue][color=green]
                      > > understand what it does ;))[/color]
                      >
                      > I'd say that even if you *do* know what it does, it's more readable.[/color]

                      When I read ++i, I think "here, i is incremented". When I read i++, I think
                      "ok, i is incremented, but the value of i++ is the old value of i" or "this
                      expression will be evaluated and i will be incremented after".
                      What I have seen is a lot of people thinking "here, i is incremented" when
                      they read i++. And that leads to errors when they use i++ in expressions...


                      Comment

                      • Jon Skeet [C# MVP]

                        #12
                        Re: One other reason.

                        Vincent Lascaux <nospam@nospam. org> wrote:[color=blue][color=green]
                        > > shows the same IL being generated for both.[/color]
                        >
                        > How do you see the generated IL ?[/color]

                        Use ILDASM.
                        [color=blue][color=green][color=darkred]
                        > > > I agree with that point : i++ is more readable (provided you dont need[/color][/color]
                        > to[color=green][color=darkred]
                        > > > understand what it does ;))[/color]
                        > >
                        > > I'd say that even if you *do* know what it does, it's more readable.[/color]
                        >
                        > When I read ++i, I think "here, i is incremented". When I read i++, I think
                        > "ok, i is incremented, but the value of i++ is the old value of i" or "this
                        > expression will be evaluated and i will be incremented after".
                        > What I have seen is a lot of people thinking "here, i is incremented" when
                        > they read i++. And that leads to errors when they use i++ in expressions...[/color]

                        But you really only get much *choice* about which to use when it's
                        standing alone. I very rarely use it within another expression, eg:

                        x = i++;
                        y = ++i;

                        I'd almost always write the above as:

                        x = i;
                        i++;

                        i++;
                        y=i;

                        just because it's clearer even when you *are* clear what the two
                        operators mean.

                        So essentially, the way I write code, the two operators are almost
                        always identical, but I find i++; easier to read.

                        --
                        Jon Skeet - <skeet@pobox.co m>
                        Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

                        If replying to the group, please do not mail me too

                        Comment

                        • Daniel Billingsley

                          #13
                          Re: One other reason.

                          If a person doesn't readily understand what i++ does when they see it, then
                          this discussion is way over their head and they wouldn't know the difference
                          between ++i and i++ anyway. Your last statement is laughably ridiculous to
                          the point that you're not really contributing anything sensible to this
                          discussion.

                          "Vincent Lascaux" <nospam@nospam. org> wrote in message
                          news:3f854a72$0 $10411$626a54ce @news.free.fr.. .[color=blue][color=green]
                          > > And that's fine for you, but I suspect (given the balance of code that
                          > > I've read) that most other people prefer i++[/color]
                          >
                          > I suspect that most teacher teach i++ rather than ++i (I don't know why :
                          > ++i is easier to teach and more performant than i++).
                          >[color=green]
                          > > I like to read what I'm incrementing before I see
                          > > that I'm going to increment it.[/color]
                          >
                          > I agree with that point : i++ is more readable (provided you dont need to
                          > understand what it does ;))
                          >
                          >[/color]


                          Comment

                          • Daniel Billingsley

                            #14
                            Re: One other reason.

                            Jon, "readabilit y" is a subjective thing of course, and unless someone can
                            demonstrate some psychological testing that demonstrates which is the case
                            it is simply a matter of personal taste. Having said that, I will say that
                            anecdotally speaking, looking at other people's code you will see i++ 100
                            times for every once you see ++i (at least), and that would suggest that i++
                            is probably much more quickly grasped... much like when you read you don't
                            actually have to spend any time processing the sequence of letters y-o-u
                            because your brain instantly recognizes that pattern as the word "the" - but
                            come across t-h-e-e used to mean the same thing and there would be a
                            definite slowdown because of unfamiliarity.

                            What I'm trying to say is you've demonstrated that Vincent is clearly wrong
                            on his first point (performance). He is also almost certainly wrong on his
                            second point, generally speaking, but I know of no evidence proving it so.

                            "Jon Skeet [C# MVP]" <skeet@pobox.co m> wrote in message
                            news:MPG.19ef5c ccfc36f0a898983 4@msnews.micros oft.com...[color=blue]
                            > Vincent Lascaux <nospam@nospam. org> wrote:[color=green][color=darkred]
                            > > > And that's fine for you, but I suspect (given the balance of code that
                            > > > I've read) that most other people prefer i++[/color]
                            > >
                            > > I suspect that most teacher teach i++ rather than ++i (I don't know why[/color][/color]
                            :[color=blue][color=green]
                            > > ++i is easier to teach and more performant than i++).[/color]
                            >
                            > Ah - now you're making measurable claims. Do you have any evidence that
                            > ++i performs better in C#/.NET than ++i does? A quick test of:
                            >
                            > static void Foo()
                            > {
                            > int i=0;
                            > i++;
                            > Console.WriteLi ne (i);
                            > }
                            >
                            > static void Bar()
                            > {
                            > int i=0;
                            > ++i;
                            > Console.WriteLi ne (i);
                            > }
                            >
                            > shows the same IL being generated for both.
                            >[color=green][color=darkred]
                            > > > I like to read what I'm incrementing before I see
                            > > > that I'm going to increment it.[/color]
                            > >
                            > > I agree with that point : i++ is more readable (provided you dont need[/color][/color]
                            to[color=blue][color=green]
                            > > understand what it does ;))[/color]
                            >
                            > I'd say that even if you *do* know what it does, it's more readable.
                            >
                            > --
                            > Jon Skeet - <skeet@pobox.co m>
                            > http://www.pobox.com/~skeet
                            > If replying to the group, please do not mail me too[/color]


                            Comment

                            • Jon Skeet [C# MVP]

                              #15
                              Re: One other reason.

                              Daniel Billingsley <dbillingsley@N O.durcon.SPAAMM .com> wrote:[color=blue]
                              > Jon, "readabilit y" is a subjective thing of course, and unless someone can
                              > demonstrate some psychological testing that demonstrates which is the case
                              > it is simply a matter of personal taste.[/color]

                              I wouldn't go that far - there are certain things which are *obviously*
                              more readable in general without needing a psychological study to prove
                              it. However, I agree that on many things it *can* be a matter of
                              personal taste.
                              [color=blue]
                              > Having said that, I will say that
                              > anecdotally speaking, looking at other people's code you will see i++ 100
                              > times for every once you see ++i (at least), and that would suggest that i++
                              > is probably much more quickly grasped... much like when you read you don't
                              > actually have to spend any time processing the sequence of letters y-o-u
                              > because your brain instantly recognizes that pattern as the word "the" - but
                              > come across t-h-e-e used to mean the same thing and there would be a
                              > definite slowdown because of unfamiliarity.[/color]

                              Excatly.
                              [color=blue]
                              > What I'm trying to say is you've demonstrated that Vincent is clearly wrong
                              > on his first point (performance). He is also almost certainly wrong on his
                              > second point, generally speaking, but I know of no evidence proving it so.[/color]

                              Right - we've only got anecdotal evidence (the way people actually
                              write code) and our own personal tastes. It's not necessarily proof,
                              but it's good enough for me :)

                              --
                              Jon Skeet - <skeet@pobox.co m>
                              Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

                              If replying to the group, please do not mail me too

                              Comment

                              Working...