Recent posts

Employment & Contracts at Silicon Valley Startups

Recently I was helping a friend from Australia with employment contracts & options from few Silicon Valley startups. Then it struck me that I need to share this knowledge with other folks in the same shoes. I cannot believe that I had not blogged about this earlier.

So you already know that Silicon Valley is the world’s hub for startups. Companies that are starting up with big visions to turn into a multi-million dollar company that is going to revolutionize the industry they are focused on. The fact is that only few ever succeed to become a feature article, a story making headlines, leading to an IPO or an acquisition and making its employees wealthy in the process. Contact a business law Highland Park office if you need help solving any employment issue that your business is facing.

So you came to Silicon Valley and are ready to start cracking working for a startup to help it reach success. Here is a few things you need to know about employment and contracts when joining a startup or running your own startup in the valley.

Salary

Check out glassdoor.com to see company salaries, reviews, and interviews – all posted anonymously by employees in Silicon Valley. Don’t forget that the salary is only a part of the whole package so make sure you understand the next topic on stock options which can make that average salary skewed.

The low down is that if you have been head hunted and the company really wants you then you control the price on your head. Not a website showing you what the average Joe out there earns.

Stock options

If you are joining a startup or about to start one you will be hearing a lot about stock option grants, also known as ISO (Incentive Stock Option). The purpose of stock options is to attract and retain the best available personnel and promote the success of the company’s business. Basically to make the employee feel like they own a part of the company and will feast in the rewards of the company’s success. If you’re looking for some of the most reliable dividend stocks I recommend to visit https://www.stocktrades.ca/best-canadian-dividend-stocks/.

“Employee Stock Options are call options which grants its holder the right, but not the obligation, to buy the company’s shares at a fixed price known as the “Grant” or “strike price” before the expiration date is reached.” ~ optiontradingpedia

The long-term goal is that those stock options will be worth something in few years… more than they are at the time of issue. Like x10 more. And the employee will profit favorably during a private acquisition or an IPO (Initial Public Offering on the public stock market) of the company. At that point the stock “option contracts” are said to be “exercised” and converted to real stock and sold to new holder/owner. Assuming that they don’t expire before then.

Typically in an early startup, employee’s wage is sacrificed for more stock options. This is high risk but more of a rewarding strategy assuming the stock options percentage (%) is favorable. I wrote (%) percentage since this is typically worth more than being given a volume that is hard to justify & work out. The reverse holds true that once the company has grown well into few dozen employees and doing well financially, stock options are reduced and wage levels out with industry standards.

Here’s a previous blog post I did on equity split, common terms & compensation 101.

Let’s do the numbers

Issue value = volume x issue stock value
Your profits = (issue value * growth (assume x10)) – issue value

So your $100K of stock options could be worth $1 million and you profit $900K before taxes.

If you worked at this company for 10 years and earned a wage of $50K then its like earning $150K per year in wages. Now is this worth it? What are the opportunity costs? Work them out. Since taxes will be different in both scenarios and you may have been able to early a larger wage with bonus per year which would have compounded exponentially – especially if you had invested that money! So is it worth it? Theoretically you could be better off earning a higher wage then taking a pay cut to get more stock options. Work this out and don’t fall prey to what may happen in the future because failure in a startup in pretty high in the early days.

At-Will Employment

California is an At-Will Employment state. This means that you or the company has the right to terminate the employment relationship at any time, with or without cause, and with or without notice.

At first this sounds a bit harsh but it has its merits. Back in Australia you have to give the employer notice and this is always a 2-4 week period. You have to. In California if you are leaving on good terms then it’s customary to give a 2-week notice as a nice gesture. However not required by law. Now, if you are leaving on bad terms like say to due unfair treatment, you can just walk out the door immediately. Why waste another breath in a place you are not happy at? However, if you believe your employer is terminating a contract unprofessionally, it’s wise to consult an employment lawyer to understand your rights and options.

The other angle is that the employer can terminate you instantly. Now if this termination is unfair you can seek legal action. For this reason, many employers have what is called Performance Improvement Plan (PIP) which gives the employee a fair chance to succeed. If this doesn’t work out then a termination by law is customary. It also protects the employer from legal action. Which happens very frequently.

Health Insurance

You need insurance in the USA. Without it you can end up a sitting duck should you get sick and not have enough money to cover the bills. Medicine in the USA is very expensive. A standard visit to the GP could cost you around $200.

Just about every startup that has funding will be providing it’s employee a form of medical cover. Typical choice of 2 or more insurers (options) will be available. These 2 options will be in the form of Health Maintenance Organizations (HMO) or Preferred Provider Organizations (PPO).

In a nutshell PPO is choice with higher co-pay and HMO is less choice with lower co-pay.

Co-pay

A co-pay is what you are expected to cover after every medical expense. Say you visit a GP and your co-pay is $10. So you pay $10 to the medical foundation your GP belongs to and your insurance company covers the rest. Same with medicine, it’s all $10 out of your pocket per prescription. PPO co-pay is typically double of HMO so you end up paying around $20.

In or Out of Network

If you select HMO you will need to find a medical group to join. This is called In-Network and is the medical network (a group specialists affiliate themselves with) you will use to find & see the same GP. Yes you must find a GP which is taking patients and then work through them. I personally like the Palo Alto Medical Foundation. A group of large hospitals & medical facilities in the bay area. Once inside this network you GP will only ever assign you to see a specialist that “belongs” to that network.

On the other hand if you have PPO you can opt to see a GP or specialists In-Network (co-pay will be lower) or go outside to another network also known as Out-Of-Network where your co-pay will be higher but you will have the choice and medical coverage to see a specialist of choice. One you selected. It’s what you pay for, the choice.

If you’re healthy and have selected a good network then HMO is a good choice. If you’re paranoid and have health issues get PPO. The price difference isn’t that much.
But be warned, plan choice only ever happens once per year. Typically in December. The only other time you can alter the plan is when a “major event” has occurred like adding your spouse to the plan or loss of employment.

Dental

This usually comes bundled with your employee health plan and is typically the Delta Dental. It will cover around $1,500 worth of dental procedures on a tiered coverage plan with gap where standard checkups are 100% covered, fillings 80% and major work like root canals 50%. Some dentists can cover this gap so ask before you choose a dentist. Typically you need not make any decisions here, it’s a 1 plan for everyone. Use this great opportunity to get your teeth fixed like removing mercury fillings and replacing them with ceramic versions and get that crown you always needed but couldn’t afford in Australia due to bloated dental fees and crappy coverage back home.

I did a story comparing the Australian private insurance to the American here. The American is definitely better by a long stretch. The problem becomes if you don’t have insurance in American then your a dead man walking should you get sick.

Paid Time Off (PDO)

In America this is typically 2 weeks. Half of the comfy 4 weeks we get in Australia. However if you are head hunted you can negotiate this to 4 weeks or more. Some companies are now starting to give 4 weeks since a work and life balance is becoming a very popular topic in productivity and employee morale & motivation.

Having 4 weeks per year of holiday leave will give you ample opportunity to travel to beautiful places like Yellowstone, Yosemite, Los Angeles, New York, Hawaii etc. so you get to enjoy your USA adventure while helping a company succeed.

Other perks

Other ways employers have been luring employees is via additional perks.

  • Travel allowance. If your travel is covered you can not only go green but also have free travel. Bonus!
  • A fixed amount to buy your own computer equipment like a nice shiny Apple hardware. Everyone loves a Mac.
  • Free lunch. Such a common trend today. It has 2 benefits. The employee doesn’t have to buy or spend time making their lunch and the employer gets more productivity from their employees since the employee doesn’t have to travel to a shop to buy lunch thus spending less time having lunch. Also the employee gets to socialize with fellow colleagues during lunch hour building a tighter solid organization.

Some notable companies like AirBnB, Facebook, Google, Dropbox et al. provide plenty of perks and sell their way to your hear. Additionally, if your organization is in the process of pre-employment, you might want to use a cognitive ability test that helps you understand if a candidate can do the job.

GTDfaster: Top GTD productivity app is now live on iTunes

GTDfaster iPhone app just went up on iTunes App Store and we are super excited!

Thank you to all our wonderful Beta testers. You guys have made a HUGE difference in making this app kickass. As promised we will be sending you promocodes to download the app free of charge.

GTDfaster iPhone app is the 1st glimpse of things to come. Visit http://gtdfaster.com/ regularly to see updates, new features & services we planed for release in 2012. We are aiming to change the way you get things done.. so that it’s faster and your productivity skyrockets. Get more stuff done fast.

Now go and please check out GTDfaster.. and don’t forget to give us a review! You rock!!

Get GTDfaster from iTunes App Store:
http://itunes.apple.com/us/app/gtdfaster/id488633128?mt=8

About GTDfaster

Stuff is constantly bouncing around in our heads. Do you remember it all? Do you often forget it and remember it too late? Missed an occasion or forgot a great business idea? All this can lead to untold stress and anxiety as you try to manage it day to day.

The Getting Things Done (GTD) method created by David Allen rests on the principle that a person needs to move stuff out of the mind by recording them externally. This is the GTD principle. The GTDfaster app does exactly that! Following this GTD principle this GTD app helps you be more productive and less stressed so you can get on with life and get stuff done fast!

  

Any GTD app you pickup should make it easy for you to store, track and retrieve all information related to the things that need to get done. GTDfaster takes care of all of this for you. Here’s how this GTD app excels above other GTD apps:

1. Collect everything (stuff) that catches your attention. Immediately! No need to enter any additional properties until you are ready to process.

2. Gain control over the collected materials by processing stuff in your Buckets. Processing means deciding what to do with—not actually doing— by processing and organizing the items one by one.

3. Retrieve any notes from your finely assembled and customizable list of Buckets. Of course the standard GTD buckets are still there but with the addition of your customized buckets also known as Projects.

The power of GTD is in your hands. It’s simple and efficient. Get GTDfaster today and enjoy the world of GTD productivity. Now you know what all the GTD fuss is about 🙂

Need help?

If you have any questions or need help send us a tweet on Twitter at: http://twitter.com/#!/gtdfaster or me directly on http://twitter.com/#!/ernestsemerda

You can also watch this 20 min video explaining all the workings of the GTD process and GTDfaster. http://www.youtube.com/watch?v=0LQUh5sALgE

~ Ernest

Silicon Valley Code Camp 2011

Last weekend myself and Omid Mozayani (another Aussie; recent addition to the valley) spent the weekend of Saturday and Sunday, October 8th and 9th, 2011 at Silicon Valley Code Camp 2011. Held at the Foothill College in Los Altos/CA with an attendance of well over 2,000 (registered 3,417) people and 209 sessions organized in a University style setup over these 2 days. Impossible to attend each one but plenty to cherry pick from. It felt like I was back at Uni(versity) running between lectures. I loved it! Here’s what happened.

What is Code Camp

Code Camp is a new type of free community event by and for the developer community where developers learn from fellow developers. It is 2 full days of talking about code with fellow developers. Sessions range from informal “chalk talks” to presentations. Basically there is lots of education, networking and good food.

Pictures from Code Camp @ Foothill College

Lecture – Crockford on ECMAScript5

Lunch – feeding time for thousands of nerds

Ernest Semerda – nerd out and about

Lecture – multi threaded design

More pictures here on my Flickr.

Code Sessions

Choosing what sessions to attend was key since it was impossible to attend everything when you consider that each session took around 45 min. Here is a wrap of the 3 areas I focused on; ECMAScript (JavaScript) with code encapsulation, Writing Clean Code and Web Analytics. This website will highlight key points.

ECMAScript 5 (JavaScript)

Douglas Crockford ran 2 sessions on ECMAScript 5: The New Parts and ECMAScript: What Next?. Crockford is involved in the development of the JavaScript language and popularizing the data format JSON (JavaScript Object Notation), and for developing JSLint. You may recall me talking about JSLint in a previous blog post on JavaScript Patterns.

More on Crockford is here (his personal site) and here: Crockford on JavaScript. Also read about how JavaScript is the world’s most misunderstood language. Recommended reading! You will want to learn more about this great language.

ECMAScript’s Fifth Edition is now available in all of the best browsers. This is what you are getting:

  • Use “Strict mode” in all your JavaScript code.
    • As per my previous post on JavaScript Patterns here.
    • Old JS compiler ignores it so it’s safe to use today in all your JavaScript.
    • A bug in JS used to advantage today for backward compatibility.
    • “Strict mode” will break old bad programs. If you are writing good programs they will just work.
  • No more implied global variables within functions.
    • Yipee! Major fail in JavaScript where undefined variables would chain to the prototype making it very difficult to isolate your code, and to reuse it in new contexts.
    • If you forget to “var” a variable it now becomes undefined so you can address it vs. letting it slide by. Bad coders beware!
    • To append something to the global object add “window.function/var”.
  • “apply” and “call” do not default to the global object.
  • No “with” statement. Read why it was considered harmful to use.
  • Restrictions on “evil” eval. Here’s why it’s evil. *Cough* code injection!
  • No more octal literals. Not needed since punch card days.
  • Forgetting to use the new prefix will now throw an exception, not silently clobber the global object.

Use something like this today to check if your browser is running in Strict mode:

function in_strict_mode() {
    return (function () {
        return !this;
    }
}
  • Make it a habit to do static analysis using JSLint. If you are using it already your code is probably good and ready for strict mode.
  • Use “Safe JavaScript Subsets” like Caja & ADsafe projects which allow you to safely run 3rd party software on your website.

JavaScript Code Organization and Encapsulation

Shawn Van Ittersum presented ideas for organizing, encapsulating, and simplifying JavaScript code, including: creating JavaScript objects and classes with truly private members, using Douglas Crockford’s module pattern and classical inheritance constructs provided by Dean Edward’s Base.js, Prototype, and MooTools; abstracting JavaScript code from HTML templates, CSS styling, and the DOM; designing with polymorphism (duck typing) for code reuse and simplicity; and using JSLint to identify problems in your code before runtime.

The idea behind the power of Encapsulation is simple:

  • Encapsulation limits widespread interconnection,
  • Gives you Freedom to change internal implementations without affecting external code and
  • is referred to as Loose Coupling – an approach viewed as positive in the field of computer science to remove dependency between systems and allow horizontal scaling.

Ittersum’s lides with code samples are located here.

Writing Clean Code

Theo Jungeblut ran this session and basically the crust of the presentation was that writing clean code makes us more efficient.

This presentation was based on C# and Visual Studio 2010. However the following patterns and practices can be applied to every other programming language too.

Over the lifetime of a product, maintaining the product is actually one – if not the most – expensive area(s) of the overall product costs. Writing clean code can significantly lower these costs. However, writing clean code also makes you more efficient during the initial development time and results in more stable code.

  • Readability
    • Follow coding guidelines.
  • Simplification and Specialization
    • KISS (Keep it simple, Stupid!) – most systems work best if they are kept simple rather than made complex.
    • SoC (Separation of concern) – focus on 1 thing.
    • SRP (Single responsibility principle) – every object should have a single responsibility, and that responsibility should be entirely encapsulated by the class.
    • OCP (Open/closed principle) – software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification aka inheritance & encapsulation.
  • Decoupling
    • LSP (Liskov substitution principle) – guarantee semantic interoperability of types in a hierarchy, object types in particular.
    • DIP (Dependency inversion principle) – high-level modules should not depend on low-level modules. Both should depend on abstractions. And abstractions should not depend upon details. Details should depend upon abstractions.
    • IHP (Information hiding principle) – prevent certain aspects of a class or software component from being accessible to its clients aka encapsulation.
    • Contracts – 2 categories: preconditions and postconditions where a precondition states that certain things must be true before a method can execute, and a postcondition states that certain things must be true after a method has executed.
    • LoD (Law of Demeter or Principle of Least Knowledge) – specific case of loose coupling where units (code) only talk to immediate friends (not strangers) assuming as little as possible about the structure or properties of anything else.
    • IoC (Inversion of control) – reusable generic code controls the execution of problem-specific code. It carries the strong connotation that the reusable code and the problem-specific code are developed independently, which often results in a single integrated application.
    • SOA (Service-oriented architecture) – develop code in business functionalities (discrete pieces of code and/or data structures) that can be reused for different purposes.
  • Avoiding Code Blow
    • DRY (Don’t repeat yourself) – reduce repetition of information.
    • YAGNI (You ain’t gonna need it) – do not add functionality until it is necessary.
    • Quality through testability (all of them!)

There is also a good bunch of tips from The Pragmatic Programmer located here.

And don't forget, Scout rule = leave a better place!

Recommended book

SOLID (Single responsibility, Open-closed, Liskov substitution, Interface segregation and Dependency inversion) is a mnemonic acronym introduced by Robert C. Martin

Web Analytics

Massimo Paolini presented on Google Analytics. The most profound thing he said which delivered a strong message is:

"Web analytics is about Revenue NOT traffic."

Bang! Right there. Too many site owners are mislead into trying to decipher visitor totals vs. focusing on the true picture; and that is how to understand and optimize their site visitors across online marketing efforts. The process is then rinse & repeat.

Finally, Web Analytics is NOT a precise science. You are looking for trends. Differences. To help you make decisions moving forward. This is because some people clean their systems ie.delete cookies etc..

Presentations from Silicon Valley Code Camp

For more presentations from these 2 days follow the link below to presenter uploaded presentations to SlideShare. Includes 2011 and previous years. Enjoy!

http://www.slideshare.net/search/slideshow?type=presentations&q=silicon+valley+code+camp+2011&searchfrom=basic

More links to Silicon Valley Code Camp

Code Camp main site: http://www.siliconvalley-codecamp.com/
On Facebook: http://www.facebook.com/groups/6125701762/
On PB Wiki: https://codecamp.pbworks.com/w/page/16049741/FrontPage
On Twitter: http://twitter.com/#!/sv_code_camp

So, in conclusion, this was an awesome & insightful 2 days packed with plenty of great applicable content.

Enjoy!
~ Ernest

Object-orientated development: a lesson in PHP5

PHP has been given a major stabbing and bashing in the last few years. Mainly due to inconsistency, non native support for UTF8 and the fact that only from v5 has it been “object-orientated capable”. However, PHP just works. Out of the box. It delivers on a promise to produce dynamic web pages.

Below is a best practice guide on using PHP in an Object Orientated (OO) manner.

Why Object-Orientated (OO) Programming

  • Objects can store data internally. Therefore variables don’t need to be passed from function to function like in procedural programming.
  • Better organization, portability and reuse of code. You can place common functionality in a Class inside its own separate file using a common naming convention that can be reused in other applications by using an include. Think DRY (Don’t Repeat Yourself) principle.
  • Maintainability is improved. Code is easier to spot and alter in the 1st place. Another DRY principle.
  • Gets you building sites using MVC (Model-view-controller) framework like CodeIgniter, Zend Framework et al.. which are built around PHP5 OO and enforce good coding standards, practices and patterns.
  • Allows you to experience Convention over Configuration (CoC) principles in your MVC application.

Ok, so hopefully you are now convinced that OO is the way forward.

Object-Orientated (OO) Paradigms

Before I begin, let’s cover some basics of OO. That is, a Class represents an object, with associated methods and variables. Therefore all the functionality we will build will be wrapped in Classes. Think of them as blueprints for an object.

PHP treats objects in the same way as references or handles, meaning that each variable contains an object reference rather than a copy of the entire object. Note, since objects can be passed as arguments to a function they are by default “copied” unless you specify the argument as a reference variable &$variable.

Here’s a run down of some fundamental OO Paradigms you should be considering and even using to write kick ass OO code.

These paradigms are all used in my sample code below.

Inheritance

Inheritance extends a Class (base) to bring additional functionally to your Class (child). This allows you to create a hierarchy of interlinked classes. In PHP5 only 1 Class can be inherited.

For example, if we have a parent Class “Dog” which holds common Dog like behavior like “bark” we can extend that into our child Classes say “Poodle”, “Husky” etc… Therefore Poodle and Husky can both inherit the same method called “bark” which specifies the shared functionality without having to repeat it across other children Classes.

More on inheritance is covered here: http://www.php.net/manual/en/language.oop5.inheritance.php

Constructor and destructor methods

These are methods called upon creation or destruction of Class object. Typically if you want to initialize a certain property on the creation of an object or cleanup post use.

More on these methods is covered here: http://php.net/manual/en/language.oop5.decon.php

Member privacy (visibility)

This defines who has access to members and methods.

<strong opinion>I believe visibility is a lot of hog wash in PHP. PHP was designed by Rasmus Lerdorf for “web development to produce dynamic web pages” (ref: wiki). Member privacy is largely important when building components that are used by 3rd parties. Like something you would do in Java/C++ with dll/com objects. There is absolutely no good reason I know of why you’d want to hide certain Class functionality from your own developers. Use Interfaces if you must “guide” them on what they can and cannot use. Python got this right!</strong opinion>

More on member privacy is covered here: http://www.php.net/manual/en/language.oop5.visibility.php

Encapsulation

Encapsulation is a reference to well-defined interface to a set of functions in a way which hides their internal workings. The benefit here is it can reduce complexity for another developer by not exposing the whole inner workings of a class. This is achieved using member privacy (discussed above).

More on encapsulation here: http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)

Interfaces

Allows you to specify a Class templates for other developers to showing which public methods can be implemented without exposing how these methods are handled. Only methods can be declared in an Interface, not variables. More than 1 Interface can be extended in a Class.

More on interfaces can be found here: http://en.wikipedia.org/wiki/Object-oriented_user_interface

Overloading

Overloading allows you to dynamically create or extend public properties or methods. These dynamic entities are processed via magic methods.

More on overloading here: http://www.php.net/manual/en/language.oop5.overloading.php

Patterns

Factory: The Factory pattern allows for the instantiation of objects at runtime. It is called a Factory Pattern since it is responsible for “manufacturing” an object. A Parameterized Factory receives the name of the class to instantiate as argument. And;
Singleton: The Singleton ensures that there can be only one instance of a Class and provides a global access point to that instance. Often implied in Database Classes, Loggers, Front Controllers or Request and Response objects.

More on Patterns here: http://www.php.net/manual/en/language.oop5.patterns.php

Now let’s look at how all of this would fit into code.

Note that I have tried to fit all these practices into the 1 sample of code below. Read the internal comments I put in to understand what is going on. Any mistakes or questions please use the comments section below to let me know.

The CODE – in PHP

// Interface implementation
interface BaseInterface
{
	function method0();
}

// Class definition with keyword "implements" to implement BaseInterface interface above.
class BaseClass implements BaseInterface
{
	// property declaration
	private $attribute3 = "This is PHP5";

	// method declaration, by default this is public
	function method0() {
		print "This is Method0";
	}
}

// Always use Upper camel case naming notation for class names
// Inheritance is achieved by using the "extends" keyword with class you want to extend.
class ChildClass extends BaseClass
{
	// This variable is accessible without needing an instantiation of the class.
	public static $attribute0 = "Yes I'm visible";

	// This variable can only be accessed within this class
	// This is also an encapsulated attribute never exposed outside the class.
	private $attribute1;

	// This variable can be accessed outside this class
	public $attribute2;

	// Note the above visibility of the attributes.
	// There are 3 types and can be accessed - public (everywhere), protected (class & inherited) or private (only by class).

	// A class can only have 1 constructor
	// Suitable for any initialization that the object may need before it is used.
	function __construct($arg1, $arg2, …) {
		// Use operator arrow to access class variable
		// Note the lack of $ in front of attribute1. This is valid and also a common mistake among newbies.
		$this->attribute1 = "ABC";
	}

	// A class can only have 1 destructor
	// Called when the object is explicitly destroyed.
	private function __destructor($arg1, $arg2, …) {
		$this->$attribute1 = "";
	}

	// This method has no "visibility" declared so by default it becomes "public".
	function method1() {
		print "This is Method1";

		// Access to base class method / attribute using parent::
		// This call docent automatically evoke base class contractor / desconstructor unless called via parent::
		print "From BaseClass: " . parent::$attribute3;
	}

	// "final" stops this method from being overridden.
	final public function method2($a) {
		$this->attribute2 = $a;

		// Displays to screen the "encapsulated" attribute
		print $this->attribute1;
	}
}

// Accessing static attribute without instantiating a class
print ChildClass::$attribute0;	// Output: 'Yes I'm visible'

// Creating new instances of the child class
// Note that since ChildClass has arguments in the constructor function those need to be passed during this object's instantiation.
$foo = new ChildClass(1, 2, ...);
$bar = new BaseClass();
// Like functions, this instantiated object will have its own "class scope" so any method/variable is different to say $bar object.
$soap = new BaseClass();

// Accessing object members
$foo->attribute1;		// Output: 'ABC'
$foo->method1();		// Output: 'This is PHP5'
$bar = method0();		// Output: 'This is Method0'

I think that is enough to digest for now. If you want to read more on Object-Orientated PHP5 I recommend you visit PHP.NET here: http://www.php.net/manual/en/language.oop5.basic.php

Hope this post has shed more light on OO in PHP and you are ready to crank out some clean and usable OO code.

~ Ernest

ECMAScript: The history of JavaScript

JavaScript is a very interesting language that has caught my eye in the last year. Previously I blogged about the power of the Module Pattern in JavaScript; why it’s powerful and how to make sure your site complies to this great pattern. The language has come a long way and is growing up fast to be the defacto language of choice for all front-end UI/behavioral functionality. Flash, the old heavy dog, is on its way out. JavaScript, part of the HTML5 stack, is looking the most promising.

This post isn’t about how great JavaScript is, it’s about its history. Before one delves into anything one should always understand the basics. So let’s begin with some basics and then its history. The history is rather interesting.

What is JavaScript anyway?

JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions.

For the business guy

  • JavaScript is client-side language. Meaning anyone with a browser can view it in its entirely. Nothing is hidden. This is how we have access to any site’s code. Right click on any webpage and select “View Source” – Bingo!
  • JavaScript is downloaded via your browser and then executed within the browser. This is where performance bottlenecks are experience and browser compatibility issues.
  • JavaScript’s real name is actually ECMAScript.

For the tech guy

  • JavaScript is a “prototype-based scripting language” meaning it is object-oriented where classes are not present, and inheritance is performed via a process of cloning existing objects that serve as prototypes.
  • JavaScript is “dynamic”; meaning that it executes at runtime.
  • JavaScript is “weakly typed”; meaning you can cast memory to any type and
  • JavaScript has “first-class functions”t meaning it supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning them to variables or storing them in data structures.

History of JavaScript

There are many stories online but I think this one below (source) explains it nicely.

Here is something else you should know about Javascript that seems like it was almost designed to be confusing as possible:

  • There is a programming language called Javascript.
  • There is a programming language called Java.
  • There is an interpreter (‘thing that makes it go’) for the programming language Javascript built into most web browsers
  • There is an interpreter for the programming language Java that is sort of built in to most web browsers, or was.
  • THESE TWO PROGRAMMING LANGUAGES HAVE ALMOST NOTHING TO DO WITH EACH OTHER

Back in the olden days, there was a company called Sun that had invented a programming language they decided to call Java. It was very trendy and exciting. There was a company called Netscape that made the trendiest and excitingest web browser. Sun wanted Netscape to include the magical crap that would make Java work with their browser, because everyone was gonna get Netscape, so everyone would also automatically have the stuff that makes Java programs work. On the other hand, Netscape was saying, “but lets also make our own tiny programming language that runs right in the browser so instead of having to make up new html tags like ‘blink’, web authors can make annoying shit we haven’t even thought of yet!” So they said, “Sun, we’ll ship your ‘Java’, but we want to be allowed to call our other programming language, which has absolutely no relationship to yours and is intended to do completely different things, JavaSCRIPT.” And Sun said, “OK, swell. go nuts. That won’t matter to us. ONCE JAVA TAKES OVER THE WORLD!”

So Netscape said to a guy named Brendan, who worked at Netscape, “Please make us a programming language. Also, you have to call it Javascript. Also, if you can make some of it kind-of sort-of look a bit like Java, that would be even better. Also, you have only 10 days to do this so get cracking!”

Fortunately, it turned out that Brendan was a cool genius and he secretly designed a cool programming language and dressed it up in some vaguely Java-looking disguises, kind of like how children will sometimes wear a huge cloak and stand on top of one another in order to get into R-rated films.

But Brendan’s disguise worked too well! People were like “wtf is with this crap version of Java? IT SUCKS!” Also, even a cool genius like Brendan has some some limits, so he did make a few mistakes when he was making his programming language in only 10 days. Also, because Netscape had basically thrown down the gauntlet and said, “You think the blink tag is annoying? Marquee makes you want to rip your eyeballs out? YOU HAVEN’T SEEN NOTHING!” people did manage to find insanely annoying things to do with Javascript. All the cool people installed special software on their web browser JUST TO MAKE JAVASCRIPT NOT WORK. So it took many years before people started to figure out that Brendan’s language was wrapped in an elaborate disguise and that it was actually cool.

Weirdly, some of the main people who did this were people at Microsoft, who had tried to confuse this whole mess out of existence by coming out with programming languages named stuff like J++ and JScript. Netscape, at the time, was threatening to rip Microsoft apart, like a crab rips up a cuttlefish with his claws. So Microsoft, adopting the strategy of the cuttlefish, made a million confusing “J” programming languages, hoping to escape intact. A prophet by the name of Douglas started saying, “guess what nerds, it turns out Javascript is actually sort of awesome.” He managed to attract a fair number of acolytes, who fiddled with Brendan’s invention and realized that it was rather elegant and could certainly be made to do all sorts of useful, non-annoying things on webpages, if only people would stop blocking it.

And so the era now known as Web 2.0 began. There are a lot of things people associate with Web 2.0, but for people who make the internet, one of the biggest things was seeing sites like Flickr or Oddpost do cool stuff with Javascript and other technologies that had been previously considered lame.

And then, in a sort of poetic irony that makes this story almost seem like it was pre-scripted to Teach us a Lesson, JAVASCRIPT succeeded in doing what JAVA had intended to do. Microsoft, Java, Sun, Netscape, all were brought low by their hubris. But humble Javascript, the throwaway, ‘you get 10 days to make this’, blink-tag-replacing runt of a language was able to sneak onto every computer in the world thanks to its clever disguise. Servers are written in Javascript. Databases are built to talk Javascript. The people who build browsers and operating systems move heaven and earth to make Javascript just a tiny bit faster. Java’s still out there, of course. In various forms. It probably makes sure your account is updated when you pay your water bill. It’s making the underpinnings of your android phone work. It’s figured out a way to play host to a zillion new trendier programming languages. But Javascript won the original prize.

Anyway, I’m just pointing this out because I remember the time when I didn’t know the difference between Java and Javascript and I’d find a tutorial for one or an article about the other and I was like “wtf, how do these go together.” The answer is, “they don’t. Marketing people just tried to name them as confusingly as possible.”

JavaScript today is..

  • Used in every website you visit online.. like 99.9999% of them.
  • At the core of famous server-side Node.js, an evented I/O framework.
  • If you heard of beautiful frameworks like jQuery, YUI, and more recently SproutCore and Cappuccino (Objective-J).. all JavaScript.
  • HTML5? replacement for Flash and other slick interface functionality, yap you guessed it.. JavaScript.
  • It is the most important language today! To keep track of your programming project — its progress, bugs, or issues, you may introduce jtrac to your team.

What next

Plenty more informative & juicy articles on this front are being lined up. Not to mention I am starting a fun project with few smart software engineers in the valley which aims to give back to the community around this most important language today, JavaScript. Stay tuned to find out more on what’s next!

~ Ernest

Aussie founders in Silicon Valley

There are over 17,000 Australians living in San Francisco and the Bay Area (Silicon Valley). And some of these Aussies are making their presence felt in the Valley’s high-tech scene.Back in March 2009, when I arrived in the Valley full-time, I had no clue about the extent of the Aussie footprint here. As time ticked on and I got familiar & orientated around the tech scene the area has to offer I got fired up and inspired. I started to see what fellow Aussies were up to, the impact they were/are leaving and great opportunities this area provides.

Below is a list of these Super Aussies and the companies they are running (have run & sold) in the high-tech scene of Silicon Valley.

Founder/s Company Notes
Mike Cannon-Brookes & Scott Farquhar Atlassian Known for Jira, Confluence etc. 26K customers from 144 countries use Atlassian tools. Operates in Oz & SF.
Andrew Lacy Tapulous Acquired by Disney.
Bardia Housman & Adam Broadway Business Catalyst Acquired by Adobe. Bardia is soon to launch and soon to launch StartupHouse.
Elias Bizannes StartupBus Also runs Silicon Beach OZ & The DataPortability Project, blog and soon to launch StartupHouse.
Ryan Junee, Simon Ratner & Julian Frumar Omnisio Acquired by Google.
Ryan Junee Inporia See Omnisio above + also a mentor at 500 Startups and StartMate.
Andrew Roberts Ephox Operates in Oz, Palo Alto & Europe.
Sam Chandler NitroPDF Operates in Oz & SF.
James Nicol Fundly
Ben Keighran Chomp
Mick Johnson GasBag & Whereoscope
Lars Rasmussen Google Maps & Google Wave Recently moved from Google (Sydney) to Facebook in Silicon Valley.
Gower Smith Zoom Sytems
Leigh Jasper Acconex
Upcoming startups from my aussie mates.
Denis Mars Player.ly Currently in stealth-mode. Y-combinator alumni.
Vincent Turner PlanWise Aims to empower consumers with tools for planning and forecasting your finances. Presented at Finovate NYC.
Last updated: Sept 2011

Advance.org – Global Australians. Global Networks.

Advance.org helps create opportunities for Australians living abroad. They organise events/forums in and around San Francisco / Bay Area to help Aussies to connect together, share ideas, spark mentorship & marketing programs. More here: advance.org

Aussie incubator for Australian start-ups – The Startup House

Bardia Housman (see above ref Adobe) has purchased a 36,000 sq foot building (at 880 Harrison Street, San Francisco, CA 94107),  in the heart of San Francisco, to transform it into an incubator for Australian start-ups. It’s currently being built up but will most definitely be a kick ass place for Aussies enterprunrs. More on this project with Elias Bizannes (see above ref StartupBus) in the video below. All the best guys! Looking forward to paying a visit.

Media coverage: Recently published in the Sydney Morning Herald (SMH)

Gold diggers: Aussies strike it rich in Silicon Valley
By Asher Moses, September 15, 2011

  • Tony George from Austrade in Los Angeles helps Australian start-ups get a foothold in the US.
  • Austrade provides grants, helps entrepreneurs with research, advice about market entry, referrals to service providers such as lawyers and accountants, and most importantly hooking them up directly with potential customers.
  • Pollenizer and Startmate are helping the Australian tech start-up scene grown. But the conventional wisdom is still that start-ups needed to go to the US to raise funds and be exposed to the movers and shakers in the tech industry.

If you know of other Aussies in Silicon Valley/SF that are steaming ahead with their product/s please let me know and I will add them to this list above. Thanks!

Aussie Aussie Aussie, Oi Oi Oi!

~ Ernest

Hiring, Tips on finding rockstar software engineers

Another great day at Hacker Dojo and another great discussion on startups and finding talent in the bay area. So I was asked by a founder of a mobile startup company in the bay area on my experience hiring engineers. Here’s the jist of this discussion.

The big 3 – finding rockstar engineers

1. Utilize your network to find rockstar engineers.

There is nothing like finding the right person through your professional or personal network. Those are usually qualified leads; especially if the person you found them through you know well and is also a great engineer. Great engineers like to hang out with other great engineers.

So hit up your LinkedIn, Facebook and Twitter to let your network know you have an amazing opportunity open for the right person. And, if you need to develop a custom software, you may visit the Emergent Software homepage for more info.

If you are on a budget, stay away from external recruiters. They are expensive and hungry to get a sale through the door. They work on commission so will flood you with resumes. My experience has showed me from that flood only 3-5% of the talent is what I would class as rockstar engineers. If you must use one, detail & finecomb your requirements to them so the flood of resumes is more like a filtered clean stream of decent talent. You may also read some resources from sites like https://ursusinc.com/blog/ to find useful tips on how to hire a reliable and skilled tech employee.

2. Rockstar engineers are not looking for a job.

It is your role to convince them to come and work on your idea with you because it is better for them. Better for them because of growth (financial & personal) opportunities (*Mastery) and that they will be “changing the world” (*Purpose). Read my previous post on Compensation 101 so you nail this right. Most of all, if you can also offer flexibility (*Autonomy) you will be on a winning hiring streak.

(*) = if you haven’t yet read Daniel Pink’s book Drive: The Surprising Truth About What Motivates Us.. then I highly recommend you do. The key 3 points marked with * above are paramount to getting these rockstar engineers on board your train.

3. Attitude over skills.

Engineers with great attitude can be relied on. Their great attitude allows them to be in constant growth phase. Open to change. Positive attitude. And be able to move with the changing times. This is actually Talent. Talent is the ability to learn new things. Skills get outdated fast in this fast changing landscape while talent is something which stays with one forever.

Bonus – how to kick off an interview

So you got a rockstar engineer to come in and have a chat with you.. what next?

  • Interviewing is a 2 way street. You are interviewing the candidate and the candidate is interviewing you. This especially applies for rockstar engineers. Don’t forget this and try to make their experience as pleasurable (and memorable) as possible.
  • Start the process by asking the candidate “What is your most proudest moment in your professional career”. This gets the candidate talking and you can listen, gauge and ask specific questions to drill down into topics that might not have made to their resume.
  • Draw a mindmap as the candidate talks about their proudest moment. This is there to help you understand, navigate and ask better questions. Also shows to the candidate you are paying attention. Remember, your interviewing a rockstar engineering.

More on hiring

If you found this post useful and are now thirsty for more hiring hacks, check out my extensive list of posts (notes) from events I attended where the likes of Auren Hoffman (Rapleaf), Russell Fradin (Dynamic Signal), Dan Arkind (JobScore) etc… shared their experiences.

Have questions? use the comments section below or contact me.

Are you a rockstar engineer?

Then I want to speak to you. We are hiring for many exciting positions at coupons.com.

Coupons.com is located in Silicon Valley (California) and is the leading provider of consumer-printed coupon marketing and technology solutions leading the shift from print based couponing to Internet delivery, a $6.6 billion per year industry. Coupons.com recently got valued at $1 billion company.

~ Ernest

Free Education: Learn almost anything for Free

“Wisdom is not a product of schooling but of the lifelong attempt to acquire it” ~ Albert Einstein

“We now accept the fact that learning is a lifelong process of keeping abreast of change. And the most pressing task is to teach people how to learn.” ~  Peter F. Drucker

These quotes should come as no surprise to you. They state the obvious. But how many people forget to put this into practice. They finish up school and hit the workforce thinking that learning is behind them. That was school right. Wrong! The problem lies with wrongly associating pain to learning. Learning definitely require a level of discomfort. Just like exercise. You need to expel energy (strain) and this puts you out of a comfort zone. But this is the only way to do it to push that bar forward and bring change.

Once you understand that everything in life requires exerting energy (pushing the bar) to bring change (growth), your thinking changes dramatically and learning becomes a beautiful & peaceful (sometimes obsessive) process bound with fruitful outcomes of wisdom and enlightenment. We didn’t get this far in human civilization without education. An urge to understand more. And we will get further, inspire others and make a change in this world by education.

You are lucky

There has never been a great time in human history when education was so freely available and accessible to such a large population of people! Information is now free. Well a lot of it is is anyway. And more will become available – this is the trend. The old days when the few (rich) had access to it are over. Education (in 1 form or another) is now available to everyone. Public libraries, Internet, People et al. All you need now is the craving to learn. A will, drive, yearnings, fire inside to self-educate and expand your mind.

Free Education – General

Below is a list of great free online tech resources available to anyone willing to exert their energy and learn something new.. and change you forever.

Khan Academy

An organization on a mission. A not-for-profit with the goal of changing education for the better by providing a free world-class education to anyone anywhere.
Learn now: http://www.khanacademy.org/

  • Holds a library of around 2,400 education videos created by Khan. And growing everyday!
  • Topics covered on Algebra (inc Linear), Arithmetic, Banking and Money, Biology, Brain Teasers, Calculus, Chemistry, Math, Computer Science, Cosmology and Astronomy, Credit Crisis, Currency, Current Economics, Finance, Geometry, History, Physics, Probability, Statistics, Trigonometry, Valuation and Investing, Venture Capital and Capital Markets etc…
  • Sal (the founder) presents the topics using low-tech conversational tutorials, step-by-step doodles and diagrams on an electronic blackboard. And it works! Sal is a great teacher. He know how to break complex topics into simple, understandable and elegant ways of looking at them. It makes you smile because you will just get it! Learning couldn’t be easier. I have learnt heaps here.
  • Sal has built an amazing team of smart folks from McKinsey & Fog Creek Software including John Resig (the father of jQuery).

Hacker Dojo

A community center for hackers and thinkers. Located in Mountain View (California) at the heart of Silicon Valley next to Y Combinator and a host of other high-tech companies.
Discover: http://events.hackerdojo.com/

  • Free weekly Python classes ran by Karl Krueger (Googler). My favorite at the moment (Aug/2011).
  • Other events worth mentioning include iOS Developer Study Group, Machine Learning, Startup Monthly and many more. Visit events page for a full list.
  • And other times you will be sitting listening to a CEO / CTO talk about new high-tech innovation in their space or helping address common industry problems. Not to mention the many smart folks you can chat with and bounce ideas from during and post a meetup.
  • Hacker Dojo also has a nice library where you can kick back to read a book on a love sac or in a private cubby.

Google Code University

Provides sample course content and tutorials for Computer Science (CS) students and educators on current computing technologies and paradigms.
Discover: http://events.hackerdojo.com/

  • Topic covered include Programming Languages, Web Programming, Web Security, Algorithms, Android, Distributed Systems, Tools 101 andGoogle APIs & Tools.
  • Learn here one of the hottest languages today – Python.

Free Education – University

Harvard CS50 Computer Science

Introduction to the intellectual enterprises of computer science and the art of programming. It was ran last year so the content is fresh.
Take course: http://cs50.tv/2010/fall/#l=lectures&r=about&v=lectures/0/week0f

  • This course teaches students how to think algorithmically and solve problems efficiently.
  • Topics include abstraction, encapsulation, data structures, databases, memory management, software development, virtualization, and websites. Languages include C, PHP, and JavaScript plus SQL, CSS, and XHTML. Problem sets inspired by real-world domains of biology, cryptography, finance, forensics, and gaming. Designed for concentrators and non-concentrators alike, with or without prior programming experience.
  • The instructor David J. Malan is friggin amazing! I wish I had him teaching me Computer Science in my undergrad. His full of energy and uses many examples to back up the theory.

Stanford’s Introduction to Artificial Intelligence (AI) – Fall 2011.

Artificial Intelligence is the science of making computer software that reasons about the world around it. This is a bold experiment in distributed education organized by Stanford University in Palo Alto, CA.
Sign up for free course: http://www.ai-class.com/
Follow: http://twitter.com/#!/aiclass

  • Class begins October 10. Register using the link above!
  • From Humanoid robots, Google Goggles, self-driving cars, even software that suggests music you might like to hear are all examples of AI. In this class, you will learn how to create this software from two of the leaders in the field.
  • Sebastian Thrun and Peter Norvig – both top guns at Stanford University Computer Science with backgrounds from Google.
  • The course will (note Oct 10, 2011 start) include feedback on progress and a statement of accomplishment. The curriculum draws from that used in Stanford’s introductory Artificial Intelligence course. The instructors will offer similar materials, assignments, and exams.
  • Peter’s book AI, a modern approach, is a good read: http://aima.cs.berkeley.edu/ with Python (Yipeee) code samples

Stanford Engineering

SEE programming includes one of Stanford’s most popular engineering sequences.
Take course: http://see.stanford.edu/see/courses.aspx

  • Three-course Introduction to Computer Science taken by the majority of Stanford undergraduates, and seven more advanced courses in artificial intelligence and electrical engineering.
  • I haven’t gone through these but they look great! and all course material like Video Lectures, Syllabus, Handouts, Assignments, Exams and Software is provided.

Introduction to Databases – Stanford University

Databases are incredibly prevalent — they underlie technology used by most people every day if not every hour. Databases reside behind a huge fraction of websites; they’re a crucial component of telecommunications systems like those used in https://www.circles.life/au/plans, banking systems, video games, and just about any other software system or electronic device that maintains some amount of persistent information.

Take course: http://www.db-class.org/

  • Class is ran by Professor Jennifer Widom, the Fletcher Jones Professor and Chair of the Computer Science Department at Stanford University.
  • Students will have access to lecture videos, lecture notes, receive regular feedback on progress, and receive answers to questions. When you successfully complete the class, you will also receive a statement of accomplishment.

Machine Learning – Stanford University

Machine learning is the science of getting computers to act without being explicitly programmed.
Take course: http://www.ml-class.com/

  • Class is ran by Professor Andrew Ng is Director of the Stanford Artificial Intelligence Lab, the main AI research organization at Stanford.
  • Students will have access to lecture videos, lecture notes, receive regular feedback on progress, and receive answers to questions. When you successfully complete the class, you will also receive a statement of accomplishment.
  • This is the original Stanford AI course which the one in Fall 2011 is being based on.

MIT OpenCourseWare

MIT OpenCourseWare (OCW) is a web-based publication of virtually all MIT course content. OCW is open and available to the world and is a permanent MIT activity.
Explore & take courses: http://ocw.mit.edu/index.htm

  • Talk about Unlocking Knowledge and Empowering Minds. Free lecture notes, exams, and videos from MIT. No registration required.
  • I haven’t gone through this site yet but it was highly recommended. No prices for guess what MIT is… Massachusetts Institute of Technology. A private research university where six MIT students who were trained to become experts in card counting and subsequently took Vegas casinos for millions in winnings. Watch the movie 21 and you will learn about this MIT Blackjack Team.

No excuses!

There you have it. No excuses for not being able to afford or attend to university commuter science courses. If you have others which you feel should make this list please contact me and I will list them here.

… and just remember this famous quote by Napoleon Hill …

“Whatever the mind of man can conceive and believe, it can achieve.”
— Napoleon Hill

Happy learning!
~ Ernest

If you read this far you must like my notes,
subscribe here and never miss a single post.

JavaScript: made better using the Module Pattern

I’ve just finished reading JavaScript Patterns by Stoyan Stefanov and boy has it opened up my mind and inspired me to write better, faster, cleaner and more modular JavaScript code using the Module Pattern.

Stoyan’s book covers many patterns and anti-patterns (the common old approach to JavaScript coding).

Stoyan provides detailed explanations why and where to use each pattern inc. module pattern. Since there is so much content in this book I decided to write about what I believe will add immediate value to any developer working with JavaScript, how to make JavaScript better using the module pattern.

No hacks around poor JavaScript

JavaScript is unlike back-end server-side code where if the code becomes a bottleneck you just throw more boxes (hardware) at it to speed thinks up. JavaScript downloads & runs within the user’s browser. So if you got lazy or just didn’t know better to follow Convention over Configuration (CoC) or the rapid development principle of Don’t Repeat Yourself (DRY) and you hacked something together.. the user will get poor experience and even limited to a single browser. This is where JavaScript Patterns play an important role and understanding them is the 1st step in becoming a JS Ninja.

JavaScript – what you need to know

Let’s shake some old grounds and cover the what you need to know about JavaScript in 2011.

  • There are no classes in JavaScript. You create a blank object when you need one and then start adding members to it.
  • Sometimes when people say “Singleton” in a JavaScript context, they mean the Module Pattern – covered below and discussed in detail in Stefanov’s Chapter 5. Every time you create an object using the object literal, you’re actually creating a Singleton. And there’s no special syntax involved.
  • When you think about objects in JavaScript, simply think about hash tables of key – value pairs. Similar to what are called associative arrays in other languages.
  • Use literal notation patterns instead of object definitions. Literal is more concise, expressive and less error-prone. See Appendix 1.1 at the end of this post for examples.

Module Pattern – organize your code

Let’s start with what’s most common out there on the internet. You may have seen (or even do) this.

Code sample – anti pattern

Declaring:

var array_string = "[object Array]";
var ops = Object.prototype.toString;
var MAX_NUM = 123;

function inArray (haystack, needle) {
    for (var i = 0, max = haystack.length; i < max; i += 1) {
        if (haystack[i] === needle)
            return i;
    }
    isEnabled = false;
    return −1;
}

function isArray (a) {
    return ops.call(a) === array_string;
};

var pageTitle = "New title";

Calling:

isArray(arr_user);

The problems here are:

  • All these are global (variable and functions) are shared among all the code in your application living in the global namespace. High chance of naming collisions between your and other developer’s code (think maintenance).
  • isEnabled above has no var declaration so automatically becomes chained to the global namespace outside the function.
  • When something in your code is chained to the top of the prototype it takes longer time to be found then if it’s within a module. I will discuss the JavaScript Prototype in another post and show examples with performance differences.
  • Some best practices are broken – see below what these best practices should be.

Module Pattern – the solution, organize your code

There are many great patterns described in JavaScript Patterns by Stoyan Stefanov but my preference today is to use the Module Pattern. The Module Pattern is widely used because it provides structure and helps organize your code into self-contained de-coupled pieces of code. If you look at the source of jQuery you will find a similar pattern being used.

The Module Pattern is a combination of several patterns described in Stoyan’s book.
They include:

  • Namespaces (Stefanov’s pg.87)
  • Immediate functions (Stefanov’s pg.73)
  • Private and privileged members (Stefanov’s pg.92) and
  • Declaring dependencies (Stefanov’s pg.90)

And here’s how the same sample of code above would look when the Module Pattern was followed.

Module Pattern code sample – the pattern

Declaring:

var MYCOMPANY = MYCOMPANY || {};

// note the use of namespacing - similar to jQuery.
MYCOMPANY.Page = (function () {
    'use strict';

    // [ private properties ]
    // note the chaining of var declarations vs a var on each line
    var pageTitle    = "blank",
        isEnabled    = false,
        array_string = "[object Array]",
        ops          = Object.prototype.toString,
        MAX_NUM      = 123; // constants always are in capital case
    // end var

    // [ private methods ]
    // note the use of literal patterns vs constructor functions
    function inArray(haystack, needle) {
        var i   = 0,
            max = 0;
        for (max = haystack.length; i < max; i += 1) {
            if (haystack[i] === needle) {
                return i;
            }
        }
        return -1;
    }
    function isArray(a) {
        return ops.call(a) === array_string; // end var
    }

    // [ public methods ]
    return {
        init: function (title, enabled) {
            pageTitle = title;
            isEnabled = enabled;
        },
        isArray: isArray,
        indexOf: inArray
    };
}());

Calling:

MYCOMPANY.Page.init('Page title', true);
MYCOMPANY.Page.isArray(arr_user);

Code is now modularized and less prone to collisions.

JSLint: The JavaScript Code Quality Tool

Once you have written your new modularized code it’s a best practice to run it past JSLint. JSLint is a free JavaScript program that looks for problems & violations of some of the patterns in your JavaScript code. It is a code quality tool. Check it out here: http://www.jslint.com/

JavaScript best practices

  • Curly brackets should always be used even if there is 1 expression. Code is then more readable and maintainable.
  • Use 4 space indentation – also JSLint default. This way no matter what editor engineers use it is always displayed in the same manner.
  • Like curly brackets, always use semicolons, even when they are implied by the JavaScript parser. Why slow down the compiler to clean up the mess during runtime.
  • Naming convention for constructors is typically UpperCamelCase, functions lowerCamelCase, variables lowercase_separated_by_underscore and constants UPPER_CASE.
  • Use whitespace as much as possible by separating all operators and their operands with spaces.
  • Use Google’s Closure Compiler to minify your code before production AFTER you have passed it via JSLint (above).

Appendix

1.1 Constructors and their corresponding and preferred literal patterns.

Built-in constructors (avoid) Literals and primitives (prefer)
var o = new Object(); var o = {};
var a = new Array(); var a = [];
var re = new RegExp( “[a-z]”,”g”); var re = /[a-z]/g;
var s = new String(); var s = “”;
var n = new Number(); var n = 0;
var b = new Boolean(); var b = false;
throw new Error(“uh-oh”); throw { name: “Error”, message: “uh-oh” };… or throw Error(“uh-oh”);

And that is it for now. Have I missed something or gotten something wrong above? If so please let me know and I will correct it. How is your JavaScript looking? Need help to get it fixed? Post below or contact me.

~ Ernest

MongoDB office hours in Mountain View

You may recall my previous post on MongoDB and how powerful it is as an alternative to a relational database. Since then I’ve had a bunch of discussions with other software engineers around this space and even met up with MongoDB core engineer Chris Westin from 10gen at Red Rock to gain further insights into MongoDB.

MongoDB Leaf

New kick ass GUI for MongoDB

Chris introduced me JMongoBrowser written by Antoine Girbal (10gen engineer). It’s written in Java so you can run it on Linux, Windows and Mac OSX. So far this GUI has proven to be a success and fills the holes where MongoHub couldn’t. Out goes MongoHub and in goes JMongoBrowser.

JMongoBrowser - MongoDB GUI admin tool.

Fast crash recovery using Journaling

MongoDB uses memory 1st to write data to vs directly to file/store. This is where huge performance gains are attained. It also has Journaling, a write-ahead for operations to facilitate fast crash recovery in the storage engine. This means the stuff in memory is stored in a log incase your server goes down without affecting MongoDB’s performance.

So what happens if your box goes down? .. a common question amongst new engineers to MongoDB. Does this data also gets lost? The answer lays somewhere in between how you balance your performance needs against the risks you are willing to take with your data.

The journal is synced to disk every 100ms. So the maximum that can be lost is up to 100ms worth of changes. At the cost of additional performance degradation, you can make your application proof against even that.  The j option to getLastCommand will cause the application to block until the journal entries with the last change have been written to disk.  See http://www.mongodb.org/display/DOCS/getLastError+Command .  Of course, if you use this, your call to getLastCommand can wait up to 100ms, depending on where in the flush cycle you are. Therefore, this is left up to the user to change this default of 100ms.

Therefore, always load MongoDB with Journaling enabled, like this:

mongod --journal

This also auto cleans up crashes and puts crashed data back into MongoDB.

Don’t be alarmed when you see this

I found this in the /Journal (1GB files):

-rw------- 1 root root 1.0G 2011-06-23 02:26 prealloc.0
-rw------- 1 root root 1.0G 2011-06-23 02:25 prealloc.1
-rw------- 1 root root 1.0G 2011-06-23 02:26 prealloc.2

With Journaling enabled the server always creates those three 1GB files.  It rotates through them, recycling them.  They won’t grow any more.  But they are always that size, regardless of the size of your database. If the server dies unexpectedly, the files remain, and contain the material necessary for the automated recovery that happens when you restart the server.

More here:

Checking server memory usage

As mentioned above, Memory is used by Mongo to speed things up. The more memory you have the better and MongoDB will use your RAM as it sees need for it taking into consideration other server resources.

It’s always a good practice to check memory usage.
Details here: http://www.mongodb.org/display/DOCS/Checking+Server+Memory+Usage

Your MongoDB configuration file

Here’s a recommend set of switches to have enabled in your mongodb.conf.

sudo nano /etc/mongodb.conf

add or update your settings to these:

journal=true
directoryperdb=true
logappend=true
  • journal = as discussed above to enable fast recovery from crashes.
  • directoryperdb = creates a new physical directory for each new database. Clean way to seperate your databases.
  • logappend = Whether the log file will be appended or over-written. Always have true else after a reboot your old logs will be overwritten and you may lose important crash specific data.

More detail here: http://www.mongodb.org/display/DOCS/File+Based+Configuration

MySQL to MongoDB

Finally, I found this fantastic chart illustrating the difference in commands between MySQL and MongoDB. Should help the transition for us MySQL folks. Click the image below to download a large PDF version (Size: 213Kb).

There is also mapping chart SQL to Mongo located on the MongoDB website here.

Have more questions? Attend the weekly MongoDB Office Hours in Mountain View Red Rockhttp://www.meetup.com/San-Francisco-MongoDB-User-Group/events/16985746/ or post a question/comment below.

~ Ernest