Function name convention for "convert foo to bar"
clojure, javascript, lisp, python, ruby
Solution
I think it depends a lot on context and choosing a meaningful metaphor. ActiveRecord for instance uses the class method "find" for finding records in the database, a more meaningful idea than "input a user_id, output a user". For example:
User.find(user_id)
User.find_by_email(user_email)
For conversions, I usually like to write the conversion methods to make it easy to use in higher order functions. For example in ruby, conversions are often done with `to_*` instance methods, for example to convert a `Foo` to a `Bar` it would make sense to have a `to_bar` method for all foos, so you could write:
foo = Foo.new(...) # make a new Foo
bar = foo.to_bar # convert it to a Bar
And then to convert a bunch of foos, you could simply:
bars = foos.map(&:to_bar)
Ruby also tends to have `Foo.parse(str)` for converting a string to the object.
For javascript, I like having class methods (which I got from standard ml), for example:
Foo.toBar = function(foo) {
return new Bar(...);
};
And then you can map over it as well (using underscore in this example):
var bars = _.map(foos, Foo.toBar);
the Standard ML convention is structure (class) methods. Example fn types:
Foo.toBar : foo -> bar
Foo.fromBar : bar -> foo
And you'd use it like:
val bar = Foo.toBar foo;
val bars = map Foo.toBar foos;
Problem
I have a very common pattern of "given a `Foo`, return a `Bar`," for example, given a `user_id`, return a `User`. Is there a conventional naming pattern for these sorts of functions? Following Joel on Software, I've personally used a lot of `bar_from_foo()`, but I rarely see other people do this and it quickly becomes verbose, e.g. ``` widgets = user_widgets_from_user(user_from_param_map(params)) ``` Is there a conventional way to name, or namespace (e.g. `User.from_map()`) in any of the popular languages out there? I am particularly interested in Python but any language you can think of would br useful.