Showing posts with label languages. Show all posts
Showing posts with label languages. Show all posts

Monday, June 20, 2011

How Powerful is Your Language?

Most mainstream programming languages today are basically the same.  I mean, they are all Turing complete, they can all access databases, the web, and so on.  What else is there?

Well, my comparative languages class in college said there were four factors for evaluating programming languages:
  1. Readability
  2. Writability
  3. Reliability
  4. Cost
I would add a 5th, which is maintainability.  The argument I'm going to attempt to make today is that Dynamic Languages, and Ruby in particular, score better in these factors than static languages, and therefore are more powerful languages.

The first thing you might think of is syntax, and there is certainly something to be said for that.  Clean syntax makes for enhanced readability and writability.  And the ability to create DSLs in your language is another major plus to readability and writability.  So right off the bat Ruby is off to a pretty good start.

But I think the argument actually goes deeper than that.  Consider the SOLID design principles:
  • SRP: Single Responsibility Principle
  • OCP: Open Closed Principle
  • LSP: Liskov Substitution Principle
  • ISP: Interface Segregation Principle
  • DIP: Dependency Inversion Principle
These are principles we use to describe good code.  That is, more readable code, more reliable code, more maintainable code, and less costly code.  And I believe that Ruby, as a language, has many of these principles built right in.  And that means that it scores higher on the comparative ladder, and therefore is a better, more powerful, language!

Lets start with SRP.  So Ruby has Modules, which are pretty great.  And I would argue that they are a helpful tool for SRP.  I've had some awesome conversations on this point, but I land on the side of saying that Modules and MixIns are totally useful for SRP.  But that's about as far as we go for language support for SRP, so lets move on!

OCP is a bit more interesting, though still straight forward.  Dynamic languages like Ruby allow you to open up any class from a distance and add new methods to them, or change the definitions of existing methods.   So you can change anything in the class without having to open up the actual class definition. That's some pretty serious built in OCP support.  Of course, to be fair, this isn't a feature you're likely to depend on when you're implementing a class you want to follow OCP...  Its more of a last resort really, but we'll find its very useful for mocking which we'll talk about later.

When talking about LSP Wikipedia has this to say: "Behavioral subtyping is a stronger notion than typical subtyping of functions defined in type theory."  This is a super-wonderful sentence for my purposes here!  LSP is all about the behavior of subclasses matching their parent classes, and the beauty of this is that dynamic languages are ALL about behavior, you tend not to get to hung up with "types".  So, you still have to be careful that your derived classes' behavior is consistent with that of their parent's, but since you're already thinking about behavior instead of types, you are off to a much better start.

Interface Segregation seems simple at first glance, dynamic languages don't have interfaces, end of story right?  Not quite, because while ISP is about interfaces, what's its saying is that your interfaces should be highly cohesive so that you cannot divide the methods of an interface into discrete sets based on who calls them.  This is because we don't want to be coupled to methods we don't care about.  But in a dynamic language, the caller just sends whatever "messages" it wants to the object it is calling, so by default our "interfaces" are as segregated as they could ever possibly be!  We have perfect, automatic ISP in dynamic languages.

Dependency Inversion is sort of the crowning jewel of built in principles in dynamic languages.  Most of the time in static languages our main reason for caring about Dependency Inversion is for unit testing.  We invert our dependencies so that we can mock them out in our tests.  This is outrageously annoying because it means we can never ever ever call a constructor.  So we are forced to either a) make all our dependencies stateless or b) wrap all our constructors with factories.  It also means we have to introduce interfaces to describe a huge number of our classes. In Ruby, we don't have to think about this.  At all.  We can stub out the calls to constructors and return our own mock versions.  It's so easy it's totally stunning the first time you do it.

So there you have it!  Dynamic languages are awesome, in part, because they have the SOLID design principles built in, which makes them score better on the comparative language scale.

Monday, May 24, 2010

Rails has no place at the office

This is a milestone post for me! My first ever purposefully incendiary title!

I should probably run with it and try to get everybody super offended, to the point where you have no idea what my point is because all you can see is red. I guess I'll have to leave that for a future milestone...

Because, yeah, I'm not really serious. Rails has a place at the office. And no, this isn't going to be one of those "Is Rails ready for the Enterprise?" posts. Rails is perfectly ready for use in the Enterprise, but that's the wrong question.  As usual, the right question is much more complicated.

To start with, let me point out that this conversation has nothing to do with Ruby vs. C#. It doesn't really have anything to do with Rails vs ASP.NET MVC either. Instead I'm going to be talking about Active Record vs. Data Mapper, and View-Models vs. no View-Models, and this general concept of "the straight and narrow" vs. explicit abstraction and control. These are design patterns which apply to any language and appear in many different frameworks.

Rob Conery recently wrote a blog post in which he said,
For a lot of .NET/Java devs this will look "messy" - you shouldn't elevate "data concerns" into your model. This argument makes good sense for a large, complex site - that you're building in C# or Java. Typically Ruby focuses on the straight, narrow path and with that comes a dramatic turn towards "doing what you need to do... and no more". This resonates with me...
The part about Ruby/Rails focusing on "the straight and narrow path" really struck a chord for me.  Ruby, being a dynamic language, is very much on the "straight and narrow."  It dispenses with all kinds of things found in strongly typed languages like private, internal, protected, interfaces, etc.  These are things that are usually considered very important in a strongly typed language, and practices like DDD, but Ruby doesn't really bother with them.  Ruby favors documentation and convention over strict control.

Rails has a similar story.  It uses the Active Record pattern for its data access, which requires a 1-1 correspondence with your database.  Further, the models don't even really exist!  They're built dynamically from the schema of the database tables.

If you compare ASP.NET MVC to Rails one of the differences you'll quickly discover is this concept of a "View-Model". ASP.NET peeps seem to like these, whereas I haven't found a Rails sample anywhere that uses these.  Both Active Record and this lack of a View-Model are accomplishing the same thing: removing abstraction in favor of directness and simplicity.

Now lets step back from this for a second and ask a question.  Who in there right mind would want to have to deal with things like class and method visibility and extra layers of abstraction, which more often than not appear to be just duplication?  No one!  No one would want to deal with these things!  It's extra work!  I _hate_ extra work!

So why do we do it?  Why does DDD make a big deal out of private constructors and Factories?  Why does Fowler recommend the Data Mapper pattern over Active Record?  Why do we create View-Models to separate our Views from our Models?  Why do we do all these things that seem to just make life more complicated?  Why don't we all take the straight and narrow path on all of our projects all of the time?

Certainly it's not as simple as the language we're using.  Just because you're writing in C# and Java doesn't mean you can't use Active Record.  And it doesn't mean you can't pass your Model straight to your View.  There is also nothing about C# or Java that forces you to use interfaces, or follow the Dependency Inversion Principle.  That said, there's also no reason why you couldn't use the Data Mapper pattern in Ruby, or create View-Models.  The language certainly HELPS with some of these issues, but it's not the real difference.  These are just patterns, and they apply equally well to any language.

The reason why we introduce this complexity and divert from the straight and narrow path in our technical approach is actually due primarily to non-technical reasons.  Here are some of the reasons I think lead us to adopt these "enterprise" patterns:

  • There are more than two or three developers on the project
  • You have more than 6 entities in the domain
  • The project has a timeline longer than 3 months
  • The developers aren't intimately familiar with the domain
  • The project is likely to grow in fits and starts
  • The team members are more likely to come and go

These are not technical issues but they have technical IMPLICATIONS!

The practices prescribed by DDD are a big deal if you're working with a large complicated domain with lots of potential for change.  If you're not, then you don't need DDD.  Fowler's enterprise patterns are a big deal for the same reasons.  If you know things are complicated, likely to change, and not possible for everyone on the team to grok completely, then you need to build abstraction into your code.  And you need to try to be as explicit as you possibly can about what the code does and how it works.  And you need to look for opportunities to prevent error and misunderstanding before it happens.  These things will allow you to keep things clean, organized, and ultimately make your project successful when you're faced with "enterprise" challenges.

This is obvious.  I'm sure you're sitting there (or standing) thinking, "duh!" or "when is this dude going to get to the point?" or "does this moron really think this is revolutionary?!"

My point is as simple as this.  Rails is awesome.  Simplicity is awesome.  But as I sit here in my ivory tower looking out over the landscape I see lots of quiet subtle backlash from people against the "enterprise-y" patterns in favor of the simplicity of Rails.  This makes a lot of sense to me because, as we pointed out, who would WANT to deal with the complexity of enterprise problems and patterns?  But it is easy to be tempted by the appeal of simple solutions to simple projects.  And certainly we should always strive to find the simplest solution that could possibly work.  But we can not close our eyes to the complexities of the problem or the environment in which we are solving the problem.  And we cannot allow ourselves to be boiled alive either.

So by all means, choose the right tool for the right job, but make sure you understand the job as well as you understand the tool.

Monday, August 17, 2009

Another C# Fluke

Here's some code:
var l = new List<int?>();
l.Add( null );
( ( System.Collections.IList)l ).Add( null );

You would expect those two Adds to be equivalent and that after executing them l.Count would be equal to 2.

Instead you get an ArgumentException on the second Add. Turns out System.Collections.Generic.List implements both Add(...) and System.Collections.IList.Add(...) and the interface specific one does some input validation not done by the other Add. This validation doesn't understand Nullable types, so you get an exception.

I guess its a probably a bug, due to the fact that Nullable<> behaves kind of strangely through reflection.

Wednesday, July 29, 2009

A C# Language Quiz

I was writing some code today when I suddenly realized that I didn't how a certain very fundamental part of the C# language would behave.

Here's an example:
using System;

namespace TestNullCastToObject
{
class Program
{
static void Main( string[] args )
{
Test t = null;
object o = t;
if ( o is Test )
Console.WriteLine( "a Null Test is a Test" );
else
Console.WriteLine( "a Null Test is _NOT_ a Test" );

Console.ReadLine();
}
}

class Test
{
public int Id { get; set; }
}
}


If you compile and run that sample what do you think the output will be?

No really, think about it.

Ok, I'll tell you what I thought the output would be. I thought the output would be "a Null Test is a Test".

Ok, now I'm going to tell you what the output is.

"a Null Test is _NOT_ a Test"


Does that surprise you as much as it did me? I think I'm actually happy that it behaves this way, but I'm still surprised.

Friday, July 25, 2008

Static Languages Don’t Trust You

Some time ago I was thinking about Interfaces and class inheritance in C# and how hard it can sometimes be to get what you want.

For example, in WPF there are many controls which inherit from Selector: ComboBox, ListBox, ListView, and TabControl. Selector includes SelectedItem and SelectedValue properties as well as a SelectionChanged event.

One notable control missing from the list of Selectors is the TreeView. This control is an ItemsControl but is not a Selector. However, it still has SelectedItem and SelectedValue properties.

The reason why TreeView is not a Selector is that its items don’t have indexes (since they’re hierarchical). Selector includes a SelectedIndex property which wouldn’t make any sense on a TreeView. TreeView also provides a SelectedItemChanged event instead of a SelectionChanged event which includes more information about the change.

Clearly, it makes sense for TreeView not to be a Selector, even though it does have many similar properties. The problem is that there is no common class or interface that TreeView and ListBox (for example) both implement. This means you can’t write common code to accept either a TreeView or a ListBox and get the SelectedValue out of it.

You might need to do this if you were dynamically displaying controls, or creating any kind of framework to work with controls. To accomplish this, you now have to create your own interfaces that describe what you need (SelectedValue, ValueChanged) and then create wrappers for each of the built in controls that implement your interface. Or, you create one big class that knows how to talk to all the different types of controls. I think the first approach is the better one though as it’s easier to maintain and enhance.

This all applies if you’re writing in a static language. If you're writing in a dynamic language, you could just call the SelectedValue property because you know it’s there, and everything would work at run time.

This is just one example of the kinds of problems that are so easy to run into in a statically typed language. To solve these issues, you have to create a lot of boilerplate redundant code that serves no useful purpose. It only increases the size and mental complexity of your code base.

This led me to what I thought was an interesting realization about the difference between statically typed languages and dynamically typed languages.

Static languages don’t trust you. But Dynamic languages do.

In a static language you have to prove to the compiler that the calls you’re making make sense. In a dynamic language, everyone just trusts you to do it right.

But anyone who has ever written any serious code knows that they really can’t be trusted. I mean, I’m going to make mistakes sometimes. And that’s where unit testing comes in.

In a dynamic language the LANGUAGE trusts you completely. Your unit tests on the other hand require you to be correct. The exciting thing here is that your unit tests not only test that the coding details are correct, they also test that your meaning is correct. That makes them much more useful than the compiler alone.

And if we’re going to be writing unit tests in static languages anyway, why be forced to jump through so many hoops convincing the compiler we know what we’re doing? Do we really need to work in a environment that limits our expressive ability because it doesn’t trust us?

I think the idea of using tools (and languages) that trust me (at the same time as they're helping me) and then building my OWN validation/verification specifically for my software is pretty interesting.