Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. The Lounge
  3. do any of you others have little coding mantras that save your behind?

do any of you others have little coding mantras that save your behind?

Scheduled Pinned Locked Moved The Lounge
csharpcssvisual-studioquestion
73 Posts 32 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • H honey the codewitch

    One of mine is - when dealing with IComparable in .NET "Greater than is less than" What it means is Converting

    if(10>5);

    to IComparable it reads

    if(0<10.CompareTo(5));

    Note '>' vs '<'

    When I was growin' up, I was the smartest kid I knew. Maybe that was just because I didn't know that many kids. All I know is now I feel the opposite.

    A Offline
    A Offline
    AnotherKen
    wrote on last edited by
    #34

    Well, I more or less always knew that my greatest weakness was my tendency to want certain sections of my code to be bug free. That kind of code-blindness causes extra work when debugging. Through the years I have advanced to the point where I can realize now that I write loads of lines of bugs encapsulating some small bits of perfectly functional code. I'm actually a decent debugger now, I'm still working on the programming part.

    H 1 Reply Last reply
    0
    • A AnotherKen

      Well, I more or less always knew that my greatest weakness was my tendency to want certain sections of my code to be bug free. That kind of code-blindness causes extra work when debugging. Through the years I have advanced to the point where I can realize now that I write loads of lines of bugs encapsulating some small bits of perfectly functional code. I'm actually a decent debugger now, I'm still working on the programming part.

      H Offline
      H Offline
      honey the codewitch
      wrote on last edited by
      #35

      AnotherKen wrote:

      I'm actually a decent debugger now, I'm still working on the programming part.

      Ha! relatable content :-D

      When I was growin' up, I was the smartest kid I knew. Maybe that was just because I didn't know that many kids. All I know is now I feel the opposite.

      1 Reply Last reply
      0
      • H honey the codewitch

        One of mine is - when dealing with IComparable in .NET "Greater than is less than" What it means is Converting

        if(10>5);

        to IComparable it reads

        if(0<10.CompareTo(5));

        Note '>' vs '<'

        When I was growin' up, I was the smartest kid I knew. Maybe that was just because I didn't know that many kids. All I know is now I feel the opposite.

        K Offline
        K Offline
        kalberts
        wrote on last edited by
        #36

        The REALLY big mistake is that the C# designers carried forward the old C way of reporting something non-numeric as if it were a numeric. IT IS NOT! The value of comparing A with B is either "A is less", "They are equal", or "B is less", NOT -1, 0 or 1. C# did abandon pointers as integers - "if (pointer)" is not valid; you must test "if (pointer != null)". They should have completed the job! Every now and then I get so frustrated over this that I write a thin skin for the comparisons, casting those inappropriate integers into an enum. But C# doesn't really treat enums as a proper type, more as synonyms for integers, so it really doesn't do it; it just reduces my frustration to a managable level.

        H 1 Reply Last reply
        0
        • K kalberts

          The REALLY big mistake is that the C# designers carried forward the old C way of reporting something non-numeric as if it were a numeric. IT IS NOT! The value of comparing A with B is either "A is less", "They are equal", or "B is less", NOT -1, 0 or 1. C# did abandon pointers as integers - "if (pointer)" is not valid; you must test "if (pointer != null)". They should have completed the job! Every now and then I get so frustrated over this that I write a thin skin for the comparisons, casting those inappropriate integers into an enum. But C# doesn't really treat enums as a proper type, more as synonyms for integers, so it really doesn't do it; it just reduces my frustration to a managable level.

          H Offline
          H Offline
          honey the codewitch
          wrote on last edited by
          #37

          The problem with that is they may not be 1, 0 or -1. Any positive value and 1 are going to have to be treated the same, and the same goes for the negative values - they're all -1, basically. But other than that, yeah. Although hate enums, because .NET made them slow. I still use them, but they make me frustrated. So usually in my classes where I don't want to burn extra clocks like my pull parsers I use an int to keep state, and cast it to an enum before the user of my code touches is.

          When I was growin' up, I was the smartest kid I knew. Maybe that was just because I didn't know that many kids. All I know is now I feel the opposite.

          K 1 Reply Last reply
          0
          • M Member 9167057

            That, on the other hand, may work just fine. Depends on the language/runtime library and the source of the dates, but when I want to know if some date is today, equality works. Again, assuming the runtime library helps and you know what you're doing. There's a reason why TheDailyWTF has a couple stories on mishandling time stamps. I suppose, we could amend "Don't run home-built date/time handling" to the list of useful mantras. There's heap tons of ways to get them wrong and even if you test all you can, it may fail when a leap year occurs.

            P Offline
            P Offline
            Peter R Fletcher
            wrote on last edited by
            #38

            Pure dates are generally not a problem, as long as you (or the coder from whose output you are getting the date) don't/didn't do something very stupid. Even here, however, timezone issues can cause problems. I once had an issue which resulted from the author of the firmware of a device I was getting data from recording what should have been a pure (midnight) datestamp as the corresponding local datetime. Since I am in the GMT-5 timezone, midnight on April 4 became 7 pm on April 3! Trying to compare datetimes for simultaneity, however, is almost always a severe PITA, when the source clocks are not both perfectly synchronized and using the same basic internal representation for clock time.

            K 1 Reply Last reply
            0
            • H honey the codewitch

              One of mine is - when dealing with IComparable in .NET "Greater than is less than" What it means is Converting

              if(10>5);

              to IComparable it reads

              if(0<10.CompareTo(5));

              Note '>' vs '<'

              When I was growin' up, I was the smartest kid I knew. Maybe that was just because I didn't know that many kids. All I know is now I feel the opposite.

              A Offline
              A Offline
              Alister Morton
              wrote on last edited by
              #39

              If it ain't broke, fix it 'til it is. Oh, hang on - save your ass, you say?

              1 Reply Last reply
              0
              • Sander RosselS Sander Rossel

                I have a few. The popular "if you're doing single line if statements you're doing it wrong." The equally catchy "only psycho's don't put spaces between their operands and operators." And my personal favorite "what would codewitch do, do the opposite." :D And one that's not so much related to code, but to specs. If it'll never happen, it'll happen soon (or it'll never never happen, but people don't tend to understand that one).

                Best, Sander sanderrossel.com Continuous Integration, Delivery, and Deployment arrgh.js - Bringing LINQ to JavaScript Object-Oriented Programming in C# Succinctly

                K Offline
                K Offline
                kalberts
                wrote on last edited by
                #40

                Sander Rossel wrote:

                The popular "if you're doing single line if statements you're doing it wrong."

                I had done quite a bit of Pascal programming when C came onto the scene. I have heard numerous arguments in favor of C, as opposed to Pascal. One of the major arguments against Pascal was "All that writing! All those keywords! It is almost like COBOL!" Essentially this referred to BEGIN-END. One-keystroke braces makes programming sooooo much faster... I have argued a lot about the impact on productivity from two or three extra keystrokes. Or fewer! Before C, no modern language required parentheses around a condition! No modern language required putting braces (or other delimiters) around single statements! The parser expects a block, and a single statement is a block! Then came this craze for LOC/day prouctivity measure. "My LOC/day is bigger than your LOC/day! So there!" The more lines you can spend on trivial things, the better programmer you are. Rather than

                if ExpectedRainfall > 0 then BringTheUmbella;

                you write

                if (ExpectedRainfall > 0)
                {
                BringTheUmbrella();
                }

                - some programmers would even give the "if" its own line, putting the condition on a separate line. And lots of C programmers consistently add blank lines around every conditional statement and every loop. In the days of hardcopy listing, I frequently printed out source code double-spaced to give the impression of a lot of blank lines to make the code more readable. Screens were 24 lines tall at that time - that is not much. I wanted it to display 24 useful code lines, not twelve blank lines. I wanted that IF statement to use one of the 24 lines, not 4 or 5, plus a blank line. With C, we replaced a four-character keyword with two sets of (), one set of {} and 3-5 more line breaks, to reduce all that typing of writing "then"... But the modern mantra is "doing it like that single-line Pascal statement is wrong! The 4-5 line (+ blank line) solution with three sets of delimiters added is the right way to do it". I miss Pascal!

                1 Reply Last reply
                0
                • X xtofl

                  * How would I explain this code to the cleaning personnel * If you can explain how it's done, you can script it

                  R Offline
                  R Offline
                  Rick York
                  wrote on last edited by
                  #41

                  I used to let them test my stuff. They were really good at finding bugs and breaking stuff because they did unexpected things which was exactly what I wanted.

                  "They have a consciousness, they have a life, they have a soul! Damn you! Let the rabbits wear glasses! Save our brothers! Can I get an amen?"

                  1 Reply Last reply
                  0
                  • H honey the codewitch

                    One of mine is - when dealing with IComparable in .NET "Greater than is less than" What it means is Converting

                    if(10>5);

                    to IComparable it reads

                    if(0<10.CompareTo(5));

                    Note '>' vs '<'

                    When I was growin' up, I was the smartest kid I knew. Maybe that was just because I didn't know that many kids. All I know is now I feel the opposite.

                    T Offline
                    T Offline
                    TrinityRaven
                    wrote on last edited by
                    #42

                    Don't return null. Throw an exception instead. Removes need to null check everything. Hopefully give a more meaningful error when a problem occurs.

                    H K 2 Replies Last reply
                    0
                    • A agolddog

                      Don't solve problems which don't actually exist. Like anything, this must be used in moderation. If there's a good, easy-to-understand abstraction you can implement which isn't required today , but you can see an obvious business case for it coming, go ahead. At the same time, be careful of overengineering just because you thought of some possible, but unlikely, abstraction. Design your code in such a way that can be implemented when the problem actually becomes something to solve.

                      R Offline
                      R Offline
                      Rick York
                      wrote on last edited by
                      #43

                      I have worked in the automation systems business for a long, long time and I found it is almost impossible to over-engineer things there. I wrote almost only because I haven't seen it happen yet.

                      "They have a consciousness, they have a life, they have a soul! Damn you! Let the rabbits wear glasses! Save our brothers! Can I get an amen?"

                      1 Reply Last reply
                      0
                      • H honey the codewitch

                        One of mine is - when dealing with IComparable in .NET "Greater than is less than" What it means is Converting

                        if(10>5);

                        to IComparable it reads

                        if(0<10.CompareTo(5));

                        Note '>' vs '<'

                        When I was growin' up, I was the smartest kid I knew. Maybe that was just because I didn't know that many kids. All I know is now I feel the opposite.

                        B Offline
                        B Offline
                        Bruce Greene
                        wrote on last edited by
                        #44

                        "Registered Nurse" to remember \r\n

                        1 Reply Last reply
                        0
                        • T TrinityRaven

                          Don't return null. Throw an exception instead. Removes need to null check everything. Hopefully give a more meaningful error when a problem occurs.

                          H Offline
                          H Offline
                          honey the codewitch
                          wrote on last edited by
                          #45

                          Yikes! I'd hate to write code that way but to each their own. Null is often as not, a valid value, and not even a symptom of some sort of error. No way do I want to wrap my calls to a function that is expected to have null as one of its values with:

                          object result;
                          try {
                          result=Foo();
                          }
                          catch { result = null;}

                          more bugs, extra slow, and for no reason.

                          When I was growin' up, I was the smartest kid I knew. Maybe that was just because I didn't know that many kids. All I know is now I feel the opposite.

                          T 1 Reply Last reply
                          0
                          • H honey the codewitch

                            One of mine is - when dealing with IComparable in .NET "Greater than is less than" What it means is Converting

                            if(10>5);

                            to IComparable it reads

                            if(0<10.CompareTo(5));

                            Note '>' vs '<'

                            When I was growin' up, I was the smartest kid I knew. Maybe that was just because I didn't know that many kids. All I know is now I feel the opposite.

                            I Offline
                            I Offline
                            Ira Greenstein
                            wrote on last edited by
                            #46

                            My Mantra: "I'm too old for this ***t"

                            K 1 Reply Last reply
                            0
                            • M Marc Clifton

                              Don't write an if unless you know what the else does and why. if and switch statements can be replaced with object inheritance. Let compiler do the work for you! Anything can be written with map-reduce-filter if you try hard enough. Don't try too hard. If you're about to write some code, stop.

                              Latest Articles:
                              Fun Exploring Div and Table UI Layout

                              K Offline
                              K Offline
                              kalberts
                              wrote on last edited by
                              #47

                              Marc Clifton wrote:

                              Don't write an if unless you know what the else does and why.

                              I have seen programmers consistently adding "else /* do nothing */; after every "if" that doesn't have a natural "else". I think that clutters up both the logic and the code. Lots of operations are conditional; you perform them when conditions are met. Otherwise you don't, but you don't have to say that expicitly; that is obvious! It follows from the very idea of a conditional operation. Besides: I prefer to turn up the warning level to maximum while coding. When I take over code with zillions of empty "else"s, I get a zillion warnings about "possibly unintended empty staetement". What is the real difference between an "if" and, say, a "while"? You suggest that you always should indicate an alternative action when the condition is not met. So how to you specify the alternative action when the "while" condition is not met? If you do not, why not? Isn't that a very similar situation? Why is it less important to know what to do if a "while" condition is false than when an "if" contidion is false? Actually, I have used one language quite a bit where you could specify what to do when a "while" fails: you could conditionally break out of "for"-loops, and distinguish between breakout and completion of loop:

                              for listElement in listHead:nextpointer do
                              while listElement.key <> wantedKey;
                              exitfor
                              output ("sorry, the wanted key is not in the list");
                              exitwhile
                              output ("found! I can process this list element for you"):
                              endfor;

                              This is actually a very nice flow control construction, which is a mess to duplicate in C if you want the "exitfor" and "exitwhile" claused to exexute within the context of the loop (e.g. with access to loop local variables), which is one of the essential points. I honestly miss that flow construction. Why can't other languages offer it?

                              1 Reply Last reply
                              0
                              • H honey the codewitch

                                heh. The yoda conditionals were hammered into me in the late 80s/early 90s. The multiple comparisons are a necessary evil, as TKey isn't directly comparable. You have to use its IComparable interface. Oh how I wish .NET would let you declare a contract on operators. You can't. It's a limitation of .NET's generic types.

                                When I was growin' up, I was the smartest kid I knew. Maybe that was just because I didn't know that many kids. All I know is now I feel the opposite.

                                K Offline
                                K Offline
                                kalberts
                                wrote on last edited by
                                #48

                                If you remember to put the constant on the left side, you also would remember to double the equals sign. And why the h*** do we have to double the equals sign? This thread makes me miss Pascal so much! In Norwegian, "yoda" sounds like "joda...", ususally pronounced with a sigh, meaning "yes, but...". I hear what you say, but I am certainly not sure that you are right. So "yoda" may be an appropriate term :-) Pascal, and several other languages from that period, were designed by experts on formal languages, parsing etc. C is based on a collection of scraps left over from an early days space invation game implementation. OK, those students were certainly clever, but they were not experienced language designers.

                                H 1 Reply Last reply
                                0
                                • H honey the codewitch

                                  Yikes! I'd hate to write code that way but to each their own. Null is often as not, a valid value, and not even a symptom of some sort of error. No way do I want to wrap my calls to a function that is expected to have null as one of its values with:

                                  object result;
                                  try {
                                  result=Foo();
                                  }
                                  catch { result = null;}

                                  more bugs, extra slow, and for no reason.

                                  When I was growin' up, I was the smartest kid I knew. Maybe that was just because I didn't know that many kids. All I know is now I feel the opposite.

                                  T Offline
                                  T Offline
                                  TrinityRaven
                                  wrote on last edited by
                                  #49

                                  Different use cases. I’m stuck debugging an app that is crashing because NULL is not a valid value. A part of what makes programming fun (?), is the various ways to solve a particular problem.

                                  H 1 Reply Last reply
                                  0
                                  • K kalberts

                                    If you remember to put the constant on the left side, you also would remember to double the equals sign. And why the h*** do we have to double the equals sign? This thread makes me miss Pascal so much! In Norwegian, "yoda" sounds like "joda...", ususally pronounced with a sigh, meaning "yes, but...". I hear what you say, but I am certainly not sure that you are right. So "yoda" may be an appropriate term :-) Pascal, and several other languages from that period, were designed by experts on formal languages, parsing etc. C is based on a collection of scraps left over from an early days space invation game implementation. OK, those students were certainly clever, but they were not experienced language designers.

                                    H Offline
                                    H Offline
                                    honey the codewitch
                                    wrote on last edited by
                                    #50

                                    it's not just about remembering. It's about typos. A better argument is that compilers these days catch accidental assignment, but some of us have just had certain practices drummed into us for years and they stick. Double equals sign is necessary in the C family of languages because there are different ways to do equality and assignment. And you may find the C language family inelegant, but there's a reason they carried the day and pascal well... didn't.

                                    When I was growin' up, I was the smartest kid I knew. Maybe that was just because I didn't know that many kids. All I know is now I feel the opposite.

                                    K 1 Reply Last reply
                                    0
                                    • M Member 9167057

                                      Oddly enough, I can't remember any problems you're talking about from my own experience. And I am not even a programmer by trade, I've studied physics and programming was a side-gig at first. To me, integer numbers are exact and floats are, as it's impossible to represent arbitrary numbers with discrete values, approximations. They may be good enough for daily use, but they may fail and when they do, they fail. Maybe that's why I didn't have any problems, the concept of approximations is deeply nested in a physicist's mind. Well, that and I've recently built a system which used integer for it's measurement values (mostly because the sensor returns integers by the value of 0,01°C). So your vocabulary would have spectacularily failed me :D

                                      K Offline
                                      K Offline
                                      kalberts
                                      wrote on last edited by
                                      #51

                                      Students insist that when you measure up 3 kg of flour for your bread, that is count of the number of kilograms. Their body height is a count of centimeters. It goes the other way, too: They may use a float for the number of students in the class, arguing that when they increase the number by 1.0 for each newcomer, the float still represents the count of students. And, the more advanced ones argue, with a float, you can count any number of units. A plain int can't even count the number of living humans! Sure, most of these problem come with students who have been playing with computers in their bedroom since they were ten, all self-learned, having picked up one little bit here one there, with no trace of discipline whatsoever. But frequently, these become class heroes: Other students learn "smart tricks" from them, and "how real programmer do it, not the way that silly lecturer tells us to". So they can have a large influence on otherwise "innocent" students. This is mostly a problem with students. With professional programmers, the problem is with those who do not fully realize that e.g. a comparison does NOT return an integer (-1, 0, 1) but "less", "equal", "greater", and you should NOT compare it to numerical values. If you declare non-numeric, yet ordered, values as an enum, and create an array of, say, weather[january..december], you canNOT index this array with an integer, "because may is the fifth month, I can use 5 as an index... no, wait, I have to use 4, because it is zero based!" One specfic example: In my own C code, I use to define "ever" as ";;" so that an infinite loop, it is made explicit as "for (ever) {...}" (inspired by the CHILL language, where "for ever" is recognized by the compiler). I used this in one of the code modules I was responsible for at work. It was discovered by one of the young and extremely self-confident programmers, who was immensely provoked by it: He promptly replaced it by the "proper" way of writing an infinite loop: "while(1){..}". He searched through our entire codebase for other places where I had done similar sins, adding a very nasty remark in the SVN log for each and every occurance, requesting that everybody in the future refrain from such inappropriate funnyness - we should do our progamming in a serious manner. Oh, well - I din't care to argue. Why should I. Readable, easily comprehendable code is more essential when it will be read by people who are not into embedded systems code. Or rahter, to a developer of embedded C code,

                                      1 Reply Last reply
                                      0
                                      • T TrinityRaven

                                        Different use cases. I’m stuck debugging an app that is crashing because NULL is not a valid value. A part of what makes programming fun (?), is the various ways to solve a particular problem.

                                        H Offline
                                        H Offline
                                        honey the codewitch
                                        wrote on last edited by
                                        #52

                                        ha!, i can understand your sentiment. I recently developed a caching JSON entity framework for accessing TMDb's REST API and all their JSON fields are marked optional, which means potential for nulls everywhere. It made errorhandling hell.

                                        When I was growin' up, I was the smartest kid I knew. Maybe that was just because I didn't know that many kids. All I know is now I feel the opposite.

                                        1 Reply Last reply
                                        0
                                        • H honey the codewitch

                                          The problem with that is they may not be 1, 0 or -1. Any positive value and 1 are going to have to be treated the same, and the same goes for the negative values - they're all -1, basically. But other than that, yeah. Although hate enums, because .NET made them slow. I still use them, but they make me frustrated. So usually in my classes where I don't want to burn extra clocks like my pull parsers I use an int to keep state, and cast it to an enum before the user of my code touches is.

                                          When I was growin' up, I was the smartest kid I knew. Maybe that was just because I didn't know that many kids. All I know is now I feel the opposite.

                                          K Offline
                                          K Offline
                                          kalberts
                                          wrote on last edited by
                                          #53

                                          honey the codewitch wrote:

                                          Although hate enums, because .NET made them slow. I still use them, but they make me frustrated.

                                          The very first compiler I dug into was the Pascal P4 compiler - those who think "open source" is something that came with Linux are completely wrong. Pascal provides enums as first class types, not something derived from integer. The compiler source showed very clearly how the compiler treats enums just like integers; it just doesn't mix the two types up, it doensn't allow you to use them interchangably. It is like having intTypeA and intTypeB which are 100% incompatible. If you do casting to (or from) int, it is a pure compile-time thing: It shortcuts the error handling reporting that the types are incompatible. There is nothing that causes more instructions to be executed when you use enums rather than int - not even when you do casting. Why would there be? Why should .net make them slower? If you have full enum implementation (like that of Pascal) and make more use of it, then there may of course be a few more instructions generated. E.g. if you have a 12-value enum from janurary to december, and define an array with indexes from april to august, then the runtime code must skew the actual index values so that an "april" index is mapped to the base adress of the array, not three elements higher. Index values must be checked against the array declaration: january to march and september to december must generate an exception. But that is extended functionality - if you want that with integer indexes, and the same checking, you would generate a lot more code writing the index scewing and testing as explicit C statements. Maybe the current C# .net compiler is not doing things "properly" - similar to that Pascal compiler written in the early 1970s. I guess it could. I see no reason why it should be able to, nothing in semantics of C# "semi-enums" making it more difficult that Pascal's full enum implemnentation.

                                          H 1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups