2014-10-09

There is an Elvis in Java, kind of - but you should still obey the Law Of Demeter

Languages such as Groovy have an Elvis operator which helps you to avoid tedious checking possible null-references when navigating through objects, like those:

public class Gear {
private Collection<Object> parts;

public Collection<Object> getParts() {
   return parts;
}

public void setParts(Collection<Object> parts) {
   this.parts = parts;
}
}

public class Car {
private Gear gear;

public Gear getGear() {
   return gear;
}

public void setGear(Gear gear) {
   this.gear = gear;
}        
}

Elvis works as follows:

Car car = new Car();
Collection<Object>> partsOrNot = car?.getGear()?.getParts(); // No NPE, but null assigned!

In Java there is no strict language construct like Elvis operator, but sill Java introduces Optional which can help you alleviate the same problems as the mentioned operator:

Optional<Car> optionalCar = Optional.of( new Car());
Optional<Collection<Object>> partsOrNot =
       optionalCar
               .map(Car::getGear)
               .map(Gear::getParts);

Similarities between Elvis and Optional.map(...) method are pretty strong, although the latter is based on Lambda expression and not language syntax and because of that it introduces a little more clutter to the solution.
So, no - there is no Elvis operator in Java. And yes - there is a notion of Elvis operator in Java, pretty much powerful one.

But there is a catch. We still should be tied to clean code and some ground programming rules. One of them is the Law of Demeter:

Each unit should have only limited knowledge about other units: only units "closely" related to the current unit. Or: Each unit should only talk to its friends; Don’t talk to strangers.

Surely, the Elvis operator is the mechanism which encourages breaking this law. And the Optional.map does the same thing. They both introduce strong coupling between objects and as such, they both should be avoided, despite the language (Elvis in languages that support it and Optional.map in Java).

Although the concept of Elvis operator helps to overcome the boilerplate checking code it is still the code smell hidden in syntactic sugar. And the Optional.map with method chaining do the same thing.

I like Java for its feature balance and I think that there is no need to introduce the native Elvis operator to the language because it offers sufficient solution for situations we should avoid nevertheless.

2014-09-01

Google Apps Script - cyber life automation

What it is all about?

Internet goodies - cloud apps like Dropbox, Google Drive, GMail, even Facebook and social media - affects our style of life, influence what we do and how we do it. But hey! New possibilities brings new responsibilities and new work around them. Often you want to publish the same content on Facebook and Twitter on any other social media be notified when something has changed on shared Dropbox folder or move stared article in Pocket/Readability to Evernote or Google Drive.
There are some apps like iftt.com or zapier which can help you automate some tedious tasks accross your different internet services, but they have some limitations. First of all they let you create integration receipts based on following formula:
IF something-happens-on-service1 THEN do-something-at-service-2


Obviously - this receipts can’t fulfill the whole spectrum of some of your needs. So.. when your needs exceed capabilities of those apps (or you don’t want to have yet-another-cloud-app on board) - go for a big gun. And a really big gun is the Google Apps Scripts!
As stated here - Google Apps Script is a JavaScript cloud scripting language that provides easy ways to automate tasks across Google products and third party services and build web applications.

Example

I don’t use any Facebook mobile app. These apps are time eaters and are very heavy for my phone. Most of all - checking nervously Facebook news is against my daily workflow. But I would like to have some sort of notification when someone comments my updates on social media. It is kind to respond quickly for such situations.
For such notification I use Pushbullet service. With Pushbullet you can be notified on any device you have installed Pushbullet app: Android, IPhone, MacOS, Windows and Linux.
And how to forward unread Facebook notifications to PushBullet?  Here is a code I use for that, written in Google Apps Script, simple and easy:
var FACEBOOK_TOKEN = "your-secret-access-token-to-facebook";
var PUSH_BULLET_TOKEN = "your-secret-access-tokent-pushbullet";

function forwardMeFacebookNotifications() {
 var response = UrlFetchApp.fetch(
   FACEBOOK_API_URL + "/me/notifications?access_token="+FACEBOOK_TOKEN,
   {
   "method" : "get",
   "contentType" : "application/json",
   }).getContentText();
 response = Utilities.jsonParse(response);
 var notifications = response.data;

 for (var i in notifications) {
   pushLinkToPushBullet(notifications[i].title, notifications[i].link);
   UrlFetchApp.fetch(
     “https://graph.facebook.com/v2.1/" + notifications[i].id +"?access_token="+FACEBOOK_TOKEN,
     {
     "method" : "post",
     "payload" : { "unread" : "0" }
     });
 }
 
}

function pushLinkToPushBullet(title, link) {
 var digest = "Basic "+Utilities.base64Encode(PUSH_BULLET_TOKEN+":");
 var options = {
   "method" : "post",
   "payload" : {
     "type" : "link",
     "title" : title,
     "url" : link
   },
   "headers" : {
     "Authorization": digest
   }
 };
 var push_bullet_url = "https://api.pushbullet.com/v2/pushes";
 UrlFetchApp.fetch(push_bullet_url, options);
}


This script consist of two simple REST calls, one for Facebook REST API and one for Pushbullet API. I wll not cover how to connect to those APIs, but you should know that for each you should obtain the access token (see 2 first line of the script) - on how to get those, just read docs and tutorials provided by each services.

How to start messing with Google App Scripts?

Before messing with your Google Apps Scripts you should connect Google Apps Script Editor with Google Drive. Go to your Google Drive, and point to Connet More Apps option as below:
Screenshot from 2014-09-01 23:10:05.png

What can you do with Google Apps Scripts?

Scripts has built-in services you can inline in your code:
  • UrlFetchApp - you can see above in the script. I allows you to call any URL with http/https protocol, especially REST services.
  • Any Google services (such ass Calendar, GMail, Drive and so on)
  • Some utilietiles like encoding/decoding Base64, JSON, XML, etc.

With these building blocks possibilites are pretty powerfull. Stay tuned! In next few posts I will reveal some cool receipts with Google Apps Scritps as a main spice.