The Silver Lining

Lessons & Learnings from a salesforce certified technical architect.

Posts Tagged ‘Object-oriented programming

A Beginner’s Guide to Object-Oriented Programming with Apex: 0. An Introduction

with 5 comments

Apex has come a long way in the past few years, and as Salesforce has grown so has the number of super smart people working on the platform. There are lots of guides on how to do fancy things using JavaScript, Apex and Visualforce as well as many more whitepapers on the topics of governances and standards. However I think there is a gap, and I’d like to plug it.

Over the next few weeks and months I will be releasing articles that describe and show the basics of object-oriented programming (OOP) with Apex. My approach will be to make these articles as modular and simple as possible. The target audience? Developers with a-teeny-bit-of-experience through to those who have tons of experience but never had any formal training in OOP.

A Beginner’s Guide to Object-Oriented Programming with Apex

  1. Introduction (this post)
  2. Encapsulation
  3. Abstraction
  4. Polymorphism

What the hell is OOP?

Good question, and although many agree on some elements of OOP there is still a divergent view in the details. Contrasting it to what came before helps though.

The programming paradigm prior to OOP essentially had everyone writing code as your would an essay i.e. a single long text with one line written (and executed) after the other. There were no classes, no methods, no GOTO statements even (if you go far back enough that is). If you needed the same complex calculation in 5 parts of your application you had to write it 5 times. This is obviously a bad idea and over time the geniuses that created computer programming started inventing bits and pieces of engineering to make it easier to create, maintain and extend their code. Collectively, these features together with their experience were the beginnings of OOP.

The most commonly cited features of OOP are described below.

Encapsulation

A way to hide state (or private data), but also – confusingly – a way to bundle data and capabilities to operate on that data.

As an example consider a sausage making machine, you pour some stuff into one end and get sausages out of the other without needing to know the internal workings. The inner workings are encapsulated within the machine.

Abstraction

This is one of the trickiest concepts because it is relative, you can have levels of abstraction and it essentially means providing the appropriate level of information and data at the requested level.

With my previous example, if you are the sausage maker then you just need to know what stuff to insert into which part of the machine. But, if you were the sausage machine repair man you would need to have the tools, knowledge and access to all the bits and bobs inside of the machine. These are different levels of abstraction.

Inheritance

A controversial aspect since some languages think that inheritance is bad. In short it is the capability of a class or object to have certain methods and attributes passed down to them through a hierarchy.

Now that I’ve started the sausage story I can’t stop! All sausages share certain qualities e.g. they’re all encased in something, have some type of contents and (usually) need to be cooked before being eaten. You could represent these common attributes in a parent class and have specific types of sausages (pork, chicken, blood pudding) “subclass this superclass” i.e. inherit from it.

Polymorphism

Polymorphism is extremely rewarding when you get it right because it just feels smart. In short it allows you to define ways of dealing with data without knowing exactly how that data will be defined in the future.

To finish off the sausage story (anyone else hungry?) you could put any type of meat into the machine but in the end you will still always get a sausage i.e. provided that a certain type of input (any type of meat and spice) is provided to the machine it “knows” what to do with it (make delicious sausages) even though the types of sausages may have differences.


Don’t worry if these concepts haven’t clicked just yet, each will be covered in detail in future posts.

These concepts are obviously academic and language agnostic but Apex makes them available to you through the constructs of classes, methods and attributes of those classes, instances of those classes.

A note on terminology. In the Salesforce world an Object is most commonly used to refer to a data entity e.g. Account or CustomObject__c. In the OOP paradigm an Object is an instance of a Class i.e. MyClass.cls is an Apex class which provides the blueprint for instances of itself. This becomes clearer with an example:


MyClass myObject = new MyClass();

myObject.divideByZero();

MyClass is the class, and myObject is an instance of that class AKA an object. Got it? Great.

Why Should I Use OOP?

Because it will make you a better programmer and it doesn’t hurt with the ladies/men (delete as appropriate). Your code will be better, you will end up doing less boring work and it will be easier (and quicker) to fix bugs. I guarantee it.

Next Time on Th3Silverlining

My next post will delve into the feature called Encapsulation so hit the subscribe button to find out when it’s published. See y’all then.

Written by Wes

June 6, 2014 at 5:10 pm

Voodoo – A Todo list that demos the power of KnockoutJS

with 6 comments

Voodoo - A todo list

This small demo app will demonstrate the usage and power of JavaScript MVC frameworks and in particular KnockoutJS. You can learn more about the framework through the tutorials on the KO site. I will gloss over some of the details but you can learn more in framework documentation. My goal here is to give you a high-level sense of what’s possible. The picture along side shows what we’re building. You can find the demo here and the full sourcecode here.

The HTML

Strictly speaking jQuery is not required for KO to work but it is likely that you will often include it as a helper for the framework. As alway you need to start with the static resource inclusions.

<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="js/knockout-2.0.0.js"></script> 

And you’ll need a form in order to create new todo items.

<form data-bind="submit: addTask" id="create-todo">
    <input class="new-todo" data-bind="value: newTaskText" placeholder="What needs to be done?" />
</form>

For the first time you’ll notice the data-bind attribute. The framework recognises this attribute and parses the attribute value to determine what logic to apply. In this case the input element is bound to a JavaScript property called newTaskText.
Next up you need the markup that contains and displays each task. Some actions are available for each item too.

<div class="todos">
  <ul data-bind="foreach: tasks, visible: tasks().length > 0" id="todo-list">
      <li>
        <div class="todo" data-bind="css: { editing: isEditing }, event: { dblclick: startEdit }">
          <div class="display" data-bind="css: { done: isDone }">
            <input type="checkbox" class="check" data-bind="checked: isDone" />
            <div class="todo-text" data-bind="text: title"></div>
            <a href="#" class="todo-destroy" data-bind="click: $parent.removeTask">&times;</a>
          </div>
          <div class="edit">
            <form data-bind="submit: updateTask">
              <input data-bind="value: title" />
            </form>
          </div>
        </div>
      </li> 
  </ul>
</div>

Again you’ll notice that each element that is to be used in someway by KO has an attribute of data-bind. Below I’ve picked out a few lines to demonstrate key functionality. The following line is an instruction to run through a collection of tasks and only display the ul element if there’s anything in the collection.

<ul data-bind="foreach: tasks, visible: tasks().length > 0" id="todo-list">

The line below is used to conditionally apply a style class and ensures that the doubleclick event is bound to the appropriate handler.

<div class="todo" data-bind="css: { editing: isEditing }, event: { dblclick: startEdit }">

And here we have an example of an input element being bound to a JavaScript object field isDone – the object structure will be shown later.

<input class="check" type="checkbox" data-bind="checked: isDone" />

Now here’s some of the magic of KO. Below are the some stats based on the number of tasks in the list. If you were using jQuery or just JavaScript you would have to track the number of elements in the list and update the stats appropriately.

You have <b data-bind="text: incompleteTasks().length">&nbsp;</b> incomplete task(s)
<span data-bind="visible: incompleteTasks().length == 0"> - its beer time!</span>

With KO the view is driven by the underlying object data. If the number of items in the list changes all related information is automatically updated in the view! In KO this is facilitated through concepts known as observables and dependency-tracking.

The JavaScript

KO is the first time I’ve used OOP within JavaScript for some time, and it’s pleasure to work with the concepts in such a paradigm! In this small app there are only 2 classes, one for tasks (fairly obvious) and another for the ViewModel which you can consider the application class.
The Task class contains the properties and methods applicable to Tasks. You’ll notice how the properties are initialised using using the ko.observable() method. This is a touch more magic and it means that the values of these properties will be “watched”. If they are changed either through the user interface or via JavaScript then all dependent views elements and JavaScript values will be changed too.

function Task(data) {
    this.title = ko.observable(data.title);
    this.isDone = ko.observable(data.isDone);
  this.isEditing = ko.observable(data.isEditing);

  this.startEdit = function (event) {
    this.isEditing(true);
  }

  this.updateTask = function (task) {
    this.isEditing(false);
  }
}

The ViewModel class exposes the Tasks in a meaningful way and provides methods on that data. Types of data exposed here are observable arrays of tasks and properties that return the number of complete and incomplete tasks. The operations are simple add and remove functions. Right at the end of the class I’ve used jQuery to load JSON objects into the todo list.

function TaskListViewModel() {
    // Data
  var self = this;
  self.tasks = ko.observableArray([]);
  self.newTaskText = ko.observable();
  self.incompleteTasks = ko.computed(function() {
    return ko.utils.arrayFilter(self.tasks(),
    function(task) {
      return !task.isDone() && !task._destroy;
    });
  });

  self.completeTasks = ko.computed(function(){
    return ko.utils.arrayFilter(self.tasks(),
      function(task) {
        return task.isDone() && !task._destroy;
      });
  });

  // Operations
  self.addTask = function() {
      self.tasks.push(new Task({ title: this.newTaskText(), isEditing: false }));
      self.newTaskText("");
  };
  self.removeTask = function(task) { self.tasks.destroy(task) };

  self.removeCompleted = function(){
    self.tasks.destroyAll(self.completeTasks());
  };

  /* Load the data */
  var mappedTasks = $.map(data, function(item){
    return new Task(item);
  });

  self.tasks(mappedTasks);
}

The very last line in the JavaScript code tells KO to apply all it’s magic using the ViewModel and markup we’ve written.

Summary

To me it’s amazing how little code you need to write in order to build such a neat app. And you don’t even need to track the view state at all! Hopefully this gives you the confidence to start using JavaScript MVC/MVVM frameworks because in the end it helps save you heaps of time and effort.

Written by Wes

March 23, 2012 at 5:58 pm

Follow

Get every new post delivered to your Inbox.

Join 2,198 other followers

%d bloggers like this: