Is overriding to_s methods in Ruby bad? [closed] - ruby

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I've been experimenting and find that I like redefining Object's to_s methods.
Is this a bad idea or is it good practice?

No, you should feel free to override to_s - there are no ill side-effects. As long as your new to_s is more informative than the built-in (not exactly a high standard there), you're in the clear.
And they help make your test failures read better - sometimes by a lot - which is never a bad thing. Go for it!

I override to_s all the time in my Rails project:
def to_s
first_name + " " + last_name
end
so that it's easier to show objects in the view:
<%= #person %>

It might be tricky to do that because sometimes, inspect method just calls to_s, and if that is altered, you might have trouble debugging. If you think altering to_s may confuse you when you need to see the results by methods that rely on inspect , such as p, then maybe you need to redefine inspect for that class at the same time. As long as you are sure what you are doing, you might want to do it.

It's not "bad" per se, but it isn't "good" either. It really depends on the context.
If you are doing this for a one-shot place (for example inside your rails app's /lib/ folder, for a particular app) it is probably alright (make sure to give the file a descriptive name, such as object_to_s_patch.rb or similar, and that all patches are on the same place)
If you are doing a gem or a lib, on the other hand, I would not override it. Instead I'd add another method - Object.to_special_s or something. But I'd also try not to touch Object if possible - If you can get by with using YourModule::to_s(object) that'd be probably even better.
The reasoning behind this is that other people might be using Object.to_s for other stuff, maybe in other libs. Monkeypatching it will produce clashes with those other libs.
The only exception when doing a gem that I can think of is when the main point (or one of the main points) of that library is actually overriding the method; in other words, you are literally making a lib that overrides Object.to_s, and little else. I'd put some big warning on the documentation on that case. This way people using it will not get surprised.

Related

Is commenting every right brace good/bad style? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I am teaching an upper-division software engineering course and am reviewing every student's code. Some of my students have picked up the habit elsewhere of adding a comment to the right of every closing brace identifying the statement type, such as:
if (x > 3) {
y = 10;
} //if
I have told the students to follow the Android code style guidelines, which says nothing about this practice. On what grounds should I tell them not to do this (besides personally not liking it), or should I permit it?
Comments are for clarifying code and increasing readability. It's clear enough to most reasonable software developers that the statement is an "if." Furthermore, many IDEs and editors automatically highlight brackets such as these, so the comment isn't necessary. Generally, you should save comments for describing what methods, classes and variables do (e.g. in Javadoc), or what subroutines within a method will do. This is based on the general guideline of making sure everything you add improves the code.
Tell them that they should assume that person who review code knows language syntax and how to program. Comments should be rare, indicate and explain some weird and not obvious code section (for instance the api provided by some library is bugged and some workarounds/hacks are needed). We've got documentation (and unit tests) to explain how to use and how code should behave. For educational purpose you can write small class/module filled with such "comment-documentation", give it to students and ask them what did they learn about code from these comments.
Well, most likely this will end up in a discussion based on personal preference - which is not within the scope of stackoverflow. But aI'll answer anyway:
In my opinion, that's a bad thing to do - for multiple reasons.
It messes up the code. the more comments are in there, the less readable it is. A single } in a line tells me, instantly, that the last block ends here. with the comment behind, there is more to read - and no additional info (but people will read anyway, cause they don't know that the comment doesn't include any info... and because people tend to read everything automatically)
It leads to sloppy indentation. After all, that may even be the reasons people started that in the first place.
it's unnecessary - if I indet the code in a consistent manner, it shouldn't be necessary to note what was closed, it should be easily visible by just going up to where the last statement with the same indentation level was. In most cases (unbless you're reverse-indenting (or whatever that is called), which I don't like at all) this should be very easy, as there is nothing in between...
it leads to bigger file sizes. may be invalid on modern systems, but still.
Every time is overkill. It depends on the level of indentation and the length of your function, but these are usually signs that you need to step back and refactor. The only time I explicitly do it is for namespaces in C++

How do I make sense of Ruby documentation? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have seen code such as:
Net::HTTP::Post.new(url)
If I then use ri as follows:
$ ri Net::HTTP::Post
I get almost no documentation, and:
$ ri Net::HTTP::Post.new
results in
Nothing known about Net::HTTP::Post.new
When reading the documentation for Net::HTTP, I get the suspicion that the code should be using Net::HTTP#request_post instead. I still find the correct way to use this module confusing. Why does Net::HTTP::Post.net seem to work? Even with the Net::HTTP.request_post, I get:
undefined method `request_post' for Net::HTTP:Class.
To clarify my question, what I want is to know how to:
Find the best documentation for ruby.
Given the example provided, obtain the best way to achieve the aim (which is, to make an HTTP POST request, I'll add that I need to use provide authentication, cookie, and data in the body).
Make sense of what it means when the methods have been annotated with 'R' (does that mean 'read-only'? That doesn't make sense because I need to set the request body, which implies write...
As a contrast, this is equivalent documentation for Python, which I understand (being a python dev myself): http://docs.python.org/2/library/httplib.html
Here is the answer I will ultimately accept unless someone else has a better answer:
In order to understand Ruby's documentation, do the following, in sequential order:
Read the documentation for the module in the latest version of Ruby that is out there. Use ruby-doc.org, even if this version is for Ruby 2.0 and you're using Ruby 1.8, it is still likely to be significantly clearer and more complete.
Use google to find code examples.
Use irb to check if examples actually work.
Use ri to check if documentation for your version of ruby exists. If it exists, take a look for any insight as to what might differ in your version.
Use reflection/introspection in order to attempt to discover any exposed methods that may be useful.

Beginning variable names with the prefix 'the' [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Okay, this one is pretty hard to google.
Occasionally, I stumble upon code in any language that uses a naming convention where variable names start with the prefix 'the' under certain circumstances.
I could not figure out, however, what these circumstances are. So my questions are:
Is this convention common? Does it have a name?
If 1) is still "ungoogleable": What are the principles behind this convention? What problems does it address? I would like to understand.
If not covered by 1) and 2): Where does the convention come from? What are its origins? Is or was it connected to a specific programming language?
Examples:
From the Steinberg ASIO SDK 2.3, file asiodrivers.cpp, line 88:
extern IASIO* theAsioDriver;
where IASIO is an interface definition.
http://hl7api.sourceforge.net/base/apidocs/src-html/ca/uhn/hl7v2/util/StringUtil.html
http://xml.apache.org/xalan-c/apiDocs/classXStringAllocator.html
http://www.cplusplus.com/forum/beginner/65050/
http://www.cise.ufl.edu/~sahni/dsaac/enrich/c20/fold2.htm
I am hoping for some insight into why people do this. One example might be to tell parameters from members in setter/getter methods, but this choice of prefix seems random to me.
The only time I would be tempted to start a variable name with the would be to indicate that it is a singleton. Other than that its use seems unnecessary.
Based on personal experience (mostly Java, Ruby, Python, and long ago C and C++), the convention you describe is not common.
There is a related convention, the "Type Suggesting Parameter Name" pattern in Kent Beck's "Smalltalk Best Practice Patterns" (an excellent book regardless of whether you write Smalltalk), which names method parameters a(type) or an(type), e.g. anObject. My understanding is that this convention is to make code read a little more like English, not to avoid any naming collision that might otherwise arise. (Smalltalk classes are capitalized, so one could name parameters with downcased class names and there would be no collision.)
An expanded version of this convention which I saw somewhere prefixed parameters or locals with a or an and object instance variables with the, which makes some sense: the instance variable is "the" one most important to the containing object, while the parameter or local is just "a" thing. I wish I could remember where I saw it. I think it was written by a well-known author.
I don't normally use these conventions myself; instead I (like most code I've seen) use this. in Java and self. in Ruby to disambiguate instance variables and rely on short methods to sidestep the need to disambiguate parameters and locals. Naming variables for their roles and not their types (the best practice in any case) also usually eliminates the need for such conventions.
However, inspired by whatever it was I once read, I use the when a local shadows a method or function and I just can't think of a different meaningful name for the local.
In Ruby, a local shadows a method only when the method has no arguments:
def foo
7
end
foo = foo
=> nil # the left hand side shadowed the right hand side
This can be avoided by calling the method with empty parentheses:
def foo
7
end
foo = foo()
=> 7
but empty parentheses seem so un-Ruby to me that I prefer "the":
def foo
7
end
the_foo = foo
=> 7
In Python a local can shadow a function regardless of the function's argument count, so I find myself reaching for the more often.

Smalltalk public methods vs private/protected methods [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I noticed that the Smalltalk language has no concept of private/protected methods. All methods are public. Coming from a Java/C++ background, I've thought of this as a fundamental weakness in the language as any application created in Smalltalk would be completely open to manipulation. I guess you could rely on naming conventions to document the public API and prefix methods to indicate them as private (I believe Squeak does this), but it's still completely open.
Are there any benefits to this approach over having explicit access modifiers to control
access to method invocations?
Indeed, the Smalltalk way is to put private methods in the 'private' category. This indicates that you shouldn't use these methods, but of course doesn't enforce this.
This is by design - it's a feature, not a bug. Smalltalk was designed from the beginning precisely to be an open system.
Some advantages:
If I simply have to - maybe the library designer didn't foresee a need to expose some particular thing I simply have to have - I can still call those private methods. Obviously, this isn't something one does lightly: rather, judiciously, cautiously, knowing that it's a tactical solution.
Language simplicity.
(As per Alexandre Jasmin's comment) Smalltalk makes no distinction between what you, the programmer, can do and what the language/environment can do. That means that Smalltalk-the-image exposes all the things needed for you to build your own inspectors/debuggers/whatever without having to supply special tools using we-can-do-this-but-you-can't techniques.
Private and protected methods are in fact a significant weakness of languages like c++, java and c#. They basically say to their users: I don't want to learn and evolve. The consequence of that (and a lot more early binding) is that those languages require much more BDUF and are thus far less usable for a modern (agile) development process.
The first question is what private/protected access modifiers are about? Fundamentally, it is not about safety or security. It is about exposing the right interface to the user. Starting from that, it makes little difference between having categories protected/private and a language construct specifically for that.
I would even say that having private/protected visibility modifier brings more complexity to the problem than it actually solves.
Besides that, I don't think that private/protected visibility is a good answer to this problem
At the least, Smalltalk should have the textual convention that method names that begin with 'underscore' are verboten to call outside of the objects themselves. Unfortunately, I don't think that 'underscore' is allowed as the first character of a method name.

What's an example of Ruby code that's "too clever"? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I was having a discussion with some programmer friends who said that they see Ruby programmers (in particular) producing a lot of code that's "too clever". So I'm wondering what would that look like? I'm referring to the unnecessary use of an obscure language feature in a context in which something straightforward would have worked just as well or better. Know any good Ruby examples of this?
After giving a straight answer to your question, I'd like to also dispute the premise; whenever a group of programmers characterizes the users of another language in this way, the odds are that they are telling you more about themselves than about the community they are describing.
You could, for example, accuse c programmers of being too obsessed with low level details, or haskell programmers with being blinded by their desire for functional purity; perl mongers for brevity, etc. But you would, IMHO, by getting the causality backwards when you do so.
When I want to write a program that is best expressed in a certain style, I try to choose a language that supports that style. Sometimes you want a tool that lets you do unusual things, and for such a task having a language such as ruby is as valuable as having mathematica for math or javascript for browser manipulation in your toolkit. If I want to play with typography I hop into postscript because that's what it's best at.
It's like saying "Have you ever noticed that people who use power drills are always poking holes in things?" It's true, but it kind of misses the point.
class Tree
def initialize*d;#d,=d;end
def to_s;#l||#r?"<#{#d},<#{#l}>,<#{#r}>>":#d;end
def total;(#d.is_a?(Numeric)?#d:0)+(#l?#l.total: 0)+(#r?#r.total: 0);end
def insert d
alias g instance_variable_get
p=lambda{|s,o|d.to_s.send(o,#d.to_s)&&
(g(s).nil??instance_variable_set(s,Tree.new(d)):g(s).insert(d))}
#d?p[:#l,:<]||p[:#r,:>]:#d=d
end
end
The double-bang: !!something
I'm not gonna write what it does. Forget that you ever saw this syntax.
Any use of metaprogramming without having thought damn hard about whether there's a better way to acheive this using the normal, non-'meta' idioms of the language, I tend to find annoying.
An obsession with "DRY" (don't repeat yourself) where some fiendish piece of metaprogramming spaghetti is invoked to avoid repeating yourself, say, twice in a simple and actually-more-straightforward-and-readable-than-the-alternative fashion.
Any use of 'eval' in particular. As metaprogramming goes, this one should be your absolute last resort after trying everything else. eg a lot of rubyists appear not to have heard of Class#define_method.
The output phase of yaml.rb; that's why I co-authored zaml.rb. The standard yaml version does all sorts of metaprogramming (it was originally written by why-the-lucky-stiff, who I generally admire) but by replacing it with a straight forward hierarchical version that directly maps to the class tree we were able to eliminate several O(n^3) cases, resulting in a factor of ten speedup for cases of interest, fix several bugs, and do so in a fraction of the code.
Plus, even people who aren't ruby gurus can see what it does.
Many of the examples in this article would seem to qualify:
21 Ruby Tricks You Should Be Using In Your Own Code.
The title of the article was a bit of a giveaway, given that it reads "Should" instead of "Should Not". Code "should" be transparent. Code "should not" be tricky.
I'm not sure if this qualifies as "too clever," but I have seen code that made me wonder if the author was either a genius or an idiot. One developer seemed to have a rule that no method should have more than two lines of code. That pushed the call stack very deep and made debugging rather difficult. The upside is that his overall design was very abstract and even elegant from a distance.
Cucumber (or RSpec Stories)
Quoted from the above RSpec Stories link:
Based around plain text descriptions
of application behaviour, it lets you
write integration tests with good
reuse and good diagnostic reporting.
For example, here's a story I wrote to
check the login process.
Story: login as an existing user
As an unauthenticated user
I want to log in to Expectnation
So I can see my account details
Scenario: login details are correct
Given an event provider
And my test#example.org account
When I log in with email test#example.org and password foofoo
Then I will be logged in
And I will be shown the account page
The words such as "Given", "When" and
"Then" are cues to the story runner to
execute some code. Behind the story
sits a collection of steps. Here's a
couple of steps from this test:
Given "my $email account" do |email|
#user = find_or_create_user_by_email({:email => email,
:password => 'foofoo',
:password_confirmation => 'foofoo'})
end
When "I log in with email $email and password $password" do |email, password|
post '/user/account/authenticate',
:user => {:email => email, :password => password}
end
Notice how a clever bit of string
matching allows you to pass parameters
from the story prose.
With a small bit of bolting together, the prose stories are then run as code and the tests executed.
It depends. (I love "it depends" questions)
It depends on the knowledge of the writer and reader. I used to think the use of Symbol#to_proc in Rails was unnecessarily arcane, for example, preferring
a.map { |e| e.downcase }
to
a.map(&:downcase)
Now I'm happy when I read it, although I still don't think to write it.
There are areas of libraries (Rails and others) where I have felt excessive and self-indulgent metaprogramming may have occurred but again the division between "too clever" and "really very clever indeed" is often paper-thin. DSLs are a good area: the ways in which "macros" are made available within classes (think of all that declarative goodness in things like ActiveRecord::Base or ActionController::Base) is very hard for a relative novice to understand and would probably seem like over-cleverness. It did to me. Now I find myself referencing the same code for guidance as I implement similar capabilities.
method_missing can be abused and it's one of those things that may cause you to pull your hair out when you have to fix a bug 3 months after you've written code.
Take a look at the source of Markaby. Insanity.
You shouldn't have to go from method to method to method to try to figure out what in the hell something is doing, for the sole purpose of not repeating a few lines of code. Being too focused on the LOC count and ultra-skinny methods might feel cool at the time but is time-consuming for someone else trying to debug or follow the code (and that someone may be you months later).
compare:
if MODELS.keys.inject(true) {|b, klass| b and klass.constantize.columns.map(&:name).include? association.options [:foreign_key]} then
# ...
end
1 line (if), 132 chars, 132 avg len, 22.9 flog
vs
fk = association.options[:foreign_key]
columns = MODELS.keys.map { |key| key.constantize.columns.map { |c| c.name } }
if columns.all? {|column| column.include? fk} then
# ...
end
4 lines, 172 chars, 43 avg chars, 15.9 flog
much faster too.
Original author actually argued maintainability for the first version.
Recently uncovered this monster:
def id
unless defined?(#id)
#id = if id = local_body.to_s[/(?:#\s*|#[[:punct:]]?)#{URL_REGEX}/,1]
id.to_i
end
end
#id
end
Not that I disagree with caching a calculation, it could just be far more clear.

Resources