Quantcast
Channel: Grant Winney
Viewing all 348 articles
Browse latest View live

I can't find my logs in AWS Lambda! (they might not be enabled...)

$
0
0
I can't find my logs in AWS Lambda! (they might not be enabled...)

I setup an AWS Lambda job the other day, for cleaning up comments on SO, and then added a trigger to run it every morning. I checked it this morning and realized:

  1. The job failed for some reason.
  2. I had no idea what that reason was, because nothing was written to the logs.

According to the docs, all Console.WriteLine statements are logged:

To output logs from your function code, you can use methods on the Console class, or any logging library that writes to stdout or stderr.

But all I got on the logs page was an error message... an awful, unhelpful message:

There was an error loading Log Streams. Please try again by refreshing this page.

Telling users to refresh the page is like IT telling someone to turn their monitor off and back on - okay, it's something to do, but it's not going to fix any problems. Unless your problem is that your screen is dark.


Enable Logging

When you create a new Lambda job, logging is (inexplicably, to my thinking) not configured by default. I'm sure there's reasons for it, but considering this is a service where jobs run headless, it seems pretty important to be able to jump in and quickly see exactly why a job is failing. The metrics screens aren't enough.

So, if you've just setup a job and you're running into this same problem, check the execution role for your job, which "defines the permissions of your function". These permissions include the ability to write out to the logs (or a "log group" as they call it).

I can't find my logs in AWS Lambda! (they might not be enabled...)
Look for this panel halfway down the screen for your function. Click the "View role" link.
I can't find my logs in AWS Lambda! (they might not be enabled...)
You want to add a new policy, so click the big button that says "Attach policies".
I can't find my logs in AWS Lambda! (they might not be enabled...)
Type "cloudwatchlogs" into the filter, select "CloudWatchLogsFullAccess", and attach it.
I can't find my logs in AWS Lambda! (they might not be enabled...)
Verify the new policy shows up on the previous screen.
I can't find my logs in AWS Lambda! (they might not be enabled...)
Run your job again, then click "View logs in CloudWatch".
I can't find my logs in AWS Lambda! (they might not be enabled...)
You should see an entry, assuming your job wrote anything out.
I can't find my logs in AWS Lambda! (they might not be enabled...)
Yay, logs. 🎉

My issue ended up being two separate problems:

  • I targeted .NET Core 2.1 when I created the Lambda function (because that's the only one available), but my C# project targeted .NET Core 3.0. Oops.
  • I also forgot to add a reference to Amazon.Lambda.Core, which is really easy to do since it's not used in the project nor required by any part of the project, but its absence will cause the job to fail when it runs on AWS. 🤦‍♂️
I can't find my logs in AWS Lambda! (they might not be enabled...)

If that didn't do it for you, or you already had a comparable permission selected, there's some more helpful suggestions in this post by Dora Hodanic:

Amazon Connect and Lambda logs: Error loading Log Streams


Jumpin' on the Docker train (better late than never...)

$
0
0
Jumpin' on the Docker train (better late than never...)

If you're in a technology field, it's easy to develop the feeling that you need to know every concept out there. As if we aren't being paid to learn new things as business needs arise, but to somehow know everything ahead of time.

We make it worse by (oh so very wrongly) assuming that if someone does or knows one thing well, then they must do or know every thing well, which of course is never true. It's why George Foreman can sell grills, Jimmy Fallon sports merchandise, and Arnold Schwarzenegger became governor. We know all this on some level, even if we frequently forget it.

For me, today, that technology is Docker. I've had no reason to learn it so far, but it's been around for years, I've heard others talk about it, and now I feel like I should already know it. Well, we're using it where I work to varying degrees and I think I may be delving into some of it soon, so time to get the basics at least...


Now We're Cooking (a distasteful analogy)

If you're learning it for the first time too, here's how I'm imagining it so far, after a few articles and a handful of videos. If you're a chef and a programmer... I'm sorry.

Jumpin' on the Docker train (better late than never...)

Imagine you're a chef, in charge of recreating old dishes, improving on them, inventing new ones... but there's nothing new under the sun, and ultimately they're going to be built upon some basics, right? You have base ingredients like flour and eggs and sugar. You have a kitchen with a base set of utensils and gadgets - it's not a mechanics garage, IT lab, or a physician's office (unless your cooking is really bad).

Traditional servers

You're initially given a style of food prep to recreate, some way it was served centuries ago, and lo' and behold you find a place where they've been serving it that way all along. They're making it all work successfully, but there are no recipes or blueprints to follow. It's a piecemeal thing that's grown and evolved over time.

How do you recreate their success? Is it just the ingredients they use? Is it the machinery? The exact oven or utensils? Do the wood-paneled walls or coffered ceiling somehow play into it? The whimsy art for sale in the front window? The bathrooms? The exact combination of employees, in the same ratio of race, gender, and age, and personal knowledge?

Your only choice is to recreate everything, exactly as it is in the other kitchen, and good freaking luck with that. You'll have to build a place with the same layout, the same tools, the same plumbing, clones of the employees (this is getting shady). Most of it may be unnecessary, but how do you know for sure? Everything's tightly coupled to everything else. The safest route is all or nothing.

Before virtualization, the only way to guarantee that a complicated piece of software would run correctly on a second machine was to configure it to have exactly the same setup as the first machine it was on. But what if that first machine was a development machine, or had been around for awhile? It might have a hundred updates, or a dozen conflicting pieces of software. Maybe the only reason the application worked was because one of the 12 frameworks the developer was using happened to install something she ended up using in the app, and she wasn't even aware of it!

Hardware virtualization (virtual machines)

Realizing you can prepare new foods in the same style by using the same hardware - log cabin, brick oven, cast iron pots - you strike a deal with the owner to renovate the unused space in the back room. Now you can create any food you want... colonial era tiramisu! You'll need employees with similar skills to create similar foods, or you could hire employees with different skills to produce different foods, but the underlying hardware is the same. This analogy is starting to crack at the seams.

One way to save time and resources is to use hardware virtualization technology, such that you run an operating system inside another operating system. You've got that nice powerful machine with gigabytes of RAM and terabytes of hard disk space, but you're not using it all. You can setup a virtual machine, running Windows 3.1 or Windows XP for example - or something far more useful. 😉

OS-level virtualization

Wait, you're not interested in making most types of foods - just desserts of yore, like great-great-great-great-grandma's apple pie. You don't just want to reuse the existing building and ovens and sinks, you want to reuse the people and skills too since they happen to be proficient at making desserts. It's just as well - the back room was full of rats, completely unusable.

So you share all the existing hardware and software (that's an ugly way to refer to that portly chef), and simply install more stations nearby in the same big room. You get a portion of the sink and oven and employee's time (all segregated though, so your desserts don't blend together). As you think of more desserts to make, you just repeat the process of adding a new station until the building runs out of room and the plumbing is clogged up with cookie dough and cake batter. Are you actually still reading this?

Docker and other OS-level virtualization techniques bring us similar repeatability and stability as full virtual machines, but they use less resources because not only are we reusing the hardware... we're reusing a portion of the software too.

Docker

Even better, if you screw up a dessert or set a station on fire, it has no effect on the other stations. You roll back to a time before everything reeked of burnt tofu (what kind of dessert are you making??), and you're good to go. If you're improving a recipe and decide after a few iterations that it's all awful oh my gosh why did I ever get into cooking I should've listened to mom and become a doctor, then you can just roll back to a week ago when you thought better of yourself.

I don't know if all such virtualization works this way, but Docker is built on layers. So if someone else created an "image" you want to use, you can spin an instance of it up and build on top of it. Your app runs in a "container" that's different than the original image, and if you like what you've got you can save a snapshot of it to create a new image layered on top of the original. You can create all kinds of snapshots over time, rollback to a specific one, build 5 projects from the same image that fork off in their own directions, whatever. Sounds a lot like source control via git et al. 🤔


A Diagram (not mine)

Here's a nice diagram I'm not ashamed to say I swiped from What is Kubernetes.

  • Traditionally, every deployment required its own hardware, OS and apps.
  • With hardware virtualization, a deployment requires only its own OS and apps.
  • With OS-level virtualization, every deployment requires only its own lightweight space for an app to run in, called a container, so it can save data and such.
Jumpin' on the Docker train (better late than never...)

Hyper-V and Docker and VirtualBox, oh my

So this was a fun discovery. If you have Windows 10 and still want to use VirtualBox or VMware for virtual machines, don't just go for the alluring Docker for Windows installation. That path is a trail of tears and sadness.

Jumpin' on the Docker train (better late than never...)
  • Docker for Windows requires Hyper-V to work.
  • VirtualBox and VMware do not work with Hyper-V enabled.

So unfortunately, neither VirtualBox nor VMware plays well with Docker installed and Hyper-V enabled, but at least VMware should have this fixed next year sometime. For now, you may want to skip Docker for Windows, disable Hyper-V if you have it enabled, and install Docker Toolbox instead. Run the "hello world" docker app, and if all goes well you can use VirtualBox and Docker.

Jumpin' on the Docker train (better late than never...)

Learning Material (also not mine.. duh)

I found the following article helpful, but mostly stuck to videos:

I found the above article helpful, but as stated... mostly stuck to videos: 🙃

A few minutes in, he draws a nice little illustration showing why a container is more lightweight.
There's a cake analogy in here that (loosely) kicked off my awful analogy above.
Keep in mind some of the information is outdated. For instance, boot2docker has been deprecated in favor of Docker Desktop for Mac and Windows (or Docker toolbox, depending on your use case).
This might not be applicable to some people, since it relies on Node.js, but still useful info I think.

SO Vault: Hidden .NET Base Class Library Classes?

$
0
0
SO Vault: Hidden .NET Base Class Library Classes?

StackOverflow sees quite a few threads deleted, usually for good reasons. Among the stinkers, though, lies the occasionally useful or otherwise interesting one, deleted by some pedantic nitpicker - so I resurrect them. 👻

Note: Because these threads are older, info may be outdated and links may be dead. Feel free to contact me, but I may not update them... this is an archive after all.


Hidden .NET Base Class Library Classes?

Question asked by John Sheehan

What are your favorite lesser-known .NET Base Class Library classes and methods?

Comments

Great question! The framework is so expansive that a lot of times one doesn't think to look (or doesn't know where to look) to the framework to achieve common (and sometimes not so common) tasks. – Giovanni Galbo Sep 24 '08 at 2:13

Super-useful question! I found some really cool stuffs here. – aku Sep 24 '08 at 9:24

I didn't have to mark it, community wiki are excluded. Unmarked – John Sheehan Aug 25 '09 at 21:34

I think it would be a mistake to delete this question - even though closed, it's a useful resource to have these answers here. – Bevan Jan 15 '12 at 2:29

while(true)Navigate(); – Shimmy Feb 6 '12 at 3:33


Answer by Doron Yaacoby

Path class. I can't count the times the lack of its usage came up in code-reviews. People tend to go for the string concatenations and sub-stringage instead of using Path.Combine and Path.GetFileNameWithoutExtension, among others.


Answer by C. Lawrence Wenham

System.Security.SecureString - More people should be aware of this if their program accepts passwords or passphrases, or stores credit card numbers in memory. SecureString values are stored encrypted (obfuscated, rather), but most importantly, they are never swapped to disk and can be disposed of immediately when you're done with them.

They're tricky to use because you can only build them one character at a time (to encourage you to build them by capturing keystrokes as the user types their password), and require three lines of code to recover and then wipe their plain text, but when used properly they can make a program more secure by avoiding the virtual-memory vulnerability.

// Make a SecureString
SecureString sPassphrase = new SecureString();
Console.WriteLine("Please enter your passphrase");
ConsoleKeyInfo input = Console.ReadKey(true);
while (input.Key != ConsoleKey.Enter)
{
   Console.Write('*');
   sPassphrase.AppendChar(input.KeyChar);
   input = Console.ReadKey(true);
}
sPassphrase.MakeReadOnly();

// Recover plaintext from a SecureString
// Marshal is in the System.Runtime.InteropServices namespace
try {
   IntPtr ptrPassphrase = Marshal.SecureStringToBSTR(sPassphrase);
   string uPassphrase = Marshal.PtrToStringUni(ptrPassphrase);
   // ... use the string ...
}
catch {
   // error handling
} 
finally {
   Marshal.ZeroFreeBSTR(ptrPassphrase);
}

Edit: At the end of the example the SecureString is converted into a regular managed string, which makes it vulnerable again (be sure to use the try-catch-finally pattern to Zero the string after you're done with it). SecureString's use is in reducing the surface-area of attack by limiting the number of copies the Garbage Collector will make of the value, and reducing the likelihood of being written to the swap file.

The .Net framework is gaining more support for SecureStrings that help eliminate the need to decrypt it. The PasswordBox control in WPF stores its value in a SecureString, System.Diagnostics.ProcessStartInfo's Password property takes a SecureString, and so does the constructor for X509Certificate2. Some third party components are beginning to take it as native currency, too.


Answer by Robert Paulson (Sep 24, 2008)

System.Diagnostics.DebuggerDisplay

When you're debugging, if the class is attributed, visual studio will display the information on mouse-over. It even allows you to put in properties of private fields, etc.

[System.Diagnostics.DebuggerDisplay("MyClass: ID={ID} Name={Name} ChildName={_child.Name}")]

Ref: msdn


Answer by RoyOsherove

This saves a lot of typing on strings:

string.IsNullOrEmpty()

and

string.IsNullOrWhiteSpace()  // .NET 4 only

Also a hidden gem using events; when declaring an event, a nice way to make sure you never need to check if it's null, is by initializing it to an empty anonymous delegate at declaration time:

public event EventHandler MyASimpleEvent = delegate {};

Answer by RoyOsherove (Sep 23, 2008)

A cool way to log the name of the current method you're in:

string myMethodName = MethodBase.GetCurrentMethod().Name;


Console.WriteLine(myMethodName);

Answer by user20804 (Oct 03, 2008)

Getting the list of countries. Useful for populating the drop down box.

foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures
{
       RegionInfo ri = new RegionInfo(ci.LCID);
       Console.WriteLine(ri.EnglishName);
}

ref: http://jdconley.com/blog/archive/2007/09/05/list-of-country-names.aspx#1


Answer by Chris Wenham (Sep 23, 2008)

System.Diagnostics.ConditionalAttribute. It makes the compiler ignore methods or classes that should only be active in certain build profiles. EG:

 [Conditional("DEBUG")]
 private void DumpProperties()
 {
     foreach (PropertyInfo prop in this.GetType().GetProperties())
         Console.WriteLine(prop.GetValue(this, null));
 }

Answer by Ruben (Sep 23, 2008)

Most definitely String.Join(char separator, string[] list) to create "a,b,c" from {"a","b","c"}. This alleviates keeping track of a boolean to check whether the first item is already used.


Answer by David Basarab

Use the System.Diagnostics.Stopwatch

Don't do StartTime with DateTime, and then EndTime with DateTime.

See this answer.


Answer by Carra

Using System.Environment.NewLine instead of "\r\n".


Answer by Luke Foust (Sep 25, 2008)

System.Data.Common.DbConnectionStringBuilder

and

System.Data.SqlClient.SqlConnectionStringBuilder

These allow you to build a connection string in a programmatic way without have to remember the specific syntax.

Documentation: DbConnectionStringBuilder on MSDN


Answer by dcigic (Sep 24, 2008)

System.Collections.ObjectModel.ObservableCollection<T>

Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.


Answer by Mike Post

TextRenderer.MeasureText() is great for figuring out how large to draw your text. So often I see:

// this == something derived from Control
Size size;
using(Graphics g = this.CreateGraphics())
  size = g.MeasureString(this.Text, this.Font).ToSize();

When really all you need is:

Size size = TextRenderer.MeasureText(this.Text, this.Font);

The former is how you did it in 1.0 and 1.1; the latter is how you do it in 2.0+. It's much cleaner, doesn't requiring creating an object which must be disposed, and doesn't leave you open to accidentally not disposing of a resource. Plus if you use TextRenderer.DrawText() your text will look better and localize better. This stuff just plain rocks when you're doing custom controls.

Edit: On the I18N/G11N front, here's more info: the shaping engines for international text have been updated quite a bit in the Uniscribe subsystem of the Windows operating system, but not in GDI+ subsystem. So sometimes things looked strange/wrong if your .NET app was using the Graphics based method (AKA, GDI+). However, using the TextRenderer approach (AKA, Uniscribe) eliminates these problems and allows you to render text correctly (perfectly?) in the new locales introduced with Windows XP SP2 (such as Bengali and Croatian). (Caveat emptor: I have no idea how or even if either of these methods play with vendor specific extensions to specific code pages.)


Answer by Max Schmeling

IEnumerable<T> isn't used nearly enough if you ask me.


Answer by Seb Nilsson

System.Convert is a lot nicer than people think.

It's a bit more forgiving on what you put in. Use Reflector to see how it converts between different types.

Ints are defaulted to 0 from bad input, bools to false and so on.

It's made int.Parse, bool.Parse and all other .Parse almost obsolete for me. TryParse is still usefull for the most secure parsing.


Answer by Chris Pietschmann (Sep 23, 2008)

System.Web.VirtualPathUtility

Provides utility methods for common virtual path operations.

http://msdn.microsoft.com/en-us/library/system.web.virtualpathutility.aspx

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

    Dim sb As New StringBuilder()
    Dim pathstring As String = Context.Request.FilePath.ToString()
    sb.Append("Current file path = " & pathstring & "<br />")
    sb.Append("File name = " & VirtualPathUtility.GetFileName(pathstring).ToString() & "<br />")
    sb.Append("File extension = " & VirtualPathUtility.GetExtension(pathstring).ToString() & "<br />")
    sb.Append("Directory = " & VirtualPathUtility.GetDirectory(pathstring).ToString() & "<br />")
    Response.Write(sb.ToString())

    Dim sb2 As New StringBuilder()
    Dim pathstring1 As String = Context.Request.CurrentExecutionFilePath.ToString()
    sb2.Append("Current Executing File Path = " & pathstring1.ToString() & "<br />")
    sb2.Append("Is Absolute = " & VirtualPathUtility.IsAbsolute(pathstring1).ToString() & "<br />")
    sb2.Append("Is AppRelative = " & VirtualPathUtility.IsAppRelative(pathstring1).ToString() & "<br />")
    sb2.Append("Make AppRelative = " & VirtualPathUtility.ToAppRelative(pathstring1).ToString() & "<br />")
    Response.Write(sb2.ToString())

End Sub

Answer by Erick Sgarbi (Sep 27, 2008)

Not really hidden but:

  • System.Drawing.Printing.PrinterSettings.InstalledPrinters: Returns a collection with all printer names installed in the machine.

Answer by John Sheehan - Runscope

I didn't know about System.Net.WebClient until it was posted in an answer to a question of mine.

WebClient client = new WebClient ();
client.DownloadFile("https://stackoverflow.com/", "target.html");
client.UploadFile("http://mysite.com/", "hello.txt");

Answer by DotNetGuy

System.Web.Security.FormsAuthentication
.HashPasswordForStoringInConfigFile(string password, string format)

Does the simple and common task of getting the MD5 or SHA1 hash of a given string. Since almost every system I have ever written stored password hashes instead of encrypted data or the plaintext, this is a godsend to avoid mucking about with the Crypto stuff.


Answer by aku

TypeConverter class

It saved me a lot of time. And it helped Stack Overflow users to solve their problems:


Answer by John Sheehan

Buffer.BlockCopy

Also StringReader and StringWriter.

Oops forgot about: Debugger.Break


Answer by Brann (Mar 05, 2009)

You can play default windows sounds this way :

System.Media.SystemSounds.Beep.Play();
...
System.Media.SystemSounds.Question.Play();

Answer by Ryan Lundy (Mar 10, 2009)

Tired of typing the unwieldy

string.Equals(x, y, StringComparison.CurrentCultureIgnoreCase)

?

Instead, try one of the properties on the StringComparer class:

StringComparer Properties

Instead of the above, you can type:

StringComparer.CurrentCultureIgnoreCase.Equals(x, y);

Even though it's only slightly shorter, it's nice because it keeps the focus on the two things you're comparing, without the distraction of the StringComparison.CurrentCultureIgnoreCase parameter. And you can break it up if you like:

var comparer = StringComparer.CurrentCultureIgnoreCase;
comparer.Equals(x, y);

Answer by Jivko Petiov (Sep 25, 2008)

HashSet<T>. It is a new class in the .NET Framework 3.5 and is very similar to List<T> only better.

http://blogs.msdn.com/bclteam/archive/2006/11/09/introducing-hashset-t-kim-hamilton.aspx


Answer by Mitchel Sellers (Sep 23, 2008)

For some reason many people don't kow about System.Text.StringBuilder. I couldn't live without it!


Answer by zvikara

The BitConverter.ToString method is very useful when working with binary data. I use it for debugging, traces and within unit testing.

It will take a byte array and return a printable string representation - something like "04-08-01-23-45-67-89-AB-CD-EF".

I also use Regex.Split(string, string) for splitting a delimited strings.

It is somewhat similar to String.Split(), but using Regex.Split() is much more intuitive: Regex.Split() result string array only contain the data you need, while String.Split() result also contains the delimiters.


Answer by David Basarab (Aug 25, 2009)

System.IO.Path.Combine

Use this instead of concatenating the 2 strings yourself.


Answer by PVitt (Aug 26, 2009)

String.Empty seems to be a hidden feature for many developers. String.IsNullOrEmpty(string) too.


Answer by Gulzar

This is cool. VisualStyleInformation Class provides a lot of information about the current visual style of the operating system.

System.Diagnostics.Debugger.Break() is used by virtually everyone but is very convenient for debugging .NET services.

NetworkChange.NetworkAvailabilityChanged Event makes it easy to monitor network availability.


Answer by jesal (Sep 24, 2008)

Here's a little snippet to tell which class/method the call is coming from. Useful in some special situations:

StackFrame frame = new StackFrame(1);
frame.GetMethod().Name; //Gets the current method name

MethodBase method = frame.GetMethod();
method.DeclaringType.Name //Gets the current class name

Answer by 280Z28

If you have a very complicated object to debug and don't want to spend the time creating a Visualizer to get a specialized view, you can use the built-in HTML Visualizer by creating a ToHtmlString() method in your class. This is based on the fact that the .NET debugger very reliably allows you to add function calls in your watch windows.

Here's an example I recently did of presenting an interleaved time-lapse view of the data state throughout a group of tasks:

Compiler State View http://www.280z28.org/images/vmx/2009-08-23-Annotator-Small.png


Answer by John Sheehan (Sep 23, 2008)

System.Web.UI.WebControls.MailDefinition

"The MailDefinition class can be used by controls to create a MailMessage object from a text file or a string that contains the body of the e-mail message. Use the MailDefinition class to simplify creating predefined e-mail messages to be sent by a control."


Answer by SDX2000

WeakReference. Extract from here ...

The garbage collector cannot collect an object in use by an application while the application's code can reach that object. The application is said to have a strong reference to the object.

A weak reference permits the garbage collector to collect the object while still allowing the application to access the object.

This can be used to implement weak events, see here


Deep comparison of XmlTrees

XDocument.DeepEquals

Compares the values of two nodes, including the values of all descendant nodes.


Answer by GvS (Sep 24, 2008)

I just found:

System.Security.Cryptography.ProtectData

Used to encrypt data for the current user or the local machine.


Answer by marcc (Aug 25, 2009)

I don't think it's a hidden feature, but I don't see it used often:

[System.Diagnostics.DebuggerStepThrough]

Quite useful when you have a pile of accessor-type functions or something which you don't want to be stepping into while debugging.


Answer by csharptest.net (Sep 22, 2009)

I have to add Exception.GetBaseException(). I can't know how many times I've this code instead:

while(e.InnerException != null)
    e = e.InnerException;
return e.Message;

instead of just:

return e.GetBaseException().Message;

Answer by Robert Rossney (Oct 06, 2008)

I'd have to say System.ComponentModel.BackgroundWorker.

It's not exactly easy to use, because you still have to understand how asynchronous method calls work, and you have to know about avoiding cross-thread exceptions, using Invoke to update the UI, etc. But it's considerably easier to use than System.Threading.Thread, which is what a lot of developers gravitate towards when they need to implement a background process.


Answer by HuBeZa

Convert hexadecimal\octal\binary string to decimal:

Convert.ToInt32("2A", 16); // equals 42
Convert.ToInt32("52", 8); // equals 42
Convert.ToInt32("101010", 2); // equals 42

A great way to convert numbers to byte array:

byte[] bytes = BitConverter.GetBytes(32767);

Or better, use Jon Skeet's MiscUtil for endian bit conversion.


Answer by user17222 (Sep 24, 2008)

String.Format(). Allows you to get rid of the wonkiness of "This" + " is" + " my favorite " + " Application";


Answer by xrost

Very helpful class to measure performance System.Diagnostics.StopWatch
See detailed posts here


Answer by Panos (Sep 23, 2008)

System.Diagnostics namespace contains many "hidden" gems. I have used extensively the DebuggerStepThroughAttribute, I have subclassed many times the TraceListener class and I want to see in more detail the PerformanceCounter.


Answer by Aseem Gautam

Create custom size thumbnails from any image using System.Drawing.Image.GetThumbnailImage:

public Image GetThumbnailImage (int thumbWidth, int thumbHeight,           
                GetThumbnailImageAbort callback, IntPtr callbackData)

Eg usage:

public static Image GetThumbnailFromImage(System.IO.Stream file)
{
    return Image.FromStream(file).GetThumbnailImage(48, 48, null, new IntPtr());
}

Answer by Mike Two

More of a runtime feature, but I recently learned that there are two garbage collectors. The workstation gc and the server gc. Workstation is the default, but server is much faster on multicore machines.


<configuration>
   <runtime>
      <gcServer enabled="true"/>
   </runtime>
</configuration>

Be careful. The server gc requires more memory. See documentation for more information.


Answer by dariom

I use these built-in delegate types (and their "overloaded" cousins) all the time:

Along with Lambdas is C# 3.0 they're pretty useful and can help make things more readable. (You can of course still use them with C# 2.0 and anonymous delegates).


Answer by STW

Here's one, inspired by Marcc's related Diagnostics attribute:

System.Diagnostics.DebuggerDisplay

It allows you to define the format of the string displayed in the Immediate / Locals window of Visual Studio, providing a string like "Person: {name} Cars: {cars.Count}" will display in the windows like "Person: John Doe Cars: 2".


Answer by Konrad Rudolph

Type.TryParse()

Environment.NewLine

Answer by jon without an h (Nov 03, 2008)

System.Runtime.Remoting.Proxies.RealProxy.

This class is pretty esoteric and normally only used in weird remoting scenarios; however, I have used it for the ability to dynamically implement an interface. It is also used by some mocking frameworks for the same purpose. See also Extending RealProxy.


Answer by bbmud (May 14, 2009)

System.Net.Mail.MailAddress - no more regexp for server-side email address validation ;)


Answer by Jason Z (Sep 23, 2008)

System.Text.UTF8Encoding for converting streams.


Answer by sallen (Sep 23, 2008)

If you are drawing custom Windows Forms controls, then the following classes are essential for your OnPaint() method (or Paint event):

using System.Windows.Forms;

These classes all provide methods that will do most of the drawing work for you and keep your controls looking professional and native.


Answer by John Sheehan (Jan 05, 2009)

MatchEvaluator Delegate: Represents the method that is called each time a regular expression match is found during a Replace method operation.


Answer by Chris Chilvers (Aug 26, 2009)

If you're trying to convert between big/little endian then there is IPAddress.HostToNetworkOrder and IPAddress.NetworkToHostOrder. Why these methods were not part of the BitConverter class and in the obvious place people will look we'll never know.


Answer by Peter Mortensen

TypeDescriptor when using Windows Forms data binding. This is how BindingSource can pretend to be any other object type.


Answer by Jobi Joy

System.Linq is saving me a lot of time on Visual Studio 2008.


Answer by Wayne (Sep 23, 2008)

BaseValidator Makes writing Custom validated controls much easier.


Answer by Bart Read (Sep 23, 2008)

System.Runtime.InteropServices.Marshal

I hate having to do interop, and particularly PInvoke, but there are all kinds of goodies in Marshal for turning function pointers into delegates, and vice versa, turning Win32 error codes into something a little more helpful (often only a little though), and so on.


Answer by Dror Helper

Using StackFrame to get information about calling method and running class. You can travel the stack and get the methodName, calling calss etc. You can get the stackFrame using

StackFrame frame = new StackFrame(n);

Where n is the layer above the current call And then you can retrive information by using its properties. for example use the following the get the information of the calling method:

MethodBase methodBase = frame.GetMethod();

Answer by sisve (Mar 27, 2009)

FormatterServices.GetUninitializedObject

Creates a new instance of a type without calling any constructor. This will work with private constructors, non-parameterless-constructors, any type of constructor (since they aint called).

I believe this is the only way to ensure that a static constructor on a type is executed if you only have a Type instance. (You can not invoke it with reflection, and the Activator may fail due to nonmatching constructors.)

A somewhat esoteric problem, and solution.


Answer by Nathan Koop (Jun 02, 2009)

I came across this today System.Data.SqlTypes.SqlDateTime

it has

System.Data.SqlTypes.SqlDateTime.MinValue;
System.Data.SqlTypes.SqlDateTime.MaxValue;

among other methods & properties.


Answer by amarsuperstar

string.Join([separator], [array])

Couple this with LINQ and it rocks!

string.Join(",", customers.Select(c => c.Name).ToArray());

All your customer names in a CSV with one line of code :-)


Answer by John Sheehan (Oct 21, 2008)

System.Configuration.Install.AssemblyInstaller to install services programmatically


Answer by Pat (Mar 05, 2009)

In line with String.IsNullOrEmpty().....

String.Empty

usage:

string s = String.Empty;
//OR
string s = string.Empty;

instead of

string s = "";

Answer by Mark Carpenter (Aug 25, 2009)

One of my favorites is the DefaultValueAttribute (System.ComponentModel) for properties.

With it such things are possible:

[DefaultValue(true)]
public bool IsCool { get; set; }

Answer by Peter Mortensen

My favorite hidden feature is the SDK. OK, not very hidden, for some people, but most people seem to be able to develop .NET applications only with a tool or IDE, like Visual Studio. The SDK is free, and for small applications it's way quicker for me to write them up in emacs and then just build them with the command line compilers, csc.exe or vbc.exe.

Plus all the SDK tools are handy, too. XML Schema Definition Tool (xsd.exe), Strong Name Tool (sn.exe), and many others.


Answer by Gabe Moothart (Apr 09, 2010)

Membership.GeneratePassword() (msdn) will generate a secure temporary password for you.


Answer by Dror Helper (Sep 24, 2008)

System.Reflection.Assembly.GetExecutingAssembly.Location

Gets the path (and name) of the current running application.

I have a few related commands at my Blog


Answer by blowdart (Jul 27, 2009)

System.Security.SecurityElement.Escape

Escapes XML entities from a string so you can use it within an XML element. It's used by the framework in generation WS-Security XML, but saves four string replace statements in your own code.


Answer by Sam Harwell (Aug 26, 2009)

The Managed, Native, and COM Interop Team at CodePlex have released a modified, open source TlbImp tool that allows simple creation of customized wrappers for pesky COM libraries.


Answer by 280Z28

I found several cases where people were not aware of certain properties of the Environment class. In particular, I cleaned up several places in code and changed it to:


Answer by HashName (Jul 28, 2010)

System.Xml.XmlConvert contains lots of nice static methods to convert between XSD types and .Net types.


Answer by Mats

System.Environment is one of my favorites. Especially the WorkingSet property (gets the amount of physical memory mapped to the process context).


Answer by icelava (Sep 24, 2008)

I like to use System.Collections.CaseInsensitiveComparer to compare strings.


Answer by Dan Diplo (Jul 23, 2009)

Easy way of making an MD5 or SHA1 hash:

string hash = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile("string to hash", "MD5");

Quick way of generating a unique, temporary file on disk:

string tempFilePath = System.IO.Path.GetTempFileName();

The System.Web.VirtualPathUtility class also has some interesting methods for manipulating file paths.

Parse an enum into a string array in one line (eg. get all known colours from KnowColor enumeration into an array):

string[] colours = System.Enum.GetNames(typeof(System.Drawing.KnownColor));

If you want to annoy your server admin when he's at the console, add this to your web app :D

System.Media.SystemSounds.Exclamation.Play();

Answer by STW (Aug 26, 2009)

Microsoft.VisualBasic.IsNumeric(object)

Despite being in the Microsoft.VisualBasic.dll assembly, this method can be called by C# just as easily and can quickly let you know if the object being tested can be evaluated as a number.

Related to it are the various TryParse() methods, which attempt to evaluate an object as a number but don't raise exceptions if the call fails... These can be found under a variety of different types such as System.Int32 and System.DateTime


Answer by George Mauer

The Action lambda is a delegate and hence gets the same delegate goodies that regular ones do - such as BeginInvoke():

new Action(() => MethodIWantToRunAsychronously())
  .BeginInvoke(new AsyncCallback(x => ThingToDoWhenMethodReturns()), null);

What it does: Spawns a new thread and runs MethodIWantToRunAsychronously() on it while your continuing to execute the current method on the current thread. When MethodIWantToRunAsychronously completes, ThingToDoWhenMethodReturns() is called (still) on the new thread.


Answer by torial (Sep 27, 2008)

The DebuggerStepThroughAttribute is great for properties and also for those helper functions that you have no desire to step through. Unfortunately, it seems rarely known:

http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerstepthroughattribute.aspx


Answer by Chris S (Mar 27, 2009)

This isn't really a method but just something I found in the String class source:

// The Empty constant holds the empty string value.
// We need to call the String constructor so that the compiler doesn't mark this as a literal.
// Marking this as a literal would mean that it doesn't show up as a field which we can access 
// from native.
public static readonly String Empty = "";

Answer by thinkbeforecoding (May 07, 2009)

Decimal preserves trailing zeros :

decimal x = 1.0m;
decimal y = 1.00m;
decimal z = 1m;

Assert.IsTrue(x == y);
Assert.IsFalse(x.ToString() == y.ToString());

Assert.AreEqual("1.0", x.ToString(CultureInfo.InvariantCulture));
Assert.AreEqual("1.00", y.ToString(CultureInfo.InvariantCulture));
Assert.AreEqual("1", z.ToString(CultureInfo.InvariantCulture));

Assert.AreEqual("1.000", (x*y).ToString(CultureInfo.InvariantCulture));

This behavior is documented in the MSDN library.

The decimal.Parse method keeps track of trailing zeros too :

decimal x= decimal.Parse("1.0", CultureInfo.InvariantCulture);
decimal y= decimal.Parse("1.00", CultureInfo.InvariantCulture);

Assert.AreEqual("1.0", x.ToString(CultureInfo.InvariantCulture));
Assert.AreEqual("1.00", y.ToString(CultureInfo.InvariantCulture));

Answer by Dmitrii Lobanov (May 07, 2009)

Really useful class is System.Diagnostics.Stopwatch. It saves you from inventing a bicycle every time you need to measure time. It's really helpful when you need to make some time dependent work (perhaps periodic) in some thread.


Answer by skevar7 (Aug 26, 2009)

[System.Diagnostics.ConditionalAttribute] - can be used instead of ugly preprocessor directives. For instance:

[Conditional("DEBUG")]
public void Validate()
{
    // ...
}

Answer by Freshblood

ToString() method of Object base class is really nice thing. Override it then bring mouse over instance variable in debug time after instance variable created. Don't even need DebuggerDisplay

class Program
{

    string name;
    string surname;
    static void Main(string[] args)
    {
        Program instance = new Program() { name = "James", surname = "hetfield" };
        Console.ReadKey();
    }
    public override string ToString()
    {
        return string.Format("name is {0}, surname is {1}",name,surname);
    }
}

Answer by csharptest.net (Aug 02, 2011)

System.Runtime.InteropServices.RuntimeEnvironment

Most notably the GetRuntimeDirectory() method; however, there are several useful methods there.

    // Show whether the EXE assembly was loaded from the GAC or from a private subdirectory.
    Console.WriteLine("Did the {0} assembly load from the GAC? {1}",
       Assembly.GetExecutingAssembly(),
       RuntimeEnvironment.FromGlobalAccessCache(Assembly.GetExecutingAssembly()));
    // Show the path where the CLR was loaded from.
    Console.WriteLine("Runtime directory: {0}", 
       RuntimeEnvironment.GetRuntimeDirectory());
    // Show the CLR's version number.
    Console.WriteLine("System version: {0}", 
       RuntimeEnvironment.GetSystemVersion());
    // Show the path of the machine's configuration file.
    Console.WriteLine("System configuration file: {0}", 
       RuntimeEnvironment.SystemConfigurationFile);

Answer by Dror Helper (Sep 24, 2008)

public static int Compare(string strA, string strB, bool ignoreCase)

Great to compare two strings with possible difference in letter case.


Answer by John Chuckran

Expanding the My Namespace has always been useful to me

Namespace My

    <Global.Microsoft.VisualBasic.HideModuleName()> _
    Friend Module MyStuff
        Sub Foo()

        End Sub
    End Module

End Namespace

Answer by Peter Gfader (Apr 07, 2009)

Ignore Attribute on Unit-Tests for ignoring slow performance tests during development


Answer by Sam Harwell (Aug 26, 2009)

If you have a custom MSBuild task in your project that processes a file and subsequently creates .cs files to include in the same build, changes to the source file of the transformation often won't show in debugging without building twice. When you are generating a single file based solely on the content of a single source file, this task is best solved with a SingleFileGenerator. For multiple inputs and/or outputs, you may be stuck with an MSBuild task. In this case you can fix Visual Studio's dependency analysis by adding the following to your .csproj file:

<PropertyGroup>
  <UseHostCompilerIfAvailable>False</UseHostCompilerIfAvailable>
</PropertyGroup>

It's introduces a few other annoyances, but it will allow you to have deterministic, correct single builds (a rather important goal).


Answer by Slace

For generating code files I like System.CodeDom.


Answer by ligaoren (Feb 24, 2010)

FormatterServices.GetUninitializedObject Activator.CreateInstance

Has someone mentioned above two?


Answer by Thomas Levesque (Aug 11, 2011)

I recently discovered the ProtectedData and ProtectedMemory classes, which allow you to use the Data Protection API from .NET. It's a nice way to encrypt user credentials for storage in applications that need to authenticate on a remote server.

public static string EncryptPassword(string password, byte[] optionalEntropy = null)
{
    byte[] clearTextBytes = Encoding.UTF8.GetBytes(password);
    byte[] encryptedBytes = ProtectedData.Protect(clearTextBytes, optionalEntropy, DataProtectionScope.CurrentUser);
    return Convert.ToBase64String(encryptedBytes);
}

public static string DecryptPassword(string encryptedPassword, byte[] optionalEntropy = null)
{
    byte[] encryptedBytes= Convert.FromBase64String(encryptedPassword);
    byte[] clearTextBytes = ProtectedData.Unprotect(encryptedBytes, optionalEntropy, DataProtectionScope.CurrentUser);
    return Encoding.UTF8.GetString(clearTextBytes);
}

Shared with attribution, where reasonably possible, per the SO attribution policy and cc-by-something. If you were the author of something I posted here, and want that portion removed, just let me know.

What is the opposite method of Any in LINQ?

$
0
0
What is the opposite method of Any in LINQ?

If you are (or hope to be) a .NET developer, knowing LINQ is a huge time-saver. It's a syntax that allows you to manipulate data in a fashion that'll be familiar to anyone who's worked in a database.

Any

One of the many nice functions in LINQ is a single word that iterates through a collection, returning true if at least one item in the collection matches the condition you specify.

var currencies = new[] { "USD", "EUR", "JPY" };

Console.WriteLine(currencies.Any(x => x == "MXN"));  // False

But what's the opposite of Any<T>()?

What if, instead of finding out whether the list of currencies includes "peso", you wanted to make sure the list of currencies did not include "peso"? You could negate the above, but you might think that reads a bit funny... and I'd agree.

var currencies = new[] { "USD", "EUR", "JPY" };

Console.WriteLine(!currencies.Any(x => x == "MXN"));  // True

All

The only way to make sure that a list doesn't include a particular value, or that no item in the collection matches a particular condition, is to check every single item in the collection... and that's what All<T>() is for.

var currencies = new[] { "USD", "EUR", "JPY" };

Console.WriteLine(currencies.All(x => x != "MXN"));          // True

Console.WriteLine(currencies.All(x => !x.StartsWith("M")));  // True

Try it out

Try it out yourself below. And to learn more, read about All and Any.

How can I find the state of NumLock, CapsLock or ScrollLock in WPF?

$
0
0
How can I find the state of NumLock, CapsLock or ScrollLock in WPF?

If you're writing a WPF application and need to find the state of the Num Lock, Caps Lock, or Scroll Lock keys, you can use the Keyboard.IsToggled method (introduced in .NET 3.0):

var isNumLockToggled = Keyboard.IsKeyToggled(Key.NumLock);
var isCapsLockToggled = Keyboard.IsKeyToggled(Key.CapsLock);
var isScrollLockToggled = Keyboard.IsKeyToggled(Key.Scroll);

Add this using directive to the top of your class, if it's not already there:

using System.Windows.Input;

Internally, the IsToggled() method checks to see whether or not a KeyStates.Toggled flag is set for the specified key.

[Flags]
public enum KeyStates : byte
{
    None = (byte) 0,
    Down = (byte) 1,
    Toggled = (byte) 2,
}

What's the difference between Tuple.Create() vs new Tuple?

$
0
0
What's the difference between Tuple.Create() vs new Tuple?

tl;dr - There is none. It's a matter of preference! Keep reading if you want to learn a little something though. 😉


When writing a story, it helps to be able to express a concept in a variety of ways, conveying subtle differences... and making the story much more enjoyable.

When writing code, the opposite is true. It's helpful to know exactly how you're supposed to write a solution to a particular problem, and it doesn't help when a language tries to be flexible by providing a dozen ways to do any one thing. I'm looking at you Ruby.

One of the things I like about C# is that there's often one way to do a thing. Even when there are multiple ways, like storing a collection of items, there's usually a best way, like using generics and List<T>. To create a collection that holds any type of object T, you just specify the type - a list of string, integers, your own class - and then you have all kinds of methods available to add and remove items, manipulate them, etc.

var names = new List<string>();

var ages = new List<int>();

class Car
{
    public string Model { get; set; }
    public int Year { get; set; }
    public decimal Cost { get; set; }
}
var cars = new List<Car>();

There's another structure in C# that stores items, called the Tuple. It's sort of like a lightweight class, storing objects of different types that are somewhat related or associated with one another, without the need to define a whole new class. Similar to the List<T> above, you can instantiate it by creating a new Tuple and specifying the types.

var person = new Tuple<string, int>("Bob", 30);

var grade = new Tuple<string, string>("Susan", "B");

Unlike the List<T> though, defining a new Tuple can get annoyingly long:

var randomCollection =
    new Tuple<string, string, decimal, string, Date, bool, string>
        { "John", "Doe", 95.3, "No", DateTime.Now, true, "n/a" };

So the C# team gave us a set of helper methods which remove the need for listing argument types. There's no difference between new Tuple and Tuple.Create under the hood; Tuple.Create() is just a set of overloaded static methods that instantiate new Tuple:

public static class Tuple
{
    public static Tuple<T1> Create<T1>(T1 item1) {
        return new Tuple<T1>(item1);
    }

    public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2) {
        return new Tuple<T1, T2>(item1, item2);
    }

    public static Tuple<T1, T2, T3> Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3) {
        return new Tuple<T1, T2, T3>(item1, item2, item3);
    }

    ...

One benefit of this is brevity; another is that you can store anonymous types in a Tuple, for which you otherwise wouldn't be able to say what the type is.

public class Person
{
    public string Name { get; set; }
    public int Height { get; set; }
    public DateTime BirthDate { get; set; }
}

var people = new List<Person>
{
    new Person { Name = "Bob", Height = 72, BirthDate = new DateTime(1984,1,1) },
    new Person { Name = "Mary", Height = 64, BirthDate = new DateTime(1980,2,2) }
};

var oneAnonList = people.Select(x => new { x.Name, x.BirthDate });
var twoAnonList = people.Select(x => new { x.Height, x.Name });

var myTuple = Tuple.Create(oneAnonList, twoAnonList);

There's still not too terribly much you can do with that, since to pass it to another method, you'd still need to be able to define the "type" of the parameter. So it really comes down to convenience and readability, and in both cases the Tuple.Create helper methods win hands-down.

How do I assign C# code to a variable?

$
0
0
How do I assign C# code to a variable?

It'd be ridiculous for a language to not have a way for you to reference a particular value, so you could pass it around in your application.

string name = "Grant";
int height = 71;
bool isMale = true;
Employee e = new Employee(name, height, isMale);

But did you know most languages have a way to pass around references to code too, so you can pass the code around and call (invoke) it in other parts of your application?

In C#, the type that lets you reference a method is called a delegate, and there are several different constructs that allow you to define a delegate... depending on what exactly you'd like to do.

Action

The Action delegate lets you reference a method that does not return a value.

Single Line

For example, you might define a single-line method that displays a message (with or without parameters).

var genericHi = new Action(() => Console.WriteLine("Hello World!"));
genericHi();  // Hello World!

var personalizedHi =
    new Action<string, string>((firstName, lastName) => Console.WriteLine($"Hello, {firstName} {lastName}!"));
personalizedHi("Katie", "Smith");  // Hello, Katie Smith!

Multiple Lines

Or you could define a method that has several lines:

var sayHiToEveryone =
    new Action<string, string, string>((name1, name2, name3) =>
                                       {
                                           Console.WriteLine($"Hi {name1}!");
                                           Console.WriteLine($"Hi {name2}!");
                                           Console.WriteLine($"Hi {name3}!");
                                       });
sayHiToEveryone("Larry", "Curly", "Moe");

Note

You can also eliminate the new Action part, but then you can't use var, so not sure this is really any better. To each their own...

Action genericHi = () => Console.WriteLine("Hello World!");
genericHi();  // Hello World!

Action<string, string> personalizedHi =
    (firstName, lastName) => Console.WriteLine($"Hello, {firstName} {lastName}!");
personalizedHi("Katie", "Smith");  // Hello, Katie Smith!

Func

The Func delegate is very similar to Action, except that it lets you reference a method that does return a value.

Single Line

Again, you can define a single-line method with or without parameters.

var getNowMessage =
    new Func<string>(() => $"The time is now: {DateTime.Now.ToString("h:mm tt")}");
Console.WriteLine(getNowMessage());               // The time is now: 8:24 PM

var getTimeMessage =
    new Func<DateTime, string>((date) => $"The time is now: {date.ToString("h:mm tt")}");
Console.WriteLine(getTimeMessage(DateTime.Now));  // The time is now: 8:24 PM

Multiple Lines

And you can define methods with several lines:

var getDrink =
    new Func<DateTime, string>((date) =>
                               {
                                   if (date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday)
                                       return "🍺";
                                   else
                                       return "☕";
                               });
Console.WriteLine($"Time for a {getDrink(DateTime.Now)}.");  // Time for a ☕.

Note

And finally, you can eliminate the new Func part, but once again that prevents you from using var, so it's not any shorter.

Func<string> getNowMessage2 =
    () => $"The time is now: {DateTime.Now.ToString("h:mm tt")}";
Console.WriteLine(getNowMessage2());               // The time is now: 8:24 PM

Func<DateTime, string> getTimeMessage2 =
    (date) => $"The time is now: {date.ToString("h:mm tt")}";
Console.WriteLine(getTimeMessage2(DateTime.Now));  // The time is now: 8:24 PM

Try it yourself

You can play with these yourself on .NET Fiddle:

Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement

$
0
0
Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement

This error might look a little cryptic at first glance, but it's actually very descriptive in explaining what's wrong. You're likely to come across this one when you're starting out with C# ... or before your first cup of coffee. 😏

Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement

Basically, it's telling you that what you typed isn't a valid statement. Which begs the question, what is a statement? Well, it's every valid line (or in some cases, block) of code that makes up your program, for example:

  • Assignments: string name = "Grant";
  • Calls: MyOtherFunction();
  • Increments: x++;
  • Decrements: x--;
  • Await: await myLongTask;
  • New object expressions: new Person();

In general, most statements should either modify a variable's value in-place, perform some side-effect (like a foreach block), or at least do something with the return value.

So if you get this error, double-check the line it's complaining about to make sure it's a valid statement, specifically one of the types listed in the error message itself.

Some specific things to check for:

  • Are you missing a set of parentheses?
    Console.WriteLine
  • Did you use == instead of =?
    string name;
    name == Grant;
  • Did you combine elements of a property and method?
    public string Name() { get; set; }
  • Does your statement only return a value, but you're doing nothing with it?
    var hi = "Hello, "; hi + " Grant";

SO Vault: What are your favorite Vim tricks?

$
0
0
SO Vault: What are your favorite Vim tricks?

StackOverflow sees quite a few threads deleted, usually for good reasons. Among the stinkers, though, lies the occasionally useful or otherwise interesting one, deleted by some pedantic nitpicker - so I resurrect them. 👻

Note: Because these threads are older, info may be outdated and links may be dead. Feel free to contact me, but I may not update them... this is an archive after all.


What are your favorite Vim tricks?

Question asked by Joe Van Dyk

Post your favorite Vim tricks (or plug-ins or scripts). One trick per answer.

Try to come up with something other than the basics, btw. :D

Comments

Logically equivalent questions to: stackoverflow.com/questions/87299/… – Kent Fredric Sep 18 '08 at 18:08

Every time I come back to read the answers I learn something! – Luc M Aug 16 '11 at 14:21

Not constructive? Really? – ergosys Oct 21 '11 at 20:20

I just found the answer here for "what can you do if you forget to use sudo with vim?". Constructive enough SO question for me. – RyanBrady Jan 6 '12 at 20:21

I'd thought this was exactly the right sort of question for a SE/SO community wiki… – me_and Jan 27 '12 at 13:03


Answer by Lee

In my ~/.vimrc:

cmap w!! %!sudo tee > /dev/null %

Will allow you to use :w!! to write to a file using sudo if you forgot to sudo vim file (it will prompt for sudo password when writing)

Alternative that allows you to skip reloading the file:

cmap w!! w !sudo dd of=%

Comments

You, Sir, are my hero! – Joachim Sauer Dec 16 '08 at 10:24

much better than !w /tmp/whatever, and then remembering to sudo cp it... +1! – Mikeage Feb 22 '09 at 9:23

Inspired. Elegant. – Peter Rowell May 5 '09 at 17:23

I'm in love with this and will use this within the week =) – chauncey Jun 17 '09 at 21:29

Why not just ":w !sudo tee %"? – hhh Aug 29 '09 at 11:20

It doesn't work very cleanly - prompts to reload file and then loses where it was, at least for me. – Artem Russakovskii Sep 28 '09 at 9:35

Using gvim, I get the response sudo: sorry you must have a tty to run sudo. – Scottie T Jan 5 '10 at 13:30

Scottie: Use gksudo or another graphical equivalent in that case. – Roger Pate Jan 12 '10 at 20:14

Could someone explain how this works in detail? – Doppelganger Apr 8 '10 at 14:23

Nevermind my question, if someone is interested just look here: stackoverflow.com/questions/2600783/… – Doppelganger Apr 8 '10 at 15:22

Shouldn't you use /usr/bin/tee? – idbrii Feb 23 '11 at 19:02

You shouldn't use sudo vim. Better define EDITOR as vim (export EDITOR=vim in your .bashrc) and run sudoedit. – Gerardo Marset Apr 11 '11 at 18:09

Here's an improved version of that: github.com/blueyed/dotfiles/blob/… – blueyed Apr 13 '11 at 15:51

blueyed, I tried your version and managed to trash my /etc/hosts with it. Better not to use this, guys. – loevborg Jun 27 '11 at 9:14


Answer by too much php

Using the built-in regions to change text quickly:

ci"    -> Cut everything inside "" string and start insert mode
da[    -> Delete the [] region around your cursor
vi'    -> Visual select everything inside '' string
ya(    -> Yank all text from ( to )

The command and type of region can all be used interchangeably and don't require .vimrc editing. See :help text-objects.

Comments

Awesome, thanks. – Liran Orevi Aug 9 '09 at 8:43

didn't know about the 'a' and 'i' motions. Very useful. – deft_code Jan 8 '10 at 16:59

I can't believe I've been through over a decade of vim'ming without knowing a/i. Nice tip! – Nik Reiman Nov 23 '10 at 10:37

Oh my god, amazing! This is going to change my life. – terrace Jun 27 '11 at 4:58

These are called text objects by the way. And there's a few more than the number you specified. – ldog Oct 9 '11 at 20:58


Answer by Aristotle Pagaltzis

da<

Delete the HTML tag the cursor is currently inside of – the whole tag, regardless of just where the cursor is.

ci"

Change the content of a doublequote-delimited string.

Etc etc, along the same lines. See :help text-objects.

Comments

That is a most excellent tip. – dowski Nov 14 '08 at 20:42

In addition to <> and "", this also works with [], {}, and (). – Robert Gowland Aug 18 '09 at 13:08

It's really cool. How to remember this : a = all i = inner try these ones : a[ i[ a< i< a{ i{ – nXqd Mar 24 '10 at 12:55

If you combine this with visual mode, you can quickly replace the contents of one block with another: yi{ to copy the text from one block, move the to target block, and vi{p to overwrite it. – naught101 Apr 29 '12 at 4:20


Answer by Mapad

Shortcuts to quit the Insert mode:

Ctrl+C                        Leave insert mode (faster than Esc)

Ctrl+O                        Leave insert mode just for the duration of one command

Ctrl+O Shift+I   Leave insert mode, go to beginning of line, and return to insert mode

Ctrl+O Shift+A   Leave insert mode, jump to end of line, and return to insert mode

Comments

Neat, didn't know that one. Btw, try Ctr-r + = (5+4)*3 [Enter] while in insert mode. – Claes Mogren Dec 11 '08 at 9:48

really neat trick the <C-o> — although you don't need to use it if you're gonna use A or I right after it. – cloudhead Nov 14 '09 at 16:12

I have my (otherwise useless) Caps Lock key mapped to Esc, so I have an Esc key on the home row. Invaluable with vim. – R. Martinho Fernandes Jan 9 '10 at 21:16

I use ctrl-[ to esc. – Michael Ekoka Feb 7 '10 at 15:51

Hey I bet RAlt+numpad-keysequence 0,2,7 would work too, right? :-) – Warren P Jul 15 '10 at 15:54

How did you achieve this "button" effects in your answer? – Sarwar Erfan Feb 8 '11 at 10:23

Sarwar, it's <kbd> tag, you can see it when you try to edit the main post – number5 Feb 24 '11 at 0:32

I have giant hands so I just reach up to esc with my left pinky! – z8000 Jun 27 '11 at 2:30

By default Ctrl+C cancels insert mode. 90% of the time this won't be a problem, but it breaks blockwise visual mode. For e.g. use Ctrl+V, select the beginning of some lines, shift+i, and insert a character. Press Ctrl+C and you won't see anything inserted. To fix this, I've added: imap <C-c> <ESC>. – Joe Fiorini Jun 28 '11 at 1:34

It is really awesome!!!! – Sławosz Aug 25 '11 at 19:27


Answer by Adam Neal

*

Highlight all occurrences of word under the cursor, and move the the next one. # Searches backwards.

Comments

One of the simplest yet greatest features – Ed Guiness Jan 20 '09 at 9:13

How do you clear the search so it stops highlighting? – Albert Feb 13 '09 at 15:58

:nohlsearch will temporarily turn off search highlighting. Happy Vimming! vimdoc.sourceforge.net/cgi-bin/vimfaq2html3.pl#11.1 – Adam Neal Feb 13 '09 at 21:41

Cool! Really useful. Was this documented somewhere? – Luis May 9 '09 at 17:25

Can't believe I have used vim this long and didn't know this one – Robert Swisher Aug 6 '09 at 23:17

Also '#' does the same, but backwards. – dalloliogm Aug 14 '09 at 10:42

Another quick-and-dirty trick to clear the highlighting is to search for some nonsense string like 'lasdhgflas'. This has the benefit that you don't have to switch between :nohlsearch and :hlsearch like crazy, but the disadvantage is that pressing 'n' after clearing the highlight this way would repeat this nonsense search, and not your original search. – sundar Jan 30 '10 at 9:59

It does really help :) – nXqd Mar 24 '10 at 12:56

Holy crap I had no idea. Awesome! – rossipedia May 17 '10 at 23:21

Instead of manually typing nohlsearch, try mapping it. Ctrl-L already redraws the screen, so I make it also and remove search highlighting: nnoremap <silent> <C-l> :nohl<CR><C-l> – idbrii Feb 23 '11 at 19:04

Along the same lines, gd (which stands for "goto definition") will search for all occurances of the word under the cursor, and immediately go to the first occurance of the word in the current file. – Graphics Noob Jan 18 '12 at 21:43


Answer by Dominic Dos Santos (Sep 18, 2008)

[I

list all lines found in current and included files that contain the word under the cursor.

Comments

quite cool tip! Would be interesting to know the vim help topic for this. – amit Jan 6 '11 at 7:30

@Amit: :help [ and scroll down a bit. – Fred Nurk Jan 11 '11 at 18:31


Answer by Rich Adams (Sep 19, 2008)

Correctly indent the entire file currently open.

gg=G

Note that you may need to do :set filetype=<whatever> and then :filetype indent on before this will work. Unless they're already specified in your .vimrc file.

Comments

Great if it's ugly and you don't want to check it back into source control later.. – Adam Hawes Feb 19 '09 at 4:40

gg=G`` will format the file and take you back to where you were. – NotDan Dec 3 '10 at 19:20

This is a feature i really need – lucapette Jan 7 '11 at 22:26

So beautiful! :) – rturrado Jan 19 '11 at 15:36


Answer by Lucas Oman

Ctrl-N / Ctrl-P

Auto-complete - searches current file for words beginning with the characters under the cursor. Great for finishing long func/var names. Will also search other files you've opened during that session.

Comments

Lucas, can you explain how to do this. c-n/c-p doesn't seem to do for me what you said. thanks. – user15071 Oct 26 '08 at 3:38

Say you've defined the function "someFunction()" in your file. Elsewhere, you start to type "some" and then hit ctrl-p. A menu should pop up (even in command-line vim, not just gvim!) that gives you options to complete the name from names already in that file. – Lucas Oman Nov 7 '08 at 14:21

I usually map this to <C-SPace> as a quick auto-complete. – Ayman Aug 19 '09 at 5:48

I use the tab key to do this auto completion. Don't know how to show code in comment, but you can get the picture: function InsertTabWrapper() let col = col('.') - 1 if !col || getline('.')[col - 1] !~ '\k' return "\<tab>" else return "\<c-n>" endif endfunction inoremap <tab> <c-r>=InsertTabWrapper()<CR> – user176121 Sep 15 '11 at 4:26


Answer by Ludvig A. Norin

. (period)

Repeats the previous change

Comments

This one is really useful :) – nXqd Apr 22 '10 at 23:58

I'm appreciating the power of this a lot more lately. – justinxreese Jun 27 '11 at 3:02


Answer by jW.

:%s/search/replace/g 

Global Search and replace

Comments

:%s/search/replace/gc The 'c' makes it prompt you at each replace instance – Mark Biek Sep 18 '08 at 18:32

its not 'global' its just inside the current buffer. for global look for Greplace plugin for vim – Vitaly Kushner Jun 27 '11 at 18:45

@Vitaly: they just mean "global" in a different sense that you do. From the Vim wiki: "The g flag means global – each occurrence in the line is changed, rather than just the first." – Nathan Long Aug 17 '11 at 12:59

Use this with args and argdo to apply the search and replace to more than one file! – chandsie Aug 18 '11 at 15:49


Answer by Scottie T

:e!

Reopen the current file, getting rid of any unsaved changes. Great for when a global search and replace goes awry.

Comments

I always just use 'u'ndo to fix bad search/replaces :) – hark Nov 6 '08 at 3:20

Reloading the file will destroy your undo history for the buffer. I try to avoid that at all cost. – Aristotle Pagaltzis Nov 23 '08 at 0:52

For me :e is very useful when watching an active logfile. – Marcin Dec 18 '08 at 19:19

@Marcin, why not just use tail -f | less? – Christian Mann May 25 '12 at 21:12

@AristotlePagaltzis With 73 up, you can preserve with.. :set undodir=~/.vim/undodir// and :set undofile. Might want toset :set undolevels=1000 and :set undoreload=10000 also. – wom Jun 4 '12 at 15:16


Answer by Ned

Ctrl-A / Ctrl-X

Skip to the next number on the line and increment/decrement it. Has a C-like idea of what's decimal, hex or octal. The "skip to the next number" part is what makes this feature really useful, because it potentially saves several keystrokes getting the cursor to the right place.

Comments

I use this a lot... At first it seemed like a trivial thing to manually edit the number, but after getting used to this I realize how arduous a task it is to remember the incremented number and enter it back. All that little amount of brain cell wear and tear counts - Vim helps you stay younger! :) – sundar Jan 30 '10 at 10:05

If you use vim with GNU Screen, probably you'll need Ctrl-A Ctrl-A as Ctrl-A is meta character for GNU Screen. – Jeffrey Jose Apr 1 '10 at 2:27

@Jeffey: Because of that (and because Ctrl-A goes to start of line in emacs and bash), I've always had that mapped to ctrl-z. Personally, I found I didn't really need that as much when running things inside a screen. escape ^zz in your .screenrc – Marten Veldthuis May 7 '11 at 8:36


Answer by jug

macros

Record:

q<some key>
<edit one line and move to the next>
q

Play:

@<some key>
@@ (play last macro)
100@<some key> (apply macro 100 times)

EDIT: A slightly complex example might be helpful to get an insight into the power of macros.

Given an array (in C) of 32-bit integers in little endian, we want to convert it into big endian.

uint32_t littleEndian[] = {
  0x0f1e2d3c, 0x4b5a6978, 0x01234567, 0x89abcdef, 0x01234567, 0x89abcdef,
  0x0f1e2d3c, 0x4b5a6978, 0x01234567, 0x89abcdef, 0x01234567, 0x89abcdef,
  ...
  0x0f1e2d3c, 0x4b5a6978, 0x01234567, 0x89abcdef, 0x01234567, 0x89abcdef,
  0x0f1e2d3c, 0x4b5a6978, 0x01234567, 0x89abcdef, 0x01234567, 0x89abcdef
};

Now goto the first data line of the array (the line after uint32_t ...) and type (with the RETURN after ..6@b)

0fxqal2xbpfxq2u0qbfx4@axbpq3u0qc6@b
q9@c

if the array has 9+1 lines with six 4-byte integers in each line.

(Explanation, if you are not fluent in vim:

  • "0fx" takes you to the first x in the line
  • "qal2xbpfxq" defines the macro a to
    • "l" go one to the left
    • "2x" delete two letters
    • "b" go to the beginning of the word
    • "p" insert the two letters just deleted
    • "fx" go to the next x in the line
  • "2u0" undoes the changes we just did and goes to the first column
  • "qbfx4@axbpq" defines the macro b to
    • "fx" go to the next x in the line
    • "4@a" executes four times the macro a (replace 4 by 8 if you have uint64_t)
    • "xbp" deletes the letter under the cursor (happens to be the x), goes to the beginning of the word and puts the just deleted x as 2nd letter meaning that the macro b converts an uint32_t from little to big endian (rsp. vice versa)
  • "3u0" undoes the changes we just did and goes to the first column
  • "qc6@bENTERq" (where ENTER stands for pressing RETURN) defines the macro c to
    • "6@b" executes six times the macro b (replace 6 by the number of integers per line)
    • "ENTER" goes to the next line (see comment) meaning that the macro c converts all integers in a line from little to big endian (rsp. vice versa)
  • "9@c" executes the macro c nine times converting a total of ten lines as one line was already converted (of course replace 9 by whatever you need) )

Maybe this example is too complex for "real life", but it should give you an idea about how powerful macros can be.

Comments

Actually 100@<key> plays the macro 100 times, not for 100 lines. It's a small but important difference. If your macro doesn't advance to the next line then you just keep applying the cahnge to the same line over and over, or if your macro is based on found words, multiple lines, etc it will vary. – camflan Sep 28 '08 at 16:12

I got some problems editing. My original Edit summary was "added example of a complex macro". – j.p. Jan 7 '12 at 19:27


Answer by Ludvig A. Norin (Sep 18, 2008)

Change the lineendings in the view:

:e ++ff=dos
:e ++ff=mac
:e ++ff=unix

This can also be used as saving operation (:w alone will not save using the lineendings you see on screen):

:w ++ff=dos
:w ++ff=mac
:w ++ff=unix

And you can use it from the command-line:

for file in $(ls *cpp)
do 
  vi +':w ++ff=unix' +':q' ${file}
done

Comments

for file in *.cpp – Fred Nurk Jan 11 '11 at 18:35

Why not just :set ff=unix, then later :w? – blueyed Apr 13 '11 at 16:29


Answer by Lucas S. (Sep 18, 2008)

=%

Indents the block between two braces/#ifdefs

Comments

This doesn't work for me... But =G does... – Aaron H. Nov 14 '08 at 20:07

or gqq for the current line. – vitule Dec 16 '08 at 10:14

== for current line (just 2 keystrokes) – Cyber Oliveira Dec 18 '08 at 18:07

It does not seem to work well for Python. – Reinstate Monica Oct 21 '09 at 12:36

or {=} for current paragraph, etc. – A B Apr 19 '10 at 1:41

@Aaron, you have to have the cursor positioned on one of the curly braces before hitting =%. – Robert Gowland Jun 17 '10 at 13:50

You don't have to be on the brace to indent the contents. Use =ib and =iB to indent inside parenthesis and curly-braces respectively. =% is still good for non-brace matches, though. – nocash Apr 21 '11 at 15:42


Answer by mghaoui (Nov 10, 2008)

My favorite is:

CTRL-A: Increment a number under the cursor. 99 becomes 100.
CTRL-X: Decrement a number under the cursor. 100 becomes 99.

It's really cool.

Comments

Duplicate of stackoverflow.com/questions/95072/… – Fred Nurk Jan 11 '11 at 18:37

It was edited on Oct 5 '10 at 9:49. It was posted on Sep '08. – Gerardo Marset Jun 21 '11 at 23:46

Ya but it gets all funky with floats, so CTRL-X on 0.0 gives you -1.0 or 0.-1 and you are very likely to hit CTRL-Z every once in a while – puk Feb 24 '12 at 10:50


Answer by Brad Parks

:%s//replace/g

will replace the last term that was searched for, instead of you having to type it again.

This works well with using * to search for the word under the cursor.


Answer by Krzysiek Goj (Sep 28, 2008)

Never underestimate the power of percent.

Basically, it jumps to matching brace (booooring), but when the cursor is not on a brace it goes to the right until it finds one, which is my excuse to call this post a trick.

[x] means the cursor is on x.

[s]omeObject.methodYouWouldLikeToDelete(arg1, arg2) + stuffToKeep

just type d% to get

[ ]+ stuffToKeep

Obviously, it works with (), [] and {}.

Another examples of percent-not-on-paren:

[m]y_python_list[indexToChange, oneToLeave]

%%lce

fun[c]tion(wrong, wrong, wrong)

%cib


Answer by rgcb (Sep 18, 2008)

running shell commands on the current file without having to exit, run the command and open it again:

:%!<command>

for example,

:%!grep --invert-match foo

gets rid of all lines containing "foo"

:%!xmllint --format - 

nicely tab-ifies the current file (if it's valid xml)

and so on...

Comments

An easier way to delete lines matching a pattern is with :global. :g/foo/d – graywh Feb 10 '09 at 22:39

You can also specify certain parts of the file. Replacing '%' with '.' (period) will only run the command on the current line. Replacing '%' with '4,8' will run the command on lines 4-8. Finally, replacing '%' with '.,$' will run the command from the current line to the end of the file. – three-cups Jun 27 '11 at 2:30


Answer by ryan_s (Oct 09, 2008)

Useful in your vimrc,

set directory=/bla/bla/temp/

Makes vim keep its temporary files in /bla/bla/temp instead of in the directory with the file being edited.

Comments

+1 Awesome, I always found those temporary files annoying... – Lin Oct 8 '09 at 14:49

Ah, and this way I dont have problems running into other's .swp file – Jeffrey Jose Apr 1 '10 at 2:31

I couldn't get the fugitive plugin to work on Windows due to "unable to rename swp file" errors and similar. It was due to crappy policy settings from our IT dept. THIS SETTING LET ME WORK AROUND IT! THANKS! – Charlie Flowers Jan 2 '11 at 5:20


Answer by poisonedbit

Copy to system clipboard:

"+y

Paste from system clipboard:

"+p

Move between wrapped lines (it's a good idea to map those):

gj
gk

And for my favourite:

:Sex

Split and explore!

Comments

+1 for moving between the wrapped lines! – j.p. Jan 7 '12 at 20:03


Answer by Joe Van Dyk (Sep 18, 2008)

 :mak

Executes "make" and then will jump to the file that contain the compile errors (if any).

Comments

:make is the command. Unambiguous shorter terms are allowed, so :mak works. – Paul Biggar Aug 2 '09 at 9:54

The other day I found myself quit vim and do make and then I thought to myself, vim would be able to do this for me. here's my answer. Thanks – Jeffrey Jose Apr 1 '10 at 2:29


Answer by Leonard

When doing a search, there are ways to position the cursor search-relative after the search. This is handy for making repeated changes:

/foo/e Finds foo and positions the cursor at the last 'o' of foo

/myfunc.\*(.\*)/e-1 Finds myfunc and places the cursor just before the closing brace, handy for adding a new argument.

/foobarblah/b+3 finds foobarbarblah and puts the cursor at the beginning of bar

This is handy if you decide to change the name of any identifier (variable or function name) - you can set it up so the cursor is on the part that needs to be changed. After you've done the first one, you can do all the rest in the file with a sequence of 'n' (to repeat the search), and '.' (to repeat the change), while taking only a second to make sure the change is applicable in this spot.

Comments

And if you're not sure of the offset, you can use \zs to place the cursor at an arbitrary position in the match eg /\(foo\)\+\zs\(bar\)\+/ will always put you at the border between the foos and bars in foofoofoobarbar foobarbarbar foofoobarbarbar, etc. – rampion Mar 14 '12 at 19:21


Answer by Lucas Oman (Sep 18, 2008)

I have the following in my vimrc:

nmap <F3> <ESC>:call LoadSession()<CR>
let s:sessionloaded = 0
function LoadSession()
  source Session.vim
  let s:sessionloaded = 1
endfunction
function SaveSession()
  if s:sessionloaded == 1
    mksession!
  end
endfunction
autocmd VimLeave * call SaveSession()

When I have all my tabs open for a project, I type :mksession. Then, whenever I return to that dir, I just open vim and hit F3 to load my "workspace".

Comments

I used something similar for a while but found it doesn't like complex window splits. :( – matpie Jan 25 '09 at 10:06

Good to know. I rarely use splits; I prefer tabs. – Lucas Oman Feb 14 '09 at 15:46


Answer by Ronny Brendel (Sep 19, 2008)

As stated in another Thread, with the same Question:

Ctrl + v -- row visual mode Shift + i -- insert before type text Escape Escape

(Inserts the typed in text into multiple lines at the same time.)

Comments

This is great for commenting out a whole lot of lines at once. How do you use it to delete a few columns from the beginning of multiple lines? – 2cBGj7vsfp Oct 20 '08 at 19:15

Enter blockwise visual mode through <C-v>, select the rectangle of lines-by-columns you want do delete, and hit `d'. – ngn Oct 26 '08 at 19:35


Answer by WolfgangP (Oct 31, 2010)

In insert mode:

Ctrl+Y

Inserts the character that is above the cursor at the current cursor position and moves the cursor to the right. Great for duplicating parts of code lines.

Comments

Use Ctrl-E to insert the character below. – blueyed Apr 13 '11 at 16:33


Answer by A Lee

Ctrl+]

Equivalent to "Go to Definition" in an IDE (one must first create the tags file using e.g. ctags).

Ctrl+T

Pops to the previous element in the tag stack, i.e., the location and file you were in right before you hit Ctrl+].

:help tagsrch for more details.


Answer by Kreich

Ctrl-X then Ctrl-F (while cursor on a path string)
searches for the path and auto-completes it, with multi-optional selection.


Answer by Scottie T

:g/search/p

Grep inside this file and print matching lines. You can also replace p with d to delete matching lines.

Comments

Did not knew that one. Very usefull. Thank you. – Oli Feb 26 '09 at 11:27

Did not knew that one. Very usefull. Thank you. (dido) – Luis May 9 '09 at 17:32

Along with its cousin :v which applies to non matching lines. – ojblass Jun 20 '09 at 18:24

works also without p, as :g/search/ and with # you get the line number as :g/search/# – user2427 Nov 30 '11 at 12:51

Wow. wow and re-wow! – Luc M Dec 1 '11 at 15:57


Answer by Dave Kirby

My favourite feature is the :g[lobal] command. It goes to every line that matches (or does not match) a regex and runs a command on that line. The default command is to simple print the line to the screen, so

:g/TODO:/

will list all the lines that contain the string "TODO:". If use the default command then you can leave the last slash off.

The commands can also have their own ranges which will be relative to the current line, so to display from each TODO: to the next blank line you can do this:

:g/TODO:/ .,/^$/p

(p is short for :print).

And to save all the TODO: blocks to another file:

:g/TODO:/ .,/^$/w! todo.txt  >>

(Explanation: :w means write to a file, ! means create it if it does not exist, and >> means append if it does exist.)

You can also chain commands with the | operator, e.g.

:g/TODO:/ .,/^$/w! todo.txt  >>  | .,/^$/d

will write the block to "todo.txt" then delete it from the current file.

Also see this answer for more examples.


Answer by aaronstacy (Nov 06, 2008)

COMMENTING A BLOCK OF LINES IN VISUAL MODE

add the lines below to your .vimrc file, go into visual mode w/ "v", and hit "c" to comment the lines or "u" to uncomment them, this is insanely useful. the lines below make this possible for C, C++, Perl, Python, and shell scripts, but it's pretty easy to extend to other languages

" Perl, Python and shell scripts
autocmd BufNewFile,BufRead *.py,*.pl,*.sh vmap u :-1/^#/s///<CR>
autocmd BufNewFile,BufRead *.py,*.pl,*.sh vmap c :-1/^/s//#/<CR>
" C, C++
autocmd BufNewFile,BufRead *.h,*.c,*.cpp vmap u :-1/^\/\//s///<CR>
autocmd BufNewFile,BufRead *.h,*.c,*.cpp vmap s :-1/^/s//\/\//<CR>

Comments

A dedicated commenting plugin such as EnhancedCommentify or NERD_Commenter would be better suited for this task, over various filetypes - but this does well for a quick hack. – sykora Jan 27 '09 at 14:32

This doesn't seem much different from visual blocking over a lines, then hitting I and then inserting whatever character you want. – Nikron Feb 23 '09 at 7:19

Unless I'm missing something, blocking over lines and hitting I doesn't work (vim 7.1, 7.2, Darwin, Linux) – aaronstacy Mar 15 '09 at 21:53

Note that visual-block mode is different from visual mode. ctrl-v is the default key to enter visual-block mode. – jkerian Nov 12 '10 at 17:43

I recommend using tcomment instead. – blueyed Apr 13 '11 at 16:32


Answer by Mapad

Edit command lines with vim commands under the bash shell

$ set -o vi

Now you can edit command lines using the vim syntax!

Example:

  1. Press ESC to quit insert mode. You can move right/left with [h,j] keys, and forward/backward in the history with [k,l] keys.
  2. Press 'v' to edit the whole command line in vim

Comments

@Madpad: Amazing! – j.p. Jan 7 '12 at 20:34


Answer by phantom-99w

The other day I discovered that Vim has a "server mode". Run a command using

vim --servername <name> <file>

This will create a Vim server with the name . A regular instance of Vim then starts, but other programs can then communicate with the instance of Vim which you are then using. This probably won't help most people, but some programs can make use of this. With Jabref, for example, you can use this feature to push references directly from you bibliography manager (Jabref) into your document which you are editing with Vim.

vim --serverlist

will list all the Vim servers running at that time.

vim --remote

allows you to connect to an already existing Vim server. There are several different --remote commands to do things like commands to the server.


Answer by Adam Neal

%

Brace/parentheses match.

If you have the cursor on a parenthesis/brace/etc ((){}[]), and hit % it will jump to the corresponding one.

Comments

MatchIt plugin can make it even better (eg. jump between matching opening and closing XML/HTML tags). – Adam Byrtek Dec 5 '08 at 22:27


Answer by Jon DellOro (Nov 24, 2008)

When I use vim for writing a tidy journal, notes, etc

!}fmt

to format the current paragraph.


Answer by DustinB (Sep 18, 2008)

Read contents of an external command into the doc:

:r !ls


Answer by Kreich (Sep 18, 2008)

Shift-~
switches the case of the letter under cursor (and moves right, which allows switching a whole line or combining with the "next number/word" command)

Comments

It's just ~ not shift-~ It's just that ~ is shift-# on a UK keyboard (and probably shifted on a US one too) – Draemon Nov 21 '08 at 18:49

ALT-GR ~ on swedish – some Feb 1 '09 at 7:34

You can use visual mode ('v') to select large blocks to change, too. – Bernard Jul 22 '09 at 11:03


Answer by PEELY (Sep 19, 2008)

Delete all blank lines in a file:

:g/^$/d

Comments

Delete all blank lines in a file (even with only spaces). :v/./d – graywh Feb 10 '09 at 22:44


Answer by Christopher Cashell (Sep 18, 2008)

Putting options in comments in a file to be edited. That way the specific options will follow the file. Example, from inside a script:

# vim: ts=3 sw=3 et sm ai smd sc bg=dark nohlsearch

Comments

:help modeline for info. – sykora Jan 27 '09 at 14:29


Answer by nayfnu (Nov 13, 2008)

Knowing that the Windows clipboard buffer can be accessed with:

"*

has saved me lots of boring entering-insert-mode shenanigans. Also copy/pasting between vi sessions can be done with:

"+

Answer by arcanex (Nov 13, 2008)

Jumps.

m[a-z]

Mark location under [a-z]

`[a-z]

Jump to marked location

``

Jump to last location

g;

Jump to last edit

Comments

Don't forget '. which jumps to the last change in the file. – MattG Sep 22 '09 at 15:01


Answer by Cyber Oliveira

:normal(ize)

plays back all the commands you pass to it as if they were typed on command mode.

for example:

:1,10 normal Iabc^[Axyz

Would add 'abc' to the beginning and append 'xyz' to the end of the first 10 lines.
note: ^[ is the "escape" character (tipically ctrlv+ESC on Unix or ctrlq+ESC on Windows)

Comments

You can also use this to play back a macro: :1,10 normal @a to play back the macro recorded in register a. – Nathan Long Aug 17 '11 at 13:46


Answer by smt (Nov 10, 2008)

set backup
set backupdir=~/backup/vim

Puts all backup files (file.txt~) in the specified directory instead of cluttering up your working directories.

Comments

very nice, thanks :) – dalloliogm Aug 14 '09 at 10:45


Answer by Swaroop C H (Jan 20, 2009)

gd moves the cursor to the local definition of the variable under the cursor.

gD moves the cursor to the global definition of the variable under the cursor.

Comments

Wow! I'm using vim with javascript, and a lot of the code block stuff doesn't work well for me because js is different from c enough to throw it off (and I haven't yet bothered to try to fix it). But this works perfectly even with js! Thanks! – Charlie Flowers Jan 2 '11 at 5:39


Answer by f3lix (Jan 30, 2009)

Appending the same text to multiple lines

If you have multiple lines and want to append the same text to all lines you can use Ctrl-V to start the visual block mode, move to select the lines, then press $ to extend the selection to the end of the line and the press A to append text (enters insert mode). When you exit insert mode (ESC) the typed text will be appended to all selected lines.

This is useful e.g to append semi-colons and other stuff you need to do when programming.

Summary:

  1. Ctrl-V for visual block mode (select multiple lines)
  2. $ to extend selection to end of line
  3. A to append in insert mode
  4. ESC switch back to command mode
  5. done

PS: use I in visual block mode to insert text in multiple lines


Answer by Amjith

[[ - Beginning of the current function block.
]] - Beginning of the next funcion.
[{ - Beginning of the current code block.
]} - End of the current code block.

z<CR> - position the current line to the top of the screen.
zz - position the current line to the center of the screen.
z- - position the current line to the bottom of the screen.


Answer by Pramod (Sep 28, 2008)

  1. gv repeats the last visual selection.
  2. >>Indents the curent block.
  3. set sw=n can be used to change the amount of indent.
  4. Say you want to change the parameters to a function, try c% when you're positioned on the braces.

Comments

Regarding #4: ci( does the same as c%, but the cursor can be anywhere inside the parens. – graywh Feb 10 '09 at 22:42


Answer by ryan_s

Remove whitespace from line endings on save.

" Remove trailing whitespace from code files on save
function StripTrailingWhitespace()

  " store current cursor location
  silent exe "normal ma<CR>"
  " store the current search value
  let saved_search = @/


  " delete the whitespace (e means don't warn if pattern not found)
  %s/\s\+$//e

  " restore old cursor location
  silent exe "normal `a<CR>"
  " restore the search value
  let @/ = saved_search

endfunction

au BufWritePre *.c call StripTrailingWhitespace()

Put this in your vimrc, and add auto-commands for any file types you want to remove extra whitespace from. The last line above makes this remove trailing whitespace from C files.


Answer by u0b34a0f6ae (Sep 29, 2009)

g-

Go to previous text state. What does it mean? Browse through all undo branches with g- (previous change) and g+ (next change).

So if you undo twice in your text, then happen to change something, you suddenly have an undo/redo tree where you can't reach all branches with undo(u)/redo(Ctrl-r), but with g+/g- you can browse through all revisions!


Answer by Liran Orevi

:%j 

To join all lines into a single line.

Comments

when did you ever need this? – vitule Dec 16 '08 at 10:19

you missed a leading ":", otherwise it becomes a completely different command :) – Cyber Oliveira Dec 18 '08 at 19:04

@Léo thanks, fixed it now. – Liran Orevi Dec 1 '09 at 0:24


Answer by Ludvig A. Norin (Sep 18, 2008)

Enter a number before any command to repeat it N times. For example:

7dd <-- will delete 7 rows

7 arrow down <-- moves down 7 times

4cw <-- removes the 4 next words and puts you in edit mode to replace them

This is in my opinion the most powerful feature of them all :-)

Comments

d7d works too, and it should be faster as you don't have to press d twice in a row. – Gerardo Marset Mar 31 '11 at 13:34


Answer by Chuck (Sep 18, 2008)

v

Visual mode for selecting text to copy, delete, etc.


Answer by camflan (Sep 28, 2008)

Using Esc all the time is going to cause RSI or something, I'm sure...plus its not fast enough for me.

Instead, in my .vimrc I have

map! ii <Esc>

For the very few times I need to type 'ii', I just need to type i 3 times, which types one i, exits to normal mode, then another i to type a 2nd i.

Comments

C-[ has the same effect as Esc. Having CapsLock remapped with Ctrl, it feels very comfortable for me. – binOr Oct 9 '09 at 9:54


Answer by shyam (Oct 18, 2008)

ft move to the next occurrence of t and ; and , to move to forward and backward

tt to move to the char before t ; and , work here too.

Comments

Don't forget F and T for f/t in the opposite direction. Using ; after t won't move the cursor. Think of ; and , as repeat previous f/F/t/T. – graywh Feb 10 '09 at 22:46


Answer by Jack Senechal (Oct 21, 2008)

When you have a file (or lots of files) open and the computer crashes, you end up with annoying swap files and you have to open the originals one at a time to see if there are any unsaved changes. The problem is that you've got to hit "r" for "recover", then write out the buffer to a new file, then diff with the original... what a pain!

Here's something nice which cuts down on the last few steps:

Put the following in your .vimrc file:

command DiffOrig vert new | set bt=nofile | r # | 0d_ | diffthis
        \ | wincmd p | diffthis

Then after you recover the file, type :DiffOrig to view the changes from the saved version.

From the vim docs: http://vimdoc.sourceforge.net/htmldoc/diff.html#:DiffOrig


Answer by phi (Dec 17, 2008)

in escape mode:
xp - swaps the character under the cursor with the character in front of the cursor.
Xp - swaps the character under the cursor with the character behind the cursor.


Answer by Jed Daniels (Mar 19, 2010)

Probably too simple for this crowd, but my favorite little vi trick is ZZ to save and exit. Basically it is the same as :wq, but can be done one handed.

I suppose the next thing is to colorize tabs so they can be easily distinguished from spaces when working with python code. I'm sure there are better ways to do this, but I do it by putting this in ~/.vim/syntax/python.vim:

syntax match tab "\t"
hi tab gui=underline guifg=blue ctermbg=blue

--jed


Answer by igrigorik (Jun 27, 2011)

VimGolf @ http://vimgolf.com

Yes, shilling for own project, but it is a great way to learn Vim. Pick a challenge and try to do your best.. each time you submit, you'll unlock entries above you. Great way to pickup new tricks.


Answer by Ludvig A. Norin (Sep 18, 2008)

u <-- undo :-)

Comments

And ctrl-r redo.. for those times you undo a little too much – MattG Sep 22 '09 at 15:03

And -> :earlier 15m – Aaron H. Oct 22 '10 at 16:28


Answer by jpeacock (Sep 19, 2008)

vim -o file1 file2 ...

To open multiple files at once in separate panes.

Comments

also, -O to open in vertical panes and -p to open in tabs. (I like this one a lot ;) – David Winslow Mar 19 '10 at 22:49


Answer by Aaron H. (Nov 14, 2008)

I don't see buffers mentioned, so I'll mention them.

I finally got around to trying out Emacs the other day, and discovered buffers. I thought, wow, these are awesome, I wish VIM could do this. With a search I discovered that VIM can! For them to work, you may need to do

:set hidden

first, or add "set hidden" to your vimrc file.

Quick:

:ls          -- List buffers
:ls!         -- List ALL buffers
:bn          -- Open next buffer
:bp          -- Open previous buffer
:bf          -- Open first Buffer
:bl          -- Open last buffer
:b #         -- Open buffer
:bd #        -- Close buffer (# optional)
:bad <name>  -- New buffer named <name>

(# represents the buffer number listed via :ls)

and of course:

:help buffers

Windows are also extremely useful when dealing with buffers (Described in "help buffers")


Answer by Otto (May 06, 2010)

imap jj <esc>

This will make it so that instead of esc you hit jj. Your hands are always on the home keys, you also are instantly moving around using hjkl(arrow keys) and until you get into some funky matrix loops you never use jj.


Answer by amit (Jan 06, 2011)

:e %<.cpp 

to open myfile.cpp when currently myfile.h is open. Replace :e by :sp to split the window instead of replacing the whole window.

Comments

Check a.vim plugin. – Luc Hermitte Jan 6 '11 at 9:14


Answer by KidQueen9

I figured out a basic method for Vista or 7 that has the same effect as %!sudo tee > /dev/null % , hoping it would be useful for vim users using Vista/7.

The previous 2 versions(I removed them) were buggy. Here is the newest.

function ElevatedWrite()
    let tempf = tempname()
    let targetf = expand('%:p')
    let lines = getline(1, line('$'))
    call writefile(lines, tempf)
    execute '!hstart /UAC /NOCONSOLE "' . 'cmd /c copy /Y ' . shellescape(tempf) . ' ' . shellescape(targetf) . ' /B"'
    checktime
endfunction

A program named HSTART is needed.

P.S. I used to use the silent command in conjuction with checktime, but it has the same "problem" as system() does -- it seems that vim won't wait them to end before it execute the next command, which makes checktime get called before copy is done. (or it may be because of the UAC popup.)


Answer by CMS (Sep 18, 2008)

I really like the VTreeExplorer script for viewing portions of the folders and files in a tree view, and snippetsEmu to get TextMate-like bundles.

My favorite color scheme for the moment is VibrantInk.


Answer by hafbaked (Sep 18, 2008)

ZZ - Save & Exit
o - add blank line below current one and go to insert mode


Answer by skiphoppy (Sep 18, 2008)

I know it's basic, but my favorite vi feature is still the % key, which lets you find matching braces, brackets, or parentheses. I still remember learning it from a sentence in a Perl book by Larry Wall which said something about "at least if you do this you'll let some poor schmuck bounce on the % key in vi." I looked it up, saw what it did, and I was hooked.

It's been nearly ten years, and I still obsessively bounce on the % key while I'm sitting and thinking about what to do next, not to mention to help me match up code blocks and parentheses.


Answer by ernie (Sep 19, 2008)

Knowing that Ctrl+Q in gVim on Windows inserts a control character. For example, I often want to replace ^M characters at the end of lines. It took me a while to find the correct keystroke (Ctrl+P does not work since that's the shortcut for Paste).


Answer by Bauna (Sep 19, 2008)

cw

"change word" while editing config files!


Answer by ryan_s (Sep 19, 2008)

#

Search backwards in the file for the word under the cursor. Useful for finding declarations.

Comments

And * forwards `) – Liran Orevi Dec 1 '09 at 0:27


Answer by tchen

:syn on

For turning on syntax highlighting

:set foldmethod=syntax

To set the code folding method to be based on the language syntax, provided that the syntax is available for your language of choice. You can put this in your .vimrc file, omit the colon if you do.

zc

To close a particular fold (under the cursor)

zo

To open a particular fold (under the cursor)

zr

To unfold all folds by one level

zm

To collapse all folds by one level

zR

Unfold ALL folds

zM

collapse ALL folds


Answer by Sridhar Iyer (Sep 23, 2008)

Read/write pdf files with Vi as if they were text files: http://vim.wikia.com/wiki/Open_PDF_files


Answer by David.Chu.ca (Nov 06, 2008)

In your ~/vimrc (or c:_vimrc for Windows), add the following lines:

" set characters shown for special cases such as:
" wrap lines, trail spaces, tab key, and end of line.
" (must be turned on whith set list)
set listchars=extends:»,trail:°,tab:>¤,eol:¶

Then you can type in the command to toggle displaying tabs, trail spaces and eol as special characters:

set list

Add these settings to enable normal move around keys back to the previous line or the next line cross eol:

" Set moving around at the end of line back to previous line by
" <backspace> key and coursor keys, and normal movememt h and l keys
set whichwrap=b,s,<,>,h,l

Enjoy VIM!


Answer by André (Nov 13, 2008)

gqap reformats an entire paragraph to match the current textwidth, pretty useful for plain text of LaTeX-docs.


Answer by Nathan Fellman (Jan 20, 2009)

[d to show the definition of a macro

[D to show the definition of a macro along with where it was defined.


Answer by Dan Goldstein (Jan 27, 2009)

viwp - replace the word under the cursor with what's in the unnamed register.

What's nice about this is that you don't need to be at the beginning of the word to do it.


Answer by adam (Feb 13, 2009)

vmap // y/"

Search for the visually selected text.


Answer by raimue (Feb 19, 2009)

I am using this snippet in my .vimrc to select a block of code and adjust indentation by pressing < or > multiple times.

" keep selection on indenting in visual mode
vmap > :><cr>gv
vmap < :<<cr>gv

Answer by Jeff (Feb 25, 2009)

Count the number of matches for the search text:

:%s/search/&/g

Or, leave out the trailing g to count the number of lines the search text occurs on.


Answer by Johan (Feb 22, 2009)

How about this one I found in The Pragmatic Programmer that sorts 4 lines with the sort command (starting at the line the marker is at):

:.,+4!sort

Or just mark a section with visual mode and then type !sort:

:'<,'>!sort

Kind of cool and useful to sort a headerfile or some includes.


Edit: This is a Unix hack, the Windows port can't call shell commands (?)

Edit: Thanks to Luc Hermitte who pointed out that this should work under Windows as well. So I found a Windows XP with a working gVim installation and tried it. I found out that both !sort and :sort did work.

Very nice :-)

Comments

We can use shell commands on windows. But in this case, vim has a :sort command. No need to call an external tool. – Luc Hermitte Feb 22 '09 at 10:24


Answer by Joshua (Apr 18, 2010)

As of now my favorite command is probably :retab. It lets you convert from tabs to spaces and from spaces to tabs. You can check out :help retab for more details.


Answer by Damien Wilson (May 17, 2010)

Font selection using your system UI, straight from the docs:

For Win32, GTK, Motif, Mac OS and Photon:

:set guifont=*

will bring up a font requester, where you can pick the font you want. In MacVim :set guifont=* calls:

:macaction orderFrontFontPanel:

which is the same as choosing "Show Fonts..." from the main menu.

See :help guifont for more details. Also, Inconsolata is one of the best fixed-width fonts out there.


Answer by amit (Jan 08, 2011)

A tip useful for beginners: I use search combined with other actions. For example to convert

 A Lazy Brown Fox

to

 A Brown Fox

when currently the cursor is at the end of the line, I would use ?La and enter to jump to Lazy and then dw to delete the word. Next, if I want to delete Brown, I could use dw or I could use d/Fox to delete till the first occurrence of Fox and enter. To delete till the second occurrence of Fox, use 2d/Fox.

Using

   set incsearch 
   set hlsearch 

in vimrc is useful for highlighting searches as they are going on.


Answer by EmmEff (Sep 18, 2008)

gqip

Reformat current line. Use it all the time to reformat comments in code, etc.

Comments

gqq formats only the current line, whereas gqip actually formats a whole paragraph. gqip means: format (gq) the inner content (i) of the current paragraph (p) – ngn Oct 26 '08 at 19:51


Answer by rgcb (Sep 18, 2008)

v

Visual mode for selecting text to copy, delete, etc.

i also find ctrl+v for visual block and shift+v for visual line quite useful


Answer by leeand00 (Sep 18, 2008)

:ts to search for tags in C/C++


Answer by Jason Moore (Sep 18, 2008)

xp

transpose two characters.

e.g. 'teh' move cursor over the 'e' and type 'xp' (x=cut, p=paste cut buffer)

y (or yy) yank a line into the buffer

d (or dd) delete line (and put in buffer)

p put/paste the buffer

really, handy when combined with multipliers.

5yy [move cursor] p copy 5 lines


Answer by unexist (Sep 18, 2008)

Vimrc to highlight tabs:

syntax match Tab /\t/
hi Tab guifg=yellow ctermbg=white


Answer by dreeves

Reaching up to hit ESC all the time is much too slow. I use TAB instead. Put this in your .vimrc:

    imap <tab> <esc>

CAPSLOCK is even better if you don't already have that remapped to CTRL.

I never type literal tabs in insert mode so haven't bothered with this but if someone could replace this sentence with how to swap ESC and TAB (or CAPSLOCK), that would be super handy.

Comments

Yet another alternative is to ``:imap jj <Esc>'', this trick was mentioned somewhere in this site. When you press `j' twice in insert mode, you go back to normal mode---pretty handy. – ngn Oct 26 '08 at 20:02


Answer by Cliff (Sep 19, 2008)

dG - delete to the end of the file :vsplit file2 - show current file and file2 side by side. Could also open file1 and file2 at the same time with -o (horizontal split) or -O (vertical split) options


Answer by Kreich (Oct 02, 2008)

:vsplit [filename]

opens an additional page side by side with the current page (vertically splitting the window).
also:
:split [filename]

opens an additional page, horizontally splitting the current page.

you can move between pages with ctrl+w -> Arrow keys


Answer by mempko (Oct 27, 2008)

With vim 7 I love vimgrep.

For example to search for myfunc in all my files under my project I do.

:vimgrep /myFunc/j **/*.cpp

The /j means don't jump to the first find. **/*.cpp means recursively search only .cpp files.

To view the results you just use the quick fix window

:cw

Answer by ididak (Nov 07, 2008)

I've been using vim <branch/tag/rev>:path with git:file.vim a lot lately.

Using gq} to format comments is also one my favorite vim tricks not found in the original vi.


Answer by Benedikt Waldvogel (Nov 13, 2008)

I wrote a function to go to the Most Recently Used tab page like Ctrl-a Ctrl-a in screen does or Alt-Tab in common window managers.

if version >= 700
    au TabLeave * let g:MRUtabPage = tabpagenr()
    fun MRUTab()
        if exists( "g:MRUtabPage" )
            exe "tabn " g:MRUtabPage
        endif
    endfun
    noremap <silent> gl :call MRUTab()<Cr>
endif

Answer by Scottie T (Dec 05, 2008)

ZZ = :wq
ZQ = :q!


Answer by vitule (Dec 16, 2008)

Ctrl+w Ctrl+]

splits current window to open the definition of the tag below the cursor


Answer by hyperboreean

  • Ctrl-w-s - split horizontal
  • Ctrl-w-v - split vertical
  • Ctr-w-w - cycle through all those windows
  • :tabnew - open a new tab inside vim
  • Ctrl-PageUp, Ctrl-PageDown - cycle through those tabs

Answer by cmcginty (Feb 09, 2009)

Page Up/Down From Home Row

I'm always using C-f and C-b to move around, so it's better to map to the home row keys. The following .vimrc settings will set PageUp to to C-k and PageDown to C-j.

noremap <C-k> <C-u>
noremap <C-j> <C-d

Answer by Casey

Enhanced Tab View

Most programs have Tabs now, so why not enabled vim Tabs?

How to use it:

   Ctr-t            opens new tab
   Ctr-h            activate tab left of current
   Ctrl-l           activate tab right of current
   Alt-1 to Alt-0   jump to tab number

Add in your .gvimrc/.vimrc:

  set showtabline=2    " always show tab bar
  set tabpagemax=20    " maximum number of tabs to create

Add in your .vimrc

   " new tab
   nnoremap <C-t>     :tabnew<cr>
   vnoremap <C-t>     <C-C>:tabnew<cr>
   inoremap <C-t>     <C-C>:tabnew<cr>
   "tab left
   nnoremap <C-h>     :tabprevious<cr>
   vnoremap <C-h>     <C-C>:tabprevious<cr>
   inoremap <C-h>     <C-O>:tabprevious<cr>
   nnoremap <C-S-tab> :tabprevious<cr>
   vnoremap <C-S-tab> <C-C>:tabprevious<cr>
   inoremap <C-S-tab> <C-O>:tabprevious<cr>
   "tab right
   nnoremap <C-l>     :tabnext<cr>
   vnoremap <C-l>     <C-C>:tabnext<cr>
   inoremap <C-l>     <C-O>:tabnext<cr>
   nnoremap <C-tab>   :tabnext<cr>
   vnoremap <C-tab>   <C-C>:tabnext<cr>
   inoremap <C-tab>   <C-O>:tabnext<cr>
   "tab indexes
   noremap <A-1> 1gt
   noremap <A-2> 2gt
   noremap <A-3> 3gt
   noremap <A-4> 4gt
   noremap <A-5> 5gt
   noremap <A-6> 6gt
   noremap <A-7> 7gt
   noremap <A-8> 8gt
   noremap <A-9> 9gt
   noremap <A-0> 10gt

Answer by smcameron (Feb 10, 2009)

When updating my "blog" at work (which is just an html file) I do ":r !date" to get a timestamp.

If I find myself doing a repeated operation, I will often remap ctrl-O (which isn't used so far as I know by any vim thing) via the :map command, using ctrl-V to escape the ctrl-O.

So, for example, if I have a list of things

x
y
z

(and maybe 20 more things)

and I want to convert that to C code like:

printf("x = %d\n", x);
printf("y = %d\n", y);
printf("z = %d\n", z);,

etc.

I might do:

:map ^V^O yypkIprintf("^V^[A = %d\n", ^[JA);^[j

(ok, I didn't test the above, but, something like that.)

Then I just hit ctrl-o, and it converts each line from

x

to

printf("x = %d\n", x);

Then, if I want to kill emacs, I head over to http://wordwarvi.sourceforge.net


Answer by George V. Reilly (Feb 22, 2009)

Here's a pattern that I use a lot in keymaps. It brackets the current visual selection with a PREFIX and a SUFFIX.

vnoremap <buffer> <silent> ;s <Esc>`>aSUFFIX<Esc>`<iPREFIX<Esc>

Breaking it down, since that looks like line noise.

vnoremap        Visual-mode keymap; no further expansion of the right-hand side
<buffer>        Buffer-local. Won't apply in other buffers.
<silent>        Mapping won't be echoed on the Vim command line
;s              Mapping is bound to sequence ;s
<Esc>           Cancels selection
`>              Go to end of former visual selection
aSUFFIX<Esc>    Append SUFFIX
`<              Go to beginning of former visual selection
iPREFIX<Esc>    Insert PREFIX

For example:

vnoremap <buffer> <silent> ;s u`>a</a><Esc>`<i<a href=""><Esc>

brackets the visual selection with an HTML anchor tag.


Answer by Ton van den Heuvel (Oct 07, 2009)

Remap your caps lock key to control, and then use the easier to type Ctrl-[ shortcut instead of Escape to leave insert mode. Modern Linux distributions support keyboard remapping through the keyboard settings dialog, under Windows I use SharpKeys.


Answer by juque (Oct 27, 2009)

The very best!

:set vb t_vb= 

no more beep!


Answer by chardin

Here are some Vim commands I use a lot.

  • gUU Uppercase the current line.
  • guu Lowercase the current line.
  • :%s/^I/\r/g Change all tabs to newlines. (The ^I is the tab character).

Answer by Hamish Downer

I always set my keyboard to swap Caps Lock and Escape.

With the standard Ubuntu/GNOME desktop, go through the menus: System -> Preferences -> Keyboard -> Layouts tab. Then hit the "Layout Options" button, click on the triangle next to "Caps Lock key behaviour" and select "Swap ESC and CapsLock".

Not strictly part of Vim, but makes Vim so much nicer to use.

And other than that, use Vim for everything. Some useful extensions to allow more Vim usage:

  • for Firefox, It's all text allows you to use an external editor for text boxes, and if you want to go further then investigate the Vimperator. Also, not at version 1.0 yet, but jV makes text areas work like vi.
  • for Thunderbird, the external editor extension allows you to use gVim to write your emails, or you could use Vimperator's sister extension - muttator.

etc.


Answer by anthony

Put these two lines in your .vimrc:

map <C-J> zzjzz
map <C-K> zzkzz

Use Ctrl-J/Ctrl-K to scroll up and down while keeping your cursor in the middle of the visible range.

Comments

I don't actually like this because it "jumps" if you have the cursor close to the top or bottom of the window, but it did give me an idea and I have added. :map <C-J> <C-e>j :map <C-K> <C-y>k To provide a 'smooth' version of the same idea. – Leonard Feb 28 '09 at 2:58


Answer by slack3r

CTRL-O and CTRL-I goes back and forward in your jump history (also works between buffers!).

:grep foo -R * then use :cn and :cp to jump between matches.

Also in .vimrc: set autochdir was important to me -- it tells Vim to change the current directory to the current buffer's directory. This matters, for example, when I am in dir1 in the shell and start vim from there, then switch to some file in a different directory and try to do something like grep foo *.

In *nix K opens the man page for the word under cursor. Nice for syscalls (try 2K and 3K) and C standard library. (nK is manual section n)

:make in a directory containing a Makefile. Then use :cn and :cp to jump between errors.

I currently use

:nnoremap <silent> gw "_yiw:s/\(\%#\w\+\)\(\W\+\)\(\w\+\)/\3\2\1/<CR><c-o><c-l>

for swapping words (When I mess up argument order or assignment sides, etc.), but this needs improvement as it doesn't always work very well. Also, I'm not sure if there's a nice way to swap two distant words (Anybody?).

EDIT: Also I like keeping a text file in ~/.vim/doc in vim's help format which I call cheatsheet.txt where I put some things I don't use very often so I forget, but are nice tricks or important functionality. For example:

*cheatsheet.txt* Some clever tricks that I want to find quickly
1. COMMANDS *cheat-commands*
                                                                          *cheat-encoding* |++enc|
:e++enc=cp1251 Reopen file with cp1251 encoding

Then in vim i just do :help cheatsheet (:helptags ~/.vim/doc/ needs to be done to rebuild the help tags) or :help cheat-encoding (here, even tab-completion works). The benefit of this is I have only things that I know are relative to me and I don't need to dig in the VIM documentation. Also, this could be used for stuff other than VIM-specific info.


Answer by ground5hark (May 17, 2010)

Insert a comment before every line selected in visual line mode.

First, select the lines which need commenting out in visual line mode (SHIFT + V).

Then type this (substitute your own comment symbol):

:s/^/#

Removal:

:s/^#//

Answer by sica07 (Sep 23, 2010)

A  "append at the end of the line

The A command was a productivity buster for me. It replaces $a commands. Sorry if it was mentioned before.


Answer by OneOfOne (Jan 19, 2011)

If you are using KDE and want to paste from system clipboard you can use CTRL-R + in insert mode or "+p in normal mode.
You can also use CTRL-R * in insert mode / "*p in normal to paste the selection buffer (mouse's middle button).


Answer by omab (Jun 27, 2011)

Leader key definition:

let mapleader = ","

Remaoing j/k to work properly with very long lines:

nnoremap j gj
nnoremap k gk

Remap something less painful to mimic ESC functionality

imap jj <ESC>

Answer by Ludvig A. Norin (Sep 18, 2008)

NNyl <-- copy NN characters to the right beginning with the cursor position (ie. 7yl to copy 7 characters)

p <-- paste the characters at the position after the cursor position

P <-- paste the characters at the position before the cursor position


Answer by Joe Van Dyk (Sep 18, 2008)

I have this in my .vimrc file -- it's helpful for doing Ruby programming.

map R :wall!:!ruby %

This lets me press 'R' and have the file saved and then execute the file in the Ruby interpreter.


Answer by Ludvig A. Norin (Sep 18, 2008)

At the ex prompt you have command history using up/down arrows.


Answer by Paul Brinkley (Sep 18, 2008)

In my vimrc file:

" Moves this window to the left, center, or right side of my monitor.
nmap ,mh   :winpos 0 0<cr>
nmap ,ml   :winpos 546 0<cr>
nmap ,m;   :winpos 1092 0<cr>
" Starts a new GVim window.
nmap ,new :!start gvim<cr>

Answer by Max Cantor (Sep 19, 2008)

http://dotfiles.org/.vimrc

This one's mine: http://dotfiles.org/~maxcantor/.vimrc


Answer by Artur Siara (Sep 19, 2008)

I have some shortcuts, ie:

1.Sort a file with a few way

map ,s :%!sort<CR>
map ,su :%!sort -u<CR>
map ,si :%!sort -f<CR>
map ,siu :%!sort -uf<CR>
map ,sui :%!sort -uf<CR>
map ,sn :%!sort -n<CR>
map ,snu :%!sort -n -u<CR>

2.Open new file from current path with vertical split

map ,e :vsp .<CR>

3.Grep file with match

map ,g :%!grep 

4.Change show file modes

map ,l :set list<CR>
map ,L :set nolist<CR>

5.Turn on/off highlight

map ,* :se hls<CR>
map ,8 :se nohls<CR>

6.Turn on/off numbering

map ,n :se nu<CR>
map ,N :se nonu<CR>

7.Run - perl

map ,p !perl<CR>
map ,P gg!Gperl<CR>

8.Copy file to specified server

map ,scp :!scp % user@example.com:~/some_folder/

Answer by Mapad

Go through last edits after you scrolled:

gi

insertion where the cursor last used to be before when quit insertion mode.

g;

go to the previous position of cursor in change list

g,

go to the next position of cursor in change list

Undo/Redo what you did:

:undol

list all branches of the changes you made

10 g- or 10 u

undo 10 previous change

10 g+ or 10 Ctrl+R

redo 10 previous changes

:later 1h

go 1 hour later

:earlier 1h

go 1 hour back


Answer by Robert Swisher (Nov 12, 2008)

To turn auto indent on/off for pasting with add the following to the .vimrc:

nnoremap <F2> :set invpaste paste?<CR>
imap <F2> <C-O><F2>
set pastetoggle=<F2>

That will give you a visual cue as well


Answer by user35978 (Nov 13, 2008)

Well, I know the author said no basic.. but I didn't know this one even if I knew less-basic one. Just use o to begin insert a new-line after the present line.. I used to do something like, $a (go to the end, start writing, and create new line).. So now, only o does this :) And by the way, O insert a new line on the present line instead of inserting it after the current.


Shared with attribution, where reasonably possible, per the SO attribution policy and cc-by-something. If you were the author of something I posted here, and want that portion removed, just let me know.

What is (err.. was) the Amazon Early Reviewer Program?

$
0
0
What is (err.. was) the Amazon Early Reviewer Program?

I was paging through reviews this evening for new phones, a process I both love (new tech yay) and hate (I get lost in the minutiae, researching specs I didn't know existed and actually don't care about), when I came across a review with a small badge that said "Early Reviewer Program".

I hadn't noticed that one before, and clicking the link next to it just led to the generic "Customer Reviews" help page, which mentions absolutely nothing about such a program. Well, the nice thing about having your own corner of the web is that, after you dig up a deleted page, you can repost it. 😏

tl;dr - From what I gather, it was a program that sellers could opt into, which rewarded "early" (first 20? first month after launch? before 6 am?) purchasers of their products by "encouraging" them (frequent emails? frequent calls? creepy notes in block lettering, slipped under the front door?) to leave a review. After which the buyer may or may not be rewarded with a randomly insignificant amount of money.


What is the Early Reviewer Program?

The Early Reviewer Program encourages customers who have already purchased a product to share their authentic experience about that product, regardless of whether it is a 1-star or 5-star review. Amazon shoppers depend on reviews to learn more about products, and this program helps to acquire early reviews on products that have few or no reviews, helping shoppers make smarter buying decisions. Customers who have purchased a product participating in the Early Reviewer Program may be asked to write a review and those customers who submit a review within the offer period will receive a small reward (e.g. a $1-$3 Amazon.com Gift Card) for helping future shoppers.

1. Can I trust these reviews?

Yes. We are not giving free products or discounts to these reviewers. We only ask customers who have already purchased the product to share their authentic experience, regardless of whether it is a 1-star or 5-star review. This program is not limited to elite reviewers - we want to hear from all of our customers as long as they have no history of abusive or dishonest reviews.

2. How are reviewers selected for this program?

We want authentic reviews, and we want them from all of our customers, not just a select few. We select at random from all customers who have purchased products participating in this program, as long as they have no history of abusive or dishonest reviews and meet our eligibility criteria. We do not disclose at the time of purchase whether a product is participating in the program because we want to hear from customers who have authentically chosen to buy that product without any knowledge of a future reward. Not all products are participating in this program and not all buyers of participating products will receive reward offers to write a review. We want this program to generate enough reviews to help shoppers make smarter buying decisions; this is not a rewards program intended to encourage purchases. Amazon employees, participating sellers and their friends and family are not eligible to participate in this program.

3. How are reviews rewarded.

Reviewers will receive a small reward (e.g., a $1-$3 Amazon.com Gift Card) after they have submitted an authentic review within the offer period which meets our community guidelines. This small reward is given to thank reviewers for sharing their authentic experience, regardless of whether it is a 1-star or 5-star review. The nature of the review does not affect the reward or the chance of getting future rewards.

4. How will I know if a product has a review from Early Reviewer Program?

Early Reviewer Program reviews are identified with an orange badge that reads "Early Reviewer Rewards".

5. Can sellers influence these reviews or reviewers participating in this program?

No. Sellers can select products to participate in this program but they do not have any influence over which customers are selected to receive the reward offers or the content of the customer reviews. Sellers are also prohibited from communicating with customers about their reviews. Amazon does not modify or remove reviews from the Early Reviewer Program, as long as they comply with our community guidelines.

SO Vault: What issues carry the highest risk in a software project?

$
0
0
SO Vault: What issues carry the highest risk in a software project?

StackOverflow sees quite a few threads deleted, usually for good reasons. Among the stinkers, though, lies the occasionally useful or otherwise interesting one, deleted by some pedantic nitpicker - so I resurrect them. 👻

Note: Because these threads are older, info may be outdated and links may be dead. Feel free to contact me, but I may not update them... this is an archive after all.


What issues carry the highest risk in a software project?

Question asked by Mehrdad Afshari

Clearly, software projects are different from other industries in terms of many things like for instance, quality assurance, project progress measurement, and many other things.

Unique characteristics of software projects also makes the risk management process unique. Lots of issues in a project might lead it to unacceptable delay or failure to deliver business value. They might even make a complete disaster in the project.

What are the deadliest risk factors in a software project? How to analyze, prevent and handle them? Particularly, I'm interested in the issues that you can detect from the beginning and you should keep an eye on (for example, you might be told about a third-party API that the current application uses and lacks documentation).

Please share your experiences if they are relevant.

Comments

To be pedantic... "issues" are "risks" that have already happened. Issues don't have risk.. they just have impact, and a probability of 100%. – Mark Nold Mar 5 '09 at 23:23

Great to learn english language in SO! – alvatar May 19 '09 at 13:24

I don't think software projects are unique. If you are developing a new car a new factory or a new software there shouldn't be a big difference. As long as you are doing something new, with creative and a little bit peculiar people that is not fully understood yet and the goals are not 100% clear. I think the problem with software projects is grown out of the old, gather requirements, code, deliver project cycle. This does not apply to the examples before a building has a maintenance plan, a new car is a research project not a simple write down work... – Janusz Sep 3 '10 at 14:09


Answer by Jeremy French

Change. Especially, unmanaged, uncontrolled change are a huge risk. You can embrace or control change but don't ignore it.

Edit: Extended answer with example (as the OP asked for one)

As I said in the comments, software is abstract, especially to people who don’t work writing it. With something physical it is easy to see the progress and barriers to change. Once you are half way through building a bridge you are not going to change where it is sited but with software it is much more difficult to justify resistance to change.

For example. Once I was writing a system where in one place the title of an object was to be displayed along with links and some other detail. So I designed and engineered it to bring back the title and the other information. This solution was fairly need and simple. Towards the end of development the requirement was changed so that in some cases the category would be displayed with the title. To me this required a lot of rework or a nasty fudge in the system (making it more susceptible to bugs and less maintainable) As far as the business was concerned there was just some more text on the page, so they saw no reason for our resistance to the change.

This sort of thing happens all the time as most people don’t understand how software works, they don’t understand why it is difficult and risky to change it late in the day, but with more physical projects it is intuitive.

Comments

Which means that ultimately the biggest risk to a project is the competence of the people involved. – MusiGenesis Jan 22 '09 at 14:29

But that goes for any field. Because of the 'abstract' nature of software change is harder to fight against. – Jeremy French Jan 22 '09 at 14:32

I agree with Jeremy here. Though incompetence and arrogance are big factors for uncontrolled and unmanaged change, the abstract nature of software means change creeps in and permeates much more easily. – Mostlyharmless Jan 22 '09 at 14:50

Why do we think software is more 'abstract' than something physical like a car or a bridge? The AMC Pacer and the Pontiac Aztec are examples of design where change was not managed well. – MusiGenesis Jan 22 '09 at 14:53

MusiGenesis: There are many differences. It's not that they don't fail. But if you look at a construction project, you can roughly estimate how much work has been done and how much is left. Users can have an idea on how it's going to be from the first place. This is not the case in software. – Mehrdad Afshari Jan 22 '09 at 15:12

@Mehrdad: I can make similar estimates on my projects, assuming I'm reasonably familiar with the platform/language and the problem domain. – MusiGenesis Jan 22 '09 at 15:17

MusiGenesis: Yeah, there are measures to do so but the point is, this is much harder and less accurate, than say, counting the floors of a building :-) Another thing is, while you might be able to evaluate it, users probably won't, which does make a difference. – Mehrdad Afshari Jan 22 '09 at 15:30

@Mehrdad: your average modern car is vastly more complex than any piece of software I've ever seen, used or read about. The general statement "software tends to blow because programming is hard" is kind of a crutch. – MusiGenesis Jan 22 '09 at 22:46

MusiGenesis: Complexity is not the only factor. The non-physical nature of software makes it somewhat mysterious. And another thing that is so true about software is that writing code, involves reading code too. So writing software is a little like O(n^2) :). – Mehrdad Afshari Jan 23 '09 at 12:58

Also, as noted by Fred Brooks, adding people to a software project doesn't make it finish faster. This is not true for other kind of projects, at least not to this magnitude. – Mehrdad Afshari Jan 23 '09 at 12:59

That Fred Brooks quote is wrong though - adding people to a LATE software project makes it LATER. But that doesn't mean adding the right people at a right time can't make it finish faster. – Joris Timmermans Feb 10 '09 at 11:17

@MedKeithV: completely true. I think I missed the word "necessarily" in my comment. – Mehrdad Afshari Mar 26 '09 at 20:44

I think Joel Spolsky has quite an experience on bad changes (or rather, rewrites). – Halil Özgür Feb 16 '11 at 9:37


Answer by Joris Timmermans (Jan 22, 2009)

Assumptions are the biggest risk.
You assume that you know what your team is doing.
You assume that your team knows what they are doing.
You assume that your team would tell you if they no longer know what they are doing.
You assume that you're doing what the customer asked for.
You assume that what the customer asked for is what the customer wants.
You assume that what the customer wants is what the customer needs (notice that there are already two indirections here!)

More specifically: project schedules. The bane of everything. Your customer or management will hold you to it. Unless you multiply every estimate by 10 and add a safety margin, you're probably not going to finish the whole project before the first project schedule you make runs out.
Why? Because things change, the customer asks for more, team members leave, people take holidays at annoying times, things get underestimated. You can't tell your customer "you can't have your new business-critical feature because it wasn't in the original planning", and you'll find that most of the time you don't want to tell your customer "fine but that will add three months to the schedule". Train yourself to do this anyway. It's not popular with customers, but it's the truth.

Comments

McConnell calls this "Wishful thinking", i.e. assuming something will fix itself – Rob Nicholson Sep 29 '09 at 10:49


Answer by McKenzieG1 (Jan 22, 2009)

You need to keep a close eye on your dependencies on third-party components, particularly if they are specialized ones that may have very few other users who are doing exactly what you are doing, and that may be difficult or impossible to replace.

If there are any bugs or gaps in the features you need for your system, you will be at the mercy of the vendor's schedule and ability to fix their product. The earlier you can explore the whole surface area of your contact with any third-party components, the better. Problems in your own code may be challenging to fix, but at least they are under your control. With vendor problems you usually can't do much other than wait and complain.

Comments

Amen. I've been waiting for years for the time when I can stop avoiding third-party components like the plague, but it hasn't happened yet. – MusiGenesis Jan 22 '09 at 14:58

I wish I could vote this up 1000 times. – ojblass Mar 26 '09 at 5:50

Completely agreed - yes our medical information system has bugs but most of the issues we've been unable to fix/track down as with 3rd party controls. You take a chance with their quality – Rob Nicholson Sep 29 '09 at 10:48

In addition to technical problems caused by third-party components, legal restrictions on such components may make it very difficult for you to open the source of your system should you ever chose to relinquish support of the system to the community. – Erik Garrison Apr 7 '10 at 21:25


Answer by Slapout (Jan 22, 2009)

People & Communication

The programmers need to be able to program. The analysts need to be able to communicate to the customer in a way that pulls out what the customer really needs. Then the analysts need to be able to clearly communicate this to the programmer.


Answer by Steven A. Lowe (Jan 22, 2009)

anything you don't understand is a risk factor; this includes things that aren't specified well and things you've never done before and things with insufficient documentation etc.

mitigate the risks by planning for and doing - up front - investigation and prototyping (a "spike" project in XP terms)

be prepared with a fallback plan if the initial direction turns out to be infeasible

Comments

This is essentially the same as my answer, albeit without the down-votes. :) – MusiGenesis Jan 22 '09 at 15:19

MusiGenesis-I don't think this is like yours at all. It's similar to mine though ... so it must be right. ;-) +1 – John MacIntyre Jan 22 '09 at 16:25


Answer by John MacIntyre (Jan 22, 2009)

New, new to us, and known technologies used in new ways.

You can minimize these risks by doing proof of concepts apps in the design phase. These small projects will also serve as a communication tool in the future on how something should be done.


Answer by Joe (Jan 22, 2009)

  • Organizations that treat talent (not just programmers) as resources that can be swapped in based on job title. This is really quite common, although it's almost never as 'coarse' as my description. The common manifestation is: We're running late, if we add these 5 guys who have never even seen this project, I'm sure we can pull it off!
  • Orgs that think it can be done on time because of the technology they've chosen and not the quality of the staff. This happens less now, but there was a time when 'hard projects' were believed to be 'easy' if they did them in Java instead of C++. The reality is that a bad team using C++ would fail quickly. A bad team using Java would still fail - but it took a long long time. A good team would finish with either tech, and would finish sooner if allowed to pick the right tech for the job.
  • Re-Engineers. You know these guys. They see code that works, but isn't what they would have done - so they re-write it, or wrap it in a bunch of fluff to make it what they want it to be. It doesn't matter if they are right or wrong, this kind of inflexibility ends up with tons of code churn, but very little progress. Some code is so bad it needs to be re-written. But usually you can wait until a feature would take you through the 'eh' code and work it then since you were going to have to mess with it anyways.
  • Being micro-managed by a customer. Small companies have this problem the most. You are the little guy - you need that money. Too bad the customer calls the project manager every other day and changes something. Had a bad spec/agreement - To be expected. Had a great spec/agreement - well no, so what. Big guy says 'I want it changed or I'm cancelling the project!' - your business guys will cave. This is a real tough one. If you don't get to make most of your product before end customers get involved, it's a mess. Customer driven projects are better done under a time based contract where you can just set your soul aside for awhile and roll with the changes.
  • Sales guys obsessed with selling what you haven't made. Sales guys love to get excited. They've seen the product. They aren't excited anymore. So what that the customer hasn't seen the product and will be 'super-excited'... the sales guys need to go invent a bunch of stuff that doesn't exist and sell it. They can't seem to come to terms with the idea that the customer is not immersed in the developed product and will be excited.

Those are the worse ones I've seen.

There's always the death-by-meeting orgs, but I think Dilbert has that sufficiently covered.

Comments

+1 for "re-engineers" and "micromanagement from the client" – Andrei Rînea Nov 8 '10 at 0:51


Answer by Frank Michael Kraft (Sep 28, 2009)

Politics

If good reason does not prevail, because it is unpleasant to hear.


Answer by Otávio Décio (Jan 22, 2009)

Thinking that you gathered all requirements and being sure the client told you everything you need to know.


Answer by Jon Winstanley (Jan 22, 2009)

Users.

No matter what you build, they will use it differently to what you expected.

Involve them early and have user acceptance testing asap!


Answer by MrValdez (Jan 22, 2009)

Anything that involves money or credit card payment. Keeps me awake at night :(


Answer by Kasper

I have seen project that were on time, on budget and covered 100% of the requirements AND failed big time. When we did a post mortem it became very clear that the client's representatives were focussed on their part of the system and nobody cared about the flow between the subsystems.

So my prioritized list looks like this:

  • Unprepared customer
  • Fluffy requirements
  • Scope creep
  • unstructured change request handling

Technology and project methology is insignificant compared to the power of bad requirements


Answer by Gambrinus (Jan 22, 2009)

Basically it is not that difficult - otherwise no project would ever succeed. What you need to watch out for is:

  • clarify the aim - before AND during the project
  • decide what tools you use (programming language, dbms, etc.)
  • are you and your co-workers qualified enough
  • scale of the project (how much data, users, objects, etc. do I need to handle)
  • keep track of what you are doing
  • test, test, test and test
  • use the appropriate tools
  • do not "over-engineer" the solution (you don't need a "full-blown solution" for displaying some lists of - let's say - bank account transactions and modifying the details of the bank accounts)
  • clearly define the official paths of communication
  • define the responsibilities
  • estimate everything you want to do and record what you actually do (see mcconnell software estimation)
  • try to have a stable project-team - every co-worker lost is knowledge missing

From my expierence these are the things that troubled my developer-life the most. Ah - yes and try to keep the truck-run-over-count as high as possible - so share the knowledge about the code and especially the business-logic. code is mostly self-explanatory - but as a developer you may not know the big picture.

Comments

Indeed, a lot of them don't succeed. At least most project miss on time and resources, quality, or features. – Mehrdad Afshari Jan 22 '09 at 14:35

yes - McConnel wrote in his book that every software-project that misses its monitary- and/or time-constraints by 400% can be seen as successful. biggest problem I think is that most customers do not know what they want in the first place and start to change the spec every now and then. – Gambrinus Jan 22 '09 at 14:50

I have never heard of a project that was "Completed Successfully". Sure there are successful projects, but none of them were COMPLETED. They just crossed a threshold into being "good enough" [even that bar keeps on rising though] – Mostlyharmless Jan 22 '09 at 14:52


Answer by meade (Jan 23, 2009)

Based on research (Capers Jones http://itprojectguide.blogspot.com/2008/11/caper-jones-2008-software-quality.html) the top issues are bad requirements and bad design - without a good base to work from the project is doomed. Most rework, scope creep, etc. is due to missing information during the requirements and design phase. The best way to address this is through requirements, design and code reviews - adhoc is better then nothing, but there are systematic approaches also.


Answer by David Thornley (Jan 22, 2009)

Change is a big one. Changes need to be controlled. They can't be eliminated, but the cost of changes must be understood.

Unrealistic assumptions are another biggie, in particular unreasonable schedules. These are typically imposed externally, although programmers are notorious optimists themselves. I worked for a company once that understood software development well, but the sales staff got out of hand selling custom modifications, and that was bad.

Lack of process, or bad process. This is particularly true of larger projects. Gathering requirements first and coding like heck can work on small projects, but it doesn't scale.

Lack of commitment from the rest of the enterprise.

People, whether incompetent, uncaring, or just jerks.


Answer by Jon Hopkins (Sep 29, 2009)

Lots of good stuff already listed but I'd also add external dependencies:

  • Interfaces to other systems (particularly when unproven or unknown)
  • Deliveries by other companies (for instance a graphic design company when you're doing a web site)
  • 3rd party contractors when they're not under your close management

These are all areas I'd allow extra time from both in terms of slippage (that is they WILL deliver late) and effort (what they deliver won't be up to scratch and will need you to help them resolve / rework / test / analyse it).


Answer by Mammu (Jan 22, 2009)

Missing the following can make a s/w risky

  1. Extensibility
  2. Change Adaptment
  3. Clear goal of software
  4. Try using the software as End-USER
  5. Expertise in that domain

BTW making proper estimation of Time and effort to build the software also holds an important key for successful project.


Answer by Lonzo

  • Lack of planning
  • Skill/Resource shortage
  • Ineffective communication among stakeholders
  • Failure to get a full understanding of the requirements

Comments

I thought "Lake of Planning" was a setting in World of Warcraft? – MusiGenesis Jan 22 '09 at 15:00

Are we on the same team? – jamesh Jan 22 '09 at 15:46


Answer by JB King (Sep 17, 2009)

Here are a few that I've seen over the years:

The evolution of the end result - How well can the project sponsor articulate the final result of the project? "Build me a way to track inventory," leaves a lot open to interpretation. Similarly, a group of business users may not understand all the things that a CMS can do so the end result will change as the project progresses.

The evolution of the resources - Are things like time, money, or scope really fixed or is there some flexibility there to handle things if the project goes off track. Maybe some people on the project want to take vacation or leave the project for a change that can impact things as if the lead goes away for a month, that likely will change things for a while.

The evolution of process - How are we going to do things and will this shift over time? Generally, the answer is yes things are going to change as a team dynamic emerges and things get done, but the flexibility has to be allowed here. There may be some places where the process is so fine tuned that it just works and there aren't problems, but I haven't seen that place yet.

The handling of failure - If something doesn't go right, or some major problem is found, how is that handled? Generally there will be errors or things not done right initially and this has to be accepted.


Answer by Stephan Eggermont

No clear mission statement and lack of support from upper management of the customer.

No commitment to get requirements right and prioritized is going to kill every project. Getting the wrong people involved sure helps. Having someone around who claims she's seen lots of contractors come and go, and is not willing to put in any effort to contribute.

I've had to start doing software archeology for a project where there basically wasn't anyone around anymore who understood the whole system. That's a lot slower than the normal way of working...

New technology for technology sake is also a nice project killer. Not all technology works as well as the marketing brochure


Answer by geowa4 (Jan 22, 2009)

Marketing.


Answer by Stu Mackellar (Jan 22, 2009)

One often overlooked problem is legal clearance for using third party APIs, licensing etc. When several large companies are involved then negotiations can take months, if not years, which can really mess with your release schedule.


Answer by astronought (Sep 03, 2010)

I've heard about various attempts to write scripts in one friendly language to run code in a less friendly language like c++. Both attempts I've know about have failed. Should be obvious I know.

Comments

Scripting languages are designed to put pieces of code (such as C++ code) together. Most of them have C bindings so that they can be called from conventional compiled languages and call into them. I may be misunderstanding you, but I just don't see any real risk involved here. – David Thornley Sep 3 '10 at 13:53

I think he is talking about code generation... but in that context success cases also exist. – João Portela Sep 3 '10 at 21:43


Answer by Rob Nicholson

Not a direct answer to the question, but all developers interested in why projects go wrong should read "Rapid Development" by McConnell. The list of classic mistakes is listed on the web as well - slightly updated from the book http://www.stevemcconnell.com/rdenum.htm

From memory, McConnell sites "Lack of planning" as the most common reason projects fail.

Cheers, Rob.


Answer by mickyjtwin (Jun 03, 2010)

I'm sure most developers would agree to, after a project has been completed, you always think of things you would have coded differently, that would have saved you time etc. From my experience, one of the biggest factors that leads to failures in Software Development is inadequate preparation. Most often this comes from time pressures, low-budgets, which leads to cutting corners. Again, as most developers would agree to, we do not develop in a perfect world, with perfect budgets and ample time constraints, however having said that, you must start of with at least a plan that can be followed and tracked against.

The second reason I think Software Development fails is lack of communication. Without a clear line of communication, from team(developer) level, through to project managers, account managers, clients, or even developer straight to client (if working alone), will bring down a project faster than I get an answer on stackoverflow! With, I'm sure, many advocates for both Waterfall and Agile development, and having worked with both, one of the things that works best for both, is having daily communication catchups. This ensures the whole project team is aware of what has been achieved, what will be achieved, and how to achieved.


Answer by Alb

The two causes of failure that immediately spring to mind for me are:

  • Not creating the software iteratively with the customer. This means delivering a real working feature with each iteration, and ideally the customer trying out the software after each iteration. This prevents the case where something is released after 2 years of work to discover it's nothing like what the customer actually needed.
  • Not making the software easy to change which starts with good code factoring (DRY etc) and good test coverage.

If both of these common agile methods are fulfilled, you should have something the customer wants at each stage, or at least it will be relatively easy to make the changes required to make it so.


Answer by Gayathri (Nov 24, 2010)

The highest risk today is the gap between the technical community and the business. The number of translations of the requirements that happens from business mouth to the developer's desktop impact the way software is developed. Most often, when you discuss the issues with developer you will find his problem is genuine and requirement is not gathered properly. On the same lines when you speak to business user you will feel his concern is valid as well.

Hence the process of translation needs to be improved and as the industry is maturing there are better methods like Agile which are being practiced.


Shared with attribution, where reasonably possible, per the SO attribution policy and cc-by-something. If you were the author of something I posted here, and want that portion removed, just let me know.

Docker - Peeling back the layers

$
0
0
Docker - Peeling back the layers

After a few weeks, I'm back on the Docker train. Or is it the Docker whale? Who trains whales to haul cargo anyway? And why don't we see more protests about this? Where's PETA?? So many important questions, but at least the whale's smiling.

Docker - Peeling back the layers

A few weeks ago, I took my first real look at Docker, and learned just enough to write a bad analogy. Now I'm taking a closer look at the anatomy of a docker image, which I've always heard consists of layers, but I've never quite understood what that meant.


Old Skool VMs 🤘

My typical experience with using Linux is to download an ISO image, like Ubuntu or Alpine, and spin up a vm in VirtualBox. Then I'll install whatever I need on top of that, like RabbitMQ.

Docker - Peeling back the layers
Checkin' out RabbitMQ on a fresh-off-the-press Ubuntu vm

It works, but what if you want to:

  • rollback to before the last update? the last 10 updates?
  • make sure an entire team (or a new hire) could recreate the same exact setup?
  • deploy several slightly different versions for different environments?

You could take a snapshot of the entire VM after every significant update, but that would waste a ton of space and be stupid-kludgy to manage.


Back to Docker 🐳

Instead of creating a VM and saving that behemoth, you can create a script that defines how your VM should be built, and then commit changes to that script to a repo like any other piece of code you've written.

If you wanted the latest stable version of Ubuntu from dockerhub, where all kinds of "images" are stored and made publicly available, just do a docker pull for the ubuntu image you're interested in. The individual hashes you see are changes to the initial image. It has to pull all those changes, or layers, to get you the complete image.

$ docker pull ubuntu:19.10

19.10: Pulling from library/ubuntu
4fc5deeb8d45: Pull complete
d70e07bddb7c: Pull complete
a4bf564c51f3: Pull complete
111c7f4c8fb3: Pull complete
Digest: sha256:98051557b93f45de6ab02001287be81a693df09fe71a1d9fb45056af2671e17d
Status: Downloaded newer image for ubuntu:19.10
docker.io/library/ubuntu:19.10

Then you could do a docker run against that image with whatever command you wanted - even something as silly as just printing the date. It creates a container, runs the command in it, then outputs the result. Nifty. And super useful. 😏

$ docker run ubuntu:19.10 `echo date`
Wed Nov 27 19:09:16 UTC 2019

BTW, if you want to see the current images you've downloaded, or the containers you've created from those images, here's a couple handy commands to keep in mind.

$ docker images
REPOSITORY          TAG           IMAGE ID            CREATED             SIZE
ubuntu              19.10         c351ab52170e        16 hours ago        72.9MB
ruby                2.6           d98e4013532b        5 weeks ago         840MB
hello-world         latest        fce289e99eb9        11 months ago       1.84kB

$ docker ps -a
CONTAINER ID   IMAGE          COMMAND      CREATED         STATUS
d39fc40ff8aa   ubuntu:19.10   "date"       20 seconds ago  Exited (0) 19 seconds ago
2421438b1d06   ubuntu:19.10   "/bin/bash"  8 minutes ago   Exited (0) 8 minutes ago
40bd23d0b84a   hello-world    "/hello"     4 days ago      Exited (0) 4 days ago

RabbitMQ

That's all well and good if all you want is a base Ubuntu image, but what if you want something running on top of that like RabbitMQ? As luck would have it, there are plenty of images for you here, depending on what version of Rabbit you'd like and even what version of Linux you'd like to run it on top of!

For example, pulling down 3.8.1-alpine currently gets you this image, which starts by doing a FROM alpine:3.10 which means it's based off the Alpine image. I wouldn't recommend that though, since there's also a comment in the Dockerfile that says "Alpine Linux is not officially supported by the RabbitMQ team -- use at your own risk!"

Instead, you could pull down 3.8.1 which starts FROM ubuntu:18.04 instead. Then it runs other commands to setup OpenSSL, OTP (Erlang), and finally RabbitMQ. If you decide you need to administer Rabbit, the 3.8.1-management image builds on top of 3.8.1, so it does all the above and then enables and sets up the rabbitmq management plugin too!

You can get a better sense of what's happening if you pull each layer of the final image, instead of just pulling the final image by itself. Here I pulled Ubuntu, then the RabbitMQ image that depends on it, and finally the management image that builds on that. Notice how each subsequent image reports that some of the required layers are already available, and they aren't pulled down again.

$ docker pull ubuntu:18.04

18.04: Pulling from library/ubuntu
7ddbc47eeb70: Pull complete
c1bbdc448b72: Pull complete
8c3b70e39044: Pull complete
45d437916d57: Pull complete
Digest: sha256:6e9f67fa63b0323e9a1e587fd71c561ba48a034504fb804fd26fd8800039835d
Status: Downloaded newer image for ubuntu:18.04
docker.io/library/ubuntu:18.04

$ docker pull rabbitmq:3.8.1

3.8.1: Pulling from library/rabbitmq
7ddbc47eeb70: Already exists
c1bbdc448b72: Already exists
8c3b70e39044: Already exists
45d437916d57: Already exists
916459a32f87: Pull complete
aba97e76a6d7: Pull complete
6cfc7646d503: Pull complete
5e8c71984192: Pull complete
16722d38aada: Pull complete
b3a7c7a8fb05: Pull complete
Digest: sha256:1c000709124c4c3e3da1657ef81de7a300e92cee249163831df141ddb4145762
Status: Downloaded newer image for rabbitmq:3.8.1
docker.io/library/rabbitmq:3.8.1

$ docker pull rabbitmq:3.8.1-management

3.8.1-management: Pulling from library/rabbitmq
7ddbc47eeb70: Already exists
c1bbdc448b72: Already exists
8c3b70e39044: Already exists
45d437916d57: Already exists
916459a32f87: Already exists
aba97e76a6d7: Already exists
6cfc7646d503: Already exists
5e8c71984192: Already exists
16722d38aada: Already exists
b3a7c7a8fb05: Already exists
6b5a827c0c9c: Pull complete
32cfea652b55: Pull complete
Digest: sha256:5e144493152208e189763a61b81db5600a53531826c48ceffecf8a2f7efbac19
Status: Downloaded newer image for rabbitmq:3.8.1-management
docker.io/library/rabbitmq:3.8.1-management

Is it becoming obvious how convenient this system is? Instead of one giant steaming stew of a machine that "just works" but is impossible to exactly replicate, you're forced to slow down and document the exact steps to reproduce a given machine. Complex images are really layers over previous images, which could themselves be layers over even more previouser (??) images.

Scripting

In order to build your own images, with your own commands and setup and whatever else, you need to create a file (typically named "Dockerfile") with everything in it.

For example, I created a file with a single line in it:

from rabbitmq:3.8.1-management

And when I wipe out the 3.8.1-management image I pulled down before, and then call the Dockerfile, we get output that looks very familiar.

$ docker build .

Sending build context to Docker daemon  2.048kB
Step 1/1 : from rabbitmq:3.8.1-management
3.8.1-management: Pulling from library/rabbitmq
7ddbc47eeb70: Already exists
c1bbdc448b72: Already exists
8c3b70e39044: Already exists
45d437916d57: Already exists
916459a32f87: Already exists
aba97e76a6d7: Already exists
6cfc7646d503: Already exists
5e8c71984192: Already exists
16722d38aada: Already exists
b3a7c7a8fb05: Already exists
6b5a827c0c9c: Pull complete
32cfea652b55: Pull complete
Digest: sha256:5e144493152208e189763a61b81db5600a53531826c48ceffecf8a2f7efbac19
Status: Downloaded newer image for rabbitmq:3.8.1-management
 ---> 36ed80b6a1b1
Successfully built 36ed80b6a1b1

Each layer of your image would (unlike my tiny example above) include setup and configuration steps, environment variables, additional commands, yadda yadda. You can even add comments to the file too, so it's clear why you did what you did.

It's all one big piece of documentation on how to exactly replicate an environment, except the documentation itself can be run to create that environment... and you can commit it to a repo to track the changes.

Tip of the Iceberg

I've only touched the very tip of the iceberg so far, but I feel like I have a much better understanding now of all this "containers are built from layers" stuff I've heard about. I hope it helped you too!

If you came here looking for tips on icebergs, I have none. If you're reading this on a cruise ship and you're a member of the bridge, glance up once in awhile and avoid them. Just sayin'.

Thanksgiving 2019

$
0
0
Thanksgiving 2019

It's nearing the end of Thanksgiving, so before it gives way to Black Friday, commercialism, and the inevitable story of people beating each other up at a Walmart, here's a short list of some of the things I'm thankful for this year.

  • My wife, and best friend... who's also my wife. No that's .. that's not two people. One person, who's my wife and best friend. Sheesh.
  • My kids. They're perfect angels when they're sleeping. 😇 💤
  • A warm house to raise said kids with said wife and best friend. 🏡⛅
  • Friends who've become family.
  • Friends who I've lost touch with but were in my life for a reason.
  • A cool profession that doubles as a hobby. 👨‍💻
  • A cool hobby that doubles as.. nothing. It's just a hobby.
  • My Catholic faith, not because I deserve it, but because I need it.
  • Living in a country where we're free to pursue our interests and beliefs.
  • Not being required to eat cranberry sauce on Thanksgiving. 🤮

Happy Thanksgiving!

How do I add seconds, minutes, or hours to a DateTime structure in Erlang?

$
0
0
How do I add seconds, minutes, or hours to a DateTime structure in Erlang?

Some languages, like Ruby, give you 12 ways to do the same thing. Other languages, like Erlang, make it tough to find 1 way to do something. Awhile back, I was trying to add a period of time to an existing DateTime value (in {{Y,M,D},{H,m,s}} format), but I couldn't find a function (such as in the Calendar module) that allowed me to manipulate a DateTime value directly. Basically, my question was...

How do I add xx seconds to a DateTime value?

Use the Calendar module to convert the DateTime to seconds, which makes it easier to add the desired seconds, minutes, hours, etc.

For example, to add 10 seconds:

Date = {{2018,8,14},{13,10,25}}.
DateInSec = calendar:datetime_to_gregorian_seconds(Date).  % 63701471425
NewDateInSec = DateInSec + 10.                             % 63701471435
calendar:gregorian_seconds_to_datetime(NewDateInSec).      % {{2018,8,14},{13,10,35}}

For 10 minutes or 10 hours, just perform a little math:

Date = {{2018,8,14},{13,10,25}}.
DateInSec = calendar:datetime_to_gregorian_seconds(Date).  % 63701471425
NewDateInSec = DateInSec + (10 * 60 * 60).                 % 63701507425 (10 hours)
calendar:gregorian_seconds_to_datetime(NewDateInSec).      % {{2018,8,14},{23,10,25}}

To make life easier, I ended up creating a function to add additional time to (or subtract time from) an existing DateTime:

-type datetime() :: {{non_neg_integer(), pos_integer(), pos_integer()},
                     {non_neg_integer(), non_neg_integer(), non_neg_integer()}}.
-type timespan() :: {integer(), integer(), integer()}.

-spec add_time_to_datetime(datetime(), timespan()) -> datetime().
add_time_to_datetime(Date, {Hour, Min, Sec}) ->
    DateInSeconds = calendar:datetime_to_gregorian_seconds(Date),
    NewDateInSeconds = DateInSeconds + (Hour * 60 * 60) + (Min * 60) + Sec,
    calendar:gregorian_seconds_to_datetime(NewDateInSeconds).

SO Vault: What are some funny loading statements to keep users amused?

$
0
0
SO Vault: What are some funny loading statements to keep users amused?

StackOverflow sees quite a few threads deleted, usually for good reasons. Among the stinkers, though, lies the occasionally useful or otherwise interesting one, deleted by some pedantic nitpicker - so I resurrect them. 👻

Note: Because these threads are older, info may be outdated and links may be dead. Feel free to contact me, but I may not update them... this is an archive after all.


What are some funny loading statements to keep users amused?

Question asked by Oli

Nobody likes waiting but unfortunately in the Ajax application I'm working on at the moment, there is one fair-sized pause (1-2 seconds a go) that users have to undergo each and every time they want to load up a chunk of data.

I've tried to make the load as interactive as possible. There's an animated GIF alongside a very plain, very dull "Loading..." message.

So I thought it might be quite fun to come up with a batch of 50-or-so funny-looking messages and pick from them randomly so the user never knows what they're going to see. The time they would have spent growing impatient is fruitfully used.

Here's what I've come up with so far, just to give you an idea.

var randomLoadingMessage = function() {
    var lines = new Array(
        "Locating the required gigapixels to render...",
        "Spinning up the hamster...",
        "Shovelling coal into the server...",
        "Programming the flux capacitor"
    );
    return lines[Math.round(Math.random()*(lines.length-1))];
}

(Yes -- I know some of those are pretty lame -- That's why I'm here :)

The funniest I see today will get the prestigious "Accepted Answer" award. Others get votes for participation.

Enjoy!!

Comments

I wouldn't bother. Even if you can find 50 "funny" entries (the vast majority of suggestions so far have been overwhelmingly unfunny), they won't be funny the second time you see them. A progress bar would be more useful, perhaps with a "Tip of the Day" to provide actual helpful information. – Dan Dyer Oct 11 '08 at 11:38

Actually, you don't "program" a flux capacitor, you "charge" it. The difference may seem slight, but you'd definitely care if you suddenly found yourself in 1,000,000 BC instead of 2012 AD. Important safety tip. – Cyberherbalist Oct 13 '08 at 16:07

I love the "why the downvote" edit now that the net votes are +168 :-) – paxdiablo Jan 20 '09 at 8:07

... "waiting for the tubes to be unclogged..." – DeadHead May 8 '09 at 0:50

There are lot of them in World Of Goo! – TheVillageIdiot Jun 26 '09 at 4:05


Answer by Adam Rosenfield

The MIT campus map has a bunch of good ones:

(All loading messages are prefixed with "Please wait")

  • 640K ought to be enough for anybody
  • the architects are still drafting
  • the bits are breeding
  • we're building the buildings as fast as we can
  • would you prefer chicken, steak, or tofu?
  • pay no attention to the man behind the curtain
  • and enjoy the elevator music
  • while the little elves draw your map
  • a few bits tried to escape, but we caught them
  • and dream of faster computers
  • would you like fries with that?
  • checking the gravitational constant in your locale
  • go ahead -- hold your breath
  • at least you're not on hold
  • hum something loud while others stare
  • you're not in Kansas any more
  • the server is powered by a lemon and two electrodes
  • we love you just the way you are
  • while a larger software vendor in Seattle takes over the world
  • we're testing your patience
  • as if you had any other choice
  • take a moment to sign up for our lovely prizes
  • don't think of purple hippos
  • follow the white rabbit
  • why don't you order a sandwich?
  • while the satellite moves into position
  • the bits are flowing slowly today
  • dig on the 'X' for buried treasure... ARRR!
  • it's still faster than you could draw it

EDIT: MIT has since updated their campus map. The old map can still be found at archive.org, and the old loading messages can still be found here (for now).

Comments

checking the gravitational constant in your locale is the best! LOL! – Pablo Marambio Oct 9 '08 at 17:10

Please wait we're testing your patience. ... haha – chakrit Nov 7 '08 at 8:02

ha I used to work someplace where we did need to check the local gravitational vector, actually stored in a db indexed by lat/lon :). – Doug T. Dec 21 '08 at 17:32

"a few bits tried to escape, but we caught them" – Navneet Feb 23 '09 at 14:53

"we love you just the way you are." Aww...now I don't mind waiting. – Karmic Coder Sep 27 '09 at 18:46


Answer by Rob Allen

  • Do you suffer from ADHD? Me neith- oh look a bunny... What was I doing again? Oh, right. Here we go.
  • The last time I tried this the monkey didn't survive. Let's hope it works better this time.
  • Testing data on Timmy... ... ... We're going to need another Timmy.
  • I should have had a V8 this morning.
  • My other load screen is much faster. You should try that one instead.
  • The version I have of this in testing has much funnier load screens.

Comments

love the timmy one – helloandre Oct 9 '08 at 5:54

Upvoted for timmy. Also like the monkey one. :) – different Oct 10 '08 at 8:37

Man how long has it been since I even thought about Timmy :) thanks for the laugh. – Ron Tuffin Oct 10 '08 at 12:48

Just in case the "Timmy" stuff needs a reference: youtube.com/watch?v=FwVA698Hx2g – Rob Allen Oct 10 '08 at 14:45

AA for the Timmy one. I managed to miss that before. Almost had me on the floor in fits of giggles. – Oli Jan 16 '09 at 11:48


Answer by WebDude (Oct 08, 2008)

"Loading humorous message ... Please Wait"

Comments

You went meta on that – Varun Mahajan Oct 8 '08 at 14:19

For a long while my mailing list sig was "WARNING: SYSTEM FAILURE! Unable to insert amusing tagline." – Chris Upchurch Feb 8 '09 at 20:51

@Varun: Never go full meta. – delete Jun 4 '10 at 0:58

@delete: good advice with that username – sehe Jul 11 '11 at 14:46


Answer by AnthonyWJones (Oct 09, 2008)

Two animated gifs, one that runs twice as fast. A button that says 'Turbo Boost'. On click swap in the fast gif for a few seconds after which swap back and briefly display 'Turbo boost exhausted, click again to re-enable'. Reduce time enabled after each click.

Randomly introduce messages 'Are you sure this is helping?' and 'Must go faster, must go faster'.

Comments

making a game out of waiting is a great idea. – Karl Feb 8 '09 at 22:11

This one is really original – PRINCESS FLUFF Jul 24 '09 at 11:46

ROFL, this was the funniest and +1 for the originality. – Rakesh Juyal Oct 6 '09 at 12:43

Watch out, Namco might sue you for infringing on their minigames-during-loading-screens patent google.com/… – jsoverson Jan 15 '10 at 18:33

The Strike Commander CD-Rom-Edition featured a Breakout-like game during the rather lengthy loading times the single-speed-CD-Rom drives of its time in which you had to keep a spinning cd from falling of the bottom of the screen using a red line as paddle, controlled by the mouse. You only had one cd, so when it dropped of the screen, you had nothing left to do during the loading time. – sum1stolemyname Jun 9 '10 at 14:00


Answer by Matthew Scouten (Oct 08, 2008)

Loading Infinite Monkeys....
Monkey 1....................Loaded
Monkey 2....................Loaded
Monkey 3....................Loaded
Monkey 4....................Loaded
Monkey 5....................Loaded
Monkey 6....................Loaded
Monkey 7....................Loaded
Monkey 8.........

Comments

My favourite kernel panic message was "Enraged Monkey Error: Out of bananas! – Peter Wone Oct 11 '08 at 7:24

I just wonder when people start asking each other "How many monkeys have you got?" – phunehehe Feb 10 '10 at 12:50

There must be at least one dead monkey. – Moshe Revah Aug 2 '11 at 14:46

@Zippoxer: nonsense! you can avoid dead monkeys by mounting a scratch monkey. – Matthew Scouten Aug 4 '11 at 14:38


Answer by Peter Wone

Animate this:

Testing RAM..............OK
Testing CPU..............OK
Testing Primary Disk.....OK
Testing Patience.......FAIL

USER ERROR: OUT OF PATIENCE!

Comments

I'd say forget the out of patience error, just keep writing dots after testing patience indefinetly. – SpoonMeiser Oct 8 '08 at 15:10

You could omit the first three lines and just keep writing dots, as per SpoonMeiser's suggestion. :) – different Oct 9 '08 at 16:16

USER ERROR: OUT OF PATIENCE! Performing memory dump... – Cristián Romo Oct 17 '08 at 18:44

How about a shockwave animation of Clippy (the annoying paperclip from Office) tapping on the screen (complete with sound) and saying "It looks like you're running out of patience. Would you like to write a letter?" – Peter Wone Oct 23 '08 at 12:29

USER ERROR: OUT OF PATIENCE! Please wait while we submit error reports. – chakrit Nov 7 '08 at 8:05


Answer by Crippledsmurf (Oct 08, 2008)

Reticulating splines

Comments

see here stackoverflow.com/questions/182112/… – Jeff Atwood Oct 8 '08 at 11:56

Man, I miss those old Maxis games. – Electrons_Ahoy Oct 8 '08 at 17:03

You also get this message from the Mozy Backup Client... – Rik Heywood Dec 17 '08 at 12:04

SimTower was awesome! SimCity2000 best sim game ever IMHO! – Steve Tranby Jan 6 '09 at 0:38

+1 for SimTower and SimCity 2K :) Old maxis was the best. – maayank Aug 30 '09 at 20:05


Answer by seuvitor (Oct 08, 2008)

"Warming up Large Hadron Collider..."

Comments

Cooling down Large Hadron Collider – Matt Price Oct 8 '08 at 17:06

Dusting Large Hadron Collider. With a toothbrush. For a Barbie. – Ates Goral Oct 9 '08 at 1:15

Look up "Bose Einstein Condensate" in the context of powerful fluctuating magnetic fields. The LHC has such fields and is surrounded by 700 tonnes of liquid helium, which is a BEC. I'm not sure that's so funny. – Peter Wone Oct 9 '08 at 11:10

Opening hyperdimensional door... – Vinz Nov 27 '09 at 11:13

"Detecting presence of birds ............. DONE (NONE FOUND)" "Warming up LHC ......." – Nicholas Kreidberg Jan 15 '10 at 20:09


Answer by Snocrash

The NetPositive browser on BeOS had some great error messages! They were all written as Haiku and could be modified to suit your app or at least provide some inspiration:

http://www.8325.org/haiku/

  The web site you seek
  Lies beyond our perception
  But others await.

  Sites you are seeking
  From your path they are fleeing
  Their winter has come.

  A truth found, be told
  You are far from the fold, Go
  Come back yet again.

  Wind catches lily
  Scatt'ring petals to the wind:
  Your site is not found.

  These three are certain:
  Death, taxes, and site not found.
  You, victim of one.

  Ephemeral site.
  I am the Blue Screen of Death.
  No one hears your screams.

  Aborted effort:
  The site, passed this veil of tears.
  You ask way too much.

  Mourning and sorrow
  404 not with us now
  Lost to paradise.

  Not a pretty sight
  When the web dies screaming loud
  The site is not found.

  Site slips through fingers
  Pulse pounding hard and frantic
  Vanishing like mist.

  The dream is shattered
  The web site cannot be found
  Inside the spring rain.

  Bartender yells loud
  Your site cannot be found, boy
  Buy another drink.

  Chrome megaphone barks
  It's not possible to talk
  Not yet anyway.

  Emptyness of soul
  Forever aching blackness:
  "Blah.com not found."

  Click exciting link
  Gossamer threads hold you back
  404 not found.

  With searching comes loss
  And the presence of absence:
  The site is not found.

  You step in the stream,
  But the water has moved on
  The site is not here.

  Rather than a beep
  Or a rude error message,
  These words: 'Site not found.'

  Something you entered
  Transcended parameters.
  The site is unknown.

  Stay the patient course
  Of little worth is your ire
  The server is down

  There is a chasm
  Of carbon and silicon
  The server can't bridge.

  Chaos reigns within.
  Reflect, repent, and retry.
  Server shall return.

  Won't you please observe
  A brief moment of silence
  For the dead server?

  First snow, then silence.
  This expensive server dies
  So beautifully.

  Seeing my great fault
  Through darkening dead servers
  I begin again.

  Visit the home page
  It can't be done easily
  When the site is down.

  Cables have been cut
  Southwest of Northeast somewhere
  We are not amused.

  Site is silent, yes
  No voices can be heard now
  The cows roll their eyes.

  Silicon shudders
  The site is down for the count
  One big knockout punch.

  Yesterday it worked
  Today it is not working
  The web is like that.

  The ten thousand things
  How long do any persist?
  The file, not there.

  A file that big?
  It might be very useful
  But now it is gone.

  To have no errors
  Would be life without meaning
  No struggle, no joy

  Errors have occurred.
  We won't tell you where or why.
  Lazy programmers.

  The code was willing
  It considered your request,
  But the chips were weak.

  Error reduces
  Your expensive computer
  To a simple stone.

  Server's poor response
  Not quick enough for browser.
  Timed out, plum blossom.

  Login incorrect.
  Only perfect spellers may
  Enter this system.

Comments

I recall seeing this message somewhere: "A file of that type? / It might be very useful. / Here it will not work." – Michael Myers Feb 10 '09 at 16:46

Oh wow that really was the greatest thing I have ever read. – LegendLength Mar 19 '09 at 11:35

+1 just for the death and taxes one – Pops Jan 15 '10 at 18:53

I love haikus. Teary sniff. – cplotts Feb 9 '10 at 18:43

A lot of these are just sentences split unnaturally into "haiku", which actually requires a measure of 5-7-5 morae, not syllables. </pedant> – dreamlax Jun 4 '10 at 1:00


Answer by Zarkonnen (Oct 08, 2008)

How about randomly generating a phrase?

[verbing] [adjective] [plural noun]

And then have a small dictionary for each of these three slots: { "transglutinating", "fine-tuning" }, { "injector", "radiant" }, { "goatherd", "post-processor" }.

Comments

Do you know the Firefox plugin "Firesomething"? Brands each Firefox window with a new name - like Moongnu, Poweroyster etc. Sadly it's not available for FF 3 – Olaf Kock Oct 15 '08 at 7:26

Oh yes! I used to use that back in FF2. :D – Zarkonnen Oct 21 '08 at 11:33

heh, or "Im in ur [random]z, [random]ing ur [random]z!" – Svante Nov 3 '08 at 11:55

Make sure you figure out what the most inappropriate combination is before deploying :) – DiningPhilanderer Feb 27 '09 at 13:52

In soviet Russia [random noun] [random verb]'s YOU! – Crippledsmurf Jun 19 '10 at 0:42


Answer by slashnick (Oct 08, 2008)

"It looks like you're waiting for a website to load..."

Comments

this one made me irlol – thesmallprint Oct 10 '08 at 1:32

"... Can I help you with that?" – Dalin Seivewright Feb 8 '09 at 21:17

office2010themovie.com – jimmystormig Jul 16 '09 at 10:56

You should totally drop that and try ... – a_m0d Dec 1 '09 at 3:46


Answer by Dan Rosenstark

Sammyo's answer

Yes there really are magic elves with an abacus working frantically in here.

is the only way to be possibly funny every single time. You need ONE centralizing concept, like elves inside, and then you work with that.

This derives in:

  • Happy Elf and Sad Elf are talking about your data. Please wait.
  • All the relevant elves are on break. Please wait.

etc. etc. As long as there's one concept in there, the user will feel it's funny because they've "gotten it" and then you can go out on further and further tangents.

  • Elf down! We're cloning the elf that was supposed to get you the data. Please wait.

Comments

Heh, that's a nice concept. – Jonta Apr 25 '09 at 20:51

I like that concept there – Andrew Marsh Jul 21 '09 at 18:58

+1 I like the concept idea, and deriving the variations from it – KLE Sep 17 '09 at 13:35

Really, it's also how to be funny in a room full of people. – Dan Rosenstark Sep 17 '09 at 18:07


Answer by mdb

"Press Alt+F4 for a quick IQ test"

(this has the added bonus of being able to waste some time on making your loading messages User-Agent specific...)

Comments

If only I could do this without getting fired... – num1 Oct 29 '08 at 5:33

Ahh, Alt-H was the good old one for the Bulletin Board days with a 1200baud modem. That caught me out a couple times actually! – Carl Oct 29 '08 at 23:22

Talkers/Muds equivalent "type qu for quote of the day" <user has disconnected> – Chris J Nov 13 '09 at 23:18

@Jian Lin:cross platform only!M$ things are not OK. – Behrooz Jul 10 '10 at 17:51

This one is FUNNY !! – user279521 Aug 24 '10 at 14:37


Answer by Jeff Atwood

http://en.wikipedia.org/wiki/SimCity_2000

SimCity 2000 was the first sim game to feature the semi-nonsensical phrase "Reticulating Splines". Will Wright stated in an interview that the game does not actually reticulate splines when generating terrain; he inserted the phrase because it "sounded cool". The phrase has since been featured in SimCopter, SimCity 4 and The Sims, as well as being referenced humorously by a status message in Mozy, an off-site backup solution offered by EMC Corporation. It is also parodied in the game Spore which features the phrase "Reticulating Spines" in some of its loading screens.

Video clip of female voiceover from SimCity 2000

Comments

I remember first seeing it in SimCopter. I thought it was helicopter terminology. – Mark Cidade Oct 8 '08 at 21:22

Splines are also supposedly "reticulated" in the PS3 game "Tiger Woods Golf" while it creates a 3d model from a user-loaded photo, as part of the "Player Game Face" feature. – benjismith Oct 9 '08 at 17:00

The nice part of this one is that Mozy actually does reticulate splines when it does its change set calculations but nobody believes it. – reconbot Oct 13 '09 at 19:10


Answer by WaxEagle

Time is an illusion. Loading time doubly so.

Comments

Nice DNA reference, except, s/dually/doubly/ – Ishmaeel Oct 8 '08 at 13:04

fixed it. I couldn't remember which one it was. blasted English language. – wax eagle Oct 8 '08 at 13:14

I thought that was a Hitchhiker's reference. – Matt Ball Nov 17 '09 at 18:21

It is a Hitchhiker's reference. DNA was Douglas Noel Adams, the author. – TRiG Jan 15 '10 at 17:55


Answer by Chris Boesing

Maybe some recursion:

"Want to see a funny loading message? Take a look here"

Comments

DOH, now don't I feel stupid, I clicked the link and was like "WTF?" – UnkwnTech Oct 8 '08 at 11:08

It's funny because it's true, granted in my defense it is 4am, and I've not yet gone to bed, damn hobby projects. – UnkwnTech Oct 8 '08 at 11:11

HAhaha, THAT was funny! Im looking at u Unkwntech :P – Moulde Mar 18 '09 at 12:46

Aw crap. [I fell for it too] – mpen Mar 31 '09 at 5:02

This page looks awkwardly familiar ... – Valentin Flachsel Jun 24 '10 at 18:33


Answer by Greg

Futurama Rules! http://www.boston.com/news/globe/ideas/brainiac/futurama.jpg


Reconfoobling energymotron

Comments

You found my weak spot! Futurama reference gets the upvote :-) – Ferruccio Oct 14 '08 at 10:53

... or whatever. – Kevin Panko Jan 25 '10 at 19:30


Answer by Daniel Auger (Oct 08, 2008)

"Press play on tape."

Comments

Dammit - I'm old enough to get this. Good one. +1 – CAD bloke Oct 12 '08 at 11:48

Or similarly, "Please Turn to Side B and press Play" – enobrev Oct 26 '08 at 22:27

LOL. +1 I remember using those... and when it finally loaded you'd change your mind and choose another game. – Osama Al-Maadeed Nov 1 '08 at 6:56

+1. hahahahahah. I'm with the other oldies... – Mitch Wheat Dec 2 '08 at 15:29

+1 ... and don't forget the ,1 in ,8,1 :) – Skaldrom Y. Sarg Jan 23 '09 at 10:25


Answer by Codeslayer

Measuring the cable length to fetch your data...

Comments

Haha, you could add something like "One inch of cable length. Two inches of cable length. Three inches of..." – Jonta Mar 15 '09 at 13:26


Answer by Jeff B

  • Are we there yet?
  • Insert quarter
  • 1,000,000 bottles of beer on the wall...
  • Hang on a sec, I know your data is here somewhere
  • Well, what are you waiting for?
  • Are we there yet?
  • Have you lost weight?
  • Congratulations!
  • Are we there yet?

Comments

++ for the bottles of beer on the wall and hang on a sec – Jonta Mar 15 '09 at 13:28

+1 for "Insert quater" – Matthew Whited Jun 15 '10 at 17:48


Answer by Erik Forbes

"It is pitch black. You are likely to be eaten by a grue."


Answer by Unkwntech

"HELP!, I'm being held hostage, and forced to write the stupid lines!"

Comments

PS, I got this in a fortune cookie once. – UnkwnTech Oct 8 '08 at 11:12

Yeah, thought I heard this before – Pablo Marambio Oct 9 '08 at 17:13

Reminds me of Apple's Blue Meanies: "Help! Help! We're being held prisoner in a system software factory!" – LKM Oct 10 '08 at 7:28


Answer by BlaM

"Searching for Answer to Life, the Universe, and Everything"

Comments

Hitchhiker's Guide to the Galaxy eh? I like it. – Noah Goodrich Oct 8 '08 at 15:23

Count it up to 42 while doing it. – Daddy Warbox Oct 8 '08 at 21:30

...or show while waiting an animation of a white mouse in a running wheel ! – Tom Carter Oct 9 '08 at 10:39

"... please make sure you don't find the question" – Pablo Marambio Oct 9 '08 at 17:14

or... constantly count up to 41, wait a couple seconds, and then reset to 1. Repeat indefinitely. – Andrew Ensley Mar 26 '09 at 18:03


Answer by SpoonMeiser

"The gods contemplate your fate..."

Comments

Yes, although the quote might not be 100% accurate. – SpoonMeiser Oct 8 '08 at 15:08

"The Gods pause for a moment to contemplate your fate." Viva la DosBox! – Ishmaeel Oct 8 '08 at 16:47

That was a game! – ya23 Apr 5 '09 at 23:03

Was that from Nethack? – johnc Sep 28 '09 at 0:52

@lagerdalek, it was from Moonstone. – SpoonMeiser Sep 28 '09 at 12:07


Answer by Gene

  • Waiting for the system admin to hit enter...
  • Paging for the system admin...
  • Warming up the processors...
  • Reconfiguring the office coffee machine...
  • RE-calibrating the internet...
  • Your underwear has conflicted our DB. Please change daily.

Although not that original I really like this idea. I've been wating for a client that would let me use this kind of "features" for a while now. The possibilities are endless.

Note: not my native language so not sure about the spelling etc.

Comments

"Waiting for the system admin to hit enter..." is the best one in this thrad. – Oddmund Oct 15 '08 at 22:50


Answer by Slapout

"Program loaded. Please enter the square root of 598309209839 to continue."

"Press any key to continue" User presses a key. "NO! Not that key!"

Comments

++ for the second one. – Jonta Mar 15 '09 at 13:35

I've always preferred something along the lines of "Enter any 11 digit prime to continue:" – Dereleased Feb 15 '10 at 15:55

773 504.499, I google everything. – Behrooz Aug 15 '10 at 16:49

@Dereleased: And increase the 11 for every character the user types. Do not count down for deletions, but make sure you catch pasting. – Christopher Creutzig Feb 18 '11 at 12:15


Answer by Goran (Oct 13, 2008)

I'm up for a code-challange!

create table data
(
    word nvarchar(50) 
    ,type int
)

insert into data select 'recalibrating', 0
insert into data select 'excavating', 0
insert into data select 'finalizing', 0
insert into data select 'acquiring', 0
insert into data select 'locking', 0
insert into data select 'fueling', 0
insert into data select 'extracting', 0
insert into data select 'binding', 0

insert into data select 'flux', 1
insert into data select 'data', 1
insert into data select 'spline', 1
insert into data select 'storage', 1
insert into data select 'plasma', 1
insert into data select 'cache', 1
insert into data select 'laser', 1

insert into data select 'capacitor', 2
insert into data select 'conductor', 2
insert into data select 'assembler', 2
insert into data select 'disk', 2
insert into data select 'detector', 2
insert into data select 'post-processor', 2
insert into data select 'integrator', 2

select  top 1
    v.word as verb
    ,a.word as adjective
    ,n.word as noun
from    data v, data a, data n
where   v.type = 0
    and a.type = 1
    and n.type = 2
order by newid()

Comments

I wouldn't do that in SQL! (unless I have thousands of rows in each category) – Osama Al-Maadeed Nov 1 '08 at 6:58

let pick xs = fmap (xs !!) (randomRIO (0, length xs-1)) in mapM pick [ [ "recalibrating", "excavating", "finalizing" ], [ "flux", "data", "spline" ], [ "capacitor", "conductor", "assembler" ] ] – luqui Nov 23 '08 at 7:35

wasn't this something from BOFH? – Geo Jul 14 '09 at 11:06

it needs 'repolorizing' – Jeremy Aug 6 '09 at 13:05


Answer by Carl Seleborg

  • Waiting for Godot...
  • Please don't move...
  • Working... no, just kidding.
  • Working... hey, come back here!
  • Working... So, how are you?
  • Behind you! Ha, ha, gotcha!
  • Please count to 10...
  • Are your shoelaces tied?
  • Exercise: enumerate your shopping list as quickly as possible
  • Working... unlike you!
  • Working... well... you know...
  • Doing something useful...
  • null
  • Oh, yeah, comments! Good idea!

Ok, that's it for this time.

Comments

Do you have a bit of rope? – Eric Oct 28 '09 at 13:35

Up vote for "null" :P – yuudachi Mar 9 '11 at 19:09

Upvoting for Godot. – Mechanical snail Aug 3 '11 at 8:44


Answer by badp

  • Why so serious?
  • Er, there is something on your teeth.
  • Are you ready?
  • Prepare for awesomeness!
  • It's not you. It's me.
  • Ouch! Careful where you point that thing!

Comments

Prepare for awesomeness. Hihi – Jonta Mar 15 '09 at 13:30

+1 "Why so serious?" – Nader Shirazie Jul 1 '09 at 4:59


Answer by Boldewyn

While you're waiting, how about a little riddle for you? scalar Navier-Stokes equation http://upload.wikimedia.org/math/1/7/0/17038a0582e8b4b7f1adf55f6393a097.png

Explanation to spoil the party: This is the scalar Navier-Stokes equation, that is related to the Navier–Stokes existence and smoothness problem, which in turn is one of the Mathematics' Millenium Prize Problems.

The above mentioned 'riddle', however, is nonsense without further explanation.

Comments

Pun? It's a joke of some sort, but I wouldn't call it a pun. – TRiG May 6 '11 at 14:36

That's true. I'll update the answer. – Boldewyn May 6 '11 at 18:28


Answer by Daniel H (Oct 13, 2008)

I have a game that gives you tips when loading; there are certainly tips that you could put, unless your application is extremely straightforward. GMail puts tips under the inbox, for example; I'd read them if it put them in the loading messages. Get two things done at once: don't make your users uselessly wait AND make sure they can get things done faster. Now that I think about it, there isn't a single program I can think of that has a loading screen that shouldn't have tips there.


Answer by Jus12 (Oct 10, 2010)

"Go get a coffee or something. This is going to take a while."

Comments

I actually use coffee mug image for this purpose. :) – Vishwanath Jan 9 '11 at 14:54

"please stop staring at the completion bar. It is embarrasing me". – Jus12 Jul 12 '11 at 20:59


Answer by FryHard (Oct 08, 2008)

"Communing with nature"

"Spinning the wheel of fortune"

Dare I suggest "I'll be back"

Pick a few more famous movie lines....


Answer by poisonplant (Oct 08, 2008)

Cybernet loading self awareness....please be patient;

Starting missile launch sequence in 10, 9...;

Increasing speed to 88.8mph;


Answer by s d (Oct 08, 2008)

Checking prime directives...

  • "Serve the public trust"
  • "Protect the innocent"
  • "Uphold the law"
  • (Classified)

Comments

+1 (Classified) – epochwolf Jun 9 '10 at 17:50


Answer by idean (Oct 09, 2008)

Rewinding the DVD...


Answer by Cyberherbalist (Oct 13, 2008)

"Please wait...time not important; only life important."

Fifth Element


Answer by aib

The bits in [] are optional. Alternatively, they can show up after some time:

Waking up the AI... [Error: COFFEE_BIT not set]

Starting [sub]pixel analysis...

Loading loading messages...

Trying to give priority back to actual processing from the loading message handler...

This is a haiku
Your content is now loading
Be patient, will you?

Comments

only if be pat-i-ent please or be pat-ient puh-lease – johnc Oct 8 '08 at 23:36

It's hard to do this in a non-phonetic language like English. s/please/will you/ as necessary. – aib Oct 12 '08 at 0:07


Answer by chakrit (Nov 07, 2008)

The internet is full... Please wait...


Answer by Kevin Bomberry

Reading GoF, please wait...
Hello Clarice.
Good evening, Clarice.
I just ate your data with some fava beans and a nice chianti.
Closer, please. Clo-ser...
I like you. But I need you to be more than just eye candy around here.
Stupidity isn't a virus... but it sure is spreadin' like one!
About your data... I lost it... in a volcano.


User, n. The word computer professionals use when they mean "idiot." -- Dave Barry
Jesus saves! The rest of us better make backups. -- Anonymous
"To go forward, you must backup."
"The more I C, the less I see."
"The Internet: where men are men, women are men, and children are FBI agents."
"I'm not anti-social; I'm just not user friendly"
"1f u c4n r34d th1s u r34lly n33d t0 g37 l41d"
"Like car accidents, most hardware problems are due to driver error."
"It is easier to change the specification to fit the program than vice versa."


INITIALIZING UNIX COMMANDS:
unzip...
strip...
touch...
finger...
mount...
fsck...
more...
yes...
unmount...
sleep...
...READY.

Comments

hahahaha! +1 for the 1337 – The WebMacheter Apr 14 '11 at 17:35


Answer by Pops (Jan 15, 2010)

I can't believe that in nine pages of answers, nobody has said

Please be patient. The program should finish loading in six to eight weeks.


Answer by this. __curious_geek (Feb 10, 2010)

"Loading the Loading message.."


Answer by Secko

Just a few ideas:

  • Loading the enchanted bunny...
  • Please wait while this nice progress bar fills to 100%...
  • Let me tell you a joke, two CPUs walk into a bar...
  • Greetings Earthling!
  • I know this is painful to watch, but I have to load this.
  • Go get a cup of coffee or something... (after a while) Did you get it yet!?
  • Go read a book, I'm nearly finished.
  • Oh, no! Loading time...
  • Really sorry, it needs work I know...
  • Buy more RAM...
  • Loading screen... If you can see this then it's already loaded.
  • Starting in 0...1...2...n...
  • Hello!!! Why did you click that button?!
  • Kicking Mort from Madagascar! Please wait...
  • Busing through the motherboard, will arrive soon...
  • Hello this is the CPU: The first core and the second core are working! What!? You got a third core...

Answer by Johan Bresler (Oct 08, 2008)

Sorry my binaries are swapped, busy re-sorting them now....


Answer by Anders (Oct 08, 2008)

"Computing chance of success"


Answer by fmsf

The traditional line: "Loading a virus, please relax while your life's work is being deleted..."

Comments

I also wouldn't use that one due to obvious reasons... – BlaM Oct 8 '08 at 11:31


Answer by Steven A. Lowe (Oct 08, 2008)

Centralizing the processing units...

Randomizing memory access...

I think, therefore I am...loading!

I'm sorry Dave, I can't do that


Answer by Zing- (Oct 08, 2008)

Very funny Scotty. Now beam down my clothes.


Answer by Leanan

Rolling for initiative...
Attacking the darkness...
Making will save...

Comments

Haha, i love it, by far one of the best (if a D&D fan ) – mattlant Oct 10 '08 at 8:15


Answer by Chris Latta (Oct 09, 2008)

Searching for the Amulet of Yendor

Preparing for hyperspace jump

Slaying a Balrog

Going to DEFCON 1

Searching for the... OMG, what the heck is THAT doing there?

Comments

+1 for Yendor reference – johnc Sep 28 '09 at 1:02


Answer by user27476 (Oct 13, 2008)

"Waiting for magic to happen..."

But a serious question: is one or two seconds enough time to appreciate a funny message? In my highly subjective opinion, a too-short wait with a message that isn't obviously "loading, please wait" makes it look like you're popping up an important message and the user is missing it. I'm not suggesting you increase the wait time for the messages, though that could be an interesting thought experiment (what's better, two seconds+boring message or ten seconds+interesting message)


Answer by Christian Madsen (Jan 15, 2010)

99 bottles of beer on the wall

Changes to

99 bottles of beer

Changes to

Take one down and pass it around, 98 bottles of beer on the wall

Changes to

98 bottles of beer

And so on... Did someone already write this answer? With 9 pages already and too little time, I was too lazy to check.

Comments

If you want to see it for yourself, 99-bottles-of-beer.net – t0mm13b Jan 25 '10 at 19:24

Great. That eases implementation a lot :) – Christian Madsen Jan 29 '10 at 9:26

How about just changing it to 99 bottles every time? After a while: "(This loading message may be buggy. But the computer is actually computing stuff! Honest! I think...)" – Jonta Apr 12 '11 at 9:53


Answer by mattlant (Oct 08, 2008)

"Please wait while the punch tape loads..."


Answer by Fake Jim (Oct 08, 2008)

Accommodating poor back-end SQL query. Please wait...

Comments

LOL, funny cause it's likely true. – J c Oct 13 '08 at 11:54


Answer by willasaywhat (Oct 08, 2008)

Just use a line from Portal's "Still Alive", bonus points for audio:

"This was a triumph

I’m making a note here: huge success

It’s hard to overstate my satisfaction

Aperture Science

We do what we must because we can

For the good of all of us

Except the ones who are dead

But there’s no sense crying over every mistake

You just keep on trying till you run out of cake

And the science gets done and you make a neat gun

For the people who are still alive"

Or the ever wonderful, "Code Monkey" by the same artist, Jonathon Coulton:

"Code Monkey get up get coffee

Code Monkey go to job

have boring meeting with boring manager Rob

Rob say Code Monkey very diligent

but his output stink

his code not functional or elegant

what do Code Monkey think

Code Monkey think maybe manager want to write goddamn login page himself

Code Monkey not say it out loud

Code Monkey not crazy just proud"


Answer by Groxx (Oct 09, 2008)

Computing 6 x 9...

Comments

Estimated time to completion: 10 million years. Please wait. – Joe White Jul 1 '09 at 4:29


Answer by An̲̳̳drew (Oct 09, 2008)

Waiting for more electricity...


Answer by Federico A. Ramponi (Oct 10, 2008)

Ravaging drive C: ......... done.
Ravaging drive D: ......... done.

Answer by Oli (Oct 13, 2008)

Saw this on a stock webapp the other day

Shorting to afford data transmission


Answer by Irwin (Oct 13, 2008)

Loading: one Mississippi Loading: two Mississippi Loading: three Mississippi


Answer by cllpse (Oct 15, 2008)

On data-load: "Making stuff up. Please wait...".


Answer by Brent Baisley (Apr 25, 2009)

  • Searching for the Any key...
  • Searching for answers...
  • Looking for exact change...
  • Giving it all of got...
  • It's around here somewhere...
  • Stretching first. I don't want to pull a muscle.
  • Paper or plastic?
  • Calculating the odds...
  • Look! Over there -> ->

Answer by nopole (May 20, 2009)

"Downloading the whole Internet. Please wait..."


Answer by codymanix (May 26, 2009)

Testing RAM..............OK
Testing CPU..............OK
Testing Primary Disk.....OK
Testing USER IQ........................
Fail: IQ INSUFFICIENT TO RUN THIS PROGRAM
Aborting!

Comments

Insulting your user is never a good idea. – Fusyion Aug 3 '10 at 14:46

Having users with lack of humour is also a sad thing :) – codymanix Aug 3 '10 at 14:50

This is just insulting. Not humorous. Testing USER PATIENCE maybe – CodeFusionMobile Aug 18 '10 at 20:19


Answer by An̲̳̳drew (Jun 04, 2010)

That that exists exists in that that that that exists exists in.

Comments

I don't get it... – nathanchere Jun 4 '10 at 1:12

I do. +1.......Wherever you go, there you are. – Robert Harvey Jun 4 '10 at 3:04

Buffalo Buffalo Buffalo Buffalo Buffalo Buffalo Buffalo Buffalo. – new123456 Jun 2 '11 at 17:27


Answer by Nathan L Smith (Sep 23, 2010)

Just use the BOFH excuse server: http://pages.cs.wisc.edu/~ballard/bofh/bofhserver.pl

Comments

Yeah, those were really funny; But what was asked for was loading statements - not "unknown error" replacements. But you'll get a +1 from me anyway ;) – Frank Oct 7 '10 at 1:57


Answer by Masterofpsi (Jan 29, 2011)

Not my personal idea, but the sheer number and ridiculousness of the little tidbits here always amazed me.


Answer by Rik (Oct 08, 2008)

Please pick your your nose and look disinterested at the screen...
Thank you!


Answer by user7094 (Oct 08, 2008)

Hmmm, on a Futurama style theme, I've always wanted to say something like this:

"Let this abomination unto the Lord begin"


Answer by Johan Bresler (Oct 08, 2008)

Just taking the doggy for an urgent walk...please be patient!!


Answer by tloach (Oct 08, 2008)

To speed up process turn crank attached to computer.


Answer by sammyo (Oct 08, 2008)

Press the Any key to continue.

No not that one, the "Any" key.

Ha ha, gotcha again.


Answer by Lee Crabtree (Oct 08, 2008)

Charging capacitors to 1.21 jiggawatts...
Initializing loading message database...
Entertaining possibility of continuing...


Answer by rotw (Oct 08, 2008)

Some lame ones:

  • The loading screen is a lie.
  • Houston, we have a... oh, hi. All fine here.

Answer by Yaba (Oct 10, 2008)

Anno 1701 (a real time strategy game) has some funny messages:

  • Salting Sea Water
  • Hiding Treasures
  • Filling up Mountains
  • Creating Weather Forecast ....

Comments

They're rather specific to the game, though. Anno 1404 has some new ones, by the way. – OregonGhost Jun 11 '10 at 13:46


Answer by Guano (Oct 10, 2008)

"Time is relative.."


Answer by Cat Plus Plus (Oct 22, 2008)

"Resistance is futile. Prepare to be assimilated."


Answer by Henri Hein (Oct 24, 2008)

Klingons on the starboard bow.


Answer by Mike Hofer (Jan 06, 2009)

Insufficient disk space. Reformatting drive C: to allocate space...


Answer by Simon Hartcher (May 08, 2009)

World Of Goo has some pretty funny loading statements. Here is some that came up when I loaded just then:

Image: World Of Goo Loading Screen


Answer by David Plumpton (May 20, 2009)

There's always the Unix fortune program

Comments

And the -o flag. – new123456 Jun 2 '11 at 17:28


Answer by Zaid Amir (Oct 28, 2009)

Please Wait...

Please Wait Some More...

You're Still Waiting, Right?

You still there?...

Hello...

Oh there You are...

Still Waiting... huh

Dum dada dee dum dada...

Am bored, gonna look through your stuff.

hmmm, found Kernel32.dll

scanning kernel32.dll

kernel32.dll is useless. Deleting...

Ta Da... oh wait am not done yet.

Comments

+1 for gonna look through your stuff, our client would panic :) – medopal Dec 20 '09 at 10:54

should add a "Ha! Just kidding!" after that deleting thing :p – Svish Jan 12 '10 at 12:40


Answer by z-index (Aug 27, 2010)

Are you bored? Me too.

Waiting for something in the server.

Have you considered another ISP?

I'm tired, please be patient.


Answer by Anonymous (Oct 08, 2008)

Nowadays I'd rather frighten users by mentioning RIAA, not viruses :)

Something like "scanning your hard drive for pirated movies"


Answer by Powerlord (Oct 08, 2008)

Contacting HAL9000 for authorization... I'm sorry Dave, I'm afraid I can't do that.


Answer by plinth (Oct 08, 2008)

  1. Spinning up gerbil wheel
  2. Mounting a scratch monkey
  3. Counting an infinite number of monkeys
  4. Stretching an owl
  5. Buying the world a Coke

Answer by void (Oct 08, 2008)

Waking up your lazy processor.

Having a quick byte to eat ...

I'll be with you in a bit ...


Answer by Flupkear

"Baking cake..."

“Look behind you, a Three-Headed Monkey!”

Comments

LOL! Great quote from Monkey Island! – Andrea Ambu Feb 8 '09 at 21:01


Answer by J.J. (Oct 08, 2008)

"Drink and be merry for tomorrow this site may load"

"Et tu RAM"

"This site is like a box of chocolates, you never know what page is gonna load."

"Don't press back ... pretty please"

"All your web browser are belong to us"

Comments

Ohh ya and. "If you load it; they will wait" – J.J. Oct 8 '08 at 20:35


Answer by Mark Stock (Oct 09, 2008)

  • Preprocessing...
  • Parsing...
  • Compiling...
  • Coffee time!
  • Linking...

Comments

If I ever get to write a compiler for something, I think I'll insert this. – OregonGhost Jun 11 '10 at 13:58


Answer by MikeJ (Oct 09, 2008)

Sorry. Our server is a few bytes short of a file...

Don't throw out that cat! Get me some pliers quick...

Waving the rubber chicken over the server. please wait...

This page brough to you by the Letter Q...

Come to Ralph's Wonder Lama Emporium....


Answer by Mez (Oct 09, 2008)

"brb, need to pee"


Answer by Dynamo (Oct 10, 2008)

The MMORPG Everquest uses a bunch of these while the game loads up. A few favorites of mine are:

Warning. Half Elves are now 49.99999 Elf....

and this:

Hitting your keyboard won't make this faster....


Answer by dar7yl (Oct 11, 2008)

  • histone sequence acetylated
  • chromatin decondensed
  • pol II loaded
  • transcription commencing
  • transcription paused
  • transcription resumed
  • transcription completed
  • post transational editing
  • commencing intron splicing
  • completed messenger export
  • start codon recognized
  • translation and polypeptide synthesis commencing
  • stop codon detected
  • post-transational configuration
  • protein transport
  • enzymic reaction
  • product synthesis
  • product complete

Answer by Martin (Dec 02, 2008)

"Calculating meaning of life...."

Then at completion flash up 42.


Answer by Zorantula (Dec 02, 2008)

I once did something like this for the initial test version of an integration tool which would display its results in XML. The tool would take anywhere from 1 to 5 seconds or more (mostly depending on the speed of the database(s) being connected to) and I would display the following in the results field while the tool was processing:

<?xml version="1.0" encoding="utf-8"?>
<Arrrrrrrrrrrrrr:SearchForDoubloons xmlns:Arrrrrrrrrrrrrr="http://en.wikipedia.org/wiki/Pirate">
    <Arrrrrrrrrrrrrr:EatChineseFood>
        <FoundDoubloons>No</FoundDoubloons>
        <FoundFortuneCookie>
            <FortuneSays>That special someone loves to see the light in your eye.</FortuneSays>
        </FoundFortuneCookie>
    </Arrrrrrrrrrrrrr:EatChineseFood>
</Arrrrrrrrrrrrrr:SearchForDoubloons>

Each time it ran it would draw a different fortune from a list of real fortune cookie fortunes.

This was very well received by everyone, but removed once the tool "matured".


Answer by The Alpha Nerd (Dec 21, 2008)

Firing up the hyperspace quantum overdrive...


Answer by mvrak (Feb 02, 2009)

Oops... I accidentally the whole system.


Answer by Godcode (Mar 27, 2009)

...main screen turn on

...we get signal

...fpsajfsa;kjfa;ldsfsaf9237497498274sfj;lsafkjakfdsj

...what happen?

...what!

...How are you gentlemen !!

...All your base are belong to us.

...You are on the way to destruction.

...You have no chance to survive make your time.

...You know what you doing.

...Ha ha ha ha....

...Page was beginning...


Answer by Zan Lynx (Mar 27, 2009)

  • Loading Data
  • Verifying Data
    • Data checksum verified
    • Unpacking
    • Release the hounds
    • Data found in tree
  • Verifying User
    • Press any key
    • User is paying attention
    • User is sentient
    • User IQ > 80
    • or
    • User IQ < 80
    • Enable vegetable mode

Answer by Schildmeijer (Apr 25, 2009)

"Bending the spoon..."


Answer by Kelly S. French (Jan 15, 2010)

Out Of Cheese Error! Mr. Jelly! Mr. Jelly

Comments

+++ REDO FROM START +++ – TRiG Jan 18 '10 at 21:29


Answer by Paul D. Waite (Jun 08, 2010)

Not exactly funny, but Stephen Fry’s iPhone/iPad app (‘Fry Paper’ — now that’s funny) presents this text:

Just clearing my throat...

when loading, which seems nicely in keeping with Stephen Fry’s persona.


Answer by TimFoolery (Jan 27, 2011)

Creating VB GUI Interface...

Hitting the keyboard may lock up the system... but the printer is fine.

This would go faster if I had opposable thumbs...

I spy something green...

If you need to go to the bathroom, do it now... I don't want to stop later.

Remember back when you smoked? At least you always had something to do.

  • Warning: The internet is a dangerous place.
  • Only about half of its content is true.
  • Proof that Al Gore is the man behind it?
  • We think so.

The series of tubes is a bit congested... the city's got some plumbers working on it right now.

Ah, ah, ah, you didn't say the magic word!

  • PINGING SERVER... SERVER OK!
  • SCANNING FOR VULNERABILITIES...
  • OVERLOADING SERVER RPC STACK...
  • INJECTING ROOTKIT...
  • DOWNLOADING CREDIT CARDS... PLEASE WAIT.
  • CREDIT CARD THEFT SUCCESSFUL.

Comments

That first one is not funny, the application I work on has some truth here, in VB6! – benPearce May 29 '11 at 12:10


Answer by e-satis

Could be worse... Hotlines make you pay for it.


Answer by Henry B (Oct 08, 2008)

"Computer shutting down in ..."

"Please wait whilst your harddisk is erased ..."

"How did I get sucked in to writing out silly loading lines?"


Answer by Philip Reynolds (Oct 08, 2008)

... we're holding our sausage hostage... please be patient...


Answer by hangy (Oct 08, 2008)

  • "BRB"
  • "BBIAB"

Answer by James (Oct 08, 2008)

Please wait a moment, deciphering your intentions...


Answer by fmsf (Oct 08, 2008)

Illegal software found on your hard drive! Never mind it's a photo of Chuck Norris...


Answer by Jaap Coomans (Oct 08, 2008)

Please wait... Rebooting the Internet

Taking the red pill...


Answer by Treb

  • Hey, why did you click this button? You woke me up!!!
  • Let me think about this...
  • Please try to click a little softer, that mouse pointer is pointed!
  • Gotcha, boss! Going right at it!
  • Will do. In the meantime, can you prepare me a cup of tea?

And for the traditionalists: 'Hello, Dave!' HAL9000 http://flowstate.homestead.com/files/hal9000.gif


Answer by Throknor (Oct 08, 2008)

Locating infinite improbability drive...

Disengaging Genuine People Personalities Protocol for your sanity...


Answer by Esteban Brenes (Oct 08, 2008)

For anyone who played Everquest this might be familiar:

"Teaching Snakes to Kick"


Answer by Kip (Oct 08, 2008)

"Contemplating the meaning of life"


Answer by nwahmaet (Oct 08, 2008)

"The longer it takes me, the better it will be for you"


Answer by Robert Rouse (Oct 08, 2008)

"I have experience with [insert random program on system]. I can see [program] from my directory."


Answer by ykaganovich (Oct 08, 2008)

alt text http://www.gifs.net/Animation11/Creatures_and_Cartoons/Cartoons_Simpsons/Itchy_and_Scratchy_2.gif

Comments

I like animations like this, if loading doesn't take long. There may be copyright issues though on a commercial website. – OregonGhost Jun 11 '10 at 13:57


Answer by Ryan Delucchi (Oct 08, 2008)

Searching for an external observer required to conduct Turing Test ...


Shared with attribution, where reasonably possible, per the SO attribution policy and cc-by-something. If you were the author of something I posted here, and want that portion removed, just let me know.


The MOST EVER usefullest Docker commands (as determined by some guy on the internet)

$
0
0
The MOST EVER usefullest Docker commands (as determined by some guy on the internet)

After taking my first look at Docker and then playing around with building images, I've now progressed into other proprietary work stuff, so... won't be sharing that on here. I like having a job.

That being said, I'll just make note of any useful commands I come across this week. As much for me as you!

Creation

  • Create an image from a Dockerfile: docker build .
  • Create a container from an image (run in bkgd): docker run -d <image hash>
  • Interact with running container: docker exec -it <container hash> bash
  • Create a container and interact with it: docker run -it <image hash>

Status

  • View images: docker images
  • View containers: docker ps or docker container ls
  • View all containers (including stopped ones): docker ps -a

Removal

(Layers of) images are the blueprint for the application you'd like to run, while containers are an instance of an image. You can spin up multiple containers for a given image, and each container is separate.

Containers

  • Stop all containers: docker stop $(docker ps -a -q)
  • Remove stopped containers: docker rm $(docker ps -a -q)
  • Kill all containers (even running ones): docker rm -f $(docker ps -a -q)

Images

  • Remove image (unless a container or another image exists that's based off it): docker rmi $(docker images -q)
  • Force removal: docker rmi -f $(docker images -q)

Can I use background.html and background.js in the same Chrome extension?

$
0
0
Can I use background.html and background.js in the same Chrome extension?

tl;dr - No, pick one.

Alright, thanks for stopping by! Have a great rest of th....

What?

Oh, you expected a better explanation than that? Point taken, you probably ended up here because of an error, and not just randomly. Well, you're only allowed to specify either an array of scripts...

"background": {
    "persistent": false,
    "scripts": [ "jquery-1.2.3.js"]
}

... or a page, which can then reference the script(s) the page needs:

"background": {
    "persistent": false,
    "page": "background.html"
}

Your "background.html" page might be nothing else other than the same list of scripts you could specify in the "scripts" array, but the reason you'd usually choose an HTML page over a list of JS files is because you intend to add something else to it.

To each their own I guess.

<html>
    <head>
    <script src="jquery-1.2.3.js"></script>
    <script src="anotherscript.js"></script>
    <script src="whynotonemore.js"></script>
    </head>
    <body></body>
</html>

But if you try to specify both (which hopefully you've now realized is completely unnecessary), the extension just won't load:

The background.page and background.scripts properties cannot be used at the same time. Could not load manifest.

The command “eval git fetch origin +refs/pull/8/merge:” failed

$
0
0
The command “eval git fetch origin +refs/pull/8/merge:” failed

Like any decent dev shop, we employ continuous builds for our projects. I even use it for one-off projects like GhostSharp, to make sure any code I'm committing compiles correctly (when applicable) and that the tests all pass (always applicable).

Awhile back, I got an unexpected error from a Travis CI build that threw me a bit. It was trying to build my branch, for which there had been a PR, but it failed:

The command "eval git fetch origin +refs/pull/8/merge:" failed 3 times.

The full trace of the error was similar to this:

$ git fetch origin +refs/pull/8/merge:

fatal: Couldn't find remote ref refs/pull/8/merge
Unexpected end of command stream
The command "eval git fetch origin +refs/pull/8/merge:" failed. Retrying, 2 of 3.

fatal: Couldn't find remote ref refs/pull/8/merge
Unexpected end of command stream
The command "eval git fetch origin +refs/pull/8/merge:" failed. Retrying, 3 of 3.

fatal: Couldn't find remote ref refs/pull/8/merge
Unexpected end of command stream
The command "eval git fetch origin +refs/pull/8/merge:" failed 3 times.

The command "git fetch origin +refs/pull/8/merge:" failed and exited with 128.

Your build has been stopped.

What I eventually realized was that Travis CI (apparently) kicked off the job based on the PR that I had created against the branch (the pull/8 part in the above error), and I had just merged the PR into master. The branch wasn't deleted, but the PR was merged and closed.

Unfortunately, it was quite a while ago and I can't remember exactly what I did to fix it, but I either reopened the PR through GitHub and kicked off a build, or just kicked off a build against the (still-open) branch manually.

SO Vault: What are Code Smells? What is the best way to correct them?

$
0
0
SO Vault: What are Code Smells? What is the best way to correct them?

StackOverflow sees quite a few threads deleted, usually for good reasons. Among the stinkers, though, lies the occasionally useful or otherwise interesting one, deleted by some pedantic nitpicker - so I resurrect them. 👻

Note: Because these threads are older, info may be outdated and links may be dead. Feel free to contact me, but I may not update them... this is an archive after all.


What are Code Smells? What is the best way to correct them?

Question asked by Rob Cooper

OK, so I know what a code smell is, and the Wikipedia Article is pretty clear in its definition:

In computer programming, code smell is any symptom in the source code of a computer program that indicates something may be wrong. It generally indicates that the code should be refactored or the overall design should be reexamined. The term appears to have been coined by Kent Beck on WardsWiki. Usage of the term increased after it was featured in Refactoring. Improving the Design of Existing Code.

I know it also provides a list of common code smells. But I thought it would be great if we could get clear list of not only what code smells there are, but also how to correct them.

One smell per answer, please.

Comments

DO NOT add rules to your question. DO be grateful that people attempt to answer at all :) – OJ. Sep 22 '08 at 11:47

The rules are there to try and help improve the quality of the thread and stop people typing before thinking. You will thank me later when you have a thread you can use as a resource. I am always grateful for input :) – Rob Cooper Sep 22 '08 at 11:50

The FAQ doesnt cover things like this. Im trying to provide a thread that others will find useful. For that we need to a little bit of control. And it worked. People have been great, we have some great answers that are readable and offer solutions. Job done. I am no one, but my plan was a success. – Rob Cooper Sep 22 '08 at 18:53

Btw, the correct response to a smell is to hunt for the kinds of mistake it heralds, not to remove the smell. The treatment for gangrene is not deodorant! – Steve Jessop Sep 24 '08 at 0:01

I think you risk doing exactly that with a "fix the symptom" approach. The question should be "what was wrong with my thinking when I wrote this, that I decided it was a good idea?", not "I've broken a rule: if I change the code to obey the rule then it's fixed". – Steve Jessop Sep 27 '08 at 17:47


Answer by onnodb

Huge methods/functions. This is always a sure sign of impending failure.

Huge methods should be refactored into smaller methods and functions, with more generic uses.

See also these related questions on SO:


Answer by Stefan Rusek

Commented out code. I realize that this one is a lot of people favorite thing to do, but it is always wrong.

We are in an age when it is easy to setup a source code versioning system. If code is worth keeping, then check it in, it is saved now and forever. If you want to replace it with a new version delete it:

  • The old version will be around if you need it.
  • Commented out code makes code hard to read since it still looks like code, and takes up the same space as real code.
  • After a few changes to the original code, the commented out version is way out of date

I once saw a function that had over a hundred lines of commented out code, when I removed the commented out code, it was only 2 lines long.

Sometimes we comment out code during debugging and development. This is OK, just make sure to delete it before it is checked in.


Answer by Geoffrey Chetwood

Duplicate or copy/pasted code. When you start seeing things that could easily be reused that aren't, something is very wrong.

Refactoring to make reusable assemblies is the only cure.

See the Once and Only Once principle, and the Don't Repeat Yourself principle.

Simian, a code similarity detection tool works wonders for fixing this.

duplo is a good open source project that provides a free alternative.


Answer by TraumaPony

Methods with a ridiculous (e.g. 7+) amount of parameters. This usually means that there should be a new class introduced (which, when passed, is called an indirect parameter.)


Answer by TraumaPony

Avoid abbreviations.

Variable names such as x, xx, xx2, foo etc (obviously if you are using Cartesian coordinates, 'x' is perfectly appropriate.) Rename.


Answer by bcash

Empty catch blocks. Especially if the exception being ignored is java.lang.Exception/System.Exception.

If a block of code could throw multiple exceptions, there should be multiple catches. Each handling the appropriate exception accordingly.

An empty catch might mean the developer doesn't have an understanding of logic in the try, and the empty catch was added to pass the compiler. At the very least they should contain some kind of logging logic.


Answer by Gamecat

Comments that focus on what the code does and not why. The code tells you what it does (okay, there are exceptions, but that is another smell). Try to use the comment to explain why.


Answer by Mark Stock

Pacman ifs

nested ifs

if (cond1) {
    /* Something */
    if (cond2) {
        /* Something else */
        if (cond3) {
            /* Something else, again */
            if (cond4) {
                /* Something else, again */
                if (cond5) {
                    /* Something else, again */
                    if (cond6) {
                        /* Something else, again */
                        if (cond7) {
                            /* Something else, again */
                            if (cond8) {
                                /* Something else, again */
                                if (cond9) {
                                    /* Something else, again */
                                    if (cond10) {
                                        /* Something else, again */
                                        if (cond11) {
                                            /* Something else, again */
                                            if (cond12) {
                                                /* Something else, again */
                                                if (cond13) {
                                                    /* Something else, again */
                                                    if (cond14) {
                                                        /* Something else, again */
                                                        if (cond15) {
                                                            /* Something else, again */
                                                            if (cond16) {
                                                                /* Something else, again */
                                                                if (cond17) {
                                                                    /* Something else, again */
                                                                    if (cond18) {
                                                                        /* Something else, again */
                                                                        if (cond19) {
                                                                            /* Something else, again */
                                                                            if (cond20) {
                                                                                /* Something else, again */
                                                                                if {
                                                                                    /* And goes on... */

a severe stench emanates when a horizontal scroll bar appears


Answer by John Ferguson (Sep 23, 2008)

Magic numbers

If code has lots of numbers all the way through it will be a pain to change them and you may miss something. Those numbers might be documented or commented, but comments and code can very easily get out of sync with each other. When you next read the code will you remember what the number means or why it was chosen?

Fix this by replacing the numbers with constants that have meaningful names. But don't make the names too long. It's up to you whether to import these constants from another file or limit them to the immediate scope.

Similarly for excessive amounts of string literals in the code, either use well-named constants or read them from a resource file. This can also aid internationalisation/translation efforts.


Answer by aku

Not being able to understand what given piece of code does in less than 15 seconds

99 chances out of 100 that this code is wrong. Either it's too complicated or just badly engineered.

Cure:

Find the code author, make him to explain what the darn code does until he starts to cry "I wrote it yesterday, how can I remember what it does?! I would never write such code again! I promise!!!"

Alternate cure:

Refactor to make the code plain. Everything has a good name.


Answer by John Kugelman

Huge code blocks in switch statements. Move code to separate functions. Consider using a function table (dictionary).


Answer by Jason

Reusing Variables

Using the same variable to mean different things in different parts of the same thing, just to save a couple of bytes on the stack (or even just because you couldn't be bothered declaring a new variable). It's very confusing - don't do it!
Declare a new variable - the compiler is smart enough to place them in the same memory location for you if their uses don't overlap.

Example

var x = value;
if (x > y) doSomething();

x = someOtherValue;
if (x == 'Doh') doSomethingElse();

Answer by Coincoin

Premature optimization

If you read application level code littered with bit shifts instead of multiplication, and similar optimization tidbits, consider educating the author about the tradeoff between optimization and readability.


Answer by paul

Getting and re-getting the same property.

e.g.

if(getValue() != null && getValue().length() > 0 
    && !getValue().startWith("Hugo") ...)

Who knows what is going on inside getValue()? Could be something costly.

I would prefer:

String value = getValue();
if(value != null && value.length() > 0 
    && !value.startsWith("Hugo") ...)

Edit

I would agree with those commentators who say leave it up to the JIT to optimise the call. This will work in most cases. However, this became a bit of a problem for me in a framework where some getters did not simply pick up a property but in fact performed a hash table lookup or even disk or network action (can't remember which now). I guess the JIT can't do much there.

My point is that you don't always know what the getter does. Perhaps a naming convention such as getX for properties and fetchX for other actions might help. I just think getting/fetching a value once and then working with a copy of the value avoids the problem (unless you really know what is going on in the getter, of course)


Answer by Manrico Corazzi

Overengineered design

This is common when introducing ten thousands frameworks and then handling everything indirectly, even for very simple chores.

So you have an ORM and a MVC framework, and several different layers in your application: DAO, BO, Entities, Renderers, Factories, at least a couple of contexts, interfaces crawl all over your packages, you have adapters even for two classes, proxies, delegate methods... to the point that there isn't even a single class which does not extend or implement something else.

In this case you'd better prune some dead branches: remove interfaces wherever they don't provide useful class interchangeability, remove man-in-the-middle classes, specialize too generic methods, throw in some generics/templates where you wrote your own classes that are only wrappers for collections and don't really add any value to your design.

NOTE: of course this does not apply to larger, ever changing applications where the layers and the intermediate objects are really useful to decouple stuff that otherwise would be handled by shotgun surgery.


Answer by Peter Mortensen

Negatives

They are a burden on the human mind.

Double negatives

I ran into a piece of code such as:

if( ! value != 1 )

Quite confusing to read! I suspect the original programmer was debugging and changing the logic made the program work; however was too lazy to properly change to:

if( value == 1 )

Else is a negative

When you see else you have to mentally negate the original condition. If the original condition already includes a negative, then you have to work extra hard. Negate the condition and swap the conditional clauses.

If the else clause is the "happy path", i.e. the non- error case, then your brain has to work to follow the flow of code. Use Guard Clauses instead.

Single negatives

Even single negatives require mental effort. So it's easier to read:

if (IsSummer())

than

if (!IsWinter())

Also


Answer by Jim d

Methods with unexplained boolean arguments

Methods with boolean boolean arguments tend to hurt readability. A common example I've seen is the following:

 myfile = CreateFile("foo.txt", true);

In this example, it's reasonable to assume that this snippet creates a file called "foo.txt", but we have no idea what the "true" means. However, if the snippet was instead:

 myfile = CreateTempFile("foo.txt");

You'd have a much better idea of what the coder intended. With that in mind, it's generally a good idea to break up methods with boolean arguments into two methods. So that

 File CreateFile(String name, boolean isTemp);

becomes

 File CreateFile(String name);
 File CreateTempFile(String name);

You can also get arround this by creating an enum:

myFile = CreateFile("foo.txt", FileType.Temp);

Answer by Rasmus Faber

Static variables or the design patterns variant: Singletons

How to refactor:

  1. Find the largest scope in which the variable lives, and move it there as a non-static variable (if it is a singleton, convert it to a non-singleton and make an instance to pass around).

  2. You should now get lots of compile errors (missing reference to the static variable/singleton). For each one, decide whether it makes best sense to inject the reference as a instance member in the class (either in the constructor, if it is a mandatory dependency, or in a setter-method, if it is an optional dependency) or to pass the reference in the method-call. Make the change. This will probably propagate outwards until you reach the outer scope where the variable now lives.

A dependency injection framework, such as Guice, can make this easier. The DI framework can be configured to create only one instance of the class and pass it as a constructor parameter to all classes which use it. In Guice you would annotate the singleton class with @Singleton and that would be it.


Answer by aku

Presence of types whose names start\end with "Utility", "Helper" or "Manager"

This is a very good sign of presence of types violating SRP (Single Responsibility Principle).

Analyze such types carefully, Often you can find that single class contains a bunch of unrelated methods - split it. Sometimes you can find that some method is used only once (often happens after refactoring), consider purge such methods.


Answer by ΤΖΩΤΖΙΟΥ

Inconsistent naming of variables, methods, functions etc (mixing CamelCase with hpwsHungarian with everything_separated_with_underscores)


Answer by Rasmus Faber

Just a general comment about code smells:

Both of my answers have received several comments like this: "But sometimes XX is the right thing to do" or "If you always replace YY with ZZ you are going to end up with an overengineering pile of ...".

I think these remarks mistake the meaning of a code smell: a code smell is not the same as an error - if they were, we would probably just make the compiler find them and return an error.

A code smell is nothing more than something that suggests that here is a possible refactoring. Smells may be more or less strong, and it is usually impossible to make hard and fast rules about them.

Sometimes a method with six arguments may be the best solution, I don't think I would like a method with seven arguments, but I would oppose a coding standard that forbid them. In some applications, a static variable might make perfect sense, but I wouldn't like that a large application hid its entire internal dependency structure in a big clump of static variables.

To summarize: code smells are simple heuristics that indicate that you might want to consider refactoring and suggest a possible appropriate refactoring.


Answer by Kyralessa

Primitive Obsession

Always using "int" and "double" where you should have a class such as "Money" or "OrderValue" so that you can apply different logic or rounding. It also ensure method parameters are better structured.

string is the most common object of such obsession.

...

Judging by the comments, an example is called for. Here's one I saw a couple weeks ago.

We have an application that processes Word document content. All through our app, we had string parameters that took file paths to those documents. We found a bug in one place where, due to a poorly-named parameter, we were passing in a file name rather than a file path, causing the app to look for the file (and not find it) in the default application path.

The immediate problem was the poorly named parameter. But the real problem was passing strings around. The solution was to use a class like this:

public class FileLocation
{
    readonly string fullPath;

    public FileLocation(string fullPath)
    {
        this.fullPath = fullPath;
    }

    public string FullPath
    {
        get { return fullPath; }
    }
}

Your first reaction may be that this is a class that hardly does anything. You're right; but that's not the point. The point is that now instead of

public void ProcessDocument(string file)

we have

public void ProcessDocument(FileLocation file)

As long as we're constructing FileLocation objects correctly in the one place that generates them, we can pass them through the rest of the app with no worries, because now we can't possibly confuse them with file names, or directories, or any other type of string. This is the most fundamental reason to correct primitive obsession.


Answer by hlovdal (Oct 21, 2008)

Smell: Testing of "normal" code instead of exceptions.

Problem: The "normal operation" or most commonly/naturally executed code is put inside if bodies or attached as an else body to some error checking.

Solution: Unless it is impossible or there is a very good reason for not to, always test for exceptions and write your code so that the normal case is written without any extra indentation.

Examples:

void bad_handle_data(char *data, size_t length)
{
        if (check_CRC(data, length) == OK) {
                /*
                 * 300
                 * lines
                 * of
                 * data
                 * handling
                 */
        } else {
                printf("Error: CRC check failed\n");
        }
}

void good_handle_data(char *data, size_t length)
{
        if (check_CRC(data, length) != OK) {
                printf("Error: CRC check failed\n");
                return;
        }
        /*
         * 300
         * lines
         * of
         * data
         * handling
         */
}

void bad_search_and_print_something(struct something array[], size_t length, int criteria_1, int criteria_2, int criteria_3)
{
        int i;
        for (i=0; i<length; i++) {
                if (array[i].member_1 == criteria_1) {
                        if (array[i].member_2 == criteria_2) {
                                if (array[i].member_3 == criteria_3) {
                                        printf("Found macth for (%d,%d,%d) at index %d\n", criteria_1, criteria_2, criteria_3, i);
                                }
                        }
                }
        }
}

void good_search_and_print_something(struct something array[], size_t length, int criteria_1, int criteria_2, int criteria_3)
{
        int i;
        for (i=0; i<length; i++) {
                if (array[i].member_1 != criteria_1) {
                        continue;
                }
                if (array[i].member_2 != criteria_2) {
                        continue;
                }
                if (array[i].member_3 != criteria_3) {
                        continue;
                }
                printf("Found macth for (%d,%d,%d) at index %d\n", criteria_1, criteria_2, criteria_3, i);
        }
}

Rule of thumb: Never test the normal case, test exceptions.


Answer by Norman Ramsey (Dec 07, 2008)

Treating Booleans as magical, unlike other values. When I see

if (p)
  return true;
else
  return false;

I know I'm seeing a rookie coder and prepare myself accordingly. I strongly prefer

return p;

Answer by seanb (Sep 23, 2008)

Testing a bool for equality with true

bool someVar
....
if(someVar == true)
{
   doStuff();
}  

The compiler will probably fix it, so it doesn't represent a huge problem in itself, but it indicates that whoever wrote it struggled with, or never learnt the basics, and your nose should be on extra high alert.


Answer by NotJarvis

Any thread which depends on a sleep(n) call where n is not 0 (to release other threads).

For an example of why - see here: http://www.flounder.com/badprogram.htm#Sleep

Basically - the time you set for a sleep(n) call can always be wrong.

To avoid this sort of thing, coders should be using a more "waitFor a specific event" structure than "sleep for some arbitrary time waiting for other things" which nearly always can be wrong...


Answer by chickeninabiscuit

More of a pet peeve: not conveying role when naming variables.

For example:

User user1;
User user2;

instead of:

User sender;
User recipient;

Also, expressing a role with respect to the wrong context. Class attributes should be named with respect to their class.

Method parameters should be named with respect to their role within the method NOT the role of the passed arguments with respect to the calling code.


Answer by Sam Wessel (Sep 22, 2008)

Inappropriate Intimacy

When classes access each other's fields or methods too much.

Some suggestions how to refactor/avoid:


Answer by moobaa (Sep 22, 2008)

Comments that precede code such as the following:

// The following is a bit hacky, but seems to work...

...or...

// Quick fix for <xxx>

Answer by Rasmus Faber

Switch statements

Switch statements might be okay, but they are a smell that shows you should consider using inheritance or a State or Strategy pattern.

One example: (obvious, but I have seen something like this several time):

switch(GetType().ToString())
{
  case "NormalCustomer":
    // Something
    break;
  case "PreferredCustomer":
     // Something else
    break;
}

A bit less obvious:

switch(this.location.Type){
  case Local:
    // Something
    break;
  case Foreign:
    // Something else
    break;   
 }

How to refactor

  1. Move the switch to a separate method.

  2. Do you already have an appropriate inheritance hierarchy?

    2a. If you do, you might only need to move the individual case-statements to individual subclasses.

    2b. If not: introduce inheritance - either directly, or by using the State- or Strategy-pattern.

Edit: I am not arguing that you should replace all switches with polymorphism. Only that switches are a place where you should ask yourself whether polymorphism might make the code simpler. If replacing the switch would make the code more complex ("overengineered"), just don't replace it.


Answer by ilitirit (Sep 22, 2008)

In languages that support OO, switching on type (of any kind) is a code smell that usually points to poor design. The solution is to derive from a common base with an abstract or virtual method (or a similar construct, depending on your language)

eg.

class Person
{
    public virtual void Action()
    {
        // Perform default action
    }
}

class Bob : Person
{
    public override void Action()
    {
        // Perform action for Bill
    }
}

class Jill : Person
{
    public override void Action()
    {
        // Perform action for Jill
    }
}

Then, instead of doing the switch statement, you just call childNode.Action()


Answer by TraumaPony (Sep 22, 2008)

Catching exceptions in the same method that threw them. This can indicate that exceptions are being used for control flow, which is a big no-no. Use a break or goto instead.


Answer by Vilmantas Baranauskas

Not directly code, but it smells when VCS log messages are empty or has such pattern:

"Changed MyClass.java.".

Fix: write useful comments telling why the change has been done, not that it was done.

E.g.: "Fixed bug #7658: NPE when invoking display of user."


Answer by Shane Miskin (Sep 22, 2008)

Steve McConnell's book "Code Complete: A Practical Handbook of Software Construction" is essentially a 900 page answer to this question. It's an outstanding book.

http://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670


Answer by Adam Pierce (Sep 23, 2008)

Dumb comments or comments which are not updated when the code changes:

// Check all widgets (stops at 20 since we can never
// have more than 20 widgets).
    for(int i = 0; i < 55 && widget[i]; i++)
        processWidget(widget[i]);

Answer by AviD

Reinventing the wheel.
For instance, I love doing code reviews and finding some brand-spanking-new shiny version of 3DES. (Happens more often than you'd think! Even in JavaScript!)
"Whaaat? We MUST encrypt the CC/pwd/etc! And 3DES is SOOO easy to implement!" It's always a challenge to find the subtle flaws that make their encryption trivially breakable...

How to correct it - quite simply, use the platform provided wheels. Or, if there is REALLY an ACTUAL reason not to use that, find a trusted, reviewed module already built by somebody who knows what he/she was doing.
In the above example, almost every modern language provides built-in libraries for strong encryption, much better than you can do on your own. Or you could use OpenSSL.
Same goes for other wheels, don't make it up on your own. It's stinky.


Answer by Ticex

Large Classes

Large classes, that have more than one responsibility. Should then be separated.


Answer by aku (Sep 22, 2008)

Presence of GOTO statement.

Usually it means that either algorithm too complicated or function control flow is screwed.

No general practice unfortunately. Each case should be analyzed individually.


Answer by Apocalisp (Sep 22, 2008)

Excessive Inheritance

Many newcomers to object-oriented programming immediately pick up on the idea of inheritance. It's intuitive because it is superficially isomorphic to the way we organize concepts into hierarchies. Unfortunately, it's often the case that this is the only abstraction that they end up using, so you end up with class hierarchies like:

Buzz
  BuzzImpl
    FizzBuzz
      BatchFizzBuzz
        BatchFizzBuzzWithFoo
        BatchFizzBuzzWithBar
        BatchFizzBuzzWithNeitherFooNorBar
      FizzBuzzThatSendsEmail
    BuckFizzBuzz
      BuckFizzBuzzWithFoo
...etc.

To fix, use composition rather than inheritance. Instead of having FizzBuzz inherit from Buzz, have it take a Buzz in its constructor.


Answer by torial

Can't believe this hasn't been provided: high cyclomatic complexity for a method/function. Anything over 20 (with some exceptions like dispatcher methods) should have functions extracted out.

Source Monitor is an excellent tool for gathering source code metrics like this.


Answer by Vilmantas Baranauskas (Sep 28, 2008)

Unused variables or fields.

Remove them. There are helper tools (different IDEs, checkstyle, etc.) which may inform you if you have some.


Answer by Özgür (Mar 23, 2009)

This is from "Practical Common Lisp"

A friend of mine was once interviewing an engineer for a programming job and asked him a typical interview question: how do you know when a function or method is too big? Well, said the candidate, I don't like any method to be bigger than my head. You mean you can't keep all the details in your head? No, I mean I put my head up against my monitor, and the code shouldn't be bigger than my head.


Answer by Nathan Long (Sep 22, 2008)

Variable Scope too large.

Global variables make it hard to keep track of which function modified something and when.

Refactor so that variables exist only within a function. Functions should pass information to each other via arguments and return values.


Answer by Gord (Sep 23, 2008)

Using magic numbers for return values.

int orderID = DAL.GetOrderIDForUser(1);

if(orderID == -1) 
    ShowNoOrdersPage();
else
    ShowOrder(orderID);

It is just a matter of time before you end up with a -2 or -3.


Answer by 18Rabbit (Sep 23, 2008)

Putting in a "temporary" fix.

Temporary fixes have a funny way of becoming permanent because you never seem to have the time/inclination/memory to go back and fix them.

If you're going to fix something, fix it the right way the first time.

If it seems like it will be a huge undertaking to change it then maybe you need to re-evaluate why it needs to be changed. If it's unavoidable that it must be changed then put in the best fix that you can in the time allotted and assume that it will be permanent (because it will be).


Answer by Vilmantas Baranauskas (Sep 22, 2008)

Wrong spelling of class and method names. Look up in a dictionary if not sure or use plugin in your IDE to check spelling for you.


Answer by MusiGenesis

Gratuitous (unnecessary) use of multithreading.

I've taken over many multithreaded applications, and I never needed a code smell to know there was a problem. Multithreaded applications are usually incredibly unreliable, and fail frequently in impossible-to-reproduce ways. I can't count the number of times I've seen an application start the execution of a long-running task on a separate thread, and then go into polling mode on the main thread (usually using Thread.Sleep(n)) and wait for the long-running task to complete.


Answer by Camilo Díaz

With database access

String concatenation, specially used for giant prepared SQL-statements, when there are lines like:

String select = "select ..."
// Lots of code here
select += "and c.customer_id = ? "
select += "and da.order_id in (?, ?, ?)"

And worse, then tracking the position of the index:

preparedSt.setInt(++cnt, 15);
preparedSt.setString(++cnt, 15);

With objects properties

Repeatedly accessing beans or value objects properties like this:

customer.getOrders().get(0).getPaymentDetail().getAmount();

In very simple boolean logic

Seeing nested 'ifs' like this when single-level if's or a switch statement will suffice:

if (cond1) {
    /* Something */
} else {
    if (cond2) {
        /* Something else */
    } else {
        if (cond3) {
            /* Something else, again */
        } else {
            /* And goes on... */
        }
    }
}

Using two boolean variables to refer to a simple, unique condition, that can be deduced just by one of them:

boolean finished, nextIsPending;
if (task.isRunning()) {
    finished = false;
    nextIsPending = true;
}

Answer by orj

Classes or structs with lots of member variables.

A class or struct with more than about a dozen member variables probably hasn't been correctly factored into sub-components/classes.

eg:

class Person
{
    string Name;
    string AddressLine1;
    string AddressLine2;
    string AddressLine3;
    string Addressline4;
    string City;
    string ZipCode;
    string State;
    string Country;
    string SpouseName;
    string ChildName1;
    string ChildName2;
    string ChildName3;
    int Age;
    // and on and on and on
}

Should be:

class Address
{
    string[] AddressLines;
    string ZipCode;
    string State;
    string Country;
}

class Person 
{
    string Name;
    Address Address;
    Person Spouse;
    Person[] Children;
    int Age;
}

And this is just one contrived example.


Answer by tzot (Sep 22, 2008)

for index 0 to len-1 style looping over a list in languages where iterators exist.


Answer by keparo

Code Smell (noun)

This is a general criticism of poorly written or poorly designed software.

Example usage: "I was disappointed when I saw the source code. Everything basically works, but that code smells".

There are a lot of reasons why software might qualify as "smelly". People have listed quite a few specifics here.. Things like having overly complicated data structures, global variables and goto statements. But while these are all symptoms of smelly code, the truth is that there isn't a hard and fast rule. In programming, any specific problem could be solved a handful of ways, but not every answer is as good as the next.

Some basic principles

We value code that is easy to read. Most programmers will probably spend the majority of their time reading and editing existing code, even if it is code that they wrote themselves.

Along the same lines, reusable code is also considered valuable. This doesn't mean that code is copied and pasted.. It means that code has been organized into a logical system, allowing specific tasks to be performed by the same piece of code (with maybe just a few differences each time, like a value in each calculation).

We value simplicity. We should be able to make single changes to a program by editing code in one place, or by editing a specific module of code.

We value brevity.

Smelly code is hard to read, hard to reuse, hard to maintain, and is fragile. Small changes may cause things to break, and there is little value in the code beyond its one time use.

Code that simply "works" isn't very difficult to write. Many of us were writing simple programs as teenagers. On the other hand, a good software developer will create code that is readable, maintainable, reusable, robust, and potentially long-lived.


Answer by aku (Sep 22, 2008)

C# specific: use of ref keyword.

Often makes program behavior unclear and complicated, can cause unpredicted side effects.

Consider returning new value rather than modify existing one i.e. instead of:

void PopulateList(ref List<Foo> foos);

use

List<Foo> GetListValues();

Answer by John (Apr 22, 2009)

Magic Strings

I've seen Magic numbers mentioned here more than once and I wholeheartedly agree. One often overlooked smell I haven't seen mentioned is Magic Strings.

Example:


public string GetState()
{
  return "TN";
}

Solution:


public string GetState()
{
  return States.TN;
}

Always be weary of code that is working with hard coded string data just as you would with hard coded numeric data. Consider making the string a constant variable with a comment explaining what it represents as a minimum. There is a really good chance that this should actually be in an Enumeration.

Side note: It's not technically a smell but it greatly annoys me to see something like this as well:


if(0 == foo)
{
  DoSomething();
}

Answer by aku

Returning more data that needed

Example:

List<Foo> Foos; // returns List<T> to provide access to List.Count property

Often this leads to misuse of data structures and unwanted data modifications.

Consider providing as much data as needed.

IEnumerable<Foo> Foos;  // Returns iterable collections of Foos.
int FooCount; // Returns number of Foo objects.

Answer by Coincoin

Excessive use of code outlining

It's the new big. People use code outlining to hide their behemoth classes or functions. If you need any outlining at all to read your code, it should be a warning sign.

Consider the following:

  • Extract all types into their own file
  • Refactor the main class until it's small enough
  • You can use the partial keyword (C#), or any equivalent mechanism, in cases where you have to implement a lot of interface methods, or expose a lot of events

Answer by MrZebra (Sep 22, 2008)

Overuse of casting

Lots of casting between (potentially) unrelated types makes it difficult to tell what type variable pointed to actually is, and is usually a sign that someone is trying to be too clever with memory usage. Use a union if you really want to do this.


Answer by JohnMcG

Smell: Operator overloaded to perform a non-intuitive function. e.g. operator^ used to convert a string to uppercase.

Problem: Very likely clients will use it incorrectly.

Solution: Convert to a function with a sensible name.


Answer by GEOCHET

This answer was marked as spam or rude or abusive and is therefore not shown - you can see the revision history for details.

Answer by Norman Ramsey

Comments often make code smell. Steve McConnell said it before me, but

  1. Comments on functions and code can almost all be eliminated by choosing names and types well.
  2. Comments on data are often helpful. Beginners can be told to comment every type definition and variable declaration. This is overkill but is a good rule of thumb and is way better than commenting code.
  3. Even better comments are just ones that describe the representation invariants of data and say what abstraction the data is intended to represent.
  4. If the representation invariant is not completely trivial, the best documentation is an internal function which validates that the data actually satisfy the representation invariant. Good example: ordered binary trees. Better: balanced, ordered binary trees. In this case you write the code to check the invariant and the comment just says that every value of the given type satisfies the invariant.

Summary: strive to move information from comments into code!


Answer by Pascal T. (Sep 22, 2008)

The first wiki ever (http://c2.com) has a lot of stuff about refactorings and code smells.

http://c2.com/cgi/wiki?CodeSmell

This is my main source of information about refactorings.


Answer by Manrico Corazzi

Conditional spree

Complex behaviour implemented by intricated if...then...elseif... blocks or long switch...case copy/pasted all over the class(es).

Suggested refactoring: Replace Conditional with Polymorphism.

NOTE: overusing this strategy is also "code smell".

NOTE2: I love the Kent Beck quotation from one of his books on Extreme Programming.

If it smells change it (Grandma Beck on childrens rearing).

(or something like that, I don't have the book handy right now).

EDIT: For a comprehensive list have you considered this post on Coding Horror?


Answer by Robert Paulson

Too Many [out] Parameters (.NET)

When a method contains out parameters, especially when there are more than one out parameter, consider returning a class instead.

// Uses a bool to signal success, and also returns width and height.
bool GetCoordinates( MyObject element, out int width, out int height )

Replace with a single return parameter, or perhaps a single out parameter.

bool GetCoordinates( MyObject element, out Rectangle coordinates )

Alternatively you could return a null reference. Bonus points if the class implements the Null Object pattern. This allows you to get rid of the boolean as the class itself can signal a valid state.

Rectangle GetCoordinates( MyObject element )

Further, if it makes sense, have a specialised class for the return value. While not always applicable, if the return value is not a simple true/false for success then it may be more appropriate to return a composite of the returned object plus state. It makes caller's code easier to read and maintain.

class ReturnedCoordinates
{
  Rectangle Result { get; set; }
  CoordinateType CoordinateType { get; set; }
  GetCoordinateState SuccessState { get; set; }
}

ReturnedCoordinates GetCoordinates( MyObject element )

Admittedly overuse of this can lead to further bad smells.

A Good [out] Pattern

Note that [out] parameters are still useful, especially in the following Tester-Doer pattern.

// In the Int32 class.
bool TryParse(string toParse, out int result)

this is far more efficient than

// BAD CODE - don't do this.
int value = 0;
try 
{
    value = int.Parse(toParse);
}
catch {}

when you expect the input string toParse is probably not valid.

Summary

In many cases, the presence of any [out] parameters indicates a bad smell. Out parameters make the code harder to read, understand, and maintain.


Answer by aku

Checking for file existence before trying to access it (instead of I/O error handling).

Common error of novice programmers. Instead of handling I/O exceptions, they check file for existence.

Forget about File.Exists-like methods unless you use files as markers\locking objects. Always handle file I/O errors when trying to read/write some meaningful data.


Answer by akf

Side-effecting getters:

public Object getMyObject() {
     doSomethingThatModifiesSomething();

     return myObject;
}

Answer by John Cocktoastan

In C#, invoking GC.Collect repeatedly, for any reason. This is a serious pet-peeve for me, and is almost always indicative of "Let the garbage collector handle it!" syndrome.

Yes, in C# we have a garbage-collector. No, it doesn't make up for messy allocation/deallocation logic.

To correct: disable the GC.Collect code, use perfmon, CLR memory counters, and find those leaks. Make sure that dispose is implemented properly, and called properly.

Use "using" statements whenever possible. Refactor if necessary to make "using" statements work for you.

They call it a self-tuning garbage collector for a reason, trust it to do it's job properly.


Answer by Georgi

Trying to be more precise in an error case by parsing the error message.

I often saw something like

try {
    File f = new File("anyfile.txt");
    if(file.isDirectory()) {
        throw new IOException("File is a directory!");
    }
    file.open();
}
catch(IOException ex) {
    if(ex.getMessage().indexOf("File is a directory")>=0) {
        System.out.println("The file is a directory!");
    }
    else if(ex.getMessage().indexOf("File does not exist")>=0) {
        System.out.println("The file does not exist!");
    }
} 

The strange thing is, if you change the error message, the behavior of the code will change ;-)

How to avoid:

Split the code-block and react to the errors individually. More to type but definitely worth it.


Answer by rjurney (Sep 23, 2008)

Exception handling blocks which say only:

/* We are SO SCREWED! */


Answer by RodgerB

Smell: Long lines of code

My definition of a long line of code (because I'm a .NET developer), is any line of code that requires a horizontal scroll bar to be viewed in the editor in Visual Studio (without collapsing the toolbox or the Solution Explorer pane). The developer should visualise the poor programmer working at a low resolution, with a seemingly never ending horizontal scroll bar.

Example:

Dim cn As New SqlConnection(ConfigurationManager.ConnectionStrings("DatabaseConnectionString").ConnectionString)

Solution: Use New Lines

Break up your code into appropriately sized pieces, not bite sized, not generous, but just right.

Example:

Dim cn As New SqlConnection( _
ConfigurationManager.ConnectionStrings("DatabaseConnectionString") _
.ConnectionString)

Answer by smirkingman (Oct 30, 2010)

Negated booleans.

Wrong:

Dim NotReady as Boolean
...
If Not NotReady Then

Right:

Dim Ready as Boolean
...
If Ready then

Answer by aku

Inconsistent enum members.

I know 2 variations of this problem:

  1. enum members that actually belong to different domains (good example is .NET BindingFlags).

  2. Tricky enum members:

    enum MathOp
    {
     Plus,
     Minus,
     Empty
    }
    

This often happens when enum values used in UI.

Cure:

  1. Group enum values into different logically related enums.
  2. Don't mix logic and presentation

Answer by Brian G

How about code without indentation. I seen a friend of mine with a master's degree write software without indentation and using variables like x, x2 and y. He actually applied to a position at Microsoft and sent them a code sample like this. How fast do you think they tossed it in the garbage???

Code is for humans to read.

Please indent.

What would you do if you received un-indented code as a part of an interview?


Answer by cHao (Oct 29, 2010)

Printing "Your password may (only|not) contain the characters...". Ever. Ditto for comments and most other non-key text fields. The existence of such restrictions is a sure sign that the data is being mishandled somewhere, unless the code is just preemptively being a pain in the user's ass.

To fix:

  • If you restrict user input, there should be a valid business reason why. "Preventing SQL injection/XSS/some-other-bug" is not a valid reason; if you're having that problem, then you're handling the data wrong. Read up on escaping and/or quoting and/or prepared statements, and apply what you read. Properly.
  • Hash passwords. (Once they're hashed, it doesn't matter what the original chars were.)

Answer by Nazgul (Sep 22, 2008)

Lot of static methods

This means that those methods do not belong to the class in which they are. So move them to a relevant class.


Answer by MrZebra (Sep 22, 2008)

Overuse of meaningless variable names

If you see a function that has lots of variables like "a, b, c, x, y, z", it can indicate that the function's logic was poorly thought out. Clear variable names tend to show that the author has a more clear understanding of the operation of the function, and also assist the reader's understanding. It should be refactored by renaming the variables to something more descriptive.


Answer by Robert Paulson

Reassigning Parameters in Method Body

Reassigning parameters in the method body is a bad smell. It's a source of confusion and can be a source of errors when the code is edited later.

Was the programmer trying to alter the caller's reference, or were they just lazy and unimaginative? Was it a mistake?

void Foo( MyClass x )
{
  if( x.SomeProperty ) ....

  // ...    
  if( someCondition ) { // yuck!
     x = new MyClass(); // reassign's local reference x, parameter x is lost
  }

  // ...
  DoSomething(x); // which x should this be?
}

To fix, create a new variable, or consider refactoring such that reassignment is not necessary.


Answer by Khainestar

Assumptive code.

Code that assumes something has happened before it, or assumes that a value has been set. I know some compilers like to tell you about it but I have seen this very widespread in PHP in particular. An example.

if ( $foo == 'bar' ) {
    $bar = true;
}

if ( $bar ) {
    // code...
}

This becomes a huge problem when poor structure doesn't create objects. Then later code starts using the objects, or worse someone directly sets values into an object that doesn't exist and PHP helpfully creates a standard object, with the value in it. So later checks for is_object return true.

Solution.

If you are going to start using an object make sure that it actually exists.

$object->foo='bar';

Will create an object but it won't be the object that you think it is. Accessors are there for a reason. Use them when ever possible. This also removes the problem of assuming something is there to use as the script will error out and then it has to be fixed.


Answer by Wix (Jan 09, 2009)

A common thing I see with new programmers is having 20 includes at the top of a header file. I found that the developer is trying to do too much in one class/file (depending on language) or they are calling everything in an assembly to simply use one object/method/whatever in it.


Answer by Osama ALASSIRY

I hate it when I see code like this:

if (a==b){
  //Do This
  if (c==d) {
    //Do That
  }
  else
  {
    //Something Else
  }
}
else
{
  //Do This Again
  if (c==d) {
    //Do That Other Thing
  }
  else
  {
    //Something Else Again
  }
}

especially if most of the code is common between the cases.

it looks much nicer if we convert the code to separate functions instead of copy paste, and write something simpler like:

dothis();
if (c==d) 
    if (a==b) dothat() else dothatotherthing();
else
    dosomethingelse();

All we need to do is analyze the logic, and simplify the code. encapsulating code in small functions with descriptive names is always a good thing to do.


Answer by Khainestar (Apr 14, 2009)

Another one that has raised its head lately. Three state booleans. Yep you heard me right, three state booleans. Database fields set to be a boolean but allow null. So you can get true, false and null from them. Then code that checks not only for value but also type. Since 3 state booleans don't exist this causes some major headaches.


Answer by Omar Kooheji

Methods that are exactly the same except for one parameter.

I recently picked up an applications to review that had 20 methods, every pair of methods were exactly the same except they were processing two different types of data...

I refactored this into a base class with the majority of the functionality and two child classess that only overrode the processing that was different between the two types of data.

Much easier to understand and if a change to the way things were processed was required I usually only had to make the change in one place in the base class.


Answer by srclontz

Useless logging....

try {

}
catch (Exception e)
  log.error(e.printStackTrace());
}

Instead try to think about what sort of error might occur, and put something useful in the logs. This could be something like, "Properties File Not Found" or "Unable To Connect To Database"

Try to catch specific errors, rather than a general exception so that when it fails, the program you wrote won't be immediately blamed. For example, if there is a connection error, put it in plain english, "Database Connection Error".

Better yet....handle the error in the code without necessarily making it to the catch block.


Answer by Justsalt

Unnamed boolean parameters to functions, especially when there is more than one. Here is such a function declaration (in a C-like pseudo language):

cookBreakfast(boolean withEggs, boolean withToast, boolean withJuiceNotMilk);

The function call is incomprehensible:

cookBreakfast(true, false, true);

Solution: use enums or named parameters instead. How this is done will be language dependent.

cookBreakfast(eEggsYes, eToastNo, eJuice);

or

cookBreakfast( withEggs => true, withToast => false, withJuiceNotMilk => true);

or

BreakfastOrder bo;
bo.withEggs = true; bo.withToast = false; bo.withJuiceNotMilk = true;
cookBreakast(bo);

Answer by Michael Lang

C# (perhaps smelly in Java too): Use of collections of type object

To me this smells really funny and indicates that the purpose of a collection may have not been thought out very well. As far as I know, these should only crop up in implementations of something like a completely generic property bag paired with some helper method that performs an attempt to cast and retrieve.

Otherwise this usually indicates the objects going into the collection should implement a common interface which in turn would be the type of the collection elements.


Answer by JosephStyons (Sep 23, 2008)

Code Smell: A giant chain of classes descending from each other, and only the very last one is ever used.

Solution: Usually this says the design is waaay over-engineered. Usually the descendants can be rolled up into a simpler parent-child relationship.


Answer by timdisney (Sep 24, 2008)

Comments used to mark out unrelated or loosely related sections of code. Usually means that a file is trying to do too much and should be broken apart into separate files/classes.

//########### Code to do foo ###########
// 500 lines of code...
//########### Code to do bar ###########
// another 500 lines of unrelated code...
//########### Code to do baz ###########
// ...

Answer by jlouis

Lack of abstraction.

  • Description: the code is written such that everything happens on the same level. There is no separation between different concerns and no splitting into parts.

  • Key indicators: you suddenly find presentation code in the business layer, or you find business code in the data access layer. The line count of a feature is much too big for what it does. The code space looks 'flat' and you don't find yourself having to look up and down the chain of abstraction.

  • Fixing: refactoring is key as always. Define your abstraction layers; for instance data access, business logic and presentation. Then slowly begin pushing code into the right layer when you find it. Suddenly other code smells will show up in each abstraction layer (code duplication is common) making it possible to further simplify the code. It is very much possible to refactor such code into elegance.


Answer by Sridhar Iyer

Global variables

Normally most developers with even a thimble worth of knowledge stay away from them. But somewhere down the line, in some year, somebody inevitably adds one to short circuit some logic or just get a legacy system to work.. further down the line this causes issues in multithreaded systems which are caught much much later and almost too easily escape regression tests.


Answer by David Koelle (Sep 22, 2008)

Catch blocks that simply do exception.printStackTrace()

Exceptions should be handled properly, not simply printed.

  • If a class can't handle the exception on its own, it should be thrown to the caller
  • At a minimum, exceptions should be logged
  • If nothing else, something user-friendly should happen... (any suggestions?)

This applies to product-level code... I'd be more lax on this rule if it's for an internal tool.


Answer by JohnMcG (Sep 23, 2008)

Smell: Database columns with names like value1, value2 ... valueN

Problem: Modleing a many-to-many relationship without a marriage table.

Solution: Create a marraige table to normalize the data model.


Answer by Ferruccio (Sep 23, 2008)

Voodoo code

Code that repeats a call do something more than necessary, just in case.

Or, my favorite example: putting try/catch blocks around code that can't possibly throw an exception. Again, just in case.


Answer by Chris Wenham

Putting too much meaning into boolean parameters. Eg, the method that starts with:

public void Foo(bool isMonday)
{
   int hoursToCheck = 24; 
   bool ignoreHeader = false;
   string skipLinesContaining = "";

   if (isMonday)
   {
      hoursToCheck = 12;
      ignoreHeader = true;
      skipLinesContaining = "USD";
   }

   ...
}

The isMonday parameter is loaded with too much meaning, and the three implied parameters should be passed on their own.

The same smell manifests itself in enums and configuration settings as well. Be on the lookout for boolean-like parameters that have vague names that could imply many assumptions.


Answer by SmacL (Sep 27, 2008)

Wow, most bad smells gone already. Ok in C++ how about delete this, whereby an object commits ritual hari kari without letting anyone else know. I've seen this used variously for watcher and status monitoring routines, and it often smells pretty bad, notably when there are references to the same object elsewhere in the program that aren't informed of the objects demise.

The way I usually refactor this is to make the object pointer a member of another object with broader scope, e.g. the application object.


Answer by Mike Dunlavey

Too many classes, too many objects, too many event-like actions

Not every noun should be a class, and not every verb should be a method. If an object doesn't exist to capture and retain user input, be sure you really really need it.

Examples:

If you are given an array of x,y points, and you want to produce a graph, chances are all you need is a routine to draw it, not build it out of point and line objects.

If you have a tree structure, and there is a property of the tree that depends on properties of its subtrees, chances are all you need are functions that sweep through the tree, not a whole lot of event-handling to propogate change events from children upward.

Register and Unregistering anything smells because those are events whose purpose usually is to incrementally maintain correspondence between things. The rationale is usually to save cycles. Machines are incredibly fast these days. You could possibly just rebuild the structure in less time than you would ever notice, and it would take a whole lot less code and bugs. Another way is to get good at Diff-type algorithms to maintain correspondences.

Back pointers smell. Usually the reason is to save cycles. Then you need unit tests to try to prove that they never get inconsistent. If you design the data structure so there's almost no way you can change it to something inconsistent, then there's almost nothing to unit test.

Everybody loves object-oriented programming, right? But don't let that mean the more objects the better! Let it mean the fewer objects the better. Just because event- or message-based programming is a good way to handle certain problems, don't let that mean it's the ideal paradigm for everything. One may think they're saving cycles, but every cycle saved costs a 100 in managing complexity. Usually this turns into a creaky monstrosity that is never quite right because of messages being forgotten or duplicated or happening at the wrong times.

Comment written on a proposal of mine by my boss, a long time ago: KISS. "What's that mean?" I asked. "Keep It Simple, Stupid!" was the reply. Been living by that ever since.


Answer by Darren (Nov 19, 2008)

Many Helper Classes

Prolific use of helper type classes. I'm defining a helper class as one that contains a bunch of related methods that do some common task. They are typically used when you find yourself repeating the same type of code over and over again.

I believe that this either points to lazy coders not thinking about the best place to put the code in the existing API or a failure of the API itself not providing decent default behavior.


Answer by Pace

Input variables that are then modified within a routine. If you ever need to revert back to what was passed in, it has already been changed. I always set an input variable to some form of working variable. That way, you can always reference the original value and it keeps the code clean.


Answer by Omar Kooheji

Not checking for null arguments on publicly visible methods.

Explanation

Any method which is publicly visible assumes that all its arguments have a value.

Solution

Check for null arguments and either deal with them if it's possible or just throw an ArgumentNull exception.


Answer by Paul Shannon

Pattern Duplication

Not just copy/paste of lines but similarity in the methodology. For example, always setting up a transaction, calling arbitrary methods on objects, returning a list of objects, tidying up, etc. This could be refactored into a base class


Answer by Midhat (Sep 22, 2008)

Configurable constants included in the code


Answer by Gishu (Sep 22, 2008)

Nicely disguised question. Voting smells up and down :)

Isn't this duplication of the refactoring book? Since all of this is already available in a nice place called http://refactoring.com/catalog/index.html with examples to boot..


Answer by Richard Walton (Sep 22, 2008)

Catching un-checked exceptions - i.e. NullPointerException


Answer by AviD (Sep 22, 2008)

In contrast to the aforementioned "megaclasses", the opposite (nullclass?) are also smelly: classes that have absolutely no responsibility and are simply there for enterprisey generica. Same goes for methods that call the next method with the same arguments, which then call the next method with the same arguments, etc.

The solution, as with the megaclass, is to properly define proper responsibilities for each class, and purpose for each method. Try to flatten the class hierarchy as much as possible, adding complexity and abstractions only when absolutely necessary.


Answer by Herr_Alien (Sep 22, 2008)

Too many dimensions for arrays, like:

double *********array = NULL;

That's definitely a call for better data handling.


Answer by MicroWizard (Sep 22, 2008)

General error handling

In languages where exception handling is possible, typical bug is to have all exceptions caught. This means the developer is not aware what kind of errors could occur.

For example in PL/SQL 'EXCEPTION WHEN OTHERS' smells.


Answer by David T (Sep 23, 2008)

Allowing access to objects you own

Smell: long chains of .GetX().GetY().

Problem:

If you allow users to get access to the objects used by your class, either by making them public or via a get method then your just asking for trouble, someone could come along and do:

A a;
a.GetB().GetC().GetD().SetSize(43);

2 things are wrong with this.

  • Joe Bloggs can come along and suddenly change the size of D, in fact he can do almost anything he wants with D. This won't be a problem if you've taken that into consideration whilst writing A, but how many people check that kind of thing?

  • The users of your class can see and have access to how its implemented. If you want to change something, say implement C so that it uses a Q instead of D, then you'll break everyone's code that uses the class.

Solution: The fix depends on how your class will be used, but in both cases the first step is to remove the GetX().

If a user really does need to be able to call SetSize(43) then you should write a wrapper function in each of the classes that passes the new value down. Then if you choose to implement C so that it uses a Q instead of D then no one apart from C will have to know about it.

A a;
a->SetSize(43);

class A
{
    SetSize(int size){b.SetSize(size);}
};

etc. 

If the user of the class shouldn't need to call SetSize then just don't implement a wrapper for it.

If you find that most of D's functions need to be pulled up to A then this may indicate that your design is starting to smell, see if there is a way to rewrite C and B so they don't rely directly on D.


Answer by Don Duty (Sep 24, 2008)

Suggest you read Refactoring: Improving the Design of Existing Code by Martin Fowler, Kent Beck, John Brant, and William Opdyke (Hardcover - Jul 8, 1999)


Answer by Jake (Oct 07, 2008)

// This should never happen.

Answer by jfpoilpret (Nov 05, 2008)

Catching an exception to just rethrow it, in the same form or another form.

It is very common (unfortunately) to meet this kind of code (Java) with 3 different ways to (not) deal with caught exceptions:

try {
    ...
} catch (ExceptionA e) {
    throw e;
} catch (ExceptionB e) {
    log exception
    throw e;
} catch (ExceptionC e) {
    throw new RuntimeExceptionC(e);
}

This code is plain useless: if you don't know what to do with an exception then you should let it pass through to the caller. Moreover, this bloats the code and hinders readability.

Note that in the third case (throw new RuntimeExceptionC(e);), we can argue in some specific cases where this might be useful (normally rare however).


Answer by zonkflut (May 15, 2009)

Annother Double negative issue in C#

if (!!IsTrue) return value;

I have seen he double ! cause bugs in the past.

instead remove the !! to avoid confusion


Answer by jrista (Jun 26, 2009)

Encapsulated Dependencies

The Smell

When dependencies are directly instantiated within the dependent class, managing those dependencies rapidly becomes a maintenance nightmare. In addition, when dependency management is fully encapsulated within the dependent class, mocking those dependencies for unit testing is impossible, or at best extremely difficult (and requires things like full-trust reflection in .NET.)

Solution: Dependency Injection

The use of Dependency Injection (DI) can be used to solve most dependency management issues. Rather than directly instantiating dependencies within the dependent class, dependencies are created externally and passed into the dependent class via a constructor, public setter properties, or methods. This greatly improves dependency management, allowing more flexible dependencies to be provides to a single class, improving code reuse. This allows proper unit testing by allowing mocks to be injected.

Better Solution: Inversion of Control Container

A better solution than simply using dependency injection is to make use of an Inversion of Control (IoC) container. Inversion of Control makes use of classes that support DI, in combination with extern dependency configuration, to provide a very flexible approach to wiring up complex object graphs. With an IoC container, a developer is able to create objects with complex hierarchical dependency requirements without needing to repeatedly and manually create all of the dependencies by hand. As IoC containers usually use external configuration to define dependency graphs, alternative dependencies may be provided as part of configuration and deployment, without the need to recompile code.


Answer by Kip (Jul 26, 2009)

Error messages when users perform perfectly valid actions

I'm thinking of this one I saw when trying to change my password somewhere:

NOTE: Using a colon (“:”) in your password can create problems when logging in to Banner Self Service. If your password includes a colon, please change it using the PWManager link below.

Solution: Don't be lazy. Sanitize user input properly.


Answer by JohnMcG

Smell: query in a program that is either "SELECT *" or an insert without column names.

Problem: if the structure of the table changes, the code will break.

Solution: be explicit about what columns are being selected or inserted.


Answer by T.R. (Jan 30, 2010)

Smell:
File1:

def myvariable;

File2:

def my_variable;

File3:

def myVariable;

Problem: Spaghetti inclusions (if it's not just poor variable naming). Someone is sidestepping redefinition compiler errors (in a statically typed language) or data loss (in a dynamically typed language) by using different variables for the same purpose in each file.

Solution: clean up the inclusion mess, narrow the scope of each instance of the variable (preferably through some form of encapsulation) or both.


Answer by Matthew Sposato (Mar 12, 2010)

A ridiculous number of compiler warnings.

Even compilers dislike smelly code. I use Visual Studio with Resharper. Many of items posted in this thread would be warnings. i.e. unused variables, variables assigned a value that is never used, unused private methods, hiding inherited members etc.


Answer by fastcodejava

Too many big blocks of code.


Answer by Arne Burmeister

Naming by Type

It is totally useless to name a variable, member or parameter by type. In former times this may had sense, but today a simple click on or hover over the name in the IDE shows the declaration.

Better to use the meaning of the value for the context.

Unfortunately some IDEs like Idea have the bad "functionality" of completing a name by writing the type. Never use this!


Answer by Hannesh

Variable naming inside classes

Variable names are good enough when understood within the scope of the class.

I shouldn't have to write Shader.ShaderTextureSamplers[i].SampleTexture.TextureWidth, when Shader.Samplers[i].Texture.Width is just as readable.


Answer by aku (Sep 22, 2008)

switch statement with number of cases <= 2

Usually happens when using boolean-like enums ( enum { Off, On } ).

Consider using if-else statements


Answer by aku (Sep 22, 2008)

.NET specific: catching System.Exception exception

Usually means that code author deserves to be beaten hard with baseball bat.

Don't even try to do it unless you have a very good reason. Did I mention baseball bat, no?


Answer by Nazgul (Sep 22, 2008)

Defensive coding

Code where there are a lot of null checks is a smell. If this is the case then there is some issue with your design.


Answer by Vilmantas Baranauskas (Sep 22, 2008)

Use of specific class instead of interface when declaring variable. Smells especially bad in combination with Java's collection framework.

Instead of

ArrayList list = new ArrayList();

use

List list = new ArrayList();

Answer by MicroWizard (Sep 22, 2008)

Too short code fragments or structured to death

If I see a lot of short source files, object definitions and methods with only one row real content, I feel this project was structured to death. More brackets then code lines is the first sign.

Dare to write complete (but small !) code snippets/methods/etc. without feeling the pressure to stamp out into unreadable particles.


Answer by JohnMcG (Sep 23, 2008)

Smell: In C++, an object is dynaimically created and assigned to a bare pointer.

Problem: These must be explicitly deleted in all paths out of the program, including exceptions.

Solution: Manage the object in a smart pointer object, including std::auto_ptr, or one from the Boost libraries.


Answer by Bob (Sep 23, 2008)

Give your code a good bath using quality soap, then air out for a week, the smell will be gone.


Answer by rjarmstrong (Oct 07, 2008)

Ignoring all the fundementals or any particular construct; if it feels wrong then you've just got a whiff of a smell. Why - well because you will need to use the code you've just made and that 'wrong' feeling will give you little confidence when using it. A second opinion may be required if you're having trouble refactoring.


Answer by Jai (Sep 25, 2009)

Multi function functions

If a function is doing more than one thing. This has been mentioned implicitly in other answers but it should get a mention on its own.

Example:

// if function altList = null function returns a list of X ids
// if altList is set the function returns a list of objects of type Y

Function getData(searchStr, altList=null)
{
    // common code
    some code;
    if(altList == null)
    {
         other code;
         return array(int);
    }
    else
    {
         more other code;
         return array(object y);
    }
}

This really should be three functions:

  • Public function that gets a list of ids
  • Public function that gets a list of object of type y
  • Private shared function contains any common code.

Answer by Khainestar (Nov 17, 2010)

Got a couple lately that defy logic and boy do they smell.

php mysql calls that use $_POST and $_GET directly in the sql.

function calls in PHP function($value=false); then there is comments in the function saying that this never worked right and they didn't know why.

mysql calls that have "or die(mysql_error());" on the end.

No abstraction layer, each database call goes through the motions of creating the database connection.

I could just go on and on about this code, but I have a rm -rf to run.


Answer by Baiyan Huang (Mar 20, 2011)

Unnecessary if .. else block

Code like this should be better avoided:

if(map.find(key) != map.end())
    return true;
else
    return false;

Replace it with just one statement:

return map.find(key) != map.end();

Answer by Steve B.

loops with lots of exit points:

for (...)
{  
   if (... ) {
    continue;
   }
   else if ( .. )
   {
     if (... ){
       break;
      }
   }  
}

Answer by Vilmantas Baranauskas (Sep 22, 2008)

Use of Vector and Hashtable in Java. This usually means that programmer knows nothing about collection framework and newer versions. Use List and Map interfaces instead and any implementation you like.


Answer by Vilmantas Baranauskas (Sep 22, 2008)

When Map is used to hold unique elements. E.g.

Map map = new HashMap();
map.put(name, name);

Use Set instead:

Set set = new HashSet();
set.add(name);

Answer by JB King (Sep 22, 2008)

"Orphaned" functions that are all put into a file without any organization/order. For example, an 8000 line ASP file of 100 functions that look like spaghetti code or the beginnings of it. There may be more than one smell to this, but when I come across it, there is some pain in having to maintain legacy applications that have this "feature" ;)

The fix for this is to create some classes that group the functions and determine which are useful functions that go into a class and which should be refactored into something else.


Answer by Bazman (Sep 23, 2008)

Huge methods/functions. This is always a sure sign of impending failure.

Huge methods should be refactored into smaller methods and functions, with more generic uses.

Potential Solution:

I've found that a really great way to avoid this is to make sure you are thinking about and writing unit tests as you go.

You find whenever a method/function gets too large, it becomes very difficult to work out how to unit test it well, and very clear on when and how to break it up.

This is also a good approach to refactoring an existing huge function.


Answer by Ferruccio (Sep 23, 2008)

Weird constructs designed to get around best practice

e.g.

do
{
    ...
    if (...)
        break;
    ...
} while (false);

That's still a goto, even in disguise.


Answer by Ande TURNER (Sep 22, 2008)

Stinky Commenting


Comments should:

  • Say what the code is trying to achieve, not how it is doing it.
  • Convey something that the code cannot.

Answer by James A. Rosen (Sep 24, 2008)

The reek project will help automatically check for code smells in Ruby.


Answer by tpower

Protected Member Variables

The only place I have ever come across these is when I find the source of bug.

When these are used in code there is normally no distinction between a private member and a protected member. A developer could easily change its value thinking they can see all uses of it in the current class so it wouldn't cause a problem.

You can replace protected with private and add some protected accessors functions. Developers are used to calling base class functions so it would be easier to understand what is happening.


Answer by Norman Ramsey (Dec 07, 2008)

In OO languages, private members exposed through getter and setter methods. I'm frightened how many times I've seen students write code with members that are supposedly private but can be read or written through public getter and setter methods. Such classes 'expose the rep' just as thoroughly as public members, but with a lot more cognitive overhead.

Remove the smell by figuring out what secret the module or class is supposed to hide and reducing the number of methods accordingly.


Answer by thomasrutter (Mar 04, 2009)

A comment containing the word TODO

{
  //TODO clean this up a bit
  if (klwgh || jkhdfgdf || ksdfjghdk || bit << 8 == askfhsdkl)
    if (klusdhfg)
      return 1 + blah;
}

Answer by obelix

Functions in C++ that take pointers as arguments and then check for NULL on the first line. Pass by reference or const-reference. Makes the contract so much clearer.


Answer by Mawg (Jan 10, 2010)

Lack of ASSERT()

New guys never seem to use them. I prefer to break my code as early as possible. At the very least, ASSERT() all input parameters (and some return values from functions which you call).

MY own assert is a macro which calls the standard #ASSERT() if I am testing (#ifdef TESTING) otherwise, in a production system it writes something to the system log file.


Answer by Mawg (Jan 10, 2010)

Switch cases that fall through

switch (value)
{
  case 1:
  case 2:
  case 3: // some - usually very long - block of code
          break;
  case 4: ...etc
}

These are always worth look at closely, as they invite bugs. And they can generally be worked around by putting the common code into a function. Look for a break after every case;


Answer by deadbug

Dynamically generated SQL smells. It has its limited uses, but in general makes me nauseous.

A very simple example below ...

Don't:

DECLARE @sql VARCHAR(MAX), @somefilter VARCHAR(100)

SET @sql = 'SELECT * FROM Table WHERE Column = ''' + @somefilter + ''''

EXEC(@sql)

Do:

SELECT * FROM Table WHERE Column = @somefilter

Answer by Sara Chipps (Sep 22, 2008)

When you are doing the same thing (manipulating an object, doing similar SQL calls, processing data, changing a control) more than once in more than one place it's time to refactor. That gives way to smelly redundant code.


Answer by HLGEM (Sep 22, 2008)

From a database perspective (SQL Server to be specific) More than two layers of nested ifs - very easy to have a logic error Dynamic SQl in a stored proc - make sure that you aren't open to sql-injection attacks Cursors - is there a set-based solution? More than 5 joins especially when no columns from some of the joined tables are in the result set (do we perhaps need to denormalize for performance?) Use of subqueries instead of derived tables Over use of user-defined functions use of Select *


Answer by Karthik Hariharan (Sep 22, 2008)

everyone is pointing out specific things that bother them and that they consider a "code smell".

I think after a while, once you get the hang of it, you sort of develop a "sixth sense" about what is wrong with a piece of code. You may not be able to immediately pinpoint how to refactor it or make it cleaner, but you know something is wrong. This will drive you to find a better pattern/solution for it.

Understanding all the examples others have posted is a good start for developing this sense.


Answer by Marcin (Sep 25, 2008)

Any code that is repeated, or any instance when a variable is assigned more than once.

Both are appropriate in certain circumstances, and given the constraints of the environment, but still.


Answer by Pablo (Sep 26, 2008)

Rediculous comments:

catch
{
/*YES- THIS IS MEANT TO BE HERE!  THINK ABOUT IT*/
}

Answer by James McMahon (Oct 16, 2008)

Apologies if this was already mentioned, but I just looked through the answers and didn't see this mentioned.

Code Coupling can make maintenance a nightmare. If you have display code directly tied into with other logic, making anything but routine maintenance will be all but impossible.

When you are designing your display code, think long and hard about your design and try to keep the design part separate from the rest of your app.


Answer by onedaywhen (Oct 17, 2008)

Writing procedural code against a DBMS

Smell: looping through an ordered resultset using a cursor in SQL (or walking an ordered recordset in middleware, etc) aggregating values, setting values based on other values, etc.

Possible problem: the coder hasn't looked for a set based solution. Put another way, they haven't yet had the epiphany that SQL is a declarative language and a SQL DML statement is more like a spec than a piece of code e.g. when I write...

UPDATE MyTable 
   SET my_column = 100
  WHERE my_column > 100;

...I'm telling the DBMS what to do rather than how to do it.


Answer by Kon (Oct 22, 2008)

A large number of Ifs or Cases usually begs for creation of new classes that extend some base class.


Shared with attribution, where reasonably possible, per the SO attribution policy and cc-by-something. If you were the author of something I posted here, and want that portion removed, just let me know.

Replacing Gmail with Mailbox.org (and calendar and docs too!)

$
0
0
Replacing Gmail with Mailbox.org (and calendar and docs too!)

Google provides some amazing tools, but at what cost to our privacy? One of the biggest blockers in eliminating the grip Google has on me has been to find a reliable and affordable replacement for email (and hopefully, other tools we tend to lump in with it, like calendar, documents, tasks, etc).

I used ProtonMail for about a year, but the free version is very limited (3 folders/labels, no filters, broken contacts design), and the paid version at $5/mo is more than I want to spend on just email. They keep promising a calendar, but even when it rolls out it'll take awhile to iron out the bugs, and they offer none of the other services Google does, paid or not.

Replacing Gmail with Mailbox.org (and calendar and docs too!)
Setting an address for your contact is a "premium" feature in ProtonMail 🤨

Then I discovered Mailbox.org, another email provider that values enhanced security and privacy over serving up ads. After spending the last week getting it setup the way I want it, I think I've finally found my replacement for Gmail et al.


Getting Started

Register for an account and off you go.. easy peasy. Once you're in, click the gear icon and change your features. There's a nice little slider to increase mail and cloud (document) storage, and it shows what other features are enabled to. Pay is "as you go", and there's quite a few options depending on just how much of a geek you are... or what your privacy requirements are.

As you can see, I have a whopping $2 in my account, good for 2 months of basic usage. The free 30 day account ain't bad for trying it out, but hey I'm rolling in washingtons over here. 💸


Using Your Own Domain

Setup is far easier if you just use the default mailbox.org domain, buuuut.. I love to complicate things. Seriously though, after changing gmail.com to protonmail.com and now to mailbox.org (and being realistic that I may want to change services again someday, and since I already have a domain for this blog), it just makes sense to make this the last email address change I'll ever have to make.

Mailbox.org provides a detailed doc on setting up e-mail addresses for your domain. You'll definitely have to be comfortable configuring your own domain setup, but it's not that hard if you're willing to do some research. I can only share what I do personally.

My domain name is currently registered with Namecheap, which I configured to forward all traffic to the DigitalOcean nameservers, where I host this blog. Everything (web traffic, emails, etc) goes through Namecheap to DO, where the actual config is done.

Replacing Gmail with Mailbox.org (and calendar and docs too!)

The first thing you'll see in Mailbox.org when you try to setup an alias to your own domain is a warning telling you to add a TXT record to your DNS settings. They have to do that to verify you have access to the domain, otherwise anyone could claim any domain for their own. That would be Bad.

Replacing Gmail with Mailbox.org (and calendar and docs too!)

After you've proven you're the owner, you see this instead. Now you can add some MX records to your DNS settings, directing all traffic from (in my case) DigitalOcean to Mailbox.org's several servers (note the "priority" setting). 🐢🐢🐢🌎

Replacing Gmail with Mailbox.org (and calendar and docs too!)
Replacing Gmail with Mailbox.org (and calendar and docs too!)

But wait, there's more!  You may have proven who you are to Mailbox.org, but that's not enough for other providers like Gmail, who will mark your messages as possible spam and unceremoniously dump them in the recipient's spam folder. Fun.

Replacing Gmail with Mailbox.org (and calendar and docs too!)

To fix that, you need another DNS entry. It seems that every problem in the world is fixable with one more DNS entry. Use a tool like this one to check for an SPF record - if you don't find one, you need one, and you can find instructions here.

Replacing Gmail with Mailbox.org (and calendar and docs too!)
Replacing Gmail with Mailbox.org (and calendar and docs too!)

Let that take effect, then check it with the website again, and everything should be much greener and happier. Either this tells Gmail how to check Mailbox.org to verify you, or it causes Mailbox.org to attach some meta data to requests that Gmail uses, or... whatever. I don't care, my stuff ain't going to spam anymore. 💚

Replacing Gmail with Mailbox.org (and calendar and docs too!)

Here's my full DNS records, which might help someone. Not sure why the bottom 3 NS records are in there, but I think they were there by default so I'm leaving 'em. There's also a reference in their docs to adding a record for DKIM, but that doesn't seem to be necessary... maybe I'll revisit it later.

Replacing Gmail with Mailbox.org (and calendar and docs too!)

Syncing Calendar and Contacts to Your Phone

I found an app called DAVx5 that lets you sync your calendar, contacts, and todo items, and in practice it seems to be working well so far.

Install DAVx5

  1. Disable "battery optimization" per the app's suggestion, and allow the app to run in the background, otherwise I don't see how it'll allow updates.
  2. On the right bottom, press the orange "+" symbol.
  3. Choose “Login with URL and user name”.
    base url: https://dav.mailbox.org
    user name: your mailbox.org primary email
    password: your mailbox.org password (not thrilled with having to supply my password instead of a per-app code where permissions can be restricted)
  4. Give the name an account if it prompts you (I can't remember..).
  5. You should be prompted to allow certain permissions, like calendar, tasks and contacts. Might as well, otherwise it probably can't do what it needs to do.
  6. You should see CardDAV (for syncing contacts) and CalDAV (for syncing calendars and tasks).
  7. Choose the folders to sync.

Test the Calendar and Contact apps

You should be able to use the Google Calendar app like you would for any other calendar, instead of the ugly default Android calendar app. Create an entry on Mailbox.org, let it sync (you can set that in the mobile app), and make sure it carried over. Same goes for contacts too...

Don't forget to go into the Google Calendar app settings (if you use it) and uncheck the calendar built into Gmail, otherwise you'll have two personal calendars showing. Unless you want that. Whatever. 🙄

About Tasks...

I use Trello and have no intention of using Mailbox.org tasks, so I'm not sure if the above tool integrates tasks with whatever is built into Android or not. You might have to find a separate tool like OpenTasks (note, I have not used that tool and have no idea how or if it works).


Other Features (disposable addresses, security, etc)

They also provide a bunch of other awesome sauce right out of the box. I've pondered just what the heck ultimately happens to our digital life, and so have they apparently. I don't know how they confirm my death, but presumably once they receive a request to release it, they can (at your instruction) grant it or delete it. Not sure how it'd hold up in court, but it's interesting.

The built-in disposable addresses are awesome as well. I spent a few hours porting my online accounts to my new email, and closed quite a few that I hadn't used in a long time. That is an incredibly painful and frustrating experience, especially when there's no obvious way to even close the account. So, at the very least, I spun up a disposable address, changed it in those services and confirmed it, then deleted the address. At that point, they're effectively dead to me. 👍

While enabling 2FA, I noticed this message. Since SMS is the least secure way to 2FA (and also won't work if you go outside your coverage area), I was actually glad to see it.

Replacing Gmail with Mailbox.org (and calendar and docs too!)

So far I'm super happy with this service, and consider $1/mo a steal for an ad-free, creepy-dig-through-my-data-free experience. If I need more aliases, cloud space, or convince my wife to jump on board with the "team" settings, I'll gladly play $2.50/mo for it too.

Viewing all 348 articles
Browse latest View live