Monday, 24 August 2015

JavaScript #24 - Checking for Integer.

Book > 1000 things about JavaScript >

JavaScript #24 - Checking for Integer

In ECMAScript, we can do Number.isInteger(x); and be done. But before that, we need a good function like one below.

var isInteger = function isInteger(x){
    "use strict";
    var zero = 0;
    var one = 1;
    var isNumber = typeof x === typeof one;
    var modOneIsZero = x % 1 === zero;
    return isNumber && modOneIsZero;
}

And we will be done with it.

Now, we need to include the ECMAScript 6 version too.

var isInteger = Number.isInteger || function isInteger(x){
    "use strict";
    var zero = 0;
    var one = 1;
    var isNumber = typeof x === typeof one;
    var modOneIsZero = x % 1 === zero;
    return isNumber && modOneIsZero;
}

Tada!

JavaScript #23 - Checking if a variable is an object or not.

JavaScript > 1000 things about JavaScript >

JavaScript #23 - Checking if a variable is object or not.

Check for undefined variables.

var isAnObject = function (x) {
    return x !== undefined;
}

This checks if the variable is undefined then it is not an object.

Check for null variables.

var isAnObject = function (x) {
    return (x !== undefined) && (x !== null);
}

This checks if variable is undefined or null, it cannot be an object.

NOTE: null is actually an object in JavaScript. Weird. Try: typeof null in your code.

Check for objectness.

var isAnObject = function (x) {
    return (x !== undefined) && (x !== null) && (typeof x === typeof {});
}

typeof {} returns object. This is actually the true test for objectness of a variable.

Output

isAnObject({})
true

But, arrays are also objects.

isAnObject([])
true

 

Check for non arrayness.

typeof [] will return object. Which will defeat the purpose; so we are going to call toString() to the rescue.

var isAnObject = function (x) {
    var defined = x !== undefined;
    var notNull = x !== null;
    var realObject = typeof x === typeof {};
    var notAnArray = toString.call(x) !== "[object Array]";

    return defined && notNull && realObject && notAnArray;
}

Output

isAnObject([])
false
isAnObject({})
true

 

Check for functions.

Functions in JavaScript are also objects.

var isAnObject = function isAnObject (x) {
    var isDefined = x !== undefined;
    var notNull = x !== null;
    var realObject = typeof x === typeof {};
    var notAnArray = toString.call(x) !== "[object Array]";
    var notAFunction = typeof x !== typeof isAnObject;

    return isDefined && notNull && realObject && notAnArray && notAFunction;
}

Here, we have used a named function. We could have used typeof function(){} instead of typeof isAnObject.

So, functions can have names or they can be anonymous.

isAnObject(function(){})
false
isAnObject({})
true
isAnObject([])
false

Well, that marks the end of the tip.

Sunday, 23 August 2015

About switches in C# - should you use it, what syntax to go for.

 

Today I answered Should I use a variable for a switch statement or a return statement when using a switch in a property to retrieve a value?

Here’s my long answer plus cleanups:

The problem

public double xMax {
      get {
           double val = 0.00f;
           switch(x_option) {
                case 0:
                     val = priMax;
                     break;
                case 1:
                     val = rfMax;
                     break;
                case 2:
                     val = pwMax;
                     break;
           }    
           return val;
      }
 }

Vs.

public double xMax {
      get {
           double val = 0.00f;
           switch(x_option) {
                case 0:
                     return priMax;
                case 1:
                     return rfMax;
                case 2:
                     return pwMax;
           }
      }
 }

 

The actual problem

Here’s what you are looking at: Syntax A and Syntax B.

What should you be looking at: Consistency of syntax in your code throughout.

Pick one style and stick to it. This can be dictated by personal choice, team’s choice, boss’ choice etc.

Bothering about performance until you have bottleneck is putting cart before horse.

Switch means a f**kup.

As a general consequence of code and complexity accumulation, if you are faced with switch statement, then someone wrote bad code somewhere and tried to handle a lot of things in one yarn ball of a code.

Case in point: An API call that returns JSON which sends back 5 different values in an array and you need to figure out how to handle it or what data to pick as per your need.

Saw switch, did refactor.

Most times you should break your code into little chunks as soon as there are possibilities of multiple returns or ifs.

Take Jon Skeet’s code for example:

public int DoSomething(string input1, string input2)
 {
     int ret;

     // First simple case
     if (input1 == null || input2 == null)
     {

         ret = -1;
     }
     else
     {
         // Second simple case
         int totalLength = input1.Length + input2.Length;
         if (totalLength < 10)
         {
             ret = totalLength;
         }
         else
         {
             // Imagine lots of lines here, using input1, input2 and totalLength
             // ...
             ret = someComplicatedResult;
         }
     }
     return ret;
 }

Let’s see if we can make code a bit more readable first.

Making code readable.

private int someComplicatedTask(string input1, string input2){
    int ret = 0;
    int totalLength = input1.Length + input2.Length;
    if (totalLength < 10)
    {
        ret = totalLength;
    }
    else
    {
       // lots of LOC
       ret = someComplicatedResult;
    }
    return ret;
}

public int DoSomething(string input1, string input2)
 {
     return input1 == null || input2 == null ? -1 : someComplecatedTask(...);
 }

This should make you wonder, ‘Why did you call DoSomething when there was a chance that inputs can be null?’.

Notice how the problem is not solved yet. All I have achieved is make the code look better.

Here’s how I would have dealt with it regarding if conditions:

Condition for null inputs will be moved out to a sanitizing function. Or call will made only when inputs are not null.

...
if(input1 != null && input2 != null){
    output = DoSomething(input1, input2);
}
...

public int DoSomething(string input1, string input2)
{
    int len = input1.Length + input2.Length;
    return len < 10 ? len : someComplecatedTask(input1, input2);
}

private int someComplicatedTask(string input1, string input2){
    // lots of LOC
    return someComplicatedResult;
}

So, code looks more manageable now. There’re only two pathways per function that code can walk on, and everything is alright.

Back to the original problem.

Now let’s look at your first code snippet.

public double xMax {
      get {
           double val = 0.00f;
           switch(x_option) {
                case 0:
                     val = priMax;
                     break;
                case 1:
                     val = rfMax;
                     break;
                case 2:
                     val = pwMax;
                     break;
           }

           return val;
      }
 }

Off the top of my head, this is bad for two reasons:
1. Some time in future, x_option gains another value, you will be hunting every get {} down for appropriate change.
2. Get {} should be straight forward. Set {} should contain conditions for setting appropriate values.

So code should have looked liked this:

public double xMax {
      set {
           double val = 0.00f;
           switch(value) {
                case 0:
                     val = priMax;
                     break;
                case 1:
                     val = rfMax;
                     break;
                case 2:
                     val = pwMax;
                     break;
           }
           xmax = value * val; // say 
           // This makes break better in switch.
      }
      get { return xmax; }
 }

Since, after breaking out of your case, you can do some more (common for all cases) operations, then this is better than returning.

This example with respect to other (switch in get) one is better, since, while setting you don’t know the value, so you need a decision tree.

But while getting, your object exactly knows what it contains and returns gleefully what’s asked.

Now, your second code example shouldn’t make sense at all. Deciding what to return is not object’s duty. It should return what it has, pronto!

And while setting (set {…} ), you shouldn’t return anyway.

I hope this clears some doubts and raises few more questions since there’s a lot left to learn.

Saturday, 22 August 2015

Regarding Mathematics being pure...

 

So people say, Mathematics is pure. I do not agree.

 


https://xkcd.com/435/

 

Mathematics is pure imagination.

Here’s the thing, 1 doesn’t exist. 2 does not exist in real life. No number actually exist in real life. They all are invented; like 0.

What matters is the unit the numbers are magnitude of.

Units are also invented, here on Earth. But they impart meaning.

You never want to know just that you have two currency notes in your pocket. You want to know what their units are: 10s, 100s etc.

You never want to eat 4. You want to eat 4 slices of pizza.

You never want to walk 500. You might want to sing to maybe walk 500 miles.

I can go on about these for 4. You wanna know 4 what?

 

Now, to pick another problem Physics is applied chemistry at above molecular levels. At atomic levels, however…

What else do regions do to code in C#?

 

 

 

Regions fragment the code too.

 

 

 

You might want to read What do regions do to code flow in C#?

What do regions do to code flow in C#?

 

 

 

Regions break the code flow.

 

 

 

You might consider reading further What else do regions do to code in C#?

Constants should live in their own files in C#.

Constants should live in their own files in C#.

Consider this code:

class SomeClass {
    private const string URL = "http://example.com";
    ...
    var data = FetchData(URL, retryLimit);
    ...
}

Now, you might not be able to see the problem right away. Reason for that is: this class looks very small. But classes grow. We want nice little classes, but like Russia and China’s boundary, they grow.

When classes grow, people put code in regions, sometimes. Very bad. Regions break code flow. I’ll write that in some other post. Regions also fragment code. I will write that too in another post. (update: did post them)

Even without regions, when we are using a constant variable like, URL here, we do not know if it is a constant or not. You have to trace back to it’s origin which is a context switch and break in programming-flow. Or you have to wait for the intellisense to kick in, which again is a context-switch and a break in the programming-flow.

What can we do?

Well, pull out the constants in another file. Name it SomeClassConstants.

Here’s an example:

class SomeClass {
    ...
    var data = FetchData(SomeClassConstants.URL, retryLimit);
    ...
}

static class SomeClassConstants {
    public const string URL = "http://example.com";
}

For this pattern, read Constants done the right way in C# - Static class, constant members .

Now, you will say, But Anubhav, your solution is verbose too. Everywhere we are going to see SomeClassConstants.Variable.

Well, that’s kind of the point. As soon as you read it, you know that it’s a constant and not a variable named Variable.

This reminds me of this particular XKCD.

enter image description here

That’s all for now. We do need to name the pattern though.