Wednesday, February 16, 2011

The Shortest Distance between Two Points is MATH

They need me to put together a simple little system at work that finds known locations within a given radius of a given location. This sounded familiar, so I dug up an old SQL query of mine from a LONG time ago...

SELECT
  Name,
  Address,
  City,
  State,
  Latitude,
  Longitude,
  (
    ACOS(
      COS(@center_latitude * (PI()/180)) *
      COS(@center_longitude * (PI()/180)) *
      COS(Latitude * (PI()/180)) *
      COS(Longitude * (PI()/180)) +
      COS(@center_latitude * (PI()/180)) *
      SIN(@center_longitude * (PI()/180)) *
      COS(Latitude * (PI()/180)) *
      SIN(Longitude * (PI()/180)) +
      SIN(@center_latitude * (PI()/180)) *
      SIN(Latitude * (PI()/180))
    ) *
    (
      (@equatorial_radius * @polar_radius) /
      (
        SQRT(
          (@equatorial_radius * @equatorial_radius) -
          (
            (
              (@equatorial_radius * @equatorial_radius) -
              (@polar_radius * @polar_radius)
            ) *
            (
              COS(@center_latitude) *
              COS(@center_latitude)
            )
          )
        )
      )
    )
  ) AS Miles
FROM
  Places
WHERE
  Miles <= @search_radius

This query accepts a center lat/long (the customer location) and a radius (the distance from the location to search) and finds any known locations within that distance from the center and notes that distance in miles (so we can sort and find the closest).

It also accepts parameters for the radius of the Earth. The radius of the Earth can be expressed in many various ways. For simplification, we'll use these:

@equatorial_radius = 3963.190 miles
@polar_radius = 3949.902 miles

(Note that this equatorial radius may not account for the crust displacement during the 2004 Indian Ocean earthquake.)

This distance calculation not only plots a circle around the area, but in the projection of that circle onto the plane of the Earth it accounts for the curvature of the Earth’s surface and the bulging at the equator, derived from the WGS-84 ellipsoid model.

We never did get around to using this at a previous job. (They plotted searches as rectangles around the center... ew. Just goes to show how a fundamentally broken business idea can churn out sub-par results from an otherwise intelligent and talented team of developers.) But maybe I'll finally get a chance to use it here.

Wednesday, February 2, 2011

Prototypes, not your everyday inheritance

So a concern came up today around Javascript. Specifically it was that there are no private members in the language. I quickly spoke up saying that how closures work and the use of the var keyword keep your variables private but was met immediately with those are not instance variables and you can't have private instance members. It turns out there was some confusion as to what the prototype attribute does on functions and it's role with inheritance.

This was the example to prove that there are no private instance members in Javascript:

function Person() {
  //public member
  this.Name = "Copenhaver";

  //convention based "private"
  this._ccn = "5555555555555";

  /* thought this was unusable, but it's actually scoped inside
   * this invocation of the function and usable by other members of
   * the object currently being built.
  var ssn = "xxxxxxxxx";
}

/* this is actually creating a completely separate object that
 * will act as the parent of all objects built using Person()
Person.prototype = {
  getSSN: function(){
    //this doesn't do what you want
    //actually would try to grab this out of global scope
    return ssn;
  },

  getCCN: function(){
    //anyone could access this variable
    return this._ccn;
  }
};

Now the developer was used to using the prototype variable basically for class style definition and inheritance with Javascript. The confusion comes in with that as well. That prototype attribute on the function is going to point to a single object and that object gets hooked in as the parent of any object created with the function. Yeah think about that, so that would be a single object as the parent to many children. Not a class, an object. That is prototypical inheritance. If you wanted them disjointed then you would clone the parent first.

I personally see the prototype attribute as a bit of a wart on the Javascript language that just confuses the people who come in trying to use it the same as they did classes and inheritance in other languages. Anyway I'm starting to see all this constructor inheritance business in Javascript to be a bit off. I'm thinking that you should really think about these functions as initializers and inheritance as something to create off of:

var linkedChild1 = Object.create(sharedParent);
var linkedChild2 = Object.create(sharedParent);

//now you become a Panda... but it could effect everyone else making them sad
linkedChild1 = Panda(linkedChild1);

var unlinked1 = Object.create(parent.clone());
var unlinked2 = Object.create(parent.clone());

//now you become a Grizzly leaving everyone else behind so you can eat them
var raaar = Grizzly(unlinked1);

I haven't used this idea yet and it's partially based on a Crockford's Object.create() idea which is getting incorporated into Javascript. Figured, throw the idea out there and see what comes of it.

Links:
http://javascript.crockford.com/prototypal.html
http://javascript.crockford.com/private.html

HtmlHelper Extensions

I'll keep this fairly short. Do yourself a favor and organize your HtmlHelper extensions. That thing gets polluted quick and you'll find yourself with pages of items in intellisense and large method signatures for your configuration options.

I suggest trying an idea of having HtmlHelper extensions that create and return custom html builders for related or even individual UI widgets. The builders can have a fluent interface for more complicated configuration of the output and you get the added benefit of keeping the HtmlHelper somewhat clean.

Here is an example of what I'm suggesting.

Clean simple HtmlHelper extensions:

public static class HtmlHelperExtensions
{
  public static PhoneHtmlBuilder<tmodel> Phone(this HtmlHelper<tmodel> helper)
  {
    return new PhoneHtmlBuilder<tmodel>(helper);
  }

  //... a bunch of other things
}

With Html Builders doing the real work, possibly grouping related widgets (as I'm calling them):

public class PhoneHtmlBuilder<tmodel>
{
  private HtmlHelper<tmodel> _helper;
  private Expression<Func<TModel, string>> _phoneNumber;
  private Expression<Func<TModel, string>> _extension;

  public PhoneHtmlBuilder(HtmlHelper<tmodel> helper)
  {
    _helper = helper;
  }

  public PhoneHtmlBuilder<tmodel> For(Expression<Func<TModel, string>> property)
  {
    _phoneNumber = property;
    return this;
  }

  public PhoneHtmlBuilder<tmodel> WithExtension(Expression<Func<TModel, string>> property)
  {
    _extension = property;
    return this;
  }

  public MvcHtmlString Render()
  {
    //probably register javascript to get rendered or generate some

    //i'm not even sure if this compiles, just getting a basic format of the idea down
    return MvcHtmlString.Create(
      _helper.LabelFor(_property) +
      _helper.TextBoxFor(_property) +
      _withExtension ? _helper.TextBoxFor(_extension) : "" +
      _helper.ValidationMessageFor(_property));
  }

  public override string ToString()
  {
    return Render().ToString();
  }
}

Providing organization and possibly fluent or more options for the more complex widgets:



  

Cell Phone

@Html.Phone().For(m => m.Cell)

Business Line

@Html.Phone().For(m => m.BusinessNumber) .WithExtension(m => m.BusinessExtension) .Render()

Note that the call to Render() for the business number was optional, just trying to show options.

I hope that's helpful. I would love to hear any feedback or ideas.

Sunday, January 23, 2011

Interfaces: The Questions

I haven't been putting thought into this post so I thought I could at least post the things I have been thinking about and some resources. This is dealing with the use and idea of the code construct (C# interfaces). Feel free to comment with your own questions, answers, or resources.

what makes a good interface?
can you really refactor out to an interface?
if so how good would that interface really be?
how good did your class before hand have to be?
if not then it's important to consider interfaces up front
how do you make the judgement to put in the effort of making a good interface?
are these really just problems with explicit static typing instead of dynamic typing or inferred static typing?
how do you ensure the least astonishment with interfaces?


links for research:
http://blog.ploeh.dk/2010/12/02/InterfacesAreNotAbstractions.aspx
http://martinfowler.com/bliki/RoleInterface.html
http://simpleprogrammer.com/2010/11/02/back-to-basics-what-is-an-interface/
http://www.objectmentor.com/resources/articles/isp.pdf
http://www.lostechies.com/blogs/jimmy_bogard/archive/2010/12/02/the-case-against-interfaces-in-tdd.aspx
http://publicvoidlife.blogspot.com/2010/10/to-learn-is-to-abuse.html
http://en.wikipedia.org/wiki/Law_of_Demeter
http://en.wikipedia.org/wiki/Principle_of_least_astonishment

Nice post with some comments about the use of inheritance:
http://www.lostechies.com/blogs/derickbailey/archive/2011/01/18/i-use-inheritance-and-i-m-not-entirely-ashamed-of-it-should-i-be.aspx

Saturday, January 15, 2011

Dear John

Following a tweet from @codinghorror, I just read a short article on why John C. Dvorak doesn't use Facebook.  He outlines, in his own condescending old guy kind of way, how Facebook is just like AOL and how he didn't use it then and won't use it now.  Really?  John C. Dvorak is opinionated and wrong?  Say it ain't so!

Well, to be fair, he's not wrong about the fact that he doesn't use Facebook (I'm assuming).  And I'm sure his prediction that he won't use Facebook will continue to be true.  (So he got one right.)  But all of his reasoning in the matter is entirely invented.  John, we don't need to you explain why you don't use a particular tool.  We especially don't need you to just make stuff up about that tool to try to justify it to us.  It all ends up sounding like a student's book report on a book he clearly hasn't read.

Let's address the main points of John's little rant.  They are, in no particular order:

  1. Why make a personal home page on Facebook when I can make one somewhere else and have more control over it?
  2. Facebook pages are like AOL keywords.
  3. Facebook is a completely closed system.
A personal home page?  See, this is where you lost me.  Facebook doesn't have personal home pages.  That was MySpace.  It was a different site.  Sure, it all fits under the broad "social networking" headline, but it's still a different site.  And nothing makes you sound more out of touch with what you're talking about than to confuse vastly different subjects on the matter.  (I'm reminded of a TV commercial I saw a few years ago where some old guy sitting on his porch said he didn't understand all this "Spacebook" and "MyFace" stuff.)

Yes, John, you can go make a webpage anywhere.  You can set up a blog anywhere.  You can even host your own services on your own server out of your house.  The internet is wonderful like that.  But Facebook isn't a service for a person to make a web page.  It is, quite simply, a channel of communication.  That's all, really.  It's a way for people to talk to each other and easily share information with each other, either directly (by posting something directly to someone) or passively (by posting something which others can see, or choose not to see, etc.).

The personal home page thing was where MySpace fell flat.  It all looked like crap.  And it focused on the wrong aspect of the service.  At first people wanted to put up their own pages, sure.  But that was because they thought that's all they could do.  Facebook took a different approach, and a radically successful one.  It's not about the nodes of the network, it's about the connections between those nodes.  A page, sitting out there on the internet by itself, is disconnected.  Sure, people can read it and write on it, but it's disconnected.  Facebook, as a tool, focused on the connections and facilitates the flow of information through those connections.

In short, it's not a personal web page.  (Yes, there are "pages" mostly in the sense of a company's Facebook profile, etc.)  Actually, and this should come as no surprise, I'm finding difficulty in articulating it.  Maybe that's a testament to how ubiquitous Facebook has become in our society.  Imagine trying to describe to somebody a concept that everybody already knows.  It's actually quite difficult.  But basically, Facebook isn't a blog or a homepage, it's just a tool for communication.  I can easily see what all of my friends are up to, leave them a message, strike up a conversation, return to an old conversation, share some piece of media, etc.  That's all, and that's all it needs.  The tool provides all of this, and at its core is the benefit that it's the same tool that everybody uses.  It's by no means perfect or immortal, but right now it's immensely useful.

Now, about the AOL keyword thing.  Honestly, I would have thought that you could spot the difference.  You've been using the internet for a long time now, John.  I dare say, longer than I have.  (Thanks for making me feel young and hip by the way, if only for a fleeting moment.)  Yes, we all remember AOL.  Those of us "with any chops online" (as you so condescendingly put it) all had a personal distaste for AOL.  Sure, I used it back in the v2.5 and v3.0 days.  It wasn't bad.  It was cute.  But it wasn't "the internet."

And, just like you, we all hated the whole "keyword" thing.  Any time the nightly news anchor would direct the audience to "go to keyword blahblahblah" we would all die a little inside.  But, you see John, the rest of us got over it.  You seem to have been so burned by the keyword phenomenon (which was a long time ago, John) that you're still looking to release steam about it.  To that end, you're just taking pot shots at the current big player, which is kind of childish.

The difference between keywords and Facebook pages is that the keywords were essentially meant to be a closed system within the AOL software.  Maybe some of them actually led to external non-AOL resources (also known as web pages), I don't remember.  But the system itself was a means of quickly navigating to some point within AOL's walled garden.  Facebook pages, on the other hand, are nothing more than URLs.  I do hope you know what a URL is.  One doesn't need to be a part of some walled garden.  One doesn't need a Facebook account at all.  It's, get this, a web page on the internet.

Sure, within Facebook there is a little search bar where one can quickly find another Facebook page without needing the URL.  That's called convenience, John.  But the option is still there for anybody, with any web browser, and any affiliation or lack thereof with Facebook, to enter a URL (manually or by clicking a link) and be taken to a "Facebook page."  That's the beauty of this here thing called the internet, John.

Speaking of the openness, what was that you said about Facebook being a closed system?  Marketing departments the world over have piles of cash that disagree with you, John.  I'm not going to go into a lot of details here (especially since I already wrote a post on the subject, which was already growing out of date by the time I finished writing it), but Facebook has capitalized on a huge source of revenue by explicitly making it very easy for an external site to integrate with Facebook services, and for a Facebook page to integrate with external resources.

Interoperability, John.  It's the future.  And it's happening right now.  It all goes back to that concept that Facebook is about the connections, not about the nodes.  The things that are interoperating, such as Facebook pages, non-Facebook pages, applications of all kinds all over the internet, etc. are just nodes.  Facebook works to provide connections between those nodes.  Sure, as a company it also makes it a point to track and monetize that flow of information.  You don't get to be worth twenty five billion dollars by giving everything away for free.  But the interoperability is by no means lacking.

In fact, you could even (and very easily) add a fairly small amount of code to your own personal site that would integrate it very well with Facebook.  Share the information you want to share, track the information you want to track, etc.  You don't need to "use Facebook" in the same way the average person does.  It has an API.  You can use your own site, and just integrate with Facebook's services.

This may not seem valuable to you, since you're already famous and people already listen to you.  But for people who are less famous there's a certain value behind a tool that can quickly and easily expose them to a community of five hundred million people, where word of mouth spreads faster than through any communication channel in human history.  (It's not unlike the Apple App Store in this sense.  Stuffy old developers love to complain about Apple's walled garden, while young entrepreneurial developers line up at the door for a service that has an audience of millions and handles distribution and billing/collections for only 30% of the cut.)

John, you sound old and out of touch.  Do you also refuse to use smart phones because you believe that a phone is just for phone calls and that's the way it should be?  For someone who has made a career out of knowing the computer industry and talking about where it's going, you seem to be a solid decade behind the times on this one.  You're a computer industry futurist living in the past.

No, Facebook isn't the end all answer to the internet.  It's a tool.  And it's a tool that has provided new things we didn't previously have or use nearly as commonly.  It has changed how people interact.  And even if it's already losing its popularity and already beginning its decline into the dark recesses of forgotten internet services, its impact is undeniable.  Honestly, I'm surprised you missed it.  That shot was heard 'round the world.

Now if you'll excuse me, I'm sure I have a lawn to get off of.