Converting String to Number in Javascript: A Gotcha

If you are used to programming in C, Java, or any similar language, you might get surprised by the way Javascript’s parseInt and parseFloat functions work.

By its name, parseInt will convert a string into a number. It does so by reading through the string and converting the characters, one by one, to numbers, until it meets an invalid character; it then stops and returns the read characters –the valid part– as a number, ignoring the remaining.

This means that trying to convert an invalid string representation of a number to a number in javascript may not result in an error. For example parseInt("123ax4") will return 123.

This is a very different behavior from how Java, or C, or many other languages would work. Most other sane languages would throw errors if you try to do that. So, if like me, you think this is dangerous, then there is a better and safer way to do it.

Enter The Unary + Operator.

Using the unary + operator to convert strings to numbers guarantees you that either the entire string is a valid number, in such case the converted number value is returned as a result of the expression, or if there is any invalid number in the string, NaN is returned. So the output of the statement + "123"; results in the integer value 123. The output of the statement + "123a"; is NaN.

List.Find(Predicate ) Considered Harmful

Hold on, it’s not goto!

I dare to say that every program have ever written on this entire planet needed some sort of searh functionality, and if it didn’t, it’s probably because it’s too lame and frickin’ uslelss.

Today I was working on a piece of code that part of it is concerned about finding items in a generic List. The code I wrote was some like this:

var products = ProductsCollection.Find(p => p.Price > 500);

Doesn’t that look concise and elegant. For me it does, the problem is, however, this code is not SAFE (yeah, i was surprised too).

When I run this code I got a System.NullReferenceException. WTF is that? ProductsCollection is totally a valid reference, however, it was empty.

OK, wait a second why should searching an empty list throw an exception? The expected result should be null or something but not an exception. After thinking about it a little, I thought, Oh, what if the list contains value types? In such case null is not a valid return type, so an exception makes sense to me now.

Here I thought I really got it and understood that List.Find will throw a null reference exception if called on an empty list. I was totally wrong if you must know. The call would simply return default(T) which is null for reference types. The exception was actually thrown when I used the return of the find!

Now I wondered “OK, now what if i’m searching a list that only contains value types and the item i’m searching for doesn’t exist in that list? What would be the result in this case? Well, let’s try it out”:

List<int> evens = new List<int> { 0, 2, 4, 6, 8, 10};

var evenGreaterThan10 = evens.Find(e => e > 10);


What the search returned in this case is the value 0, yes zero! because nothing in the list is greater than 10 so Find will just give you default(T). This can lead to some really nasty bugs. Don’t curse, this is frickin’ documented you lazy sloths.

Important Note

When searching a list containing value types, make sure the default value for the type does not satisfy the search predicate. Otherwise, there is no way to distinguish between a default value indicating that no match was found and a list element that happens to have the default value

for the type. If the default value satisfies the search predicate, use the FindIndex method instead.

Trying to be safe in this case you could simply check after finding to see if the returned value is what you actually asked for, something like that:

List<int> evens = new List<int> { 0, 2, 4, 6, 8, 10};

var evenGreaterThan10 = evens.Find(e => e > 10);

if(evenGreaterThan10 > 10)

   // valid value


   // none found


I’m not sure how do you feel about that, but for me, I really hate it! So what I ended up doing is something similar to the well known TryParse style, I overloaded the Find method with an extension method that would allow the usage to be something like this:

List<int> evens = new List<int> { 0, 2, 4, 6, 8, 10};

int i;

if(evens.Find(e => e > 6, out i))



  Console.WriteLine("None found");

The extension method is as simple as:

public static bool Find<T>(this List<T> list, Predicate<T> predicate, out T output)

  output = list.Find(predicate);

  return predicate(output);



As reported by Kevin Hall in the comments, this method has a serious bug. Consider the following code segment:

List<int> x = new List<int> { -10, -8, -6, -4 };

int myResult = -9999;

bool resultFound = x.Find(e => e > -3, out myResult);

In this case result found would be true and myResult would be zero! A yet better way to do this is by making use of the FindIndex method like so:

public static bool Find<T>(this List<T> list, Predicate<T> predicate, out T output)

  int index = list.FindIndex(predicate);

  if (index != -1)


    output = list[index];

    return true;


  output = default(T);

  return false;


Thanks Kevin for pointing that out.

I’m much happier now, I can drop the suicide thought for a while! What do you think dear reader?

Usage Of The "is" Operator Should Be Handled With Care

C# provides means to explicitly cast from a type to another type. If you want to cast from float to int you can use the (int) cast operator to acheive that. This operator simply says to the compiler, I know you don’t like this, but, please let the runtime try to do the cast. This operation can either succed or result in an System.InvalidCastException to be thrown.

In addition to this, you can overload the explicit cast operator in case you wanted the cast to happen by your own defined rules. Ok let’s see an example of this. Suppose that we have two types, Human and Employee, and in our very unfair world, an Employee is not a Human! The layout of these two classes might look like this:

public class Human
    public string Name { get; set; }


public class Employee
    public string Name { get; set; }

    public string Job { get; set; }

    public override string ToString()
        return string.Format("Employee: {0} is {1}", Name, Job);

Now let’s say that you want to support an explicit custome conversion from Humans to Employees -for a fictious rule, let’s say that every human is unemployed employee. The human class after adding the conversion operator should look like this:

public class Human
    public string Name { get; set; }
    public static explicit operator Employee(Human h)
        return new Employee()
            Name = h.Name,
            Job = "Happily Unemployeed"

You can now try to cast your Humans to Employees, and see if the cast is really applying your rules, here’s how I might attempt to cast one of humans to employee:

Human h = new Human {Name = "John"};
Employee s = (Employee) h;

If you run this code you should see the output on the console screen saying:

Employee John is Happily Unemployeed.

Now let’s see how this plays with the famous “is” operator. The is operator is binary operator with a return type of boolean. What it does, is that it checks to see if the left hand operand is actually of the same type of the right hand operand -By the same type here, I mean, the same as an instance of the same class, or an instance of a derived class, or an instance of a class the implements the right hand operand in case the right hand operand is an interface.

Here’s a simple example to see this operator in action:

bool shouldBeTrue = "Hello" is string; // true
bool shouldBeTrueToo = "Hello" is object; // true
bool shouldBeFalse =  "Hello" is ICollection; // false

Now, the interesting part:

bool shouldBeWhat = new Employee() is Human; // ?? guess guess

Pause a minute and think of the above statement. What should the value of “shouldBeWhat” be? True of False? …

OK, the value of the boolean variable “shouldBeWhat” will actually be false. Yes, Employees are not Humans! Even though you have provided an explicit cast rule that , by the virtue of its existence, states that humans can be employees. “can be” doesn’t equal to “is”, does it? So, yeah the is operator doesn’t take in account your explicit casting operators. So this is the first gottcha!

The second point I wanna mention is that, the “is” operator works by actually performing a cast. Yes it casts and checks if the cast succedes it returns true otherwise, it returns false. A typical usage of the is operator is probably as follows:

if(h is Employee)
    var x = ((Employee) s).Job;

This should look familiar to you, a typical pattern when using the is operator is by checking first if a variable is of a given type, then if it is, cast it to that given type and use it. How many casts does the above code segment contain? 2 is the answer! Yes two, one is obvious in the statment

var x = ((Employee) s).Job;

and the other one is, yeah you guessed it, the cast performed by the is operator. This is not very ideal, as it simply, adds an overhead of a second cast which should is not necessary. So, what should you do to avoid that second cast?

Use “as” instead of “is”:

The “as” operator allows you to do safe casts and aslo avoid the probability of throwing any InvalidCastException, by assigning null to the variable if the cast failed. The following segment is semantically equivalent to the previous segment, but is considered faster and safer:

var x = h as Employee;
if(x != null)
 string job = x.Job;

The above segment is faster because it includes only one cast.

Conclusion: There’s not much to say here, just deal with the is operator carefully, and if possible avoid it and use the better alternative “as” operator.

New, But Not So Obvious, Features in .NET 4.0

.NET 4.0 came out lately with a lot of new, cool, and somewhat game-changing features. These features include language features like the famous dynamic keyword in C# and this whole dynamic dispatching thing that made possible by the DLR (Dynamic Language Runtime).There are also some additions on the library level, the parallel extensions is an obvious example of that.

In this post I will mention some of the new additions that are not so well propagated.

First The additions to the string class: The BCL guys are still working on the core. Apparently they are trying to lessen the number of extension methods that you need to write as a complement to some of the very core, and widely used in any application, classes -Pretty much everyone has a StringExtensions, and DateTimeExtensions dlls.

string.IsNullOrWhiteSpace() The old string.IsNullOrEmpty() was used to check if the string variable is null or if it’s equal to the empty string (“”, or string.empty)In many cases a string that contains only white spaces is considered to be an empty string. People used to do the following check over and over again:

if(string.IsNullOrEmpty(s) && s.Trim() != string.Empty)
 // do my job;

Now string.IsNullOrWhiteSpace() is designed to save you that extra Trim call.

string.Join() Prior to .NET 4.0 string.Join was designed to accept two parameters a separator and an array of string, and it was expected to output one single string that contains the strings in the array separated by the separator. The problem with this is, if you have two separate strings and you want to join them together you would have to create an array and insert those two strings inside the array, then call string.Join passing in your separator of choice and the array. A call should look like this:

string first = "first";
string second = "second";
string[] sequence = { first, second };
string joined = string.Join(" - ", sequence);

New overloads had been added to the string.Join method, one of them accepts a params of objects and it automatically calls ToString, so that you don’t have to do that extra step of creating an array that holds your string values. Now the call to the method is simplified:

string joined = string.Join(" - ", first, second);

Modern collections support with string methods If you examine the old overloads of string methods that accept a collection, you shall find that the only collection these methods accept, is array. With .NET 4.0 things are different, now these methods support IList, ICollection, and IEnumerable (yeah, I know, this should have been possible since .NET 2.0). With this support statments like this are possible:

string joined  = string.Join(" - ", stringList.Where(s => s.Length > 3).Select(s=> s));

Second, Lazy

Lazy Loading, is a technique that implies, creating and initializing expensive objects on demand. Most nowadays ORMs follow this technique when fetching data from the database. The Lazy is a new type introduced in .NET 4.0 that enables you to lazily create your instances and validate whether an instance has been created or not without accidently creating it.For example if I have an object named ExpensiveObject like so:

class ExpensiveObject
     public ExpensiveObject() { }
     public ExpensiveObject(string connection)
         Console.WriteLine("Constructing expensive object");
         Connection = connection;

     public string Connection { get; set; }

Here’s how I would Lazily create an instance of this object:

Lazy<ExpensiveObject> a = new Lazy<ExpensiveObject>();

To check if the object has been already created or not, you can use IsValueCreated boolean propery on the Lazy object:


This should print false. If I tried to access the underlying expensive object (through the Value propery on Lazy) and then check to see IsValueCreated, the result should be true:

string  dummy = a.Value.Connection;

This statement should print True on the console window.

Note: In the above example we created an instance of ExpensiveObject using the default constructor. You can create it using a custom consructor by passing in a Func (i.e. any method that returns an expensive object)

Lazy<expensiveobject> custom = new Lazy<expensiveobject>(() => new ExpensiveObject("My Connection"));

Hope this helps!

Programmers And The Value Of Hard Focus

There was a very interesting discussion on reddit a few days ago. Some fresh programmer asked how many pure work hours do programmers work per day?

By pure work he meant, the number of hours spent on (coding/designing/testing, etc.) a task that is probably assigned to him by one of his superiors. Other activities like personal researching, blogging, etc. are not counted.

The question sound pretty interesting to me and the answers came much more interesting.

Most of the answers implied that programmers put less that four hours of pure work per day. This is half the assumed time (8 hours for most companies).

So, why do programmers work less than most of other carriers’ professionals? An immediate answer that might came to my mind “well, that’s normal because they are sloths lazy.”

<a href=" False Assumption: If I don't work HARD I will eventually fail to finish my work, and will certainly feel incompetent. There's a lot to programming than HARD work: For me, it doesn't matter how many hours I work during the day. What matters most, however, is the number of tasks I manage to finish. This is ths only productivity metric to me, and it's not related to the number of working hours, it's related to the number of hours (or minutes) I managed to keep my focus hard. The value of Hard Focus: Haruki Murakami in his excellent memori (What I Talk About When I Talk About Running) noted: >If I’m asked what the next most important quality is for a novelist, that’s easy too: focus the bility to concentrate all your limited talents on whatever’s critical at the moment. Without that you can’t accomplish anything of value The key is to concentrate all your mental abilities on one specific task and foreget about anything else as long as you're working on this one task. This is very important -actually a lot of programming techniques and tools are proven usefeul and highly adopted because it lets you forget about other details and foucs on your specific task. Luckily enough, Marukami pointed that: >Fortunately [sustaining focus for a long period of time] can be acquired and sharpened through training. Pomodoro: The pomodoro technique is designed to address this very problem. It's mainly focused on helping you stay focused by working for shorter periods of time, named pomodoros, each is 25 minutes long and during each you're focused on only one task. And while working on this one task you are not allowed to think or worry about anything else. This really helps you cultivate all your energy on attacking one problem. Conclusion: The number of working hours is not that crucial in CS-related carriers or any other carrier that requires a non-trivial amout on creativity. What matters most is to keep your mind clear, break your problem into smaller problems, and focus on these smaller problems one at a time. Now I see (and hopefully you dear reader) what every GTD book meant when they loudly screamed in readers' faces "WORK SMART NOT HARD"! What do you think dear reader?