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.
  • 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

    J Offline
    J Offline
    jschell
    wrote on last edited by
    #42

    Ennis Ray Lynch, Jr. wrote:

    Had the type been formally cast this error would have been caught immediately.

    I would suppose that sufficient unit testing and QA testing would have also caught it immediately.

    1 Reply Last reply
    0
    • R Rama Krishna Vavilala

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

      Rob Philpott wrote:

      the way to build a good system is to always, always, always keep everything as simple as you can make it.

      And extension methods can be used as a way to keep the code simple and non-repetitive. In fact you nailed it well. Keep the end code simple - minimize complexities and I do not see extension methods being a hurdle rather it can be a tool to do so.

      J Offline
      J Offline
      jschell
      wrote on last edited by
      #43

      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 1 Reply Last reply
      0
      • T TheGreatAndPowerfulOz

        It's just code. Deal with it.

        If your actions inspire others to dream more, learn more, do more and become more, you are a leader.-John Q. Adams
        You must accept one of two basic premises: Either we are alone in the universe, or we are not alone in the universe. And either way, the implications are staggering.-Wernher von Braun
        Only two things are infinite, the universe and human stupidity, and I'm not sure about the former.-Albert Einstein

        J Offline
        J Offline
        jschell
        wrote on last edited by
        #44

        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.

        T L 2 Replies Last reply
        0
        • J Joe Woodbury

          You are touching on a very sore point for me; all these features encourage increasingly bad design. The saying goes "if all you have is a hammer, everything is a nail." Likewise, if what you have is "advanced" .NET 4.x, everything must use the same. Solutions which should be brain dead simple take on a monstrous complexity, especially with the developer who wants everything LINQ"ified". It seems to me that the zeal of getting things done rapidly, including various management methodologies, have trumped long term development and maintenance. My hypothesis is that the latter requires thinking, planning and patience. It more than pays off in the end, but that's not good enough to far too many developers and managers, far too many of them aren't smart enough to do it right anyway. It's simply easier to churn out code that kind of works for now and then quickly move on to another project or company, leaving the train wreck that's going to happen to someone else.

          J Offline
          J Offline
          jschell
          wrote on last edited by
          #45

          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 B 2 Replies Last reply
          0
          • P Pete OHanlon

            Rob Philpott wrote:

            otherwise it's a dangerous thing. In the wrong hands.

            You could do dangerous things, even back in 2.0. Ultimately, any tool in the hands of a tool can be misused and abused.

            I was brought up to respect my elders. I don't respect many people nowadays.
            CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier

            J Offline
            J Offline
            jschell
            wrote on last edited by
            #46

            Pete O'Hanlon wrote:

            Ultimately, any tool in the hands of a tool can be misused and abused.

            Which doesn't prove the converse. Just because someone does in fact use it 'correctly' doesn't mean that it in not in fact more complex than needed for the current business goals. And I suspect there are very few cases where it is required. And yet users will rationalize that their usage is justified.

            P 1 Reply Last reply
            0
            • J jschell

              Pete O'Hanlon wrote:

              Ultimately, any tool in the hands of a tool can be misused and abused.

              Which doesn't prove the converse. Just because someone does in fact use it 'correctly' doesn't mean that it in not in fact more complex than needed for the current business goals. And I suspect there are very few cases where it is required. And yet users will rationalize that their usage is justified.

              P Offline
              P Offline
              Pete OHanlon
              wrote on last edited by
              #47

              jschell wrote:

              Which doesn't prove the converse. Just because someone does in fact use it 'correctly' doesn't mean that it in not in fact more complex than needed for the current business goals.

              Indeed not, nor did I claim otherwise. However, the Spidey maxim still holds true here "with great power comes great responsibility". I did have one really handy extension method in .NET 3.5, but .NET 4 provided me with the equivalent that helped me remove it. I had a string extension that checked for whitespace as well to check whether or not the string was empty. I also have a couple of WPF specific ones, but that's all I've ever really needed in my own code.

              I was brought up to respect my elders. I don't respect many people nowadays.
              CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier

              T 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.

                T Offline
                T Offline
                TheGreatAndPowerfulOz
                wrote on last edited by
                #48

                Good points, all. Judicious use of tools is always appropriate though.

                If your actions inspire others to dream more, learn more, do more and become more, you are a leader.-John Q. Adams
                You must accept one of two basic premises: Either we are alone in the universe, or we are not alone in the universe. And either way, the implications are staggering.-Wernher von Braun
                Only two things are infinite, the universe and human stupidity, and I'm not sure about the former.-Albert Einstein

                1 Reply Last reply
                0
                • P Pete OHanlon

                  jschell wrote:

                  Which doesn't prove the converse. Just because someone does in fact use it 'correctly' doesn't mean that it in not in fact more complex than needed for the current business goals.

                  Indeed not, nor did I claim otherwise. However, the Spidey maxim still holds true here "with great power comes great responsibility". I did have one really handy extension method in .NET 3.5, but .NET 4 provided me with the equivalent that helped me remove it. I had a string extension that checked for whitespace as well to check whether or not the string was empty. I also have a couple of WPF specific ones, but that's all I've ever really needed in my own code.

                  I was brought up to respect my elders. I don't respect many people nowadays.
                  CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier

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

                  That's where I add most of my (few) extensions: pre-existing sealed classes or interfaces.

                  If your actions inspire others to dream more, learn more, do more and become more, you are a leader.-John Q. Adams
                  You must accept one of two basic premises: Either we are alone in the universe, or we are not alone in the universe. And either way, the implications are staggering.-Wernher von Braun
                  Only two things are infinite, the universe and human stupidity, and I'm not sure about the former.-Albert Einstein

                  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.

                    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
                                          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