How do you write fewer lines of code?
-
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
That is sweet.
Curvature of the Mind now with 3D
-
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
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
-
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, 1997you 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 -
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, 1997John 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 -
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 -
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 -
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
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
-
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
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
-
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 -
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
Say, has Rx always been a Microsoft thing? I thought it was developed by some other folks. Marc
-
Say, has Rx always been a Microsoft thing? I thought it was developed by some other folks. Marc
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
-
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, 1997Line 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.
-
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
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.
-
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
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 -
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 BraunIn regards to what?
-
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
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
-
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
Don't write code. Generate code using code generators! ;P
-
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
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
-
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
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"
-
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
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