Tuesday, April 7, 2009

How to Avoid Cell Phone Spam

Recently I've noticed a definite upswing in the number of unsolicited commercial phone calls I get on my cell phone. What to do?

I found a simple may to minimize (or at least reduce) the annoyance. My phone uses mp3 files for custom ringtones, and is able to receive such files via email. So I

  • edited a silent and extremely short mp3 file

  • sent it to my phone

  • saved the annoying caller as a contact, and

  • set the custom ringtone for that contact to the silent file



It requires a little overhead in defining the contact, but now it means that I am no longer bothered by that caller again.

Thursday, March 26, 2009

Constant Hashes w/defaults in Ruby

Hi there. I'm back after a long hiatus. Since my last post, I've moved across the country from Buffalo, NY to Berkeley, CA, had 2 jobs, and become a father. So I ask your forgiveness for the long period between posts.

On to some code. I like to use Constants in Ruby whenever feasible. It's a logical and readable-to-the-next-coder way to store information in a way that indicates it should not change. It also gets some compile-time optimization for speed, and takes up less memory as a datum shared across the various instances of a class.

I'm particularly fond of constant Hashes for small lookup tables. Let's imagine some generic Rails controller with this code snippet:

BANAL_MESSAGE_FOR = {
:edit => 'You are editing.',
:show => 'You are viewing a single instance.'
}


Hashes in Ruby have a handy method called default= that sets what the default looked-up value should be when the key for the lookup is not found in the Hash. (You can think of the default default as nil, if that makes any sense.) However, default= returns the default value, rather than the new Hash. So this gets problematic:


BANAL_MESSAGE_FOR = {
:edit => 'You are editing.',
:show => 'You are viewing a single instance.'
}.default = "I don't know what you're doing".


The example above will break, as BANAL_MESSAGE_FOR is no longer a Hash at all.


BANAL_MESSAGE_FOR = {
:edit => 'You are editing.',
:show => 'You are viewing a single instance.'
}
BANAL_MESSAGE_FOR.default = "I don't know what you're doing".


The example above will lead to compile-time warnings about modifying a Constant.

What alternatives exists for this issue?



I've grown fond of the following approach:

BANAL_MESSAGE_FOR = lambda do
message_for = {
:edit => 'You are editing.',
:show => 'You are viewing a single instance.'
}
message_for.default = "I don't know what you're doing".
message_for
end.call


This allows us to define the particular cases with explicit Hash pairs, set a default value, and keep everything in Constant world. Depending on the particulars, we could instead go with either a class variable (@@banal_message_for) or a class method.

I still like constant-from-a-lambda, though - even despite the somewhat off-putting complexity of the lambda/call syntax. It makes it clear that we're dealing with constant data, and the complexity from the call syntax seems less egregious to me than having an additional method whose only purpose is to be called once at app start.

What do you think?

Tuesday, September 30, 2008

Hidden Functions

Let's talk about hidden functions. What do I mean by that? When I refer to a hidden function, I mean one that exists in some non-public context, and is not directly accessible from the outside. There are several ways one can realize this goal, and we'll talk our usual stroll through some appropriate languages and how they approach his problem.

Scheme



Let's start with Scheme. Assuming the follow content in a file called hidden.scm:

(define (obvious)
(define (hidden) `hidden)
(hidden))


We can then try it out using guile -l hidden.scm:


guile> (hidden)

Backtrace:
In standard input:
1: 0* (hidden)

standard input:1:1: In expression (hidden):
standard input:1:1: Unbound variable: hidden
ABORT: (unbound-variable)


We see that (hidden) is not directly accessible from the outside, however...


guile> (obvious)
hidden


It is still defined and reachable through the intermediary function (obvious). This is great for all the expected black box reasons:


  1. Users/developers can be presented with a consistent interface

  2. Purpose can be separated from implementation details, which means that

  3. Testing is easier to do, which means that

  4. Refactoring is easier to do, whether literally just an improvement to internal clarity and readability, or wherein the inputs and outputs remain the same expressions, but other improvements occur, such as faster speed of execution, reduced memory footprint, or both



Perl



I've written about Perl a bit more than I expected to lately. Let's continue with that, and see an example in Perl.


#!/usr/bin/env perl
# hidden.pl

use constant HIDDEN => 'hidden';

sub obvious {
sub hidden { HIDDEN }
hidden();
}

sub obvious2 {
my $hidden = sub { HIDDEN };
$hidden->();
}

print obvious() . "\n";
print obvious2() . "\n";
print hidden() . " is really not that hidden\n";
print $hidden->() . "\n";


Executing this program at the command line with perl hidden.pl produces the following output:


hidden
hidden
hidden is really not that hidden
Undefined subroutine &main:: called at hidden.pl line 19.


I like constants for values that don't change and are reused - call me crazy. The examples obvious() and obvious2() are very similar. The only difference is that the function which we wish to hide is declared either as a traditional subroutine or as a subroutine reference. Why the distinction?

The reason is revealed when we make a direct call to hidden(). Perl does not scope the declaration of hidden() within obvious() as Scheme does. hidden() is accessible from outside obvious() where it was declared. However, attempting to call $hidden->() at the top level fails, because Perl does scope $hidden inside obvious2() where it was declared.

I'm not a real Perl guru. I get by in the language, but I'm sure someone who frequents Perl Monks or the like could explore this idea further.

Ruby



Despite Ruby's comprehensive support for programming in the functional paradigm, it is commonly thought of as an object oriented language, not without cause. Many people are most familiar with the notion of hiding executable code through the process of private or protected access control common in OO languages.

I won't give an example of traditional OO access control in Ruby here. Rather, I'll explore ideas more akin to the preceding Scheme and Perl examples that use nested function declarations. Some of this code is intentionally broken and/or strange-looking.


class Owner

HIDDEN_PROC = lambda { %q[hidden value from Proc] }

def obvious
def hidden; %q[hidden value]; end
hidden.gsub(%r[hidden], %q[obvious])
end
def obvious2; hidden + %q[ from obvious2]; end
def obvious3; HIDDEN_PROC.call; end

end

if (__FILE__ == $0)
o = Owner.new
puts o.obvious
puts o.obvious2
puts o.obvious3
begin
puts o.obvious.hidden
rescue
puts %q[Could not access o.obvious.hidden]
end
begin
puts o::HIDDEN_PROC.call
rescue
puts %q[Could not access o::HIDDEN_PROC.call]
end
puts o.hidden + %q[ - not really all that hidden]
end


Let's take it for a spin with ruby hidden.rb. (Note that the boolean expression (__FILE__ == $0) is only truthy when the file is executed directly like this, and not when the file is required in the manner of a library file.)


obvious value
hidden value from obvious2
hidden value from Proc
Could not access o.obvious.hidden
Could not access o::HIDDEN_PROC.call
hidden value - not really all that hidden


hidden() is callable from within obvious(), and we can even do a regular expression substitution on its value. Fine and dandy. Its hidden status is called into question by it being accessible from within obvious2(), even though it was not declared there. Let's ponder why that is for a moment.

If a function in Ruby were genuinely hideable, as in Scheme, it would not be so available. However, one must keep in mind that there are technically no functions in Ruby at all: they're methods, and that distinction makes all the difference. A method is a function that is attached to an object (or class), and what would it imply if a method were not accessible by its owning object? It wouldn't be much of a method, and that's where Ruby's OO nature wins out.

In order to restrict access to some executable code within an object, we can either comply with OO practice and use traditional access control, or do something akin to obvious3(), in which we define a callable HIDDEN_PROC that is not publicly accessible, but is callable from within obvious3() (for example). If we wanted even more separation, we could define HIDDEN_PROC as a lexical variable within the obvious3() method, rather than as a class Constant. Such an approach would be very similar to the Perl example's definition of $hidden.

Erlang



On to Erlang, which has some interesting features regarding exporting of functions. Here's our file hidden.erl.


-module(hidden).
-author("Kevin C. Baird").
-purpose("Demonstrate hidden functions in Erlang").
-export([obvious/0]).

obvious() -> hidden().
hidden() -> 'value from hidden'.


Here's our erl session that uses it:


$ erl
Erlang (BEAM) emulator version 5.5.5 [source] [async-threads:0] [hipe] [kernel-poll:false]

Eshell V5.5.5 (abort with ^G)
1> c(hidden).
{ok,hidden}
2> hidden:obvious().
'value from hidden'
3> hidden:hidden().

=ERROR REPORT==== 30-Sep-2008::10:05:09 ===
Error in process <0.31.0> with exit value: {undef,[{hidden,hidden,[]},{erl_eval,do_apply,5},{shell,exprs,6},{shell,eval_loop,3}]}

** exited: {undef,[{hidden,hidden,[]},
{erl_eval,do_apply,5},
{shell,exprs,6},
{shell,eval_loop,3}]} **


Because only obvious is exported, it is the only function publicly available. We could have used as complex a basis as we wanted to determine its eventual value, all of which could be safely hidden within our hidden module. That's what encapsulation's all about.

Haskell



Another purely functional language I've discussed is Haskell. In fact, its strongest advocates would probably deny Erlang the label purely functional, as it does not segregate side effects as fully as Haskell does.

In any case, we can have a quite small Hidden.hs file:


-- Hidden.hs
-- Kevin C. Baird
-- Demonstrate hidden functions in Haskell

obvious = hidden
where hidden = "value from hidden"


That executes as you'd expect by this point, as seen in hugs:


$ hugs Hidden.hs
__ __ __ __ ____ ___ _________________________________________
|| || || || || || ||__ Hugs 98: Based on the Haskell 98 standard
||___|| ||__|| ||__|| __|| Copyright (c) 1994-2005
||---|| ___|| World Wide Web: http://haskell.org/hugs
|| || Bugs: http://hackage.haskell.org/trac/hugs
|| || Version: September 2006 _________________________________________

Haskell 98 mode: Restart with command line option -98 to enable extensions

Type :? for help
Main> obvious
"value from hidden"
Main> hidden
ERROR - Undefined variable "hidden"

Wednesday, September 17, 2008

Boston, San Francisco and SDD

My colleague Jim Lindley and I will be going to Boston for a few days for our employer. We do TDD/BDD with RSpec and Rails currently, and the folks in the Boston office are at some point along a similar continuum. We'll show them what we do, they'll show us what they do, we'll learn and grow and laugh and share and love, etc. Then I'm off to San Francisco for some interviews related to my planned relocation out there.

Yesterday, I came across a blog post by Paul Barry about SDD with Rails. The two upcoming trips already had me thinking about my workflow, and Jim and I had been talking about trying move another abstraction step up from our current speccing practice, and SDD seems like a good match for our next project. It's a rewrite of an existing app that is currently in a different language - our job would be to match it feature-for-feature and also to make some necessary changes and additions.

SDD seems like a good way to keep the QA folks who already know how the app should work more involved in the the speccing process in a way that actually has impact. That's the beauty of having the human-readable descriptions be executable.

Paul also links to Bryan Helmkamp's talk on SDD at GoRuCo2008, which is very good. I would encourage anyone to read Paul's post and watch Bryan's talk.

Thursday, August 28, 2008

Celebrity sighting(?)

My last post was about Perl and my experiences working with it and its fans. I'm not a huge fan of the language - I'm planning another post that details what I like and don't like about it. I think it has few characteristics that are fundamentally flawed, for example.

However, I'm pretty sure I saw Larry Wall in the Detroit airport a few weekends ago when I was flying to Seattle for a friend's wedding. The excitement that I heard in my own voice when I pointed him out to my wife Jenn made me realize that I think Perl's good points have been a positive influence on programming culture.

So thanks, Larry.

Monday, August 4, 2008

Perl and is_valid_aref()

This post is about Perl, the politics of interacting with fellow developers, and Duck Typing (although we didn't really know it at the time). It's also fairly stream-of-consciousness.

I used to work at a Perl shop, and in a big rewrite we did, we made heavy use of array references. A dynamic lanugage like Perl (or Ruby, or whatever) will encourage conscientious developers to have some tests and/or error checking, so we often wanted to ensure that our input parameters to some specific subroutines that expected array refs were actually valid arefs. How should one do this checking in Perl?

Here's one obvious approach.


sub is_valid_aref_mere_mortals {
ref shift eq 'ARRAY';
}


Here we have a straightforward subroutine. We use Perl's shift to pull the first parameter off the stack, get the type to which it refers with ref, and check with the stringy equality operator whether or not the referred type is 'ARRAY'.

This wasn't good enough for an ex co-worker of mine, who fancied himself a Perl Wizard (with some justification, in fairness to him).

Some idiot could bless a non-ARRAY behaving scalar as a ref to an ARRAY. My solution in that case is to berate the offender in public for having done something so horrible. Such a blessing is a direct violation of the duck typing idea that you don't have a datum pretend to be a specific type (however your language defines type) unless it can implement all the pertinent behavior expected of that type in that context. With great power comes great responsibility.

We also had no instances of such blessing in our app. All of our args were all either just simple arefs, or errors (usually an undef value). So in practice, I think a simple ref check would work fine. However, if you're concerned about the blessed as aref issue, the solution below has some advantages.


sub is_valid_aref {
my( $arg ) = @_;
$arg and eval { @{ $arg } or 1 };
}


It's a bit tricky, so I'll explain it. You extract the first parameter in the stack as $arg. The and keyword assures that $arg is truthy before we proceed to the eval. The eval attempts to dereference $arg into a regular (non-reference) array. Rubyists can think of this use of eval in Perl as akin to a begin rescue end block.

If the dereferencing results in an error, it will stop evaluation of the eval block, resulting in an undef value, meaning that the expression returned by the function is false.

Why is there an or 1 at the end of the eval block? That's for situation in which your $arg is an empty array ref. An array of zero length evaluated in truthy scalar context in Perl is false. However, we want such a data structure to produce a truthy return value from this function. Therefore, when a valid but empty array ref is dereferenced into an actual array, it is false but does not break out of the eval block. The expression with the eval block then continues with the or 1, which ends up being truthy, ensuring that a valid empty array ref is considered valid by this function.

I lie when I say this was my ex co-worker's solution. He strongly objected to putting this test inside a function, because developers should just know Perl idioms, and the function call would add too much overhead. I thought instead that the value of naming this obscure bit of code with what its purpose is would be worthwhile. He disagreed. So he would have tests like the line of code below copied and pasted with no explanatory comments wherever we needed to check aref validity:


fail if not $arg and eval { @{ $arg } or 1 };


I saw that for the first time and thought WTF? I then added a comment explaining what that particular monstrosity was supposed to do, something like 'checks if a valid aref'. He objected strongly (again), saying that coders should just know Perl idioms.

We finally got him to accept the presence of the comment after about 30 minutes of arguing.

Try them out for yourself, if you like. I use $proc as a generic name for a procedure/function/subroutine/code reference. Some other people prefer $cref for code ref or $sref for subroutine ref.


my( %proc_of ) = (
'mere mortals' => \&is_valid_aref_mere_mortals,
'eval version' => \&is_valid_aref
);

sub report {
my( $label, $candidate, $proc_of_href ) = @_;
for $proc_name ( keys %{ $proc_of_href } ) {
my( $proc ) = $proc_of_href->{$proc_name};
print $proc->( $candidate )
? "$label is a valid aref according to $proc_name\n"
: "$label is not a valid aref according to $proc_name\n";
}
}

report( '[]', [], \%proc_of );
report( '()', (), \%proc_of );
report( '{}', {}, \%proc_of );
report( '(undef)', (undef), \%proc_of );


Results in this output. Note that I haven't included the deceptive blessing situation, on which the two subs would differ:


[] is a valid aref according to mere mortals
[] is a valid aref according to eval version
{} is not a valid aref according to mere mortals
{} is not a valid aref according to eval version
(undef) is not a valid aref according to mere mortals
(undef) is not a valid aref according to eval version


It seems to me that the clarity improvement from having the name is_valid_aref for that code is worth the relatively small overhead of the function call. I also think that it serves a pedagogical use - a new developer who isn't familiar with the blessing concern could in fact be educated about it by seeing this code under such an explanatory label. But I'd be interested in any other reasons to avoid putting this test inside a named subroutine. If I'm being stubborn for insufficient reason, I'd like to be illuminated and corrected.

Monday, July 28, 2008

Mea Culpa re: Typing

I was going through some Rails code today, making sure that I had good coverage and writing or modifying whatever specs as needed. I found this code:


module DisplayHelper
# snip ...
EMPTY_STRING = %q[]
# snip ...
def should_see_edit_link?(options)
return EMPTY_STRING if options[:new_record]
return false unless (memoized_user = options[:user])
# more stuff with memoized_user ...
end
end


Do you see the problem? The first line within should_see_edit_link? should be


return false if options[:new_record]


My initial version was not a proper predicate, in that it did not restrict its returned values to only true or false. Bad coder. For what it's worth, the methods that use should_see_edit_link? themselves return EMPTY_STRING if should_see_edit_link? is truthy. Alas, not a good enough excuse.

This is exactly the sort of error that advocates of static typing mention as support for their preferred type system. The most experience I have with bondage & discipline typing is with Haskell, where I find it takes its proper place as part of a cohesive whole for understanding Haskell's approach to currying, implicit typing, the pointfree style, and so on. All of that is great, I just haven't found that static typing reduces the error rate in my code. In fact, it gets in my way more often than anything else. Maybe that's why I'm getting more into Erlang rather than Haskell. All of this is probably inseparable from the fact that I got into coding with dynamic languages.

The type error that prompted this blog post is atypical for me. I'm not claiming to write completely bug-free code, it's just that my errors tend not be the sort that can be caught by a static type checker. In fact, the only errors of this sort that I can remember making are this individual error and some others in Perl related to composite data structures being coerced into scalar context. The latter were more indicative of Perl's idiosyncratic (and in my opinion, failed) experiement with context than with dynamic typing as it's generally implemented outside of Perl. So I'm not sure that they count.

How about anyone else? Has static typing ever really saved your butt dramatically?

Caveat: Please don't interpret this post as going anywhere near addressing static typing as it relates to hardware optimizations during compile time. I'm just taking about human errors resembling the example.