Sohan's Blog

Things I'm Learning

Excess of Private Methods Is a Code Smell

Private methods, when used meaningfully, are a great tool for writing beautiful object oriented code. But as many other things in life, excess of private methods is bad, too!

In my opinion, we use private methods to:

1.  isolate a block of code to be reused inside the class.
2.  extract code from another method for code readability.

Now, taking these two use cases in mind, here’s an easy conclusion:
The lower the ratio of public to private methods, the harder it is to write unit tests since the “units” are potentially larger.
I don’t know if there is any rule of thumb, but you will smell it when you see your unit tests require a lot of setup and assertions. Here’s a code example from the Play! framework, an MVC franework for Java developers.

ActionInvoker.java

You will see there are public methods with 100+ lines. I hope you agree with me:
“The ActionInvoker.java code is not readable”
For the sake of readability, introducing private methods with good names would help. However, that doesn’t eliminate any of the possible code paths from the public methods. So, if you are lucky, you will see really long unit tests with complex setup conditions and mock expectations. Otherwise, there will be no tests at all! Without any tests for such long and complex methods, use them at your own risk. I won’t :(

Disclaimer: I like the play! framework a lot. However, if you take a look at their code and if you think unit testing is important, you’ll see they have a lot of rooms for improvement with simple extract method refactoring.

Quiz: C# Async and Await. What Is the Output of This Code?

C# 5.0 (CTP version at this point) has support for async and await to allow clean implementation of non-blocking IO using a task-continuation model. I was just playing with it and here’s the sample code to tease your brain. Tell me what is the output of this program?

How to Extend a Ruby Module?

Modules in Ruby are like classes with a few important differences. One of the differences is, a module cannot inherit from another module using the same syntax as class inheritance. However, its pretty easy to inherit a module’s method into another module, by just using the include ModuleToInclude syntax. Here’s an example if you are looking for one:

Should You Unit Test Interaction With Static Methods?

No. You should not. Here’s an example:


If you are somehow mocking this static method, you are potentially making it dangerous for other places where this static method is used. Eventually, this will create red test results that are hard to find and make your tests dependent on each other.

Should You Unit Test Methods With a Lot of Mocking?

Well, anytime you have a lot of mocking, it is probably a smell. Particularly, a first smell is violation of the law of demeter. However, we were having discussion about whether or not we should write unit test for something like the following example:



As you can see, this method actually does a quite important task. It invokes the search method with specific parameters that will determine your search results. Now, we were debating whether or not the example unit test actually brings any value.

Here’s what we have discussed:
Pros:
It confirms that you are actually calling the third party method with the right parameter.
Cons:
The test is too tightly coupled with the implementation, so it will break if something changes inside the method irrespective of its actual output.

But we failed to come to an unanimous decision on its usefulness. We all agreed on the point that it definitely needed some integration tests to make sure the search had actually worked.

Here are two questions for you:

  1. Would you skip the unit test altogether for this method and rely completely on an integration test? Why/Why not?
  2. If you are to rewrite this code, how would you write this using TDD?

Looking forward to see your input on this!

Comments

Isa Goksu
The first question actually has two aspects. It has a design part, and an implementation part. You have to judge which part we are doing here since you know the actual work there. If it is a design side, you write an integration or a functional test to find out whether wiring is done correctly or not. If it is on the implementation side, you have to write a unit test that verifies the behaviour.

What I see from just a little code snippet here is basically you are creating a wrapper/facade for the library, or a delegate or even an anti-corruption layer kinda something. And your wrapper object is basically created in such a way that it looks like a Humble Object (http://xunitpatterns.com/Humble%20Object.html). Therefore I'd go for integration test. If the team you are working on is a distributed team, then you might have some trust and/or communication issues, therefore writing an additional unit test wouldn't hurt. Then again that's not necessary.

Main thing here is to understand that TDD won't tell you that you have write unit tests all the time. What TDD say is have a coverage before you operate, and drive your design with this mentality. One thing I like in Ruby community is that they do focus on Specs rather than focusing on unit/integration/functional tests differences. A tool like RSpec or Cucumber is even designed in such a way that they give you tagging support which you can easily mark your test with #requiresDB, #requiresFileAccess, #opensBrowser, etc.. And then you can create multiple builds by using these tags to have prioritized test suites.

Second question is probably an obvious one. If I were to re-write using TDD, I'd probably end up having an anti-corruption layer to the library which is designed 1:1 from the actual library, hence not need to be unit tested.

Ruby Present? Method

Ruby has a nice little keyword called unless, that checks the opposite of if. So, you are probably used to a code like this:

return customer.first_name unless customer.nil?

If you haven’t used present? before, you can in fact turn the above unless into a more familiar and easy to understand if statement:

return customer.first_name if customer.present?

So, in most cases when you are using unless with a negative condition, you can use present? and if instead. I find it way easier to read.

present? does the opposite of blank?. So, you will get the following:

nil.present? #=> false
[].present? #=> false
"hello".present? => true
["a"].present? #=> true
Hope it helps!

Comments

Sohan
Yes, you are right.
michaelkoper
So far as i know is present? not a Ruby method but a Ruby on Rails method. http://api.rubyonrails.org/classes/Object.html#method-i-present-3F

.zero? is indeed a ruby method.
Sohan
Yap, you can do my_integer.zero? instead of my_integer == 0

or my_integer.nonzero?
Anonymous
Is there an equivalent for zero? ?
Except for != 0 of course…
Sohan
Thanks Ashif!
Ashif Manjur
Yes, I often halt at whether I am doing it wright anytime I use 'unless' in any condition. Its much more easier to read if I use 'if'. Thanks for this short but useful post…

Constructors Are Methods, Too!


Yes, if your constructor does something meaningful. This is just like another method and should be treated equally for unit testsing purpose. Here’s an example that should need unit test:

It looks simple, so testing it should be simple, too. I would only skip the default constuctors, as long as they don’t do anything interesting.

Comments

Alexander Beletsky
Sure, the constructors are methods too.. but they should not do anything more except internal initialization.

I had a little habbit to put additional logic inside constructor, to be possible to write something like

= new DoSomethingClass(x, y);

I'm getting rid of that also because of bad testability. Instead of that I write now:

var smth = new DoSomethingClass(x, y);
smth.DoIt();

How to Annoy Your Customers? Learn From GoDaddy Account Status Email

Just looking at this screenshot alone, what do you think it is?
I have a few domains registered with GoDaddy. I went with them, because at that time, I didn’t know of another renowned provider. But they have always been the best of producing the most confusing ever user interface. The account status email is one step ahead in that same direction.

This is how it starts:

At the top right corner, it says July 2011, in grayed out font! A deliberate attempt to de-emphasize the statement period!

Just below the date, there is a fake input box and a button labeled Go. This is an image and if you click it, it will actually open a new page instead of asking for user input right inside the search box. This is just following the theory of most surprise (as opposed to principle of least surprise)!

Next, in red background, they welcome me by saying, Welcome, S. M. Sohan! Customer Number: ### wtf? Customer Number? Do I give a shit what my customer number is? Why is the welcome grouped together with search and contact? How are these related?

Then it says, Log in to your account on our secure website to view your most recent account statement. What does this mean? Does it mean, this statement is not recent? Is this not secure?

Then it says, Summary of your account as of 7/21/2011**. That f’ing footnote will tell you that, the information may not reflect recent changes! What? Is this good enough till 7/21? If not, why do you even send this bullshit to me?

Then it has 4 boxes side by side. The first one, Messages has Alerts: No, Notification(s): Yes. View now is a button to their site. How stupid is this? Why bother saying alerts “No”? If you know I have notifications, why not put it right here? Why are you confused about notification”(s)” - you should know if its just one (notification) or more (notifications). How lazy is that?

Items Expiring is the other funny one. It says, Domain names: No. Then it says renew now. What? You’re saying nothing is expiring. Why on earth I would renew something?

Then it takes almost 50% of the screen for asking me to contact with them through a number of channels including Facebook. Really? Facebook fan of GoDaddy? Crazy people!

In the end, they don’t care putting a note of thanks, let alone personalize it with the name of an actual person. Isn’t it rude to end an email this way?

Now, with all these hammerings - as if it fell short of creating enough fun, it says, More for You: followed by tens of fine print links to things that don’t matter at all to me. Oh boy! you are awesome!

I am not a designer by any means. However, I think, even I can design a better version than this crap. Here’s my version in a screen mockup.






Avoid Duplication in Config Files

Any kind of configuration file, be it an ugly xml file or a prettier yml or properties file, its been a source of frustration to me. Here’s a list of few such pain points:

  1. There are two config keys that point to the same value. e.g. db_username=master, data_source_user=master
  2. There are two config keys for urls that point to the same domain, but different paths. e.g. market.com/cameras and market.com/undies
  3. Config entries with placeholders. e.g. weather_url= weather.com/%s or weather_url= weather.com/%s/hourly
  4. Config entries with default values that should not default to anything.
  5. Config entries that are required but don’t fail the application deployment when not set.

Are you having to deal with similar pain points? Some more?