Public and Private Methods with Javascript

How to achieve public and private methods with Javascript

This is just a short post on how I construct my javascript objects to provide public and private method functionality (without using a framework). As much as I enjoy Javascript there are a million ways to do very similar things - hopefully this explains one good approach to do this.

What this approach provides you with:

  • Private methods
  • Public methods
  • Follows OOP practices

What this approach doesn't provide you with:

  • Inheritance :-(
  • If you want inheritance I highly recommend checking out the ExtJS framework. It's a very powerful framework that promotes good coding standards and architecture.

Why do I place high importance on using private methods/properties?

When I write any code I aim to hide as much of the complexity of the library from the outside world. The less functionality I have to expose to the outside world, the easier it is to refactor the code in the future, as you know exactly how your class can and can't be used.

So here is the example..

/**
 * A javascript object to manage data about a product (eg: book, computer, car or house etc..)
 */
var ProductInstance = function(id, name, price, discount){

    /**
     * ID of the product
     */
    var _id = id;

    /**
     * Name of the product
     */
    var _name = name;

    /**
     * Price of the product
     */
    var _price = price;

    /**
     * Discount of the product
     */
    var _discount = discount;

    /**
     * Private method to calculate discounted price
     */
    function _calculateDiscountedPrice() {
        var discountedPrice = _price;

        if( parseFloat(_discount) >  0 ) {
            discountedPrice = discountedPrice - _discount;
        }

        return discountedPrice;
    }

    /**
     * Private method to build up post data of an object
     */
    function _buildPostData() {
        var data = {}

        data.id = _id;
        data.name = _name;
        data.price = _price;
        data.discount = _discount;

        return data;
    }

    /**
     * Private method to save a product
     */
    function _save() {

        // You could save to local storage..

        // You could make an AJAX request to save to server..
        //$.ajax('/product/save/', _buildPostData());
    }

    /**
     * Public method to get Id
     */
    this.getId = function(){
        return _id;
    }

    /**
     * Public method to get Name
     */
    this.getName = function(){
        return _name;
    }

    /**
     * Public method to set name
     */
    this.setName = function(name){
        _name = name;
    }

    /**
     * Public method to get Price
     */
    this.getPrice = function(){
        return _price;
    }

    /**
     * Public method to set Price
     */
    this.setPrice = function(price){
        _price = price;
    }

    /**
     * Public method to get Discount
     */
    this.getDiscount = function(){
        return _discount;
    }

    /**
     * Public method to set Discount
     */
    this.setDiscount = function(discount){
        _discount = discount;
    }

    /**
     * Public method to set Discount
     */
    this.getDiscountedPrice = function(){
        return _calculateDiscountedPrice();
    }

    /**
     * Public method to save product
     */
    this.save = function(){
        return _save();
    }

    return this;
};

var productOne = new ProductInstance(1, 'Product One', 20, 5);
console.log(productOne.getId()); // equal "1"
console.log(productOne.getName()); // equal "Product One"
console.log(productOne.getPrice()); // equal "20"
console.log(productOne.getDiscount()); // equal "5"
console.log(productOne.getDiscountedPrice()); // equal "15"
//console.log(productOne._calculateDiscountedPrice()); // Method will not exist as method is private
//console.log(productOne._buildPostData()); // Method will not exist as method is private
//console.log(productOne._save()); // Method will not exist as method is private

var productTwo = new ProductInstance(2, 'Product Two', 50, 30);
console.log(productTwo.getId()); // equal "2"
console.log(productTwo.getName()); // equal "Product Two"
productTwo.setName("Product Two - Updated");
console.log(productTwo.getName()); // equal "Product Two - Updated"
console.log(productTwo.getPrice()); // equal "50"
console.log(productTwo.getDiscount()); // equal "30"
console.log(productTwo.getDiscountedPrice()); // equal "20"
//console.log(productTwo._calculateDiscountedPrice()); // Method will not exist as method is private
//console.log(productTwo._buildPostData()); // Method will not exist as method is private
//console.log(productTwo._save()); // Method will not exist as method is private

As you can see with the overly verbose example above, you can easily achieve public/private methods in Javascript. It's a very simple example, but in the real world your '_save' method could be quite complicated (even to the extend of using a different class to do the saving). Being able to hide all of that complexity from the outside world allows you to easily refactor it in the future. You can even unit test the above code quite easily as its not tightly coupled to any other components.



Dion Beetson
Founder of www.ackwired.com

A Developers Resume and Interview

Technical/Developer Resume, Interview and Coding Tests

I've recently been involved in recruiting new software engineers to build up a team at my workplace.

If you are looking for a new technical developer role, the post below might provide some insight into the processes you may have to work your way through.

1. Wrestle your way through the recruitment agency

Many companies use a recruitment agency to filter the volume of job applications, or even head hunt the developers the company is looking for. You could be one of the most talented developers around, but if you don't structure your CV correctly, you may find you are constantly being blocked at this point.

Recruiters will basically look through your CV to ensure you meet the selection criteria of the position you are applying for. Here's what you can do to increase your odds of making it through this phase:

  • Research the selection criteria for the position you are applying for.
  • Clearly outline how you meet that selection criteria within your CV.
    Are they looking for:
    • Team mentoring?
    • Experience in building scalable web applications?
    • Test Driven Development?
    • Experience in agile methodologies?
    • Outstanding communication skills?
    • Experience in Javascript based web applications?
    • PHP developers? or Frontend Developers?
    • You really need to nail this criteria
  • Use dot points, or short sentences if you have to.
  • Including large paragraphs of information make it harder for recruiters to find exactly what they are looking for.
  • Use the correct terminology, for example:
    • If you have been helping developers in your day job, use the word 'mentoring'.
    • If you have worked on big applications, use terms like "large scale", "master/slave databases", "caching implementations" etc.. 
    • If you worked in a specific environment, was it SCRUM, Waterfall, XP?
    • Recruiters will look for keywords that match the selection criteria they are recruiting for.
  • Double, actually no, triple check your grammer, and use the spell checker. There is nothing worse than a CV with spelling mistakes.
  • Keep it short, as recruiters will most likely skim read over your CV. I know you most likely have a lot to express within your CV, but really try to outline the most important - you have your interview to explain in more detail.
  • Include the most important information up the top - most people wont read more than 2 pages.
  • Trial your CV on a few advertised positions, get feedback, refine, and try again - if you send your CV out to every recruiter in the first few days, you may live to regret it.

2. Your potential employer reviews your CV

So, you have impressed the recruitment agency and your CV has most likely been forwarded onto the company you applied to. The employer will go through a very similar process, with the difference being, they will most likely have a technical background (eg: technical managers or team leads). They will look more thoroughly into your CV (I still doubt they will read it word for word), but they will analyse technical ability, so it's also important your CV demonstrates your strengths and weaknesses. For example:

  • Define the coding languages your primary experienced with.
  • What databases do you have experience with?
  • What frameworks do you have experience with?
  • What version control platforms have you worked with?
  • What testing do you usually implement?
  • What type of projects you have worked on?
  • What type of project teams have you worked with?
  • Be prepared to be able to backup everything you have outlined in your CV.
  • Be prepared to share some good examples about projects you have worked on.

3. Interviewing with your potential employer

If you make it the the stage, you have obviously ticked all the boxes on paper - good work! In my experience the interview is usually looking to determine 2 primary objectives:

  1. Are you technically capable to work within the team?
  2. Do you fit the culture of the team (this was so important to our team).

You really need to have a balance of both. Being technically awesome but hard to work with (arrogant or opinionated etc..) wont get you very far, being a great team player but not being able to back it up with your technical skills will most likely not get you far either.


For your interview:
  1. Always prepare a few questions to ask your interviewees - it shows your serious about the position.
  2. Know the background of your interviewers (if you know who they are), and the company.
  3. Be prepared and practice some of the questions they might ask you.
    In my experience, these may include some of the following:
    • What design patterns would you recommend using and why?
    • How would you solve a problem you don't know the answer to?
    • What would you do if you had a blocker on a project you were working on and no one was in the office?
    • How do you test and become confident in a component you have developed?
    • What's your most challenging coding problem you have had to solve, and how did you solve it?
    • If you are given a problem you don't know how to solve, how would you solve it?
    • How do you scale a web application?
      For example.. Load balancers, master slave databases, sharding, asynchronous programming, application caching, SQL optimisation etc..

4. Technical Coding Tests:

This is my favourite! I really enjoy reviewing technical tests - you can learn a lot by looking through someone else's code. Unfortunately for you, some developers can be egotistic when they review - they really are looking for the perfect solution. Sometimes they may even look for similar coding styles to their own, or similar to members within their team.

Here are some things to look out for and to include:

  • If it's a 24 hour coding challenge, spend more than an hour on it, but probably less than 16 hours. We had one developer who spent nearly 18 hours coding his technical test - it was fairly impressive though!
  • Show your knowledge of design patterns, but try to use well known ones and not patterns that the reviewer wouldn't recognize. Patterns I would look for are:
    • Dependency Injection.
    • Use of interfaces, you can type check against interfaces.
    • MVC implementation (if it was a front-end test).
    • Single use/purpose classes, don't add all of your logic into a single class.
    • OOP design, I wouldn't code up a procedural application.
    • Security awareness - ensure there is NO XSS (cross site scripting) or SQL Injection.
    • Use of class inheritance.
  • Write a few unit tests to show you at least considered it.
  • Document your code, yes document your code!
    • Use correct spelling and grammer.
  • Format your code neatly.
    A pet hate of mine (which most developers who have worked with me know about me), is when developers use a mix of TABS and SPACES for indentation. As much as I prefer SPACES over TABS in any application, consistency is the key, use TABS or SPACES, don't use both.
  • Consistent file naming, variable naming, method naming, and code formatting.
  • oh and never ever use global variables - that was pretty much an automatic fail in our books.

Some final notes

  • Adjust your CV based on the position you are applying for.
  • If you are applying to slightly different roles, eg front-end developer or back-end developer, have a generic CV with all your skills. You can use that as a base to copy and paste into a CV targeted to the position you are applying for. Trust me you will have far more success in this approach even though it does take a little longer to apply for jobs - You really want to be able to showcase the skills the employer is looking for.
  • And finally, try not to go into the interview asking for huge amounts of money up front. Spend time proving to your interviewers that you are awesome, smart and well matched to what they are looking for - make them want you. After that is when you will have the power to ask for the salary you are worth.

Good luck!

Dion Beetson
Founder of www.ackwired.com