Answer to a Beginner’s JavaScript Question

A friend of a friend is learning how to code in JavaScript (non-technical, first programming language). Here’s the question:

I’m very early on in the lesson, and I simply can’t wrap my brain around it. It’s like math equations and they just look like gibberish to me. I keep thinking that if I just keep plugging away at it, it will start to make sense, but I’m just stumbling through with no understanding of what I’m doing.

This is simple, basic, beginner code:

var my_number = 7;
var timesTwo = function(number) {
    var my_number = number * 2;
    console.log("Inside the function my_number is: ");
    console.log(my_number);
};

timesTwo(7);
console.log("Outside the function my_number is: ")
console.log(my_number);

 

And while I kind of get the gist of it, I can’t “read” it like a sentence, where I understand each step, like I do basic HTML and CSS. Stuff like this:

<div id="header">
    <p id="name">Your Name Here</p>
    <a href="mailto:you@yourdomain.com"><p id="email">you@yourdomain.com</p></a>
</div>

 and this:

.right {
   background-color: ‪#‎E3E4FA‬;
   height: 800px;
   width: 88%;
   float: right;

I can read it like a sentence and understand each and every word. I’m doubting myself, that if I’m struggling this much with these simple beginner concepts, there is no way in god’s green earth that I will be able to keep up with a bootcamp course. Did y’all have this kind of experience when you were learning? Did you hit a wall, then have a breakthrough and the rest was understandable? Or was this all super easy to you from the start?

“ANSWER” (MY ADVICE):

The stuff you can read (HTML and CSS) is written in a “declarative programming paradigm.” So congratulations, you understand this style of programming. The other important style you will have to master is the “imperative programming paradigm,” where behavior and flow are implemented in distinct steps. This is the most common and more general-purpose programming paradigm. Most programmers will need to know a mixture of both.

For most beginners, the biggest learning curve is learning your first imperative programming language. Although the concepts will get more and more advanced as you learn, the simplest concepts are often the hardest because you are starting from scratch. The best way to learn is by combination of hands-on (doing), experimenting (tinkering), focused research (asking questions/reading forums), and traditional learning (reading, tutorials, sometimes classroom).

To avoid information overload I recommend that you break things down into small nuggets. You don’t have to understand everything at once. If you are struggling it’s often because you aren’t breaking the problem down into small enough pieces or there is a concept you might be over-complicating. Learning how to code can be fun and rewarding, so if it’s not, you’re doing it wrong. Relax and enjoy the process of experimenting with code. Software developers can get away with reckless experimentation that would otherwise be materially expensive in the real world, so don’t be afraid to make mistakes or get confused in the beginning. Learning can be messy, but it should always be fun. After all, it’s all in your head.

Let’s go over your code snippet. I’ve typed it into notepad, added some minimal HTML, and saved it as a web page on my desktop called “example.html.” I’ve opened it up in Chrome, hit F12 (F12/Debug mode is your friend), and displayed the Console output:

 

js-source

…as you can see from the console output, the gist of the lesson was to demonstrate that the variable “my_number” outside of the function is a *different* variable than “my_number” inside the function. The first is global scope, while the second is function scope (exists only in the function).

To get a better understand of what is going on, here’s an informal explanation of what is happening, line-by-line:

1. var my_number = 7
Assign the number 7 to the GLOBAL scope variable “my_number”

2. var timesTwo = function(number) {
Declare a function called “timesTwo” that takes in a parameter (input variable) “number” We are not running or executing the function here, we are just defining (declaring) it. Later on when we get to the line that says “timesTwo(7)” we are calling it and passing 7 as the value for input variable “number”… but right now we are just declaring the function name and input parameters.

3. var my_number = number * 2;
We are still in the definition of the function “timesTwo.” Here we multiply the input variable “number” by 2 and assign it to the LOCAL scope variable “my_number”. It is unrelated to the GLOBAL scope variable “my_number” on line 1.

4. console.log(“Inside the function my_number is: “);
We are still in the definition of the function “timesTwo.” All we are doing here is displaying the literal string “Inside the function my_number is: ” to the console. I say “literal” because it is in quotes.

Note that in a web browser, the end user won’t be able to see the console. You have to go into debug mode to see console output. It’s just for troubleshooting. In real-world (“production”) code you wouldn’t be doing this, so this is just for simplicity (learning).

5. console.log(my_number);
We are still in the definition of the function “timesTwo.” Here we are displaying the value of the LOCAL variable “my_number,” which will be the local variable “number” times 2. Recall that “number” is an input variable, so we don’t know what will be displayed later until we call our function (“timesTwo”) later on.

6. };
This is the END the definition of the function “timesTwo.” (closing curly brace + end of statement semicolon).

7. timesTwo(7);
Now we are calling (running) the function we have just defined. We are passed in the value 7 for the input parameter (input variable) “number.” Since we are really running through the function now (not just defining it), go through steps 2 through 7 again with the number 7 plugged into “my_number” to see what happens.

NOTE: if you are the kind of person who tends to overthink things, you may be confused as to why the literal number 7 was passed in instead the value of GLOBAL scope my_number, which was also 7. I’m not sure why other than perhaps the author of this example wanted to show that 7 could be passed in literally (directly) rather than using the variable. Sometimes when you read code you must keep your inferences and judgments separate from your observations–that’s a troubleshooting skill that you will develop over the years (balance of critical thinking, scientific method, observation, inference, and intuition).

8. console.log(“Outside the function my_number is: “);
All we are doing here is displaying the literal string “Outside the function my_number is: ” to the console.

9. console.log(my_number);
Here we display the GLOBAL scope variable my_number. Notice that is hasn’t changed since line 1. You could pretty much delete lines 2 through 8 and you would get the same answer on line 9.

Although the language is JavaScript, I’ve seen this lesson since the 1980’s across several different languages: BASIC, FORTRAN, Pascal, C, C++, Visual Basic, C#, and Java. There will be some gotchas with JavaScript variable scope compared to those other languages, but in the general case (and certainly this case), the variable scope rules are the same.

Hope this helps.

How to Choose the Right Service Bus

How to Choose the Right Enterprise Service Bus
http://www.slideshare.net/KaiWaehner/spoilt-for-choice-how-to-choose-the-right-enterprise-service-bus-esb

Gartner Magic Quadrant: ESB vendors 2012
ftp://ftp.software.ibm.com/software/emea/de/commerce/magic_quadrant_for_application.pdf

After reading the above two sources, you might begin to think that the Oracle and IBM SOA solutions are overkill, too expensive, or requires too much vendor lock-in for your needs. If so, read on:

Apache Camel (Integration Framework) VS
Apache ServiceMix (OSGI Container) VS
Mule ESB
http://stackoverflow.com/questions/3792519/apache-camel-and-other-esb-products

NServiceBus + ServiceMatrix/ServiceInsight/ServicePulse
http://particular.net/

Low Cost SOA using Microsoft technologies
http://www.utwente.nl/ewi/trese/graduation_projects/2012/RT-003.pdf
If you are a Microsoft-stack developer, then this paper is really easy to follow. If your SOA needs are simple then some of the solutions he mentions may be enough for your project. Although the paper covers the VETO service mediation pattern, you should also look up VETRO–the R (“Routing”) is important.

JMS and ESB
http://stackoverflow.com/questions/5322675/jms-and-esb-how-they-are-related

Reliable Messaging: Transport ACK vs Application ACK

http://www.infoq.com/articles/no-reliable-messaging
“From a business perspective, a well-designed business solution does not need reliable messaging.”

  • The article demonstrates cases where transport acknowledgements (WS-ReliableMessaging) are insufficient; instead, application acknowledgements (“business-level acknowledgements”) are necessary.
  • In my experience, the distinction is similar to cases in USMTF/VMF messaging applications where lower-level transport acks or even header acks are ignored in favor of more semantically meaningful message-level acks in the body of the message.

 

IISExpress in Application Server Mode: External + HTTPS

IIS Express can also be run from the command line in “Application Server Mode”. (REF: http://blogs.msdn.com/b/robert_mcmurray/archive/2012/07/03/working-with-the-different-iis-express-modes-and-https.aspx) This option is desirable if you need to run IIS outside of Visual Studio; however, due to a design limitation (flaw?) in the iisexpress.exe command-line, you can’t use the HTTPS protocol, only HTTP. I’ve found a reasonable workaround in PowerShell that works with both IIS 7.5 and 8. We take advantage of the \config option to load in our own customizations. We override the protocol to allow HTTPS and also broaden the port bindings (we want the site to be accessible by other systems for testing, not just localhost, so we drop “localhost” from the port’s bindingInformation).

NOTE: You may first need to make a one-time reservation of the port using “netsh http add urlacl url=… user=…” from an elevated command prompt. “netstat -ab” can help determine which ports are in use. (The “b” option requires an elevated command prompt but it gives you the process names.)

param (
    [string]$site_path = "%IIS_BIN%\AppServer\empty_wwwroot",
    [string]$site_port = "8080",   
    [string]$site_protocol = "http" # needs to be http OR https
)

$dirConfigRoot = "$env:USERPROFILE\My Documents\IISExpress\"
$dirConfigTemp = $dirConfigRoot + 'tmp-config\' + [system.guid]::newguid().ToString()
$dirAppRoot = "${env:ProgramFiles(x86)}\IIS Express\"
$srcCfg = "$dirAppRoot\AppServer\applicationhost.config"

# create temp dir with a copy of applicationhost.config
new-item -ItemType directory -Path "$dirConfigTemp"
copy $srcCfg $dirConfigTemp

# modify temp applicationhost.config to allow site protocol (http OR https)
# this fragment is based on http://robrich.org/archive/2012/07/06/iis-express-protocolhttps.aspx
$doc = New-Object System.Xml.XmlDocument;
$doc.Load("$srcCfg");
$vdirNode = $doc.SelectSingleNode("//sites/site[@id='1']//virtualDirectory");
$vdirNode.physicalPath = "$site_path";
$bindNode = $doc.SelectSingleNode("//sites/site[@id='1']//binding");
$bindNode.protocol = "$site_protocol"; # override protocol
$bindNode.bindingInformation = "*:" + $site_port + ":"; # allow public by dropping localhost
$doc.Save("$dirConfigTemp\applicationHost.config")

# run
set-alias iisexpress "$dirAppRoot\iisexpress.exe"
iisexpress /config:$dirConfigTemp\applicationHost.config /siteid:1 /systray:true /trace:error

# clean up when exit
remove-item $dirConfigTemp -force -recurse

If you get this exception when you run the above script:
Failed to register URL “http://*:8080/” for site “Development Web Site” application “/”. Error description: Access is denied. (0x80070005)

Then you’ve need to make the one-time reservation of the port I mentioned earlier. Set this from an elevated command prompt:
netsh http add urlacl url=http://*:8080/ user=everyone

Of course, substitute whatever port you are trying to set for 8080; for example, 44300 for HTTPS:
netsh http add urlacl url=https://*:44300/ user=everyone

SalesForce Canvas Library for .Net

https://github.com/short000/salesforce-canvas-dotnet

SalesForce.com does not directly support CORS or JSONP for cross-origin resource sharing of an IFRAME; instead, they have their own implementation called SalesForce Canvas. Since SalesForce instances (and therefore your IFRAMEd application) must be exposed to the Internet, some validation is required. It involves reading an encoded “signed request” and comparing a hash of it against a SalesForce consumer secret known by the non-SalesForce application. If those two things match up, we can assume the request is valid and use the OAuth token and other rich user+server contextual information provided by SalesForce. This contextual information is required for eventing over XmlHttpRequest (XHR). For security reasons the validation of the signed request against the consumer secret should be done server-side.

SalesForce has a nice PDF about Canvas at http://www.salesforce.com/us/developer/docs/platform_connectpre/canvas_framework.pdf. It even covers publish-subscribe XHR eventing between the application and SalesForce; however, the thing I don’t like about their documentation is that they push their Heroku platform too much in their examples. Although it’s cool if you are looking for a PaaS, if not, Heroku is unnecessary and complicates things when you are just trying to grasp the basics. If you’re a .Net developer you have to substitute your own equivalents as you go through their tutorial, so I wrote a simple library in C# with two simple “Hello-World”-style examples, one in ASP.Net MVC and the other in ASP.Net Web Forms. Here’s a link to my implementation in GitHub: https://github.com/short000/salesforce-canvas-dotnet

It includes a tutorial (https://github.com/short000/salesforce-canvas-dotnet/blob/master/SalesForceOAuthExamples/ReadMe.pdf) for configuring your SalesForce Connected App to work with this example.