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 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • 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
                    • L Lost User

                      Rob Philpott wrote:

                      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.

                      Hmmm... I'll just say, it seems you are doing it wrong then. I use extension methods, but only to the point where it is obvious and could easily be added by re-inventing the wheel right then and there on the spot. For example, I often use IEnumerable<T> but prefer many of the Extensions offered by LINQ when using IList. Not too difficult to make myself.

                      public static void ForEach<T>(this IEnumerable<T> collection, Action<T> action)
                      {
                      foreach (var item in collection)
                      {
                      action(item);
                      }
                      }

                      I package it up and call it a done deal and use it. Now if a developer can not figure out what SomeRandomCollection.ForEach(item => {//Do stuff}); means then I do not want them working in my code base anyways. Granted extensions can and will be abused. But that is true of any feature.

                      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.

                      J Offline
                      J Offline
                      jelamid
                      wrote on last edited by
                      #70

                      Collin Jasnoch wrote:

                      Now if a developer can not figure out what
                       
                      SomeRandomCollection.ForEach(item => {//Do stuff}); means then I do not want them working in my code base anyways.

                      If you are working for someone else it it this attitude that causes the most grief for the business. Which is the situation that the OP is in. In this case it is not your code base, you have no control over who sees it next, and you will collect bad karma as those who follow will curse your name. :)

                      L 1 Reply Last reply
                      0
                      • J jelamid

                        Collin Jasnoch wrote:

                        Now if a developer can not figure out what
                         
                        SomeRandomCollection.ForEach(item => {//Do stuff}); means then I do not want them working in my code base anyways.

                        If you are working for someone else it it this attitude that causes the most grief for the business. Which is the situation that the OP is in. In this case it is not your code base, you have no control over who sees it next, and you will collect bad karma as those who follow will curse your name. :)

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

                        jelamid wrote:

                        If you are working for someone else it it this attitude that causes the most grief for the business. Which is the situation that the OP is in. In this case it is not your code base, you have no control over who sees it next, and you will collect bad karma as those who follow will curse your name. :)

                        Ahhh you may be missing my entire point and/or may not be familiar with Extensions. The ForEach extension for IList which is within the "System.Linq" namespace is common knowledge for programmers using the .Net Framework 3.5 and up. Er it should be. And my point is, if it is not then you need to do some homework before touching a system built on that framework. I chose the ForEach extension onto the IEnumerable because of this reason. It should be understood and if it is not that means you lack the basic understanding of extensions which were added multiple frameworks ago. That is not my problem nor should it be. If the business chose/authorized the use of a framework it will be used. If the management then assigns inappropriate resources (i.e. someone that lacks the basic knowledge of the framework) to the code base that is managements fault (or the resource not fully disclosing their actual understanding), not the original developers fault.

                        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.

                        J J 2 Replies 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.

                          M Offline
                          M Offline
                          Mike E Andrews
                          wrote on last edited by
                          #72

                          Here's one of the problems I see... Extension methods do have their "problems," and yes, perhaps, they are a hack of a sort or an anti-pattern. Regardless, they are very useful for all kinds of situations that makes code far more readable and understandable than its code-filling counterparts with some type of red sauce. The problem I run into with using extension methods is a lot of developers, like a lot of people in general, are just afraid of the unknown and extension methods are the "unknown" when first someone is introduced. I hear all the time... "How will anyone know how to use it especially if they don't know about it?" "We need to program for the Junior Developer so that this code is maintainable later on." "This is too complex for a mere mortal to comprehend." Perhaps all good points, perhaps not, but you get the idea... Here's an example of a very useful extension method that makes implementation code more readable:

                          public static IEnumerable AsEnumerable(this IDataReader reader) {
                          while(reader.Read())
                          yield return reader;
                          }

                          So, what would you do with it? How about this as a simple example?

                          //... Something happened here
                          using(var reader = cmd.ExecuteReader()) {
                          return reader
                          .AsEnumerable()
                          .Select(CreatePerson)
                          .Where(person => person.Name.StartsWith("B"))
                          .ToList();
                          }

                          Here is the non-extension method counterpart:

                          //... Something happened here
                          using(var reader = cmd.ExecuteReader()) {
                          var persons = new List();
                          while(reader.Read()){
                          var person = CreatePerson(reader);
                          if (person.Name.StartsWith("B"))
                          persons.Add(person)
                          }
                          return persons
                          }

                          Where is the complexity in this example? Which is more readable? It just gets old that those who really enjoy this kind of work and want to explorer the possibilities are constantly stymied by those who merely want to maintain the status quo. To be fair, though, like most endeavors, you can take it too far. There should be a balance. We shouldn't disdain anyone that wants to use extension methods to improve their code and provide meaningful functionality for others, but likewise we also shouldn't tolerate everything written as extension methods.

                          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
                            Jasmine2501
                            wrote on last edited by
                            #73

                            Sure yeah, anything can be abused to the point where it's no longer awesome. Even sex with supermodels gets old after a while :)

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

                              M Offline
                              M Offline
                              Member_5893260
                              wrote on last edited by
                              #74

                              Actually, extension methods work in .Net 2.0 as well, if you include the following line of code somewhere in the project (hint: just so it makes sense, why not put it somewhere near the extension class, and comment it, too!?):

                              namespace System.Runtime.CompilerServices { public class ExtensionAttribute : Attribute { } }

                              I like them in general: they're especially useful for enums, for basic data classes returned by web services, and specifically for creating String.EqualsIgnoreCase which, to me, is the one thing I really miss which Java has and C# doesn't (and, sometimes, for case-insensitive "find" and "indexof" methods on lists, which are seriously handy). I think if you keep your extension methods reasonably simple and then name them so it's obvious what they're doing, then there's nothing wrong with them: like anything else, though, you can get lost in myriad paths of complexity if you go nuts. The same is true of a lot of stuff in C#: you can go just as insane using something like "yield return xxx" instead of returning an enumeration: nest enough of those and you can cause yourself some problems in the long run, especially if they start to recurse... the point here is not how much trouble you can cause yourself, but rather how nice it is that we have a language powerful enough to let us be really, really stupid if we want to...

                              1 Reply Last reply
                              0
                              • R Rama Krishna Vavilala

                                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 Offline
                                J Offline
                                jschell
                                wrote on last edited by
                                #75

                                Rama Krishna Vavilala wrote:

                                I fail to understand why they break architecture or design.

                                You said the following and my presumption was that you were using them to solve a problem and not just because you wanted to.... "...in those cases where the code is not really in your hand. "

                                1 Reply 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(); }
                                  }

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

                                  Naerling wrote:

                                  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?

                                  Because there are some tasks that one cannot do via SQL. Or at least cannot do it efficiently and/or without writing the entire SQL block (not statement) in the string. Not to mention of course that SPs can act as a database layer in the database just as one might have a database layer in C# and for much the same purpose given that the database in in fact a separate server.

                                  Naerling wrote:

                                  Furthermore when using LINQ to SQL or LINQ to Entities you get a bonus of moving your queries from in-code strings

                                  Of course the down side of that can be that some developers do not know or prefer to ignore that some tasks should not be done in the client. Thus they create LINQ rather than using a SP.

                                  Naerling wrote:

                                  and easy to read LINQ queries.

                                  That of course is entirely subjective. Like any code it can be written in form that is in fact hard to read. And without code reviews whether it is in in fact "easy to read" is likely nothing but a rationalization by the author. Which one can say about any language.

                                  Sander RosselS 1 Reply Last reply
                                  0
                                  • Sander RosselS Sander Rossel

                                    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 Offline
                                    J Offline
                                    jschell
                                    wrote on last edited by
                                    #77

                                    Naerling wrote:

                                    LINQ is a great tool which can make code easier, more flexible, better maintainable and more readable

                                    X is a great tool which can make code easier, more flexible, better maintainable and more readable. That hard part of that statement is finding any software technology X where that statement was never made.

                                    Naerling wrote:

                                    I've seen horrors in .NET 2.0 (pre-LINQ) you can't even begin to comprehend.

                                    I have seem messes in every technology that I have ever encountered. Including hardware.

                                    Sander RosselS 1 Reply 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

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

                                      Fabio Franco wrote:

                                      Bad programmers will find ways to screw up good design despite the language and its features.

                                      Naturally however technology (language) does not equal design.

                                      1 Reply Last reply
                                      0
                                      • J jschell

                                        Naerling wrote:

                                        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?

                                        Because there are some tasks that one cannot do via SQL. Or at least cannot do it efficiently and/or without writing the entire SQL block (not statement) in the string. Not to mention of course that SPs can act as a database layer in the database just as one might have a database layer in C# and for much the same purpose given that the database in in fact a separate server.

                                        Naerling wrote:

                                        Furthermore when using LINQ to SQL or LINQ to Entities you get a bonus of moving your queries from in-code strings

                                        Of course the down side of that can be that some developers do not know or prefer to ignore that some tasks should not be done in the client. Thus they create LINQ rather than using a SP.

                                        Naerling wrote:

                                        and easy to read LINQ queries.

                                        That of course is entirely subjective. Like any code it can be written in form that is in fact hard to read. And without code reviews whether it is in in fact "easy to read" is likely nothing but a rationalization by the author. Which one can say about any language.

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

                                        if (arguments.All(a => a.MakesSense))
                                        {
                                        Console.WriteLine("That is so true!");
                                        }

                                        Output: That is so true! Of course LINQ shouldn't always be used to replace the SQL part from a database, but it sure makes it easier!

                                        It's an OO world.

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

                                        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.

                                          G Offline
                                          G Offline
                                          greyseal96
                                          wrote on last edited by
                                          #80

                                          One of our wise sage developers here has the following quote about extension methods: "Extension methods feel like you're having an affair..." That just about sums it up. :laugh:

                                          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