Sunday, April 27, 2008

Polling for your Opinon

I figured I'd try a new type of blog here, one where I try to solicit the opinion of my readers (all 6 of you, and you're very much appreciated). I'm going to attempt to start a debate here, and I'm going to ask readers to stay strongly opinionated and objective.

So here's my topic of debate: Static-Typed languages versus Dynamic-Typed languages. I'm going to place Groovy, Python and Ruby at the forefront of the discussion for Dynamic-Typed Languages. I'm placing Scala, C++ and OCaml at the forefront of the dicussion for Static-Typed languages. I'm refraining from adding Java because although it is statically typed, there's far to much class-casting for my tastes to call it a "well-done" static languages (although annotations have really helped that problem!). I'm ignore C for the same reason. I'm ignoring C# because I don't know it, and I fear it may suffer from similar problems to Java to count as a real static language.

Here's some points of contension:

  • Statically-typed languages will always be better than dynamically typed languages because you can ensure more compile-time safety.

  • Content Assistance is one of the "power triad" features of an IDE (those being Debugging, Searching and Content Assistance). As such, static languages will always be better to develop in, as they have much better support for accurate content assistance

  • Dynamic languages are much better for getting things done quickly, using less code.

  • Static languages are made by more intelligent people because their compilers have to be more complex than dynamic languages

  • Dynamic languages are always slower than Static languages



Anyway, feel free to argue one or many points. I'd like to see what all your opinions are! I tried to make these statements strongly on one side or the other, but I can also make them insulting if it helps discussion :)

If you'd like to include sample code, please use the following HTML: <div class="sourceCode"><pre class="prettyprint">SOURCE CODE HERE <pre><div>

Tuesday, April 22, 2008

Playing with Scala Closures/Scope

Today I spent some time trying to play with scala closures and for-comprehensions. For-comprehensions are still a bit greek to me (although the gap in understand is rapidly disolving), but I'm getting a good feel for closures.

Here's a sample Scala closure:


def myClosure = {
//Argument Specification (optional)
x: Int =>

//Operations
x+5;
1 until x //Last statement's result is auto-magikly returned
};

I've commented the important parts of a closure. The beginning is the argument to the closure (in this case, a single integer labeled "x" throughout the closure. The => follows the arugment before executable statements of code. Closures do not need arguments, as they have access to all variables within their defined scope. Here's an example of plain-old use of a closure:


object MyApplication {
def main(args : Array[String]) = {
//This is actually a closure that has access to the "args" parameters because it's defined in the scope of the method definition.
}
}


The interesting thing here is that you don't need {} to define functions in scala. Example:

object MathHelper {
def square(x : Int) = x * x;
}


Interesting asside. The other neat thing about closures is that they're also OBJECTS so you can make calls on them. Here's a silly example where I'm defining a function that calls a closure and performs other processing


def methodTest(a:Int, b: Int) = { x: Int =>
x+x
}.apply(a)+b


Because Closures (really functions) are objects, you can do some nifty tricks with them, such as composition [ f(g(x)) ], programatic execution [ functionRef.apply(args) ], and other DSLy tricks Scala has come up with.


Another thing I really love about Scala is that the scoping rules make sense. Inner scopes can see all variables in an outer scope, and you can nest functions as deeply as desired.

def function1(x : Int) = {
def function2 = {
x
}
function2()
}

Console.println(function1(5)) // Prints 5


As you can see, since function 2 is defined with the scope of function1, it has access to function1's arguments. This also holds true for class constructors:


class MyFunObject(y: Int) {
def function1(x : Int) = {
def function2 = {
x*y
}
function2()
}
}

object Test extends Applicaiton {
var obj = new MyFunObject(6);
Console.println(obj.function1(5)) // Prints 30
}


Now the test prints 30.

So, you can really see how scoping just starts to feel more natural in scala. You no longer fight the "static" vs. "instance" battle, as Scala does not allow statics (besides "objects", which have the same scope-feel to them).

Not only is this all amazing, but it's TYPE-SAFE. Scala determines types for closures and spits compiler errors if you don't specify a type and it cannot deduce the type correctly (or you specify a wrong type). Now THAT's power!

Thursday, April 17, 2008

Inversion of Scoped Objects

In C++ it was common to use paradigms known as RRID (Resource Release is Destruction) or RAII (Resource Allocation is Initialization). The basic premise of these are you want to be guaranteed a section of code is execute upon exiting or entering a block respectively.

They usually look like the following:


template<typename T>
class scopedLock {
T& m_lock;
public:
ScopedLock(T& lock) : m_lock(lock) { lock.acquire(); }
~ScopedLock() { m_lock.release(); }
};

//Later
void MyClass::doSomethingSyncrhonized() {
ScopedLock scopeLock(mutex);

//Do syncrhonized code
}



You're guaraneteed that when doSomethingSynchronized returns, the ScopedLock destructor is called, therefore releasing the lock. This is regardless of how you leave the scope.

Spring has done an "inversion" of this principle for making code simpler. Let's look at JdbcTemplate objects. I want to open a connection, perform some query, map the results into an object and return a list of that object ensuring my connection is closed at the end. Here's the code:



List<MyStuff> list = jdbcTemplate.query(
"select stuff with parameters ? and ?",
new Object[]{param1, param2},
new RowMapper() {
Object mapRow(ResultSet rs) {
return new MyStuff(rs.getString("Important"), rs.getString("Stuff"));
}
});



If you notice, the pattern is inverted. I never specify anything about the connection object. The jdbcTemplate takes care of that for me. I place all my code inside the anonymous inner class that is an instance of RowMapper (Think Anonymous Inner Class ~= Closure). No where in the "closure" am I catching exception OR manipulating the connection. JdbcTemplate is ensuring that code happens before and after that scope, similarly to how C++ ScopedObjects work, but with a complete inversion in thought.

Scala tops Java by introducing real first-class functions and amazing abilites. Let's look at the Future class in Scala (pulled from Scala-By-Example):


def future[A](p: => A): Unit => A = {
val result = new SyncVar[A]
fork { result.set(p) }
(() => result.get)
}


If you notice, a "future" creates a synchronized variable store (like an atomic variable) called result. Future then forks and executes the passed in function in the fork (syntax fork { stuffToDo }). Much more elegant way of performing things before and after a method call. Scala can also pool threads as the client code isn't specifically starting/stopping threads at this point.


Addendum


As I was just re-reading the Scala section, I realize how lame my conclusions are. I plan to make some really good sample code when I got some more time. Unfortunately when I was writing the entry, the baby woke up. Anyway, the thing I was really trying to point out is that the Inversion of Scoped Objects creates the idea of "New Language Features." The "fork" command could actually just be a static method that takes in a closure and executes it on a separate thread. Anyone with some Scala/Java knowledge could write this code and make sure it calls the closure in the middle. I read a Ted Neward post about using Scala to create a "safe_execution" language feature in a similar manner. This function would merely call a closure within a try catch and log exceptions. This can be really powerful, especially in environments where you don't have control over all the code being executed (Eclipse Plugins/RCP is a good example where a "safe_logging_execute" would be helpful). Anyway, I may go in and clean up the scala bit to be more coherent when I get back from Chicago.

Tuesday, April 15, 2008

Tribute

So... I think it's been long enough since my dad passed away for me to try to collect my thoughts and record some things I'd rather not loose. My dad was a really great man. I wanted to write about the things about my dad I most admire and hope I can live my life in the same manner.


  • Working Hard and Serving Others


    My dad was a really hard worker. No matter what he was doing, he worked as hard as he could and tried to do the best job possible. I remember dad had a whole lot of "projects" around the house. Things he was working one that he never finished. Part of that I think was the perfectionist in him, part of it was that he was so busy helping everyone else get their stuff done. I learned from my dad that when you do something for someone else you make sure to do it the best you're able.

  • Friendliness


    My dad would talk to anyone around. He would try to make people smile. Even when he was in so much pain from his cancer that he could barely walk, he still tried to cheer up the people coming to visit him. I remember when an middle-eastern man moved into our town and opened a gas station. York County PA is not well known for tolerance or treating outsiders well... Anyway, my dad started talking to this man when he would get gas. My dad mentioned to me how he was disappointed with how people were treating him. Eventually, dad found out that the gas station needed some painting and wallpapering done. Dad decided to help him out. When I'm at grocery stores/malls/etc I tend to be "busy" and ignore the people around me. My dad noticed people, sometimes to my chagrin (especially during high school). I hope someday to be comfortable enough to be able to see the people around me and help them out like my dad did.

  • The man behind the camera


    I ALWAYS knew my dad cared about me and was proud of my acheivements. I also was aware of when I disappointed him. I feel bad for friends who have unsupportive or non-existent fathers. My dad's faith in my helped me do things I never thought I'd be able to. It was like a safety-net. No matter what I knew dad cared, and that he'd encourage me to try something else. Dad came to EVERY event I (or my siblings) were ever in, usually with a camera. After his death, we were trying to find video clips of dad from all the myriads of home movies he took. It was really hard because dad was almost always behind the camera. If I had something important going on in my life, I knew my dad would be there. That's something I always want to give me children.



I really really want to write a lot more, but I'm going to try to limit myself to an hour of blogging tonight (more than I've done in any other two-week period). Hope you all enjoy.

Scala + Annotations

So, in my private effort to create a Scala Web framework that doesn't look like Rails... I started taking a closer look at Scala-Java interaction. Specifically I wanted to know if I can use JPA for persistence in Scala. I figure hibernate and/or JPA should be more familiar to users and I wouldn't have to write anything to wire it together. Anyway, I was impressed when I found that this is all that's required to map a Scala class with JPA:


@Entity
class MyScalaClass {

@Id
@Column{ val name="O_ID" }
var id: Long = -1
var name: String = _
}


Anyway, I hope to have more extensive Scala coverage along with any slick ways of handling things I can think of. One thing I really love about Scala is that it decided to "make the compiler your batman" again (Anyone who knows that reference [hint: C++ developers should] wins a prize). Since Scala is type safe AND infers a type, I can not only implicitly do things, I can make some good compile-time guarantees. Hopefully this combined with Java-bytecode interoperability will make for a great platform with which to build a (non-railsy) Web-Stack.

Friday, April 4, 2008

Eclipse Plugin Trick

I just tried out this eclipse trick on my machine at home. The trick basically serves the following needs:

1) Eclipse is installed as a "root" user and you need to install new plugins as yourself
2) You're using multiple versions of eclipse (for testing) and you want to "share" plugins across versions (i.e. the plugin is written for 3.1 and you're testing through 3.4 milestones).
3) You're anal-retentive and need to organize EVERYTHING!


Basically, when you're looking for updates and installing them, the LAST screen before eclipse actually downloads code (title is: Installation), you can highlight each feature and tell it what location to install into. Just select a feature, right click and set a location. You can later enable/disable this locations at will. They can also be used in OTHER eclipse installs (perfect for testing across multiple eclipse versions).

Thursday, April 3, 2008

HDMI Price Gouging!

I just jumped on the HDTV bandwagon, went to best buy and picked up my upconverting DVD-player. The craziest thing was, the DVD player (not the cheapest one on the shelf) was CHEAPER than the cheapest HDMI cable (3 ft. for $70). WTF!!!! (check this link) The other crazy thing was audio rca cables were $40 cheapest!

I remember working the Sound scene. There were differing quality of cables for differing lengths of run. For the longer runs, you wanted a higher quality cable (possibly with gold plating). Yes... Gold does conduct electricity better (at least for carrying signals). However, you still have copper being the primary conductor of the cable. The real issue is signal degradation over lengthy runs. However, I'm looking at the 3-6 ft. gap between my DVD player and my HDTV. I've run cables hundreds of feet and not had to spend $70 for connectors + 3ft.

Anyway, to all the potentially unaware... SAVE YOUR MONEY. The difference between a $60 cable and $10 cable isn't such that the human ear can tell the difference (at least for *most* humans, including professional trained). I ended up going somewhere else to get my cables. Best Buy, once again you've shown me you're no longer the best buy.

Scala vs. Groovy

This past evening, I had a quiet moment or two (baby was sleeping and Sarah had a movie that just didn't appeal to me) to attempt to code something in Scala. What I was attempting to do was develop a mathematical/physics modeling library that would allow you to instantiate a "length" parameter, divide by a "time" parameter and get back a "speed" parameter. I wanted something type-safe, and robust. I was essentially trying to re-invent the sample in the beginning of the "Template Meta-Programming" book.

Here's what I learned about Scala (vs. my experience with Groovy).
  • Scott Davis said this about groovy, "When I'm not sure what to do, I just close my eyes and start writing Java." I'd have to say for Scala, "When I'm not sure what to do, I just close my eyes and starting thinking about what would happen if ML and Java had a bastard love-child."
  • Groovy appears to be a bunch of crazy features on top of Java (some even appear conflicting). Scala appears to be a well-defined cohesive set of features (for the most part).
  • Both have really neat closure semantics and the ability for terse-powerful syntax
  • Groovy has great support for IntelliJ and Ant, with moderate-ok support for Maven/Eclipse. Scala (2.7.0) has a pretty good eclipse plugin and great maven support. (It also supports ant)


I'd like to take some time here and just go over a few neat features of Scala. I'm going to call these the two trinities of Scala. The first trinity being def, var and val.
  • def => is the keyword you use when defining a method.
  • var => is the keyword you use when defining a mutable (non-final) local variable.
  • val => is the keyword you use when defining a const-ish (final) local variable.
The neat thing about these three is that you can use them almost anywhere. If I define a val in a class scope, you can access it as a public member of that class. If I define it in a closure, it's a local variable in the closure. Similarly with var.

The next trinity is Class, Object and Trait. (You could really add closures/functions to this, but I'm thinking from a Java perspective).
  • class => Defines a class. Think how Java defines classes. Only, there are NO statics.
  • object => Defines a named instance. The neat thing here is an object is global (singleton), named (i.e. can use methods/members like statics in Java), and can extend other classes! You can do pretty much anything you do in a class definition, only it's a singleton. This is Scala's answer to statics, and it's really really neat.
  • traits => This is like a Java Interface, but with 100% more ability to add implementation. This allows Scala to have a form of multiple inheritance. Scala disambiguates deadly diamond problems through a technique known as class linearization (also used in python). I haven't played much with traits yet, but probably will when I figure out how to start using these features.


Sometime in the future I may post some sample code with scala vs. groovy to do similar things. I'd really like to figure out a way to use both of these languages in tandem, as they both have some amazing features. I tend to prefer scala because of its type-safety, but there's something to be said for Groovy's Meta-Class programming.

Tuesday, April 1, 2008

My Latest Toy -> Configuring Shorewall + Squid

So, I spent the evening making sure squid was working correctly. I haven't fully verified squid-guard, so I'll just go over the details of how to configure squid.


Setting up Network Devices


First of all, make sure the box HAS two network devices. My setup was strange in that I was using eth0 for my internal network and eth1 for my external network. Basically I set up eth1 for automatically detecting IP (from my cable-provider) and eth0 to be at a set location (192.168.0.1). After this, I installed shorewall. There's a nifty FAQ here that explains how to set up shorewall for a gateway (if you don't mind weeding through all the other stuff in the faq)


Configuring Squid for Shorewall


Mostly I followed this tutorial. The only hang-up I had was that I forgot when defining "my_network" that a mask is a MASK, not a range. Therefore i wanted 192.168.2.0/255.255.255.0 not 192.168.2.0/255.255.255.255.

Conclusions


I'm really wishing I had used Ubuntu Server edition instead of being lazy and re-using the same disc I installed on my home PC. However, getting this stuff set up is not that hard, it's just a matter of finding the right docs to weed out the unecessary info. These programs are VERY powerful and I'm only interested in a portion of their power.

The sad part is, a coworker gave me an IP tables book that I haven't gotten through yet. I didn't have the patience to "really figure it out", so I decided to get things done. The last task is to get SquidGuard set up and blocking spam/pron. I'll try to have more fun coding excercises in here later too. I was about to make another Ivy rant (freaking Ivy), but that's already been done.