Thursday, October 24, 2013

Understanding Entity Relationship Mapping, Part 2: Annotating Entity Relationships

In Understanding Entity Relationship Mapping, Part 1: The basic concepts I glazed over some of the basic concepts that would be encountered when dealing with establishing relationships between Entities. This post would take a look at how to use Annotations to specify these relationships.

The relationships that would be annotated are the four types that you have in relational data model:

  1. One-To-One annotated with @OneToOne
  2. Many-To-One annotated with @ManyToOne
  3. One-To-Many annotated with @OneToMany
  4. Many-To-Many annotated with @ManyToMany


If concepts like Cardinality, Direction of Relationship, Cascades, Owning side and Inverse side of Entity relationship is new to you, then it is would be good to first read Understanding Entity Relationship Mapping, Part 1: The basic concepts

The relationship would be classified into two: Single Valued Mappings and Collection Valued Mappings. It is worth stating that the examples were written with Hibernate's implementation of JPA in mind, but would work with any other standard implementation of JPA 2, as no Hibernate specific annotation is included.

So let us begin.


Understanding Entity Relationship Mapping, Part 1: The basic concepts

It is possible to create a working functionality of a system using tools/technologies that is not fully understood, as long as some minimal knowledge is present: what things are, where to find them, and how to wire them together in other to get them to work. And thank heavens, with the help of search engines, you can easily scour the web for solutions to anomalies that pops up, due to the lack of complete grasp of the tool being used. But without a more in-depth knowledge, or at least a grasp of the basic fundamental concepts, it would become difficult to accomplish more complex or customized tasks, troubleshoot issues and general extend beyond the basic functionality.

This was how I was treating mapping entity relationships in the ORM domain, via Hibernate's implementation of JPA, for a time now. I had the basic knowledge of relational database modelling, how relationships are constructed using primary keys and foreign keys in SQL, how data can be fetched from tables that are related using joins: basic knowledge that has its roots solely in the relational way of looking at databases. So I was able to annotate up entities and set up relationships. Get stuff persisted and maybe updated. But I kept running into minor errors now and then, configuration issues, minor oversights etc.

One of the areas these annoyances kept popping up was in how to describe relationships between entities. After I have had enough of head banging against the wall, I decided to just take a step back to understand, at least, a little bit more, the tool I am using and what I was dealing with here.

This blog post is the outcome of that stepping back. It has two parts to it. This post, which describes some basic terminologies that you would come across while working with most JPA implementations and the second: Understanding Entity Relationship Mapping, Part 2: Annotating Entity Relationships, which shows how entity relationships are annotated.

So here we go:

Monday, September 23, 2013

How To Use .call(), .apply() and .bind() In Javascript

Back in March I wrote a post "Understanding Constructor Functions in Javascript and This keyword" in which, while explaining the concept of this in Javascript, I stated that it is impossible to tell what the this keyword references by just looking at the function definition. You only get to decide or know what the this keyword refers to, by the way the function is called. Call the function one way, and have this refer to one object, call it another way and you can have it refer to a totally different object. Showing that in Javascript, this is a context-indicator.

I mentioned that normal calling of a function (i.e. have a function fx, call it via fx()) and calling with the new keyword i.e. (new fx()) are some of the various ways to call a Javascript function and have the this keyword switch context.

There are 3 other ways a Javascript function can be called with the ability to determine what this keyword references. call, apply and bind. To be technically specific: Function.prototype.call, Function.prototype.apply, and Function.prototype.bind.

Sunday, September 22, 2013

Javascript is not Java. Deal with it

There are different paradigms when it comes to programming languages. With each paradigm, you have different and unique methods and concepts that are used in the task of computation and getting the computer to do what you want. Sometimes these concepts share similarities; sometimes they go about their task in totally different ways. The merit of a paradigm is thus judged against the backdrop of the problem it is being used to solve and whether it is the best fit.

It would then be totally silly and dense to put a language down solely on the fact that it incorporates a different paradigm when compared to a language you are familiar with. Most of the bashing I see targeted at Javascript is largely due to this: coming from a different programming paradigm and getting miffed when different ways of doing things are encountered in the Javascript land.

At the risk of being wrong and committing fallacy of hasty generalization, I would say Java developers are most guilty of this (maybe it has to do with the misleading "Java" in Javascript? :p)

I say this, because from personal experience, (which I know is limited) I do not get the same close mindedness from the Python, Ruby and C# devs that I know.(This explains the title of the post I guess :p)

Maybe it is that difficult to come to terms that Javascript is a prototype based object oriented language and not a class based language?

Consequences of this close mindedness towards Javascript, thus lead to hacks and practices that try to bend and mould Javascript into something which it is not. I most of the time find this to be quite uneducated.

Coming from a Javascript-first background, before Java, I guess made it quite hard for me to have this kind of narrow mindedness and priggish attitude? I guess this helps to easily appreciate the unique ways of doing things in both languages. I like to think that this makes a better developer, as it is quite interesting to see how different ideas are implemented across languages and borrow from them in situation, when it is germane.

So when (if) I want to learn Haskell, I won’t go about complaining over how it has so many concepts; tricky and odd concepts and how it does things different when compared to say Javascript. And I wont try to write Javascript in Haskell.

And by the way, Javascript is not the only language that has its good parts. Every language does, Java, C++ inclusive :)

Monday, September 16, 2013

Fixing org.springframework.http.converter.HttpMessageNotWritableException Error

A couple of days back, I ran into an interesting error while retrieving persisted entities as JSON  in SpringMVC:

[Request processing failed; nested exception is org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Infinite recursion (StackOverflowError)...


I had to do some poking around and reading up on documentation to figure out how to fix it.

As it turned out, the fix wasn't that complex and the culprit was Jackson: the Java-JSON processor being used to transform the retrieved Java entity to a JSON representation.

The error occurs when you try to retrieve an entity that has a bi-directional @OneToMany relationship with another entity.

Monday, September 09, 2013

Enum in Java.

Let us assume you have the need for some constants in your application; say the three primary colors: Red, Green, Blue. You could create a class specifically for holding the constants thus:
class PrimaryColorsStatic {
        public static final String RED = "red";
        public static final String GREEN = "green";
        public static final String BLUE = "blue";
}

and any of these can be used: PrimaryColorsStatic.RED or PrimaryColorsStatic.GREEN or PrimaryColorsStatic.BLUE

This would work, but it is very limited. Let say you want to hold, apart from the name, the hex code and rgb code of the color as part of the constant? How would this be done with the mechanism above? Whatever way you find to implement this would feel forced as static variables of classes were not designed to help fulfil such use cases.

Enum in Java provides a more robust mechanism for dealing with constant values in your application.

Enum can be formally defined as a special data type that enables for a variable to be a set of predefined constants.

The basic syntax is simple. The primary color example can be represented as an Enum with the following code:
public enum PrimaryColorsEnum {
     RED, GREEN, BLUE
}
[this means that the file would be saved as PrimaryColorsEnum.java]

and an example of accessing it would be:
public main void() {
    PrimaryColorsEnum RedHolder = PrimaryColorsEnum.RED;
    System.out.println(RedHolder);
}

This would print red to the console as a string.

Just knowing the above syntax and when to use it could get you by with Enum, but you have hardly scratched the surface with just that.

To fully appreciate Enums, let us take a step back and see if we can grok the concept in a more detailed level.

Friday, August 30, 2013

Getting Started with Git...Introduction to the basic work flow

This is a very fluid and informal guide to some of the git commands you would come across with a relatively moderate level of frequency as you work with Git. It covers the basics of the git work flow.

And by the way, this is not a true life story...

So yes! First day at work! Congrats! You managed to pass through the technical assessments and various stages of interviews (you did a swell job selling yourself and how awesome you are innit?) Phew! Now it’s the time to come in and start doing all those stuffs you profess you can do! Yes!

After the round of introduction to other folks in the company and your co-developers, you are "introduced" to your work station: All set up nicely; with the right number of monitors just as you like it. Your favourite IDE is already installed too! Cool!

Your new company uses version control to manage collaborative development. Well if they don't am sure you won't be there wanting to work for them...right? Yes, right.

Done with all the introduction and already taken your seat. Your team-lead tells you to get comfortable and that you would be receiving instructions in your email in a couple of minutes regarding getting started, things to configure, account credentials blah blah, etc. etc.

And true to his words, in a couple of minutes your Github username and password arrives in your inbox accompanied by the repository URL you would be working with. Also with those came some additional jargon about common practices, style guides, team practices, schedules etc.

You take about 30 minutes to get acquainted with the new materials you have just received...

...done, cool stuffs in general but now It’s time to set up the project you would be working on!

Even though no one says it is, you feel this innocuous task of setting up your working machine, is somewhat of a test. And you can literally feel eyes behind your back watching to see how you would proceed. But before starting to hyper venting you do yourself a huge favour -- tell yourself  “c'mon, don’t be that paranoid”.

You take a deep breathe and quickly proceeded to doing what needs to be done.

Saturday, August 17, 2013

JProwork-0.1.0 now available as a Maven Artifact

JProwork, a Java Wrapper for Prowork's API is now available as a Maven Artifact.

    <dependency>
        <groupId>com.blogspot.geekabyte.jprowork</groupId>
        <artifactId>Jprowork</artifactId>
        <version>0.1.0</version>
    </dependency>

The version 0.1.0 is the first official release and it supports all publicly available API from Prowork as at of this writing.

See the source for the release on github.

Roadmap and versioning 
Moving forward, the plan is to maintain JProwork in tandem with the evolution and changes in Prowork's API. The version format would be <major>.<minor>.<subminor> which, in this case, would translate to  <Prowork's API Version>.<Major Changes in Jprowork>.<Minor and Bugfixes>

Tuesday, April 30, 2013

April 30, 2013


This would be the first of my monthly recaps. I intend this to be one of the avenues I sprinkle some personal touch on this blog: a break from my seemingly impersonal technical post and rants. I hope I get to sustain it. :)

Trip to Nigeria
I was back in Nigeria from 22th March to 5th April. It did not feel as if I have been away for that long (don’t know if that is a good or bad thing). But the trip was nice. Met up with family and friends, and took a break from the gray weather of the Netherlands! :p

Hung out at CChub…for the first time!
Was already out of the country by the time CChub (Co Creation Hub) was kicking off, so it has always been at the top of my list… a really “must do list”… to pay CChub a visit whenever am in the country. I did. How could I have not?  :)

Cchub is as I imagined it to be. I am really excited that such a space exists, at least if for nothing else (creating an open innovation ecosystem, Pre-incubation to start-ups  gingering the Tech. community etc.), for providing a shared office space with constant power and internet developers.

Gtbank sucks!
Like really. The customer friendliness of the bank has taken a rather sad dip. Gtbank used to be the friendly bank: staffs willing to help, smiling and courteous and all; but my experience at the bank was really disheartening. Frowning and saucy staffs was the order of the day. Sad!

Then long queues have started creeping into Gtbank. I spent 2 hours at one of the Gtbank branch in Ibadan! Reminds me of the horrors of having to go to Union bank/First bank back then!

Not happy that Gtbank is going down this way. :(

Inverters have gone mainstream!
Well, that isn't surprising..is it? 

And...

MTN still sucks! 
Need I say more?

Cologn and Bonn...A nice weekend
The next weekend after I got back from Nigeria saw me in Germany (Cologne and Bonn). Hung out with a couple of colleagues I worked with last year on AIESEC International. It was nice to see everyone is fine and doing good. Meet some other guys in Cologne that were really into rap music...kindred spirits, we are, I’ll say and we spent some nice time bopping heads to some Biggie, Coolio, ‘Pac, 50, Dre and Kriss Kross.

While in Germany, I even got to compose a poem…while in a club :) 

SimpleJSMap
April saw me making simpleJsMap public. It’s A MAP-like implementation that I wrote in Javascript that makes saving stuffs on the client side easier via keys and values. 

JProwork
I also completed most of the work on JProwork and its ready to go. JProwork is a Java API wrapper for Prowork.

Kicked the Facebook Addiction
April is the month I eventually managed to rid myself off the attention sucking and time wasting and zombie turning Facebook! It was getting too much. It was like an addiction and it was getting frustrating. It got to the point that I couldn't concentrate on a task at work for 30 minutes straight without having the urge to go check Facebook. At that point it became obvious it was detrimental to my well-being and I needed to kick it out. I toyed with the idea of totally deleting my account but kept on holding back at the final stages; all thanks to Facebook’s various tactics and emotional blackmailing during the deletion process.

So instead of deleting, I trained my will power to totally get rid of Facebook. And I did it. I feel a lot better, less drained and focused now.

Queens Day!
Yes today is April 30! And in Netherlands it’s the Queen’s day! But in Amsterdam, its not just Queen's Day it is one hell of a party! Somewhat a street carnival. Everyone dressed in orange, on the streets, marijuana smoking, party rocking, and Liquor flowing!

It’s crazy!

So you guessed it, once I press the publish link on this post, I am hitting the streets too!

And if you ask me, it is sure a nice way to bring April to an End :)

Saturday, April 27, 2013

JProwork Ready to Go

JProwork is a Java wrapper for Prowork. 

Prowork itself is an intuitive project management app that makes team collaboration easy. It was launched 2011 at Start-up Weekend in Nigeria. It recently won the Apps4Africa 2012: Business Challenge. 

For more information, check: About Prowork and the team behind it and  How it works.

Overview
JProwork is then a Java wrapper for Prowork’s API. It encapsulates the API calls to Prowork and exposes Prowork’s entities as Java objects to the developer. 

As can be seen below:


It sure would make developing on Prowork faster with Java. 

JProwork has been a weekend project for a couple of weeks now and right now it is done as far as covering the existing Prowork's API is concerned. Just need to put some structure here and there regarding versioning before we can have a first official release. But in the meantime you can grab the Source code from Github and to give it a spin, compile the source, update your class-path as necessary and you should be ready to go:

Dependencies
Jprowork requires Gsona Java library that can be used to convert Java Objects into their JSON representation and also to convert a JSON string to an equivalent Java object.

Roadmap and versioning
Things left to do?

Have a proper versioning structure in place. I plan to go with the format of: <major>.<minor>.<subminor> which, in this case, would translate to  <Prowork's API Version>.<Major Changes in Jprowork>.<Minor and Bugfixes>

Mavenized JProwork and also have it available as Jar files.

Documentation
Documentation is in the code. You can grab a copy of the documentation using Javadoc. A generated Javadoc is also included in the repository.

Do give it a spin ;)

Saturday, April 20, 2013

simpleJsMap


I find having to riddle the Dom with stuffs dirty :(

Just because there is no other way to easily keep stuffs on the client side, we sometimes do this; and it is painful! having to unnecessarily pollute the DOM.

I was in such a situation a couple of months back where I was on a project in which stuffs, AKA. the states of the application were being pushed to the DOM attributes just to keep them.  Dirty!!!

I didn't want to continue doing this, so instead, I rolled up a little thingy that enabled me put my stuff out of the DOM. :)

I called it simpleJsMap.

simpleJsMap is a simple MAP-like implantation that enables me to keep and retrieve my stuffs easily in the memory via keys and values without having to set things in DOM attributes.

This felt a lot cleaner :)

simpleJsMap is on github so it can easily be grabbed, and hopefully, someone apart from myself finds it useful. :)

Getting Started

Include the simplejsmap.js file into your script. The variable simplejsmap would then be available. 
<script src="//path/to/simplejsmap.js" type="text/javascript"></script>
<script type="text/javascript">
// simplejsmap now available
</script>

I am a big fan of pure Javascript first before framework, thus simplejsmap is not dependent on any Javascript framework; not even jQuery :p

So once you have the script included you ready to go.

Function reference


createMap()
var map = simplejsmap.createMap();

Creates the map like object and assigns it to variable map. You always start using simplejsmap by calling this function.

add(key, value)
var map = simplejsmap.createMap();
map.add("key1", "value one");
Adds stuff that needs to be kept. The stuff has a value and is associated with a key. Returns true if successfully added and false if not. If the key is already present, nothing happens and false is returned also. To modify the value of a key that is already added, update() function is used.

key and value can be of any Javascript type.

update(key, value)
var map = simplejsmap.createMap();
map.update("key1", "updated value");
Updates the value already added by a given key.  If the given key exists, its value is updated. If the key is not found, no update operationis done. False is returned instead.

remove(key)
var map = simplejsmap.createMap();
map.remove("key1");
Removes a value accessible via the given key.  If the given key is already in existence, it is removed and true is returned. If not, false is returned.

get(key)
var map = simplejsmap.createMap();
map.add("key2", "Hello World");
var val = map.get("key2");
Gets the value stored via given key.

getLength()
var map = simplejsmap.createMap();
var len = map.getLength();
Returns the number of stuffs/keys that has been added.

getKeys()
var map = simplejsmap.createMap();
var keys = map.getKeys();
Returns all the keys that has been added as an array.


UPDATE
simpleJsMap can now be gotten via bower. Just use "bower install simpleMapJs" to add it to your project.

Friday, April 19, 2013

Callback functions in loops in Javascript

In other to implement the Reddit twitter bot for r/Java (@redditJava) and r/programming (@redditprogrammn), I had to get the lists of entries from Reddit, loop through it and call a function to tweet each item. On successfully tweeting, a call back function is called that stores the id of the item that was tweeted. This list of saved Id is checked every time, before tweeting, in other to prevent double tweeting.

A simple way to get this done is to get the items to be tweeted in a form of an iterable (array or object in javascript), loop through the items and in the loop, put the logic that tweets the item and the call back function.

A pseudo code would look thus:
for (var n=0; n < thingstotweet.length; n++) {
      // tweet function
      Tweet(thingstotweet[n], function(e,r) {
         // the call back function
          //if no error, then save the id of the tweet
          if (!e) {
              Db.save(thingstotweet[n]);
          }
      })
   }

In Javascript, this is a faulty implementation. If you implement such a solution for having callbacks inside a loop you would soon find out that the things gets out of sync. For instance in the tweeting example, one tweet would be sent while a different one would be saved in its place. And the reason is simple: It takes time before the function sending the tweet returns and the call back is called. And since functions call like this in Javascript are non blocking, in the time it takes before the calling function returns and the callback called, the value of n would have changed leading to saving the wrong item. 

For example.
1. Start the loop when n is 0;
2. Tweet the item in index 0 in the thingstobetweet list
3. The tweet function is sending the tweet but it takes a couple of seconds.
4. Value of n increased to 1. Still tweet has not been sent, so call back Is not to be called yet
5. Value of n increased to 2. Still tweet has not been sent, so call back is not to be called yet
6. Value of n increased to 3. Finally the tweet was sent successfully, time to call the callback
7. The call back is called. But n is now 3. So thingstobetweet[3] is saved for a tweet at thingstobetweet[0]

How then do you deal with this? What would be the correct way to implement a task that needs a callback function inside a loop?

There are two ways I normally implement a solution for this specific scenario:

Use Closures

In a previous post I briefly explained closures in Javascript.  Dealing with callbacks in loop is a situation where closures can be put to use. The solution is to create a closure for the tweet function. A pseudo implementation would be thus:
  for (var n=0; n < thingstotweet.length; n++) {
      (function(clsn){
          // tweet function
          Tweet(thingstotweet[clsn], function(e,r) {
              // call back function
             //if no error, then save the id of the tweet
              if (!e) {
                  Db.save(thingstotweet[clsn]);
              }
          });
               
      })(n)
 }

You can check the post on closures in Javascript for more information and why the pseudo code above works.

Use Recursive Function

The other solution is to implement a recursive function.  An implementation would be thus:
 var tweetRecursive = function (n) {
      if (n < thingstotweet.length) {
          // tweet function
           Tweet(thingstotweet[clsn], function(e,r) {
              // the call back function
              //if no error, then save the id of the tweet
              if (!e) {
                 Db.save(thingstotweet[clsn]);
                 tweetRecursive(n + 1);
               }
           });        
       }
  }


  //start the recursive function
  tweetRecursive(0);


The logic to send the tweet is defined as a recursive function.  This works because the function to tweet the next item (the recursive function) is also called in the callback function. This would ensure that there is no out of sync situation and the correct tweet would be saved for the one that was sent.

The only repercussion in this implementation is that it breaks the asynchronous nature as the tweets would be sent in a procedural manner, i.e. one after the other instead of asynchronous fashion.

Saturday, April 06, 2013

Closures are hard? Not really: A simple introduction to closures in Javascript


The concept of closures exists in various programming languages. Javascript is one of such language, and anybody who spends an ample time with it would sooner or later run into situation where using closures is warranted.

But closures are hard? Not really.

So what are closures? From personal experience, giving a detailed pseudo-academic explanation benefits little in really getting the concept; well, at least for me. I realized that even after understanding it, translating that knowledge into practical usage remained a little fuzzy for a while until I had to use it in real projects once or twice after which I sort of formed a personal mental model for it.

So I won’t give a too much detailed explanation. There are tons of posts and articles out there that already did that. I listed some at the end of this post. What I would quickly outline is how I came to understand it to the extent of practical usage.


Sunday, March 17, 2013

Difference Between Protoype and __proto__ in Javascript


So what’s the difference between __proto__ and prototype property in Javascript?


The prototype is used to create __proto__  Simple!

Yes, I know. That statement does not help much in terms of explaining what is going on :) But stick with me, the plan is to make it clear by the end of the post.

So let's dig into explaining this stuff!

The subject of prototype is related to Javascript objects and object creation and relation; so before going further, I recommend first reading Understanding Constructor Function and this Keyword in Javascript as this would provide some basic information that would help in understanding some of the basic concepts needed.

Saturday, March 16, 2013

Understanding Constructor Function and this Keyword in Javascript


Back in 2006 I wrote a post on using constructor functions in Javascript to create objects. This post builds on that post, expounding it a little bit further.

By definition, a constructor function is a normal Javascript function. Nothing more, nothing less. What makes a function a constructor is how it is used. When a function is used in such a way that it can create an object, by calling it with Javascript's new operator, then it becomes a constructor function.


This means all and any function you have in Javascript can be used as a constructor function.

var Person = function () {
  console.log("I am a function");
}
We can call this function normally:
Person(); //prints to the console "I am a function"
console.log(typeof Person) //prints to the console ‘function’
So let’s now use this function as a constructor and create an object:

var bond = new Person();
Now let us confirm that bond is indeed an object:

console.log(typeof bond) //this prints "Object"
Now that is all about Constructor functions.  It is as simple as that: A function that is the same as your normal Javascript function but can be used to create objects.

But you would notice that the object created above is empty (without properties) and maybe of little or no use. Compared to the example given in my previous post, which had properties. 

So how do you actually make an object with some already set properties at creation? Before we go ahead and look at this, its worth mentioning a characteristics of functions in Javascript (apart from this fact that they can be used to create objects).
Functions are first class citizens in Javascript and also Functions can have properties just as objects! Yes just like you add properties to an object, you can do same to a Javascript function.

Friday, January 04, 2013

Now You Know What I Did Last Weekend: @redditJava




I am a regular reader of Hacker news: It’s a great place to discover interesting stuffs. But I don’t go checking http://news.ycombinator.com every now and then, neither do I subscribe to their RSS feed. I get most of the stuffs I read on Hacker news via twitter. There are Hacker news’ bots that I follow on twitter which provides the utility of having *hot* articles tweeted once they have attained a certain number of points or comments. Namely: @newsyc150, @newsyc100, @newsyc50 and @newsyc20.

So recently, when I decided to pay a little more attention to Reddit, the first thing I looked for were twitter bots I can follow that would feed me with interesting contents from Reddit. One nice thing about Reddit, unlike Hacker news, is the fact that Reddit have sub categories or channels which are called subreddits which cater to specific topics. You got subreddits for Politics, Gaming, Movies, Music…the list is almost endless. So I basically was on the lookout for twitter bots for subreddits I may be interested in.

But my searched returned null.

Since I could not find one, I decided to make one for myself. And I decided to make one for the Java subreddits since I recently started playing with the language again. (By the way having the bot track other subreddits is simply a matter of configuration).

The idea is simple enough: get stuffs from Reddit, have a way of getting only the interesting ones based on the number of points and comments, and then tweet only those. Also, make sure you also don’t have the same thing tweeted twice. The content is there, the APIs are there, so I set about getting this done within a weekend.

For this, I used Node.js. Reason? Well, I spend a lot of time with Javascript now, notable because I work with the language at work, building the world smarter customer service app, which enables business to keep more happy customer: Casengo; and since Javascript is very much capable, why not?

It was fun hacking this bot together the last weekend as I also took time to play around with stuffs: For storing information to prevent double tweets, mongoDB was used; this allowed me to get pretty conversant with the idea of document based DB and how it works in mongoDB. I also stumbled on node-supervisor. A handy Node Module which prevented the need to manually stop and start the server on every change in the code. Use node-supervisor to run a node script, it watches for any changes in your file; on change, it automatically reloads the script. This definitely made the development flow smoother.

I also checked up on writing Node Modules while following generally accepted guidelines especially if you want your module to be compatible npm. Also learnt one or two things about setting up mongoDB on AWS’s EC2.

Apart from the obvious Twitter and Reddit API’s I equally got to play around with bit.ly and goo.gl API’s.

And finally once deployed, I used forever to keep the script running. Forever ensures that a node process continuously runs and automatically restarts itself when it exits unexpectedly.

Javascript is definitely a pleasant language to work with. But you could trip if you fail to wrap your head around some of its unique and basic characteristics. First all, it is a Prototyped based OOP language (not class based) it is also event driven and easily supports asynchronous programming. This alone could result in some unexpected behaviour if you do not put these unique characteristics in mind. An example, where one can easily be tripped would be handling asynchronous API calls inside a for loop. (More on this in coming post) You also have things like variable hoisting, scoping, closures, the abstruse this etc., all which may make the language appear weird at first approach.

It was a weekend well spent and would spend some more free time modifying things and perhaps adding more subreddits that catches my fancy. The bot is already up and running by the way and you can follow on twitter here www.twitter.com/redditjava and the code is hosted on github here https://github.com/dadepo/redditTwitterBot.git