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 2 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.
  • X Xiangyang Liu

    Reiss wrote:

    programming question != question about programming

    And also

    question about programming != Mark's Question About Programming
    

    --- Mark does not ask programming questions, the questions ask him. :)

    My Younger Son & His "PET"

    D Offline
    D Offline
    Dalek Dave
    wrote on last edited by
    #35

    There is no Spoon.

    ------------------------------------ I will never again mention that I was the poster of the One Millionth Lounge Post, nor that it was complete drivel. Dalek Dave CCC Link[^] Trolls[^]

    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
      Mark_Wallace
      wrote on last edited by
      #36

      Including the title of your posting, you asked the same question three times. There's gotta be a moral in there somewhere.

      I wanna be a eunuchs developer! Pass me a bread knife!

      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
        Mehdi Gholam
        wrote on last edited by
        #37

        While you were pondering the question me and OG were down at the pub, that's one way of writing less code. I think someone mentioned getting someone else to write the code is another option... But seriously, I believe you write less code by better design and better algorithms.

        Its the man, not the machine - Chuck Yeager If at first you don't succeed... get a better publicist If the final destination is death, then we should enjoy every second of the journey.

        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

          P Offline
          P Offline
          Paul M Watt
          wrote on last edited by
          #38

          I have started using Test Driven Development (TDD). I find that my class interfaces are much more usable, because I am using them while developing. The code is tested as I develop. I don't waste that extra time writing for features that I think I am going to use, I only write when I need. Including the test code, I find I write less code overall.

          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
            swjam
            wrote on last edited by
            #39

            ...or a Project Manager.

            ---------------------------------------------------------- Lorem ipsum dolor sit amet.

            1 Reply Last reply
            0
            • M Marc Clifton

              Bassam Abdul-Baki wrote:

              Using someone else's code is not technically reducing it.

              I was wondering if someone would say that. Well, technically, it reduces the lines of "my" code. Otherwise, you would have to take this to the logical extremes of 1) any framework code + calls to Win API and 2) might as well reduce it to lines of code in the MSIL/assembly language. That doesn't make a lot of sense to me. Marc

              My Blog

              B Offline
              B Offline
              Bassam Abdul Baki
              wrote on last edited by
              #40

              True, but then call your app from a script thereby reducing it to just the call. :) There's no right answer for this. Generally speaking, we reduce, improve, and optimize functions since that is where "our" code usually is.

              Web - BM - RSS - Math - LinkedIn

              T 1 Reply Last reply
              0
              • N Nagy Vilmos

                It's just an example! :sigh:


                Panic, Chaos, Destruction. My work here is done. Drink. Get drunk. Fall over - P O'H OK, I will win to day or my name isn't Ethel Crudacre! - DD Ethel Crudacre I cannot live by bread alone. Bacon and ketchup are needed as well. - Trollslayer Have a bit more patience with newbies. Of course some of them act dumb - they're often *students*, for heaven's sake - Terry Pratchett

                B Offline
                B Offline
                Bassam Abdul Baki
                wrote on last edited by
                #41

                Hey, if the grammar police can write up tickets in a programming website, then the IT police must have a wider jurisdiction. :)

                Web - BM - RSS - Math - LinkedIn

                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
                  Single Step Debugger
                  wrote on last edited by
                  #42

                  Easy – you need to get smarter. This highly reduces LOC.

                  There is only one Vera Farmiga and Salma Hayek is her prophet! Advertise here – minimum three posts per day are guaranteed.

                  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
                    Andy Brummer
                    wrote on last edited by
                    #43

                    Good design and reducing plumbing code more than anything. Nothing complicates an app and drives up the line count than fighting with an object model that doesn't match what you are trying to do with it. If you have to routinely make changes to multiple parts of your model that require complicated operations to connect, then you are going to write a bunch of extra code.

                    Curvature of the Mind now with 3D

                    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
                      Judah Gabriel Himango
                      wrote on last edited by
                      #44

                      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

                      M A T 3 Replies 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

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

                        Judah Himango wrote:

                        I use a custom extension method and type, inspired by F#'s match expressions:

                        Ooh, that's sweet! I remember encountering this a while ago, but I'm glad you reminded me. Marc

                        My Blog

                        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

                          A Offline
                          A Offline
                          Andy Brummer
                          wrote on last edited by
                          #46

                          That is sweet.

                          Curvature of the Mind now with 3D

                          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

                            C Offline
                            C Offline
                            Chris Maunder
                            wrote on last edited by
                            #47

                            Remove functionality that seemed a great idea at the time but simply results in an unused feature and a ton of code to support the plumbing.

                            cheers, Chris Maunder The Code Project | Co-founder Microsoft C++ MVP

                            1 Reply Last reply
                            0
                            • realJSOPR realJSOP

                              Ahh yes. For me, there has to be more than two lines of code to make it worth it, and then you have to consider th4 amount of stack and heap manipulation involved in making the function call (if it's "redundant", it probably requires some sort of poarameter for the function, thus increasing stack usage) versus just leaving the code where it is. Like everything else in coding, there are trade-offs.

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

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

                              you can eliminate the stack and heap overhead with function inlining.

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

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

                                John Simmons / outlaw programmer wrote:

                                This bizarre search for "less code" leads to the crap

                                not always. sometimes eliminating code also eliminates bugs and makes a product better

                                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
                                • B Bassam Abdul Baki

                                  True, but then call your app from a script thereby reducing it to just the call. :) There's no right answer for this. Generally speaking, we reduce, improve, and optimize functions since that is where "our" code usually is.

                                  Web - BM - RSS - Math - LinkedIn

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

                                  that's the whole point of this thread.

                                  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

                                  B 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
                                    Judah Gabriel Himango
                                    wrote on last edited by
                                    #51

                                    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 2 Replies Last reply
                                    0
                                    • P PIEBALDconsult

                                      What's a line of code ? OOP, generics, code generation, code reuse, implants[^]...

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

                                      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 1 Reply Last reply
                                      0
                                      • 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
                                        #53

                                        Judah Himango wrote:

                                        Another way I write less code is by using the Reactive Extensions (Rx)

                                        Ah, you remind me that I need to learn more about Rx. Thank you! Marc

                                        My Blog

                                        1 Reply Last reply
                                        0
                                        • T TheGreatAndPowerfulOz

                                          that's the whole point of this thread.

                                          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

                                          B Offline
                                          B Offline
                                          Bassam Abdul Baki
                                          wrote on last edited by
                                          #54

                                          I know. No need to needle it into me.

                                          Web - BM - RSS - Math - LinkedIn

                                          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