Saturday, September 24, 2011

How I like to define JavaScript Objects

I've been really impressed by the expressiveness and power of JavaScript lately.  It's much more capable a language than I ever used to give it credit for.  The flexibility of JavaScript also can make it often harder to understand what is going on.  There are many ways to accomplish the same thing and they can look like completely different things.

If you have need to create a lot of custom "classes" in your application, I have a few things I've grown to appreciate.  In this post I'll talk about a style of class definition that I find readable, provides good encapsulation and can provide good performance when accessing functions on these objects.  I'm sure that if I'd worked with JavaScript longer I'd be able to enumerate all the problems with my approach, but so far I don't think there is a lot of down side. But I think part of the reason I like my approach is that it reminds me of Java with less ceremony.

Here's what I usually see around the web:
function MyClass (some, params, needed) {
    this.doSomeInit();
}
var p = MyClass.prototype; //Or = new ParentClass();
p.baz = "lorem";
p.fuzz = "ipsum";
p.foo = function() {
    return this.baz + this.fuzz;
};
p.bar = function() {
    return this.fuzz + this.baz;
};
I've also seen:
function MyClass (some, params, needed) {
    this.doSomeInit();
}

MyClass.prototype.baz = "lorem";
MyClass.prototype.fuzz = "ipsum";
MyClass.prototype.foo = function() {
    return this.baz + this.fuzz;
};

MyClass.prototype.bar = function() {
    return this.fuzz + this.baz;
};
So what's going on?  
The above code is basically just 2 different ways of defining a JavaScript "class".  I put class in quotes because JavaScript doesn't technically have classes.  It has objects.  My main gripe with these approaches is that it requires that these objects expose a lot of their internal structure by updating their prototype so that these public functions can manipulate the internal state of the object and do work. The only real difference in the 2 styles above is that one is slightly more efficient since it avoids the chaining of object property calls that's required.  There is a cost to calling MyClass.prototype each time you define a new function.  So if you're looking for speed you put that in a variable.

I prefer to do something like the following:
function MyClass (some, params, needed) {
    var baz = "lorem";
    var fuzz = "ipsum";

   function myPrivateFoo() {
       console.log("PRIVATE");
   }

    this.foo = function () {
        return baz + fuzz;
    };    
    this.bar = function () {
        myPrivateFoo();
        return fuzz + baz;
    };
}
This approach means that I don't have to expose the variables baz and fuzz.  I also get to use the parameters, "some", "params", "needed" without the need to create internal vars or properties on the prototype.  The functions foo() and bar() are both public privileged members of our object.   It also makes it easy for these public functions to use private functions.  My main reasons for liking this approach is that I think it's cleaner in that I like that my constructor encapsulates the class definition like you'd see in Java. I also like that my object can be more shy about what they expose to the world.  But is there a downside to this?  Actually there is.  

The catch is that every time the constructor is called all of the code in my constructor gets run.  All the function definitions are added to the prototype every time.  That's not so good.  Why?  Because if your custom object needs to be constructed a lot, then yes you'll take a hit in the performance department.  However that's usually a smell of something else not being quite right in the design and can be mitigated with a pattern that separates construction from execution and ensuring you are being judicious about your object creation. However if it truly is something that needs to be created thousands of times, then by all means follow one of the other approaches.  Or take a hybrid approach and define any functions that are fully public and don't require internal knowledge of your object state and define them explicitly with the MyClass.prototype.myFunction syntax and anything that has to access the internal state can be defined in the constructor.  There's not really a right answer here.  I'm just sharing my preference and providing a small argument for it.  

If you were to look at performance from another perspective, my approach may actually be preferred.  If you are using functions that an object exposes in a loop, or another pattern that requires lots of calls, my approach means that there are fewer property lookups on the object prototype since local variables can be used more often.  In practice I find that I'm not constructing custom objects very frequently, but I am calling functions on those objects in loops quite a bit.  So for me this approach is a good fit.  

Anyone else have a different take? I'd love to hear about it in the comments.

Friday, September 23, 2011

Starting Fresh

I'm no longer a part of the Redshirt Labs gang of 5 that was actually 4 for quite a while and felt like 2 for a long time, but whatever.  I'm done.   Of course we still hang out and eat the same lunch at Prince Al's, but no longer will I be pining over what to do next with Zengaku.  The rest of the gang will figure it out.  I'd offered to take it off there hands, but they didn't go for that.  I also considered licensing the source code and doing a fork, but I reconsidered and felt like a clean break would be best.

So begins the adventure once more.  This time with a little more solitude.  But if I make an application that only sells a few hundred dollars worth on the market, that's a bit easier to swallow than when you have to split that 5 ways.  Plus I'm not going to be making games.  Which I think would be fun, but is a tough business to get into and requires a lot of talent that I don't have.  Mainly a lot of art, music, sound and game design skills.  I could probably implement the code for a game if you gave me the spec/design docs, but coming up with all the rest is way to much for me and I can't go and hire all that talent either.  This is just a hobby after all.

So I've made the initial steps of setting up my new business.  I've got an idea for a first application.  I'll share that soon enough. I got a website, a hosting service, a remote repository and an official business license.  I'm working on my registration with the Apple Developer Program. It's all getting started.  Now to start making the application.  My hope is to have it delivered to the App Store before the Christmas holidays.  Not that it would help sales or anything, just that I need a goal and that seemed reasonable.

I'm not going to get into the details of my business idea, or the application I plan to build just yet.  If you ask me in person I'll tell you about it. But mostly I'm just not ready to share much else at this point.  I have a lot of work to do.  I'd like to have a decent landing page on my website, get some blog content lined up,  get the application in progress and moving forward and so on and so forth.  Then I'll have loads more to talk about. But for now this is about it.

I may have to write a bit about my new affection for JavaScript and functional programming.  I don't know if I'd say I know a lot about either just yet, but I've definitely spent some time getting familiar with JavaScript over the last couple months and I'm actually quite impressed.  But also looking forward to doing a bit of C/C++ work once more.

Wednesday, March 30, 2011

A couple of things Developers Should Know but often Don't

I've been reviewing a lot of code lately. Mostly Java code, but some C, some C++ event some Objective C.  There have been some patterns to the coding mistakes/miss-steps that I've seen and been pointing out in a number of these review.

Loops
This one seem to be the most common of late. And I had to convince some people of the merit of my stance.  Basically my theory is that you should almost never need a while loop.  So if you ever see yourself using one.  Ask yourself why.  Most times you'll be declaring some kind of iteration tracking variable and incrementing or updating it somehow as you loop through whatever structure is being iterated over.

The problem there is that the variable gets declared and used outside the loop.  Now C doesn't help here so it's common for C developers to make this mistak in languages that do help. In my case Java.  Using a for loop allows you to declare a variable that is scoped to you loop so you can be sure you don't accidentally keep the variable longer than you need and use it by accident somewhere else in your function.

I think the latest C standard (C99) fixes this, but it's pretty common that you can't count on that so a lot of C developers still don't think about this feature.  Just about the only time I think a while loop is a bit cleaner or clearer is if you are creating an infinite loop; in that case the simple while(true){} is pretty universal.  Although I've seen for(;;){} a number of times as well so I'm still not sold on that.

Proper Scope
Along the same lines as my previous issue with loops is ensuring that your variables are scoped properly.  I hate seeing Java functions with a long, long laundry list of auto variables that are potentially not needed since the the parameters may make their allocation unnecessary.  Although this isn't really a memory or optimization effort it does help a bit in that respect.  The Java stack frame will be allocated with space for all the local variables.  Event the objects, although only space for the reference is allocated by default.

So although you will not be preventing local variables from being allocated, if you have the the objects you create properly scoped they will at least only do the object allocation when needed and will be dereference and available for GC as soon as possible.  But the optimization can come into play if your objects are only going to be created if certain parameters are passed into that method.  So in cases where your parameters don't require the objects to be created you save that time and memory.  But like I said, this isn't really the reason to scope them properly.

The best reason for scoping variables is for clarity and maintenance. The issue with keep a variable around longer than you need to is that it is unclear if you intended to use it later and just forgot, or worse yet you do use it later, but didn't actually mean to do so.  Don't laugh.  This happens a lot.  In particular in long, hairy functions.  I don't like those either, but baby steps.


Over use of if this set this else set that
I think this is a pretty easy one.  Which would you think is clearer and more concise:
Option 1:
if (conditiona) {
   var = boo;
}
else {
   var = bar;
}

Option 2:
var = (conditional) boo : bar;

Option 2 is the clear winner in my books hands down every time.  I think this is the very reason why the ternary operator gets included in pretty much every language I've had the pleasure of working with.

I have lots of other gripes and faux paus that I see on a daily basis, but these are just some of the most common that I've seen of late.  One of my biggest pet peeves is when OO design gets perverted into some crazy mess of over complicated goo.  Often that seems to start with good intentions and the classic over use of inheritance rather than composition.  I've trained myself similar to the for loop to stop every time I see inheritance to ask if it is actually the most appropriate solution to the problem at hand and if it truly adds value beyond what composition could provide.  I feel like I'm stating the obvious since I've been reading about this stuff on blogs like this for years, but I keep seeing these same issues in the code I look at being created on a daily basis so people still aren't getting the message.  I figured I may as well add to the ocean of data out there pleading with developers to clean things up.  But I'm sure it's a Sisyphus like task. But I'll keep pushing that damn rock anyway.   It's just how I roll.

Sunday, March 6, 2011

Samsung's Lost a Customer Today

I have a Samsung HTDV.  I was quite happy with it until recently.  It started to behave rather oddly when I powered it on.  I'd hear this relay clicking sound repeatedly before it actually powered on.  At first this happened for 2 or 3 cycles.  Then it was 10, then 20, then it was starting to take upwards of 5 minutes before the TV would actually turn on.

This started around the time my 1st child was born so my time for such distractions was at a minimum.  I finally decided to look up on the inter-webs to see if others had seen this problem and maybe there would be a quick fix. I soon found that this seems to have been a common issue with a number of Samsung LCD TVs with my model number.  They called it the "bad capacitor issue".  Apparently they installed some sub-standard capacitors that eventually wore out.  As the issue progresses eventually your TV would never power on again until the faulty capacitors are replaced.

So I looked up the Samsung support site and called the support group.  They told me I had to provide my proof of purchase and fax it to them.  And so I did. But after all that I found out that since I've owned my TV for longer than 3 years I don't qualify according to Samsung's policy on the matter.  I said: "That's fine, but it's my policy that if a company doesn't want to fix a product issue that is obviously due to an error on their part, they'll lose me as a customer."  The service rep just stuck to the script and said: "Sorry, but this is Samsung's policy."  I don't care if that's the policy.  After this experience Samsung's not going to get another dime from me.  It's too bad too.

I had heard over and over again that they had a quality product.  But this is all it takes to really sour a customer on your products.  I wouldn't have minded if they'd just offered to fix the issue and replace the capacitors at fault.   But that's just not the story I'm telling you today.  I'd rather be praising them.  But I'm not.  Instead you're reading this little buyer beware story.  Oh well.  When I decided to get a new TV I wonder who's going to be getting my money.  Maybe Apple will finally have produced a real Apple TV product.  One can dream.

Globe & Mail talks about Cord Cutting

I was reading the Globe & Mail a couple weeks ago in between feeding my newborn daughter and catching up on sleep. The article in question was this one: Globe & Mail - This is Where we Leave Cable Behind.  I found it pretty interesting given my past experiences within the cable business.  I'd expected the article to be all about digital streaming over the internet, but rather it talked more about how digital cable is slowly being supplanted by the newer and cooler sounding IPTV.

The majority of the article talked about how IPTV is being deployed aggressively by a number of telecom companies to go on the offensive vs. the big canadian cable stalwarts.  And it seems that despite the limited footprint of the product they are making inroads.  This is basically the Telco's punch in the nose after getting bullied by the cable folks for so long in the realm of mobile phones.

The part of the article that I latched onto was when it was quoting from someone they'd interviewed who was using the IPTV service from one of the providers.  The whole article was talking about the great new features and web-like experience that this new IPTV technology could provide.  But at the moment the offerings provided in these early markets where the service is available they have a very cable-like experience thus far.  And the guy they are interviewing doesn't really care about that.  What he's excited about despite all that is the fact that the program guide and other software that he interacts with on the device provides a user experience more like what you'd expect from a product built in the last 4 or 5 years and not like it was built in the 80's using Atari games as the design aesthetic.

If I were a cable operator...and I'm not, but if I were I might want to consider getting a new program guide experience as soon as possible.  I know my feelings are similar to the guy in the Globe's article.  If my provider had a much nicer user interface with a well laid out and simple flow of control for searching, browsing and discovering content on my TV I'd be a lot more satisfied than I am today.  So what I'm saying is that in terms of short term bang for the buck the cable companies really should consider just giving their guides a real facelift.  Let a real designer go to town on it.  Let a real software company build it for you and deploy, deploy, deploy.

I'm not saying that IPTV is a waste of time.  Not at all.  I believe it's likely where all paid TV is going to go and needs to go.  But it's more of a longer term strategic thing as far as I can tell.  But if they want to stop the bleeding.  And I'm thinking they do, they would be well served to bring their guides into the 21st century.  They don't even need to add new features....just make the ones they already have work better.

I'd love to be a cord cutter, but my morality gets in the way...

I have a hard time with "cord-cutting".  I would love to stop giving my service provider so much money for a service that I think I'm over-paying for, but I also don't have a clear alternative that provides the same level of service without going outside the law.  The frustrating part isn't that no one else can provide the service at the same level of quality or even better.  It's that government regulations and the entrenched telecom companies keep blocking competition any chance they get.

Just across the boarder services such as Hulu, Amazon On Demand, VUDU, and others provide access to a lot of high quality streamed content that I can't have for a number of political and legal reasons.  I could do as a number of my tech savvy friends have done and setup a Usenet account or use Bit torrents to get at the content I'd like.  Or more recently some have tried services which allow you access to US services through a VPN like service so the service provided doesn't detect you aren't in the US and as such allows you to stream content to you're hearts content. The last option is probably the most morally ambiguous.   The first 2 are pretty clearly stealing.  And I have a hard time with that since I love the content.  I want to pay those who produced it their due.  They provided me the entertainment value and I feel obligated to pay them for that value.  This is why the last option is more palatable to me.  At least in that case the producers of the content are still getting paid.  You're just subverting their contract with the contents owners to not distribute the content outside certain geographic boundaries.

I find that as time passes and things like UBB have come to a head my moral arguments are carrying less and less weight with me.  I'm starting to feel like the only way we'll be able to change the way video content is delivered is to hurt them where it seems to matter most, even if that will in turn still hurt me, in that the content I love may not have the funds to be produced any more. I could quite easily sign up for  a Usenet service, pick up a Mac Mini with HDMI out and install Plex or another XBMC varient quite easily.  I know the programs to install that can automatically download the content I'd want and it's all pretty easy to find.

However it's not all doom and gloom.  There's still a chance that my provider will learn something here.  For me the UI and the UX matter a great deal more than the feature list.  If they can just spend some time focusing on that they would find someone like me a lot easier to please.  They already provide a pretty impressive feature set.  I can deal with VOD shows that are handcuffed by not allowing me to fast-forward through the commercials.  I can also deal with a DVR that doesn't have all the bells and whistles that a TiVo can provide.  Just make it easier to use, make it drop fewer scheduled recordings, make it easier for me to find the VOD content you have, and make it not so horribly ugly to look at on my big screen TV.  I don't think I'm asking for too much here.