What the heck...

Chris Shaffer's Development Life

About the author

Author Name is someone.
E-mail me Send mail

Recent posts

Recent comments

Don't show

Authors

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2010

Ruby and Immutability

Just a quick note.  It occurred to me this morning that with how dynamic Ruby is (being able to add methods/properties to an instance of a class, etc), it is probably difficult to make an object immutable.

Not so - Ruby supports immutability, though it does it in a slightly different way (which is at a glance both better and worse than what I am used to in C#).  In Ruby, immutability is assigned at the instance level by calling the freeze method.

As I said, this seems both good and bad.  On the bad side, as a consumer of a potentially frozen object I have to either test each object (using the frozen? method) before attempting to change or risk throwing an exception.  On the good side, the freeze method is enforced by the run-time; In C# I can write a class meant to be immutable, but this really amounts to specifically designing the class not to have the capability to change rather than telling the compiler "I want this class to be immutable".

Anyway, just another interesting aspect of Ruby.  I'll have to write some code using freeze to get a better feel for it.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: Development | Ruby
Posted by clstopher on Monday, March 08, 2010 7:22 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Beginning Ruby

Well, I'm messing around with Ruby at home for the most part -- haven't really experimented much more with IronRuby at work.  I'm continuing to read the Rails book I have, though I think I will wait to start messing around with Rails until I have a better feel for Ruby itself.  Learning the language itself hasn't presented any real challenges, however I have a fair ways to go before I am writing idiomatic Ruby code.

To work on learning the language, I've decided to use my intermittent computer free time to go through www.rubyquiz.com.

To that end, I spent a good deal of time (more than I would have expected) working on the first quiz (implementing the "Solitaire Encryption" method).

I started out with a simple Encoder class with a single encode method, and a TestEncoder class that ran the encode method and verified the result using the example from the quiz.  As I started filling in the encode method, I started breaking things out into separate classes and added tests for each of those classes.  It felt a lot easier to do with Ruby than it has in the past in C# to do these things, though I can't really point at any single reason why that might be.

My final solution ended up with the following classes: Deck, Keystream, Encoder, Decoder.  Most of the time I spent coding up the solution went into the Deck class, which includes methods like shift_right, triple_cut, and count_cut.  Looking at the code now, I think it seems a little odd that I wrote each of those methods to return an array; I did that because it made the testing a little easier (I could instantiate a single deck and then have several asserts that all assumed the deck was starting out clean, instead of either instantiating a new deck before each assert or having each assert work on the deck dependent on the previous statements).  Once I had the methods implemented and testing correctly, I added a ! version that actually modified the deck.

Remaining now is to go through the other solutions that were submitted to the Ruby Quiz site to learn some of the ways I can improve my Ruby code.  Just glancing at one example showed me a potential key-saver -- there is an array indexer that takes two numbers or a range and returns a slice of the array.  I used the slice method a lot, and also spent a good bit of effort on the math required to get the numbers to pass to it; Statements like:


return cards.slice(0, sstart) + @cards.slice(sstart + 1, num) + [val] + @cards.slice(send + 1, @cards.length - send - 1)

Will both look better and be easier to work on if they looked more like:


return cards[0..sstart] + @cards[sstart + 1, num] + [val] + @cards[(send + 1)..-1] 

(I haven't tested that line, just quick replacement).  Not only do I get rid of good set of length, but using "..-1" makes a lot more sense than "@cards.length - send - 1".  It's a relatively trivial change, but worth making.

Somewhat related, but as part of this I also did some work on getting a dev environment set up on my laptop; I installed many of the things mentioned in a post on thoughtbots (found with a little googling).  I'm using zsh now (don't really know any of the differences between this and the default yet, but digging the prompt including the current git branch that the referenced config files gave me) and MacVim (started with just regular vim that came with OS X, but decided to try a different one when I saw that the default was compiled with -ruby...May go back to regular vim but compile it myself, we'll see what happens).

Also made a Rakefile for this project, with only one target (test).  I haven't spent any time learning the Rakefile syntax yet, but the little I have now (copied and pasted from the Ruby Koans project if I remember right) looks nice (Ruby syntax version of make?).

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: Development | Ruby
Posted by clstopher on Sunday, March 07, 2010 8:07 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Ruby (and Rails)

At CodeMash 2010, I went to several sessions on Ruby; I've decided to check it out a little more since returning.  I really like the Ruby I've seen, and after going through the Ruby Koans I think I'd like to try some more.  I'm also interested in Rails, as it seems like we've had several smaller projects come through here that might have been good candidates for it (though I have no experience, so my definition of good candidate may not be appropriate).

Since I'm working in a .Net shop, I'm curious about IronRuby on Rails.   Following the instructions here, only issue so far has been that you have to move your IronRuby executables to a root folder with no spaces (spaces kill irake with a message "Illegal characters in path", not being in the root caused a "Path too long" error).

I'll try to keep up here with details as I go.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by clstopher on Monday, February 08, 2010 3:08 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Designing to Interfaces

At CQL, we have biweekly developer meetings where all the developers get together and talk about anything we've found to help us do our work.  This includes tools, libraries, techniques, whatever.  A couple of weeks ago we started going over design patterns.  A few of us know about them and occasionally use them, but we have several developers that don't, which is something we would like to change.  So the first meeting we covered the Factory pattern and the Command pattern.  This past Friday we were going to continue with the patterns discussion by talking about Facade and Decorator, but while considering examples and what to talk about, I realized that Decorator especially relies on explicitly designing to Interfaces (Patterns in general do, but many of the other patterns can be more implicit about it via inheritence).  After discussing it with Chad, we decided it would probably be better to spend a meeting talking about Interfaces, hows and whys, before continuing with the design pattern meetings.

There are probably a few hundred articles on the net already about the importance of designing to Interfaces, but I want to gather my thoughts here so I can hopefully provide a good presentation on it in two weeks.

So first, what does designing to an Interface mean?  Fundamentally it means that when I write a piece of code that depends on other objects/methods, I don't directly reference those objects/methods, but instead reference the idea of those objects/methods.

Why would we want to do this?  Well, there are many reasons, but they all boil down to one real core reason, and that is coupling.  When you design to an Interface, you are making your code less tightly coupled to the objects/code that you are referencing.  The two primary benefits for this are code reuse and code extensibility.

Code reuse is enhanced because if I have written my code to depend on only the idea of the other objects/methods, then I can literally cut and paste my code from one project to another and not have to make any changes to that code at all (or even better, I could roll that code up into it's own assembly and just add a reference, but that is the same as cutting and pasting).  So any tests that I've written for my code provide additional value, as well as the confidence of knowing that it has been working in the first project for a while, so it will continue to work in the new project.  Additionally, if I add any additional functionality to the code when I bring it to the new project can easily be brought to the original project, giving us a two-way reusability path.

Code extensibility is offered because I can now switch out the implementation of the objects/methods that my code depends on without worrying about breaking my code.  So, for example, I can make my code work with any data backend I want (ie, SQL Server, XML File, Web Service, etc).

That sounds great! How do we do it?  Well, implementation depends on the language you are working with.  We are a Microsoft shop, doing all of our work in C# and primarily working with ASP.Net.  In this environment, we have essentially two methods of designing to Interfaces.  The first (and IMHO best for this environment) is to use interfaces (duh :) ).  The second is to use a base class (most likely abstract, though not necessarily).  The reason I say interfaces is the better choice for .Net is because you cannot have multiple inheritence, but you can have a class implement as many interfaces as you like.  Of course, there will be exceptions to this(aren't there always exceptions? :) ).

I've talked about all the good things that come from designing to interfaces, how about the bad things?  The only bad thing I can think of is in a way a good thing, and that is that you should be very careful about adding properties/methods to an interface.  The reason for this is that an interface is essentially a contract; You are saying "If you implement these properties/methods on your object, you can use my code."  If you change the interface in any way, you are altering a contract that may be used in many places, and will involve making changes to all of the classes that implement your interface as well as (possibly) requiring changes to the code that works with your interface.  So you should not haphazardly change an interface that is already being used.  Like I said, this can be a good thing as it can make you think a little more about it, and maybe to come up with a better way (for example, making a new interface that inherits from the old one, thereby allowing all the existing code to stay the same).

Another topic that I think should be covered is things not to do with an interface.  The first thing may seem obvious from the previous discussion, but make sure that you don't add unnecessary fields to an interface.  What are unnecessary fields?  Anything that your code does not directly reference is unnecessary.  As an example, consider CreatedDate/ModifiedDate/CreatedBy/ModifiedBy fields that are quite commonly found in a database.  These fields should very rarely show up in an interface, because you should not be using those fields in your code (aside from in the data persistence layer, which should be the only code that maintains those fields).  By adding those fields to the interface, you are requiring anybody who wants to use your code to implement them, even though your code is not using them.

Another thing to avoid doing with interfaces is checking the type of the passed in object; Avoid code like "if (PassedInUserInterface is AdministrativeUser)."  The reason is that if you later on want to create another interface that behaves like an AdministrativeUser, then you have to search out and update all of your if statements to be something like "if (PassedInUserInterface is AdministrativeUser || PassedInUserInterface is DomainAdministrativeUser)," or you are forcing the user of your code to follow inheritence patterns that they may not want (descending DomainAdministrativeUser from AdministrativeUser).  Seeing code like this (or considering writing code like this) should immediately make you think of instead adding a property to the interface (remember to think this through of course :) ) and taking advantage of polymorphism.  A better approach would be to add a property like "IsAdministrator", then the classes that implement your interface can set that as they like.  This improves the readability, extensibility, and testability of your code, so do it (and avoid testing the type of your object)!

Anyway, how about an example or two?  I'm writing this on my Mac, and as usual I am going to be too lazy to fire up Parallels and Visual Studio, so the following code comes with a Disclaimer: I have not attempted to compile this code, and it probably won't actually do so.  In fact, there's a possibility that if you take this code and run it, your hard drive will have Lorem Ipsum written over every sector and your monitor will turn purple.

Don't worry though, it's not very likely.

So my first example is one that I've used in discussions with others often, though I've never really written it all out and fully realized it.  It's a very common task that we have to write a login page for a project, and they almost always look exactly the same.  Username, Password, Login button, error message when the info is wrong, and maybe a forgotten password button.  In a typical project, this would all be written up and referencing the User(AppUser, Staff, ApplicationUser, whatever) class that corresponds to the project.  Or maybe it's a quick login page that references a single username/password stored in the web.config.  Whatever it is, it represents code that looks very similar every time you implement it.  The method that gets executed when the user clicks the "Login" button probably looks similar to this:

protected void Login()
{
	AppUser UserLoggingIn = AppUser.LoginUser(txtUsername.Text, txtPassword.Text) 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: Development | Patterns
Posted by clstopher on Saturday, February 16, 2008 11:16 AM
Permalink | Comments (0) | Post RSSRSS comment feed