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. How do you write fewer lines of code?

How do you write fewer lines of code?

Scheduled Pinned Locked Moved The Lounge
questioncsharpphpcsslinq
72 Posts 38 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.
  • J Judah Gabriel Himango

    Another way I write less code is by using the Reactive Extensions (Rx). Instead of events + properties + plumbing, you instead use System.IObservable<T> and Linq. So, instead of this:

    // Old way of doing this
    public class FileUpload : INotifyPropertyChanged
    {
    private string fileName;
    private int progress;

    public event PropertyChangedEventHandler PropertyChanged;
    public event EventHandler UploadCompleted;
    
    public string FileName
    {
        get { return fileName; }
        set
        {
            if (fileName != value)
            {
               fileName = value;
               RaisePropertyChanged("FileName");
            }
        }
    }
    
    public int Progress
    {
       get { return this.progress; }
       set
       {
           if (this.progress != value)
           {
               this.progress = value;
               RaisePropertyChanged("Progress");
    
               if (value == 100)
               {
                   if (UploadCompleted != null)
                   {
                       UploadCompleted(this, EventArgs.Empty);
                   }
               }
           }
       }
    }
    
    private void RaisePropertyChanged(string propertyName)
    {
       if (PropertyChanged != null)
       {
           PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
       }
    }
    

    }

    Instead you can write this:

    // New way, courtesy of Rx
    public class FileUpload
    {
    public IObservable Progress { get; }
    public IObservable FileName { get; }
    }

    Consumption:

    // tell me when progress changes
    fileUpload.Progress.Subscribe(p => Console.WriteLine("progress updated to " + p));

    // tell me when upload is done
    fileUpload.Progress.Where(p => p == 100).Subscribe(p => Console.WriteLine("finished!"));

    My Messianic Jewish blog: Kineti L'Tziyon My software blog: Debugger.Break() Judah Himango

    M Offline
    M Offline
    Marc Clifton
    wrote on last edited by
    #55

    Say, has Rx always been a Microsoft thing? I thought it was developed by some other folks. Marc

    My Blog

    J 1 Reply Last reply
    0
    • M Marc Clifton

      Say, has Rx always been a Microsoft thing? I thought it was developed by some other folks. Marc

      My Blog

      J Offline
      J Offline
      Judah Gabriel Himango
      wrote on last edited by
      #56

      Yeah, always has been an Microsoft thing. I spoke with the authors of Rx this spring at the Mix conference. Very sharp guys. I asked them whether Rx will be merged into .NET framework proper. They responded that while they were considering it, they're leaning against it because it's entirely additive (LINQ over System.IObservable<T>), and that the core pieces of Rx (System.IObserver<T> and System.IObservable<T>) are already baked into the .NET framework. Anyways, very nifty framework that few know about.

      My Messianic Jewish blog: Kineti L'Tziyon My software blog: Debugger.Break() Judah Himango

      1 Reply Last reply
      0
      • R realJSOP

        Close the IDE after the next semi-colon.

        Marc Clifton wrote:

        One obvious answer is, replace redundant code with a function.

        But that's just writing the code somewhere else, so that doesn't count. There are no "good practices. You can eliminate error checking (bad practice), elminate line breaks (bad practice), or according to some start writing in VB (bad practice). This bizarre search for "less code" leads to the crap we get from Microsoft.

        ".45 ACP - because shooting twice is just silly" - JSOP, 2010
        -----
        You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
        -----
        "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass." - Dale Earnhardt, 1997

        C Offline
        C Offline
        Ctznkane
        wrote on last edited by
        #57

        Line breaks made the code more readable. I don't think the elimination of line breaks should be a desired outcome. Code shouldn't be measured based on "# of lines". While reducing redundancy is desirable, the goal there is to increase maintainability, not to decrease the number of lines of code.

        1 Reply Last reply
        0
        • M Marc Clifton

          From Mehdi's question about "is less lines of code better" -- Question: How do you go about writing fewer lines of code (omitting removing line breaks as an answer) ? One obvious answer is, replace redundant code with a function. Another possible answer is, using Linq to replace for-next loops (funny how we [well, I do] still call them for-next loops) One other answer to that comes to mind is using OOP to eliminate "if" statements regarding type. Anyways, that's my question--if you really want to achieve fewer lines of code but the same behavior, what really are good practices? Marc

          My Blog

          A Offline
          A Offline
          AspDotNetDev
          wrote on last edited by
          #58

          I find going to work works.

          Somebody in an online forum wrote:

          INTJs never really joke. They make a point. The joke is just a gift wrapper.

          1 Reply Last reply
          0
          • J Judah Gabriel Himango

            I tend to collapse if/else statements. If there's just a single if/else, I'll use the (what's the name of this?) operator:

            return foo ? "it was foo" : "it was not!";

            For big if/elses, or switch statements, I use a custom extension method and type, loosely inspired by F#'s match expressions:

            return answer
            .Match(42, "It was 42!")
            .Match(7, "Perfecttion!")
            .Match(-1, () => throw new ArgumentException(...))
            .DefaultTo("unknown!");

            I find that cleaner and more concise than big if/else or switch blocks.

            My Messianic Jewish blog: Kineti L'Tziyon My software blog: Debugger.Break() Judah Himango

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

            I make extensive use of the ternary operator[^]. I also like your use of method chaining. My experience is that most peoples brains explode when they see such code.

            If your actions inspire others to dream more, learn more, do more and become more, you are a leader." - John Quincy 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

            1 Reply Last reply
            0
            • T TheGreatAndPowerfulOz

              you could have used a static class to much the same effect.

              If your actions inspire others to dream more, learn more, do more and become more, you are a leader." - John Quincy 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

              P Offline
              P Offline
              PIEBALDconsult
              wrote on last edited by
              #60

              In regards to what?

              1 Reply Last reply
              0
              • M Marc Clifton

                From Mehdi's question about "is less lines of code better" -- Question: How do you go about writing fewer lines of code (omitting removing line breaks as an answer) ? One obvious answer is, replace redundant code with a function. Another possible answer is, using Linq to replace for-next loops (funny how we [well, I do] still call them for-next loops) One other answer to that comes to mind is using OOP to eliminate "if" statements regarding type. Anyways, that's my question--if you really want to achieve fewer lines of code but the same behavior, what really are good practices? Marc

                My Blog

                J Offline
                J Offline
                Jorgen Sigvardsson
                wrote on last edited by
                #61

                I have always subscribed to the idea that good code is 50% data structures. A good clean DS that fits your problem domain often reduces the code needed to manipulate them. I tend do look at the problem, and then figure out how I need to organize my data in terms of containers (lists, arrays, trees, graphs). Then I build a facade API around the data structures that matches my problem domain.

                -- Kein Mitleid Für Die Mehrheit

                1 Reply Last reply
                0
                • M Marc Clifton

                  From Mehdi's question about "is less lines of code better" -- Question: How do you go about writing fewer lines of code (omitting removing line breaks as an answer) ? One obvious answer is, replace redundant code with a function. Another possible answer is, using Linq to replace for-next loops (funny how we [well, I do] still call them for-next loops) One other answer to that comes to mind is using OOP to eliminate "if" statements regarding type. Anyways, that's my question--if you really want to achieve fewer lines of code but the same behavior, what really are good practices? Marc

                  My Blog

                  V Offline
                  V Offline
                  Vivi Chellappa
                  wrote on last edited by
                  #62

                  Don't write code. Generate code using code generators! ;P

                  1 Reply Last reply
                  0
                  • M Marc Clifton

                    From Mehdi's question about "is less lines of code better" -- Question: How do you go about writing fewer lines of code (omitting removing line breaks as an answer) ? One obvious answer is, replace redundant code with a function. Another possible answer is, using Linq to replace for-next loops (funny how we [well, I do] still call them for-next loops) One other answer to that comes to mind is using OOP to eliminate "if" statements regarding type. Anyways, that's my question--if you really want to achieve fewer lines of code but the same behavior, what really are good practices? Marc

                    My Blog

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

                    If several classes use the same function, create an abstract class that implements this function and all others inherit from it. There's also the possibility of using attributes to create a an aspect based design which uses these aspects or behaviors (attributes) for specific logic and through reflection the attributes themselves perform the logic instead of classes that use them. It's a very useful solution that I took too long to start using it.

                    "To alcohol! The cause of, and solution to, all of life's problems" - Homer Simpson

                    1 Reply Last reply
                    0
                    • M Marc Clifton

                      From Mehdi's question about "is less lines of code better" -- Question: How do you go about writing fewer lines of code (omitting removing line breaks as an answer) ? One obvious answer is, replace redundant code with a function. Another possible answer is, using Linq to replace for-next loops (funny how we [well, I do] still call them for-next loops) One other answer to that comes to mind is using OOP to eliminate "if" statements regarding type. Anyways, that's my question--if you really want to achieve fewer lines of code but the same behavior, what really are good practices? Marc

                      My Blog

                      D Offline
                      D Offline
                      dpminusa
                      wrote on last edited by
                      #64

                      In my early C# Windows Forms efforts I was frustrated because I was writing rundundant try/catch/finally blocks all over the place. I probably added 25% - 30% more code. I needed to handle exceptions, of course, but how to minimize the code to do this? I now have a different scheme that seems to be a reasonable improvement with my current level of knowledge. Here is what I do: Add some Unhandled Exception Code to Program.cs:

                      // Add the event handler for handling UI thread exceptions to Windows Form Events.
                      // NOTE: Remember to turn Exception Handler OFF in the Debugger for testing!!
                      // NOTE: A separate Event Handler is Needed for other threads added to the Application.
                      Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);

                      // Set the unhandled exception mode to force all Windows Forms errors to go through the Handler.
                      Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

                      My Exception Handler (Application_ThreadException) does the following: 1. Creates a message for the user from the Exception Object it receives by parsing the Exception properties and the Form.ActiveForm properties.. 2. Produces different levels of detail for the user based on the Options Settings in the App setup. 3. Offers to email the Exception to App. Support. 4. Logs the Exception for follow-up. In my Forms I capture and rethrow anything that I need to make a specific point of to the user, like Invalid URL or Email Addresses, etc. With this approach I am only writing the core Exception handling once and only handling the specifics in the Form Methods by exception. This still may NOT be the ultimate approach but it is an improvement. I would be interested in how others handle Exceptions to balance the need for control over writing too much code.

                      "Courtesy is the product of a mature, disciplined mind ... ridicule is lack of the same - DPM"

                      1 Reply Last reply
                      0
                      • M Marc Clifton

                        From Mehdi's question about "is less lines of code better" -- Question: How do you go about writing fewer lines of code (omitting removing line breaks as an answer) ? One obvious answer is, replace redundant code with a function. Another possible answer is, using Linq to replace for-next loops (funny how we [well, I do] still call them for-next loops) One other answer to that comes to mind is using OOP to eliminate "if" statements regarding type. Anyways, that's my question--if you really want to achieve fewer lines of code but the same behavior, what really are good practices? Marc

                        My Blog

                        S Offline
                        S Offline
                        SeattleC
                        wrote on last edited by
                        #65

                        Marc Clifton wrote:

                        Question: How do you go about writing fewer lines of code ?

                        Learn to write better code, of course. Better code is almost always smaller than bad code. Not to mention easier to understand. Yeah, I know. How to write better code... "Replace redundant code with a function" is half an answer. The rest of the answer is to look at the problems you are solving and find the common parts, and factor those parts out into functions or objects that you then reuse wherever they occur. You have to learn to look at a problem this way, and you also have to be granted the time to look at a problem this way. Slow Down: Nobody ever won a Pulitzer Prize for prose that just dripped off the end of their fingers. They worked over their story again and again; tightening it up, rewording awkward sentences, taking out stuff that didn't move the story along. They probably also had an excellent editor, ruthlessly abusing their beautiful words, saying, "This doesn't make sense." and "That sounds awful." Programming is like that too. The best looking code has been gone over several times by more than one pair of eyeballs. A Tale that Grows in the Telling: Some of the most beautiful code (and some of the ugliest) is the product of evolution, of the constant search for a better way over a period of years. Throw it Away: Some of my best coding efforts have been cleanups of code I (or someone else) wrote long ago. It's way easier to write beautiful code when you don't also have to solve a hard programming problem at the same time. Master your Craft: If you want to write a masterpiece in German, better know your German pretty well. If you want to write a masterpiece in C++, the same applies, duh. If you aren't comfortable with all the language features and all the idioms of the language you're developing in, it's unlikely that you will write beautiful code. So get out your books and brush up on those obscure corners of the language. Because you'll need them eventually. Get Old: It takes years to get really good at the craft of programming. If you have 2 years of experience, you probably feel pretty good about your skillz. If you have 10 years in, you probably think you're the bomb. If you have 30 years experience, you know those first two guys were just fooling themselves, even if they were your younger self. Seriously, good code isn't written by graduate students or new college hires, no matter how gifted they are, or how long they've been plink

                        1 Reply Last reply
                        0
                        • M Marc Clifton

                          From Mehdi's question about "is less lines of code better" -- Question: How do you go about writing fewer lines of code (omitting removing line breaks as an answer) ? One obvious answer is, replace redundant code with a function. Another possible answer is, using Linq to replace for-next loops (funny how we [well, I do] still call them for-next loops) One other answer to that comes to mind is using OOP to eliminate "if" statements regarding type. Anyways, that's my question--if you really want to achieve fewer lines of code but the same behavior, what really are good practices? Marc

                          My Blog

                          B Offline
                          B Offline
                          BubingaMan
                          wrote on last edited by
                          #66

                          It seems to me that the obvious question here is "refactoring". I'ld also warn against reducing lines of code for the sake of having less code. Usually, that takes away lots of readability. For example, consider the need to loop over nested hierarchical lists. These things, depending on what you need to do obviously, easily leads to loads of code to deal with looping multiple lists at the same time while making a bunch of recursive calls. You *could* reduce that code immensly by stuffing it all into linq lambda's. But not a single developer would look at that code and understand what it does without deconstructing all those lambda's. And it's pretty safe to say that even if you wrote the code yourself, it will make your brain melt if you need to implement a change therein a couple months later. So less code is not necessarily "better" code. Having said that, after finishing up a use case, I always go over the code with a refactoring brush and do what needs to be done.

                          1 Reply Last reply
                          0
                          • M Marc Clifton

                            From Mehdi's question about "is less lines of code better" -- Question: How do you go about writing fewer lines of code (omitting removing line breaks as an answer) ? One obvious answer is, replace redundant code with a function. Another possible answer is, using Linq to replace for-next loops (funny how we [well, I do] still call them for-next loops) One other answer to that comes to mind is using OOP to eliminate "if" statements regarding type. Anyways, that's my question--if you really want to achieve fewer lines of code but the same behavior, what really are good practices? Marc

                            My Blog

                            B Offline
                            B Offline
                            BrainiacV
                            wrote on last edited by
                            #67

                            OK, two stories, one where less is not better and another where it is. At one time my former Bitch Supervisor from Helltm called me into to her office to complain about the code of one of her favorite scapegoats (she always had two in waiting). She was repeating her favorite word, "Unacceptable!, unacceptable!, just look at that code!" From across he desk I looked at the monitor. The code was nicely formatted and there were comments, it was easy on the eyes, and I was thinking, "If there is a problem here, it will be easy to find." But I wasn't allowed to look too closely at it. Afterwards I heard from the programmer that she had insisted he change the code. He had used three move statements to construct a string, she didn't understand what it was doing, but once she heard what it was supposed to do, she made him use a sprintf call. Stating that one line of code was easier to maintain than three. So she took what would have been the smallest and fastest three statements and replaced them with an interpreted call that if it hadn't already been in use, would have added Ks of code to the application (this was back in the days of MS-DOS and we were limited to 470K for our application). A prime example of what I call, "Management by Magazine Article." My second story is where I was the new software manager at my current place of employment. I had requested the lead programmer make a dropdown list of dates a little more readable by putting a space between the three character month and year. He complained that it would require another subroutine to generate that date. I agreed and asked what the problem was. He showed me the screen full of code he had written to generate the current date and said he'd have to replicate it in order to add the space. "Unless you know a better way..." which was his way of getting out of work with his previous boss. Unfortunately, I knew a better way (or that there had to be a better way). Using built-in functions, I reduced it to three lines of code that was far more robust than his POS. He still says, "If you know a better way...", but now his is asking for advice.

                            Psychosis at 10 Film at 11 Those who do not remember the past, are doomed to repeat it. Those who do not remember the past, cannot build upon it.

                            1 Reply Last reply
                            0
                            • M Marc Clifton

                              From Mehdi's question about "is less lines of code better" -- Question: How do you go about writing fewer lines of code (omitting removing line breaks as an answer) ? One obvious answer is, replace redundant code with a function. Another possible answer is, using Linq to replace for-next loops (funny how we [well, I do] still call them for-next loops) One other answer to that comes to mind is using OOP to eliminate "if" statements regarding type. Anyways, that's my question--if you really want to achieve fewer lines of code but the same behavior, what really are good practices? Marc

                              My Blog

                              T Offline
                              T Offline
                              toddsloan
                              wrote on last edited by
                              #68

                              If your a .NET Web developer, you purchase Telerik's ASP.NET AJAX controls. :D

                              1 Reply Last reply
                              0
                              • M Marc Clifton

                                From Mehdi's question about "is less lines of code better" -- Question: How do you go about writing fewer lines of code (omitting removing line breaks as an answer) ? One obvious answer is, replace redundant code with a function. Another possible answer is, using Linq to replace for-next loops (funny how we [well, I do] still call them for-next loops) One other answer to that comes to mind is using OOP to eliminate "if" statements regarding type. Anyways, that's my question--if you really want to achieve fewer lines of code but the same behavior, what really are good practices? Marc

                                My Blog

                                M Offline
                                M Offline
                                MattPenner
                                wrote on last edited by
                                #69

                                I think the real goal isn't reducing the total number of lines but making the code more readable and reducing duplication. You can do this by refactoring codes into methods and other classes or using frameworks. I'd caution against reducing code for reducing's sake. I've seen some really unintelligible ternary operator statements that were written on a single line. I would often take these out for a more readable two or three line if statement or whatever. I'm a big fan of using frameworks. For instance, I use a lot of jQuery and I love the CSS selectors (bear with me if you have no interest or use for my example). I started a project where I need to do scraping of a website. Fine, using WebRequest and such I get a single string object with all the HTML. To get specific parts of data from the html string most examples on the web start diving into complex and ugly string manipulation functions and some smarter ones use Regex. Better yet others start making use of HtmlAgilityPack. But this returns an XmlNode tree and forces me to use XPath if I want to select specific portions of data. I'm not against XPath and I've used it in other areas but I really like CSS selectors and I'm pretty much a master at them. So, I found Sharp-Query. This is an awesome framework that lets me do exactly what I want. I deliver it the html string and pass a CSS selector query to get, say, all the table rows that have a specific value in one of the columns. I replaced dozens of ugly lines of code with one readable line. Sure, I added a framework which added hundreds of lines of code in total. But it makes my app much more readable and much more stable.

                                1 Reply Last reply
                                0
                                • M Marc Clifton

                                  From Mehdi's question about "is less lines of code better" -- Question: How do you go about writing fewer lines of code (omitting removing line breaks as an answer) ? One obvious answer is, replace redundant code with a function. Another possible answer is, using Linq to replace for-next loops (funny how we [well, I do] still call them for-next loops) One other answer to that comes to mind is using OOP to eliminate "if" statements regarding type. Anyways, that's my question--if you really want to achieve fewer lines of code but the same behavior, what really are good practices? Marc

                                  My Blog

                                  I Offline
                                  I Offline
                                  ilovecashmere
                                  wrote on last edited by
                                  #70

                                  "K&R style": if(true){ } "Shorthand": true? : Case

                                  1 Reply Last reply
                                  0
                                  • N Nicholas Butler

                                    One way is to get the computer to write the tedious, repetitive code for you. It's relatively cheap to ensure that generated code is correct and so I don't count those lines of code in the total. I'm more interested in counting the lines of code I have to type, test and debug - those are the ones that cost! As a quantitative example, I wrote a code generator ( affectionately called Jenny ) that created wrappers for CRUD operations over the Entity Framework. Jenny is about 1,000 LOC, but for about 100 database tables it generates 8,000 LOC in the DTO assembly, 20,000 in the DAL and 7,000 in the BLL. That's 35,000 lines of copy/paste/edit code I didn't have to write. Plus, if I change my mind about my implementation, I can edit all that code at once by running Jenny again. Nick

                                    M Offline
                                    M Offline
                                    Mycroft Holmes
                                    wrote on last edited by
                                    #71

                                    Nicholas Butler wrote:

                                    get the computer to write the tedious, repetitive code for you

                                    Somehow I don't think that is in the spirit of the OP :laugh: Doesn't EVERY developer use a code generator, and the good (old) ones wrote their own. The mind boggles at the amount of time wasted if a code generator is not used.

                                    Never underestimate the power of human stupidity RAH

                                    1 Reply Last reply
                                    0
                                    • M Marc Clifton

                                      From Mehdi's question about "is less lines of code better" -- Question: How do you go about writing fewer lines of code (omitting removing line breaks as an answer) ? One obvious answer is, replace redundant code with a function. Another possible answer is, using Linq to replace for-next loops (funny how we [well, I do] still call them for-next loops) One other answer to that comes to mind is using OOP to eliminate "if" statements regarding type. Anyways, that's my question--if you really want to achieve fewer lines of code but the same behavior, what really are good practices? Marc

                                      My Blog

                                      Y Offline
                                      Y Offline
                                      YSLGuru
                                      wrote on last edited by
                                      #72

                                      The easiest way to write less code? Delegation.

                                      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