how to refactor these code?

Z

Zhenning Guan

def ss(s = 'hello', yeah = nil)
if yeah
puts "something"
else
puts "other thing"
end

#code continue ....
end

I have this method, use it like that:

ss('hi', yeah = true)
ss('hello')
ss('****', yeah = true)
ss('hello',yeah = true)

very ugly.. sometimes I just need to passed yeah = true, but I have to
added 'hello' first.

what should I do?
 
B

burke

A little more context would be helpful, but you could do something
like:

def ss(options={})
s = options.delete:)s) || "hello"
yeah = options.delete:)yeah)

puts (yeah ? "something" : "other thing")

#code continue ....
end

ss:)hello => 'hi', :yeah => true)
ss:)yeah => false)

and so on.

Burke Libbey
 
R

Robert Klemme

2010/1/26 Zhenning Guan said:
def ss(s =3D 'hello', yeah =3D nil)
=A0if yeah
=A0 =A0puts "something"
=A0else
=A0 =A0puts "other thing"
=A0end

=A0#code continue ....
end

What do you need argument "s" for?
I have this method, use it like that:

ss('hi', yeah =3D true)
ss('hello')
ss('****', yeah =3D true)
ss('hello',yeah =3D true)

very ugly.. sometimes I just need to passed yeah =3D true, but I have to
added 'hello' first.

what should I do?

Define two methods. At least from the interface this is cleaner.
Generally flags that control method behavior are considered bad
practice because they tend to make the implementation of a method more
complex and tie things together that might really be independent (just
consider what happens if you inherit a class and want to change only
one of the two variants).

Note, you can still share an internal implementation under the hood e.g.

def ss1
ss_impl "something"
end

def ss2
ss_impl "other thing"
end

private
def ss_impl(x)
...
end

But your example is really a bit short to come up with a definitive
answer how to improve this.

Kind regards

robert

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,160
Messages
2,570,889
Members
47,421
Latest member
StacyTaver

Latest Threads

Top