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. Extension Methods - Satan's favourite construct (controversial to nerds)

Extension Methods - Satan's favourite construct (controversial to nerds)

Scheduled Pinned Locked Moved The Lounge
csharpfunctionallinqbusinessregex
94 Posts 34 Posters 1 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.
  • J jschell

    Joe Woodbury wrote:

    You are touching on a very sore point for me; all these features encourage increasingly bad design.

    Only to a limited extent. There are extreme cases but most development with 'clever' code has a smaller scope than would be normally covered by a real design. Of course since there is seldom anything even close to a real design - that is the real problem.

    Joe Woodbury wrote:

    It's simply easier to churn out code that kind of works for now and then quickly move on to another project

    One must be agile like that.

    J Offline
    J Offline
    Joe Woodbury
    wrote on last edited by
    #50

    jschell wrote:

    Only to a limited extent.

    I believe it is to a great, if not massive, extent. I have observed over the years that complex software tools and languages tend to result in increased complexity in all parts of a solution. I believe that the developers and architects "see" the solution through the lens of what surrounds it. In many cases it's as though they become blind to simplicity. Very trivial examples are the countless times I've seen vector used when a simple array would suffice. A less trivial example are designs involving a complex class hierarchy with extensive collections and multiple threads when a simple class, some global objects and one or two threads would be sufficient. (Another example is an architecture I dealt with which used WCF while plain sockets would have resulted in smaller, simpler and faster code which would have been much easier to maintain. It wouldn't have taken much longer to write and would have avoided a continual source of problems which easily added hundreds of hours of time to the full development process.)

    jschell wrote:

    Of course since there is seldom anything even close to a real design - that is the real problem.

    True.

    1 Reply Last reply
    0
    • J jschell

      Roger Alsing wrote:

      Bad coders write bad code..

      So presumably you are claiming that your usage is correct and understandable. And it is only others that have problems? And perhaps only those that are less intelligent than you would have any trouble understanding it? What classes have you taken to issue that your usage is correct? What standards do you use to insure that your usage is something that most average developers would have or should have learned?

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #51

      I'm in danger of getting a man crush on you. I'm having a similar issue with a guy at work, who is exceedingly clever, and has written all sorts of clever extension methods, and other goodies, without documentation or comment - so in order to program successfully on the system his solution is to ask him how to do it! your responses here may well be used against him :)

      MVVM# - See how I did MVVM my way ___________________________________________ Man, you're a god. - walterhevedeich 26/05/2011 .\\axxx (That's an 'M')

      1 Reply Last reply
      0
      • J jschell

        ahmed zahmed wrote:

        It's just code. Deal with it.

        As a professional developer I don't just deal with code though. It is my responsibility to insure that, to the best of my ability, I deliver something that provides the best value to the business. I don't care if the next three developers think my code is boring. I would however have a problem if the next three developers were afraid to touch my code because the complexity was so high that they couldn't figure out.

        L Offline
        L Offline
        Lost User
        wrote on last edited by
        #52

        It's gone beyond a crush, now I want your children.

        MVVM# - See how I did MVVM my way ___________________________________________ Man, you're a god. - walterhevedeich 26/05/2011 .\\axxx (That's an 'M')

        1 Reply Last reply
        0
        • R Rob Philpott

          Sometimes I yearn for a return to .NET 2.0. The C# that came with it was a great language and now that generics were included it was essentially complete in my mind. Since then, they've been adding all sorts of dubious things to the language LINQ being the most notable but now we also have the async/await business which really is anything but the simple solution to asynchronous programming they tell us it is. Extensions methods, everyone's favourite encapsulation anti-pattern debuted with LINQ in order to make it work and some people (me) viewed them with suspicious eyes at the time but didn't really know how bad things could get. Having recently worked on a system where they have been abused to the fullest I can tell you. You start off with pretty hollow objects with very little in the way of methods, just enough to get at the data. Then, you put all your logic in extension methods, preferably in different assemblies. A sort of warped onion architecture. Now, any normal developer who goes looking for a type's methods won't find them in the type or even that assembly. A missing reference will make them disappear completely. Also, with careful planning, you can make it exceedingly hard to move that logic back where it belongs because doing so will cause all kinds of circular dependency issues. Immutable code! Shocking stuff, but if you really hate the world, don't forget the Action<> and Func<> delegates. These are useful because you can avoid passing meaningful data to methods. Instead just pass delegates everywhere (a functional programming approach I'm told). This makes it practically impossible for anyone to work out the execution flow by examining the code. Combine the two and you have one thoroughly malevolent system. People bang on about patterns all the time in software development, but if you ask me (I'm aware you didn't) the way to build a good system is to always, always, always keep everything as simple as you can make it.

          Regards, Rob Philpott.

          Sander RosselS Offline
          Sander RosselS Offline
          Sander Rossel
          wrote on last edited by
          #53

          That's just a load of ... LINQ makes working with collections so much easier. I can simply order any collection, or combine lists, get unique values from a list that contains double values etc. etc. Imagine that each collection I made would have to implement its own sorting functionality... I could make a static sort method, but that is actually what LINQ is too, with the difference that you can use them as instance methods (but don't have to). Furthermore when using LINQ to SQL or LINQ to Entities you get a bonus of moving your queries from in-code strings to strong typed and easy to read LINQ queries. How is that any worse than using SP's in your database (which to me are king of like black boxes since they're out of your code) and/or strings in code? The Func<> and Action<> delegates prevent me from having all kinds of 1-line methods in my class that clutter up code. Functional programming has lots of good stuff, but works very different than OOP. Having some of it integrated in an OOP language is not bad per se, but it seems you're not very open to change. I read your profile and only 10 years ago you thought nothing could beat C++, now you think nothing can beat .NET 2.0. I'm not saying .NET 4.x doesn't have its flaws, but it has everything .NET 2.0 has and more. Wether you use it is up to you, but it's there for a reason: to solve all kinds of problems and issues (and does so when used right). Maybe in a couple of years you'll think that nothing can beat .NET 4.0... Or maybe you'll be doing F# by then and nothing will beat that... I got some bad news for you, but I think the problem here... is you.

          It's an OO world.

          public class Naerling : Lazy<Person>{
          public void DoWork(){ throw new NotImplementedException(); }
          }

          R J 2 Replies Last reply
          0
          • Sander RosselS Sander Rossel

            That's just a load of ... LINQ makes working with collections so much easier. I can simply order any collection, or combine lists, get unique values from a list that contains double values etc. etc. Imagine that each collection I made would have to implement its own sorting functionality... I could make a static sort method, but that is actually what LINQ is too, with the difference that you can use them as instance methods (but don't have to). Furthermore when using LINQ to SQL or LINQ to Entities you get a bonus of moving your queries from in-code strings to strong typed and easy to read LINQ queries. How is that any worse than using SP's in your database (which to me are king of like black boxes since they're out of your code) and/or strings in code? The Func<> and Action<> delegates prevent me from having all kinds of 1-line methods in my class that clutter up code. Functional programming has lots of good stuff, but works very different than OOP. Having some of it integrated in an OOP language is not bad per se, but it seems you're not very open to change. I read your profile and only 10 years ago you thought nothing could beat C++, now you think nothing can beat .NET 2.0. I'm not saying .NET 4.x doesn't have its flaws, but it has everything .NET 2.0 has and more. Wether you use it is up to you, but it's there for a reason: to solve all kinds of problems and issues (and does so when used right). Maybe in a couple of years you'll think that nothing can beat .NET 4.0... Or maybe you'll be doing F# by then and nothing will beat that... I got some bad news for you, but I think the problem here... is you.

            It's an OO world.

            public class Naerling : Lazy<Person>{
            public void DoWork(){ throw new NotImplementedException(); }
            }

            R Offline
            R Offline
            Rob Philpott
            wrote on last edited by
            #54

            Oh dear, oh dear. Did you get out of bed the wrong side this morning? Well, I'm not going to bother to argue the points bearing in mind your post seems more of a personal attack than a measured meaningful argument. Perhaps a nice walk in the park or something will soothe you.

            Regards, Rob Philpott.

            Sander RosselS 1 Reply Last reply
            0
            • E Ennis Ray Lynch Jr

              I am completely opposed to the AS operator. It causes more problems than it is worth. You talk about sloppy programming with extension methods, ugh, AS is worse. In fact, the AS keyword brought down an entire production system. (combined with a lazy programmer) The short story is that instead of relying on strong typing from the DB the developer used AS and converted the type to the expected type. Some DBA decided to change a database type without telling any one and a few weeks later another subsystem broke because of invalid data. Had the type been formally cast this error would have been caught immediately. I am of the camp that strong typing is important. Using conversion ... everywhere as AS encourages, only serves to disassociate developers from types (ok, this includes var) and types and the knowledge thereof is a fundamental underpinning of a stable, large system.

              Need custom software developed? I do custom programming based primarily on MS tools with an emphasis on C# development and consulting. "And they, since they Were not the one dead, turned to their affairs" -- Robert Frost "All users always want Excel" --Ennis Lynch

              pkfoxP Offline
              pkfoxP Offline
              pkfox
              wrote on last edited by
              #55

              +1 :thumbsup:

              When the going gets weird the weird turn pro - Hunter S Thompson RIP

              1 Reply Last reply
              0
              • J jschell

                Joe Woodbury wrote:

                You are touching on a very sore point for me; all these features encourage increasingly bad design.

                Only to a limited extent. There are extreme cases but most development with 'clever' code has a smaller scope than would be normally covered by a real design. Of course since there is seldom anything even close to a real design - that is the real problem.

                Joe Woodbury wrote:

                It's simply easier to churn out code that kind of works for now and then quickly move on to another project

                One must be agile like that.

                B Offline
                B Offline
                BobJanova
                wrote on last edited by
                #56

                I think it happens to a greater extent than you do. When you have a web service layer, you end up writing your cross-process communication as SOAP instead of a simple socket or pipe protocol. When you have an entity mapping framework, you end up using Entity Framework to save a list of things, instead of a simple file.

                1 Reply Last reply
                0
                • R Rob Philpott

                  Sometimes I yearn for a return to .NET 2.0. The C# that came with it was a great language and now that generics were included it was essentially complete in my mind. Since then, they've been adding all sorts of dubious things to the language LINQ being the most notable but now we also have the async/await business which really is anything but the simple solution to asynchronous programming they tell us it is. Extensions methods, everyone's favourite encapsulation anti-pattern debuted with LINQ in order to make it work and some people (me) viewed them with suspicious eyes at the time but didn't really know how bad things could get. Having recently worked on a system where they have been abused to the fullest I can tell you. You start off with pretty hollow objects with very little in the way of methods, just enough to get at the data. Then, you put all your logic in extension methods, preferably in different assemblies. A sort of warped onion architecture. Now, any normal developer who goes looking for a type's methods won't find them in the type or even that assembly. A missing reference will make them disappear completely. Also, with careful planning, you can make it exceedingly hard to move that logic back where it belongs because doing so will cause all kinds of circular dependency issues. Immutable code! Shocking stuff, but if you really hate the world, don't forget the Action<> and Func<> delegates. These are useful because you can avoid passing meaningful data to methods. Instead just pass delegates everywhere (a functional programming approach I'm told). This makes it practically impossible for anyone to work out the execution flow by examining the code. Combine the two and you have one thoroughly malevolent system. People bang on about patterns all the time in software development, but if you ask me (I'm aware you didn't) the way to build a good system is to always, always, always keep everything as simple as you can make it.

                  Regards, Rob Philpott.

                  P Offline
                  P Offline
                  Pheonyx
                  wrote on last edited by
                  #57

                  You know what, I had never used extension methods until about a week ago. I created two in the space of 2 days and they make my code look a lot neater. They are simple and straight forward. Every single developer I have known likes some features and despises others. They all try and follow some pattern when developing but the one thing that makes it easy to modify someone else's code, generally is not the code itself it is the documentation. If you are going to use extension methods then have them documented so people can easily understand what they are and where they come from. If you are going to use lots of interfaces and abstract classes take advantage of Model diagrams so people can see the structure. If you were to be handed a program that was one great big God Method with no comments/documentation it would be just as much of a challenge to understand as a solution with 10 class librarys containing interfaces/abstract classes/extension methods etc if that had no documentation. As was mentioned by another person, Bad Programmers write Bad Code... but what wasn't mentioned is that Bad Programmers do not document! I've seen some god awful code, but understood what it was doing because it was documented very well. That's my view anyway. It is not necessarily about abusing features, but if you use them document how and why.

                  1 Reply Last reply
                  0
                  • R Rob Philpott

                    Sometimes I yearn for a return to .NET 2.0. The C# that came with it was a great language and now that generics were included it was essentially complete in my mind. Since then, they've been adding all sorts of dubious things to the language LINQ being the most notable but now we also have the async/await business which really is anything but the simple solution to asynchronous programming they tell us it is. Extensions methods, everyone's favourite encapsulation anti-pattern debuted with LINQ in order to make it work and some people (me) viewed them with suspicious eyes at the time but didn't really know how bad things could get. Having recently worked on a system where they have been abused to the fullest I can tell you. You start off with pretty hollow objects with very little in the way of methods, just enough to get at the data. Then, you put all your logic in extension methods, preferably in different assemblies. A sort of warped onion architecture. Now, any normal developer who goes looking for a type's methods won't find them in the type or even that assembly. A missing reference will make them disappear completely. Also, with careful planning, you can make it exceedingly hard to move that logic back where it belongs because doing so will cause all kinds of circular dependency issues. Immutable code! Shocking stuff, but if you really hate the world, don't forget the Action<> and Func<> delegates. These are useful because you can avoid passing meaningful data to methods. Instead just pass delegates everywhere (a functional programming approach I'm told). This makes it practically impossible for anyone to work out the execution flow by examining the code. Combine the two and you have one thoroughly malevolent system. People bang on about patterns all the time in software development, but if you ask me (I'm aware you didn't) the way to build a good system is to always, always, always keep everything as simple as you can make it.

                    Regards, Rob Philpott.

                    J Offline
                    J Offline
                    Jonathan C Dickinson
                    wrote on last edited by
                    #58

                    Like any language feature they are open to abuse. Just look at GOTO. Bad developers will use bad patterns no matter how limited the feature-set of the language. The reason you feel let down is that Microsoft have given bad developers more tools with which to shoot themselves in the foot. Extension Methods: Allow you to create mixins in .Net by using memberless interfaces (previously impossible). If kept internal they are a less smelly than Helpers.DoSomething(foo), and allow you to rectify what you perceive as shortcomings in code that you do not control (a good example being string.Format). Delegates: Functional code! Don't mock it if you don't know it. I strongly recommend you have a look at a tutorial on monads in C#. They increase clarity if used correctly (for example, TDOP parsers are incredibly clear compared to your run-of-the-mill parsers). Here is a nice comparison[^] of what functional languages bring to the table. C# is not a functional language and will never be: it's a multi-faceted language and this allows me to take advantage of the functional aspects of the language to solve problems, when the problems are suited to functional code. I recommend you have a serious look at these features, because when used correctly they are a serious boost to the repertoire of weapons that you have when facing tricky problems.

                    He who asks a question is a fool for five minutes. He who does not ask a question remains a fool forever. [Chinese Proverb] Jonathan C Dickinson (C# Software Engineer)

                    1 Reply Last reply
                    0
                    • R Rob Philpott

                      Sometimes I yearn for a return to .NET 2.0. The C# that came with it was a great language and now that generics were included it was essentially complete in my mind. Since then, they've been adding all sorts of dubious things to the language LINQ being the most notable but now we also have the async/await business which really is anything but the simple solution to asynchronous programming they tell us it is. Extensions methods, everyone's favourite encapsulation anti-pattern debuted with LINQ in order to make it work and some people (me) viewed them with suspicious eyes at the time but didn't really know how bad things could get. Having recently worked on a system where they have been abused to the fullest I can tell you. You start off with pretty hollow objects with very little in the way of methods, just enough to get at the data. Then, you put all your logic in extension methods, preferably in different assemblies. A sort of warped onion architecture. Now, any normal developer who goes looking for a type's methods won't find them in the type or even that assembly. A missing reference will make them disappear completely. Also, with careful planning, you can make it exceedingly hard to move that logic back where it belongs because doing so will cause all kinds of circular dependency issues. Immutable code! Shocking stuff, but if you really hate the world, don't forget the Action<> and Func<> delegates. These are useful because you can avoid passing meaningful data to methods. Instead just pass delegates everywhere (a functional programming approach I'm told). This makes it practically impossible for anyone to work out the execution flow by examining the code. Combine the two and you have one thoroughly malevolent system. People bang on about patterns all the time in software development, but if you ask me (I'm aware you didn't) the way to build a good system is to always, always, always keep everything as simple as you can make it.

                      Regards, Rob Philpott.

                      F Offline
                      F Offline
                      Fabio Franco
                      wrote on last edited by
                      #59

                      I partially agree with you, but it can be useful if used with care. Bad programmers will find ways to screw up good design despite the language and its features. One of my favorite rants is the abuse of var. While it can save you a lot of work when defining anonymous types, some people simply use var everywhere, making some pieced of code very hard to read and understand. Having said that, I use some extension methods when I need just that extra functionality of a type defined by the framework that I don't have access to. Example: I usually define enumerators to be used as members of some classes. Say:

                      enum OperationType
                      {
                      [Description("Cash Withdraw")]
                      CashWithdraw = 0,
                      [Description("Money Transfer")]
                      MoneyTransfer = 1,
                      }

                      Now, The text on the description attribute allows me to have the enum value user viewable if I want to populate a dropdownlist with it's possible values. Overmore, I can even refer to variable on a resource file to make it localizable. Now, in order to fetch this description that is user friendly/localizable I simply define an extension method that makes my life a whole lote easier:

                          public static string GetDescription(this Enum enumToRead)
                          {
                              if (enumToRead == null)
                                  return string.Empty;
                      
                              Type type = enumToRead.GetType();
                              MemberInfo\[\] memInfo = type.GetMember(enumToRead.ToString());
                      
                              if (memInfo == null || memInfo.Length <= 0)
                                  return string.Empty;
                      
                              object\[\] attributes = memInfo\[0\].GetCustomAttributes(typeof(DescriptionAttribute),
                                  false);
                      
                              if (attributes == null || attributes.Length <= 0)
                                  return string.Empty;
                      
                              return ((DescriptionAttribute)attributes\[0\]).Description;
                          }
                      

                      Of course, a lot of language sugar candy can be abused, but that is the programmer's fault, not the language. But I confess that I sometimes do regret that the var keyword was ever introduced.

                      To alcohol! The cause of, and solution to, all of life's problems - Homer Simpson ---- Our heads are round so our thoughts can change direction - Francis Picabia

                      R J 2 Replies Last reply
                      0
                      • F Fabio Franco

                        I partially agree with you, but it can be useful if used with care. Bad programmers will find ways to screw up good design despite the language and its features. One of my favorite rants is the abuse of var. While it can save you a lot of work when defining anonymous types, some people simply use var everywhere, making some pieced of code very hard to read and understand. Having said that, I use some extension methods when I need just that extra functionality of a type defined by the framework that I don't have access to. Example: I usually define enumerators to be used as members of some classes. Say:

                        enum OperationType
                        {
                        [Description("Cash Withdraw")]
                        CashWithdraw = 0,
                        [Description("Money Transfer")]
                        MoneyTransfer = 1,
                        }

                        Now, The text on the description attribute allows me to have the enum value user viewable if I want to populate a dropdownlist with it's possible values. Overmore, I can even refer to variable on a resource file to make it localizable. Now, in order to fetch this description that is user friendly/localizable I simply define an extension method that makes my life a whole lote easier:

                            public static string GetDescription(this Enum enumToRead)
                            {
                                if (enumToRead == null)
                                    return string.Empty;
                        
                                Type type = enumToRead.GetType();
                                MemberInfo\[\] memInfo = type.GetMember(enumToRead.ToString());
                        
                                if (memInfo == null || memInfo.Length <= 0)
                                    return string.Empty;
                        
                                object\[\] attributes = memInfo\[0\].GetCustomAttributes(typeof(DescriptionAttribute),
                                    false);
                        
                                if (attributes == null || attributes.Length <= 0)
                                    return string.Empty;
                        
                                return ((DescriptionAttribute)attributes\[0\]).Description;
                            }
                        

                        Of course, a lot of language sugar candy can be abused, but that is the programmer's fault, not the language. But I confess that I sometimes do regret that the var keyword was ever introduced.

                        To alcohol! The cause of, and solution to, all of life's problems - Homer Simpson ---- Our heads are round so our thoughts can change direction - Francis Picabia

                        R Offline
                        R Offline
                        Rob Philpott
                        wrote on last edited by
                        #60

                        Yes, someone else said they used extension methods on enums, and I can't really fault your example. Quite neat actually. Perhaps I didn't convey the point properly in the original post, but I'm not completely against them, just that they provide another way to wreck a system when abused. I use them on strings to give Left, Mid, Right time functionality. On balance then, I think we would be better off without them but its not to say they don't have their uses. That's where personal opinion comes in! As for var, I share your sentiments. People like it because it saves them some typing - at the expense of being able to see what types your dealing with. If that doesn't bother them, well, enough said really.

                        Regards, Rob Philpott.

                        F 1 Reply Last reply
                        0
                        • R Rob Philpott

                          Yes, someone else said they used extension methods on enums, and I can't really fault your example. Quite neat actually. Perhaps I didn't convey the point properly in the original post, but I'm not completely against them, just that they provide another way to wreck a system when abused. I use them on strings to give Left, Mid, Right time functionality. On balance then, I think we would be better off without them but its not to say they don't have their uses. That's where personal opinion comes in! As for var, I share your sentiments. People like it because it saves them some typing - at the expense of being able to see what types your dealing with. If that doesn't bother them, well, enough said really.

                          Regards, Rob Philpott.

                          F Offline
                          F Offline
                          Fabio Franco
                          wrote on last edited by
                          #61

                          Got ya, but unlike you I rarely see people even using extension methods. Maybe you got unlucky. On the other hand I see var all over the place, like an agent Smith virus.

                          To alcohol! The cause of, and solution to, all of life's problems - Homer Simpson ---- Our heads are round so our thoughts can change direction - Francis Picabia

                          1 Reply Last reply
                          0
                          • R Rob Philpott

                            Oh dear, oh dear. Did you get out of bed the wrong side this morning? Well, I'm not going to bother to argue the points bearing in mind your post seems more of a personal attack than a measured meaningful argument. Perhaps a nice walk in the park or something will soothe you.

                            Regards, Rob Philpott.

                            Sander RosselS Offline
                            Sander RosselS Offline
                            Sander Rossel
                            wrote on last edited by
                            #62

                            Nah man, sorry if you took it personal. I didn't mean it that way. I just completely disagree with you because of the points I mentioned in my post. LINQ is a great tool which can make code easier, more flexible, better maintainable and more readable. Not knowing how to use it properly is not LINQ's fault. You used to be a big C++ fan. How bad can you screw up in C++? WAAAAAAAY more than in LINQ, surely you must know... I don't think you should hate on LINQ because your co-workers screwed up. You can screw up in any version of any language. I've seen horrors in .NET 2.0 (pre-LINQ) you can't even begin to comprehend.

                            It's an OO world.

                            public class Naerling : Lazy<Person>{
                            public void DoWork(){ throw new NotImplementedException(); }
                            }

                            J 1 Reply Last reply
                            0
                            • R Rob Philpott

                              Not quite with you, but on that note, if a quantity can have a DB Null its likely going to be a reference type or Nullable<> in which you can just do (reader[i] as int?) (reader["name"] as string) etc, and that will turn you DB nulls to .net nulls for you. If you use extensions here - why not. I use them on String to give me a traditional Left and Right function. I think it's when you start involving them in the system architecture that things start to do horribly wrong.

                              Regards, Rob Philpott.

                              S Offline
                              S Offline
                              Sentenryu
                              wrote on last edited by
                              #63

                              I was going to post stating just that. Extension methods are made to give you a nicer way of calling helper functions, not to contain any business logic :thumbsup:

                              I'm brazilian and english (well, human languages in general) aren't my best skill, so, sorry by my english. (if you want we can speak in C# or VB.Net =p) "Given the chance I'd rather work smart than work hard." - PHS241

                              1 Reply Last reply
                              0
                              • E Ennis Ray Lynch Jr

                                I am completely opposed to the AS operator. It causes more problems than it is worth. You talk about sloppy programming with extension methods, ugh, AS is worse. In fact, the AS keyword brought down an entire production system. (combined with a lazy programmer) The short story is that instead of relying on strong typing from the DB the developer used AS and converted the type to the expected type. Some DBA decided to change a database type without telling any one and a few weeks later another subsystem broke because of invalid data. Had the type been formally cast this error would have been caught immediately. I am of the camp that strong typing is important. Using conversion ... everywhere as AS encourages, only serves to disassociate developers from types (ok, this includes var) and types and the knowledge thereof is a fundamental underpinning of a stable, large system.

                                Need custom software developed? I do custom programming based primarily on MS tools with an emphasis on C# development and consulting. "And they, since they Were not the one dead, turned to their affairs" -- Robert Frost "All users always want Excel" --Ennis Lynch

                                B Offline
                                B Offline
                                BC_programming
                                wrote on last edited by
                                #64

                                the as operator should only be used when the result being null is either checked, you already know that the cast will succeed (testing with is) or when having a null result will not unravel the application. If memory serves, 'as' will not call any defined cast operator routines, either, which can be desirable functionality in some cases. It should not be used as the preferred cast style, particularly where strong types or specific abstract base classes or interfaces need to be enforced. I'm a bit curious how changing a database type would cause as to return null. It rather brings up the question why you had to cast to begin with, since generally you ought to only require casts when dealing with a polymorphic system. Either way, if a person uses the as operator and does not have a reasonable basis to assume the cast will fail and does not code for the result being null- (for example, with sensitive transactions or database data, trying to preserve existing state and rollback, etc) Then I'm more inclined to say they misused the language, not that the feature shouldn't exist or is a problem itself. My personal rule of thumb is if I have a reasonable set of actions to perform if the cast fails, I use as and compare with null; otherwise, I use a direct cast and just let Exceptions occur, as well as showing any applicable compile-time errors. I also use as when I want to throw a custom exception for the case that the type fails, and don't want to cloud my code with an extra Try...Catch around the cast for an InvalidCastException. I also have to say I disagree with the sentiment that strong typing is important, too, though. I'd say that consistent typing is more important.

                                1 Reply Last reply
                                0
                                • R Rob Philpott

                                  While I'm with you about typing (I'm of age where you were brought up to respect type safety) I don't see an issue with using 'as'. I often see a condition checking if something 'is' a type followed by an explicit cast, and I tend to replace the 'is' with an 'as' and use a null check - one less cast in effect. Actually, it's not extension methods or 'as' which is the real horror. Its 'var', but we'll leave that for another day. :)

                                  Regards, Rob Philpott.

                                  D Offline
                                  D Offline
                                  Dan Neely
                                  wrote on last edited by
                                  #65

                                  Rob Philpott wrote:

                                  Actually, it's not extension methods or 'as' which is the real horror. Its 'var', but we'll leave that for another day. :)

                                  As with everything else in this thread var isn't inherently bad; it's only bad when idiots are abusing it. People who do something like:

                                  var i = 5;
                                  var bar = GetBar();

                                  deserve every bruise the Clouisville Slugger leaves; but:

                                  var foo = new Dictionary();

                                  is better than either of these:

                                  Dictionary foo = new Dictionary();

                                  Dictionary bar =
                                  new Dictionary();

                                  Repeating the type information twice on the same or adjacent lines offers nothing of value. With linq var is also useful for storing anonymous types created as intermediate values inside a single function. It's a feature best used sparingly (and I've disabled Resharper's you can use var suggestion for being way too overeager); but used properly does boost readability.

                                  Did you ever see history portrayed as an old man with a wise brow and pulseless heart, waging all things in the balance of reason? Is not rather the genius of history like an eternal, imploring maiden, full of fire, with a burning heart and flaming soul, humanly warm and humanly beautiful? --Zachris Topelius Training a telescope on one’s own belly button will only reveal lint. You like that? You go right on staring at it. I prefer looking at galaxies. -- Sarah Hoyt

                                  1 Reply Last reply
                                  0
                                  • J jschell

                                    Collin Jasnoch wrote:

                                    It seems more natural when I am coding

                                    Which is certainly reasonable as long as there is some guarantee that you are the sole person that will ever work on the code that you write. Most people don't have that luxury because they might like to move on to another job, or retire or even die and not have the business application cease to exist then. So writing code which many people find to be flat out obvious has a better chance of succeeding in such a situation.

                                    L Offline
                                    L Offline
                                    Lost User
                                    wrote on last edited by
                                    #66

                                    jschell wrote:

                                    Most people don't have that luxury because they might like to move on to another job, or retire or even die and not have the business application cease to exist then. So writing code which many people find to be flat out obvious has a better chance of succeeding in such a situation.

                                    Don't get me wrong. I am not coding just under my assumptions. I work with different teams and also (obviously) am on forums and various communities. I follow standards. I think Extensions have somehow become one of those fanatic entrenchments. It is understandable why as they are very powerful. But with all power comes responsibility :)

                                    Computers have been intelligent for a long time now. It just so happens that the program writers are about as effective as a room full of monkeys trying to crank out a copy of Hamlet.

                                    1 Reply Last reply
                                    0
                                    • E Ennis Ray Lynch Jr

                                      I am completely opposed to the AS operator. It causes more problems than it is worth. You talk about sloppy programming with extension methods, ugh, AS is worse. In fact, the AS keyword brought down an entire production system. (combined with a lazy programmer) The short story is that instead of relying on strong typing from the DB the developer used AS and converted the type to the expected type. Some DBA decided to change a database type without telling any one and a few weeks later another subsystem broke because of invalid data. Had the type been formally cast this error would have been caught immediately. I am of the camp that strong typing is important. Using conversion ... everywhere as AS encourages, only serves to disassociate developers from types (ok, this includes var) and types and the knowledge thereof is a fundamental underpinning of a stable, large system.

                                      Need custom software developed? I do custom programming based primarily on MS tools with an emphasis on C# development and consulting. "And they, since they Were not the one dead, turned to their affairs" -- Robert Frost "All users always want Excel" --Ennis Lynch

                                      A Offline
                                      A Offline
                                      agolddog
                                      wrote on last edited by
                                      #67

                                      Just to reemphaisze the lazy programmer part (which I think is actually much more the problem): I guess what's you're saying that the programmer failed to null-check the object, and bad things happened? I don't see "as" being any worse than an explicit cast; in either case, there are rules to be followed: either null check or try/catch for InvalidCastException (I think that's the right one?) and handle that case. The code I inherited is littered with things like this. Say, in a gridview's RowDataBound handler, we do

                                      Hyperlink lnk = FindControl("id") as Hyperlink;
                                      lnk.NavigateUrl = ;

                                      I guess I don't see adding a null check as any worse/better than

                                      try
                                      {
                                      Hyperlink lnk = (Hyperlink)FindControl("id");
                                      lnk.NavigateUrl = ;
                                      } catch (InvalidCastException)
                                      {
                                      }

                                      Sorry I rambled a bit. My point is, any time one assumes the information you're looking for will be there and properly formatted is just laziness/inexperience, and that seems to be the real problem.

                                      1 Reply Last reply
                                      0
                                      • J jschell

                                        Rama Krishna Vavilala wrote:

                                        They are extremely useful for interfaces especially and in those cases where the code is not really in your hand.

                                        Which suggests many problems such as a broken architecture, design or a misuse/misunderstanding of the architecture/design.

                                        Rama Krishna Vavilala wrote:

                                        and non-repetitive.

                                        Rather certain there are other ways to achieve that.

                                        R Offline
                                        R Offline
                                        Rama Krishna Vavilala
                                        wrote on last edited by
                                        #68

                                        Extension methods are nothing more than syntactic sugar. I fail to understand why they break architecture or design. Instead of saying Utilities.DoSomething(object); When you use extension method, you say obj.DoSomething(); There is nothing which still prevents you from using the first syntax.

                                        J 1 Reply Last reply
                                        0
                                        • R Rob Philpott

                                          Sometimes I yearn for a return to .NET 2.0. The C# that came with it was a great language and now that generics were included it was essentially complete in my mind. Since then, they've been adding all sorts of dubious things to the language LINQ being the most notable but now we also have the async/await business which really is anything but the simple solution to asynchronous programming they tell us it is. Extensions methods, everyone's favourite encapsulation anti-pattern debuted with LINQ in order to make it work and some people (me) viewed them with suspicious eyes at the time but didn't really know how bad things could get. Having recently worked on a system where they have been abused to the fullest I can tell you. You start off with pretty hollow objects with very little in the way of methods, just enough to get at the data. Then, you put all your logic in extension methods, preferably in different assemblies. A sort of warped onion architecture. Now, any normal developer who goes looking for a type's methods won't find them in the type or even that assembly. A missing reference will make them disappear completely. Also, with careful planning, you can make it exceedingly hard to move that logic back where it belongs because doing so will cause all kinds of circular dependency issues. Immutable code! Shocking stuff, but if you really hate the world, don't forget the Action<> and Func<> delegates. These are useful because you can avoid passing meaningful data to methods. Instead just pass delegates everywhere (a functional programming approach I'm told). This makes it practically impossible for anyone to work out the execution flow by examining the code. Combine the two and you have one thoroughly malevolent system. People bang on about patterns all the time in software development, but if you ask me (I'm aware you didn't) the way to build a good system is to always, always, always keep everything as simple as you can make it.

                                          Regards, Rob Philpott.

                                          J Offline
                                          J Offline
                                          jfren484
                                          wrote on last edited by
                                          #69

                                          If someone puts code in an Extension Method rather than the class they're writing, they're probably doing it wrong. Extension Methods should be used when you don't have access to the class but you want to EXTEND it anyway. Here's an example. Our product owner wanted all dates to be displayed in the format 17-Apr-2013 09:25:05AM (-06:00). In a table we might need to split the date and time into two lines (to take up less horizontal space) like: 17-Apr-2013 09:25:05AM (-06:00) Here's our extension method (and it saves us from repeating the code inside this method everywhere - we use it a LOT):

                                          public static string ToDisplayFormat(this DateTimeOffset dto, bool twoLineDisplay = false)
                                          {
                                          var separator = twoLineDisplay ? "<br/>" : " ";
                                          return dto.ToString(string.Format("dd-MMM-yyyy{0}hh:mm:sstt (zzz)", separator));
                                          }

                                          var displayFormattedDate = myDate.ToDisplayFormat();

                                          And I've found that it's not too hard to track down where the logic is for something like that. Just click "ToDisplayFormat" in the code and hit F12 (or right-click and Go To Definition, or if you have ReSharper, ctrl-click "ToDisplayFormat").

                                          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