Non object-oriented objects

I always feel uncomfortable when I encounter instances of certain classes in the codebase I’m working with. Perhaps uncomfortable is not the right word here; the whole situation is a huge paradox: objects that fail to behave in an object-oriented way. Of course I’m talking about classes like Tuple and Triplet (or whatever name they may have in different libraries). Continue reading “Non object-oriented objects”

Advertisements

Book review: Sujoy Acharya – Mastering unit testing using Mockito and JUnit

Some weeks ago, I was contacted by Packt Publishing to write a review about the book above. Without any further introduction, let’s just jump in and see the pros and cons of this book.

Mastering unit testing using Mockito and JUnit is a pretty new book, it was published in July 2014.

Right in the first chapter, the author digs deep into the capabilities of JUnit 4. This is a very thorough analysis of the JUnit API, starting from basic things (like how to write a basic test case) and gradually moving towards more and more advanced topics (test categories, expected exceptions). Anything you’re ever going to use from JUnit is described here – and much more. While reading this chapter I had a feeling that if the reader is an expert, chances are high that they’ve already met most of those method calls and annotations; if they’re new to unit testing, then this chapter may be somewhat too fast.
Every single aspect (method, annotation etc.) is backed by some example code, but unfortunately these problems have little to do with real life applications (like assertTrue(true)). Quick note: the book uses the when_something_then_something naming convention for tests. I like this very much, this is my favorite too, as test names become much more readable.

Chapter 2 introduces automated build tools such as maven (ant, gradle) and Jenkins. I think this is a very good idea, as nowadays such tools are compulsory for a software engineer. However, three build tools (maven, ant and gradle) described in detail (I really mean in detail: how to download and configure tehm, how to put together a simple project) is a bit too much. (I think most readers want to be true masters of unit testing, and not of different build tools. To describe the concept along with an example is awesome and would have been more than enough).

Chapter 3 is very short compared to the others. It describes the test doubles – as defined by Gerard Meszaros, which is really a prerequisite to mocking. Many times people fail to see the difference between all the types of test doubles, so this chapter is very welcome.

Chapter 4 is all about mocking with Mockito. It again dives deep into Mockito with all its annotations, API methods and capabilities.  Although similar to Chapter 1, this chapter introduces a more complex example (manipulating stocks), through which it unfolds different aspects of Mockito. There are very nice tips in this chapter, like inline stubbing (saves a lot of code lines) or configuring mock default behaviors for mocks. I’m looking forward to putting in practice some of the ideas described here.

Chapters 5 and 6 will take you to the world of code coverage and code analysis tools. This is again, very cool idea to talk about in conjunction with unit tests. Maybe I would have liked it more right after chapter 2, so Mocito and its usage could have been one after another.

Chapters 7 and 8 are about using Mockito in real life. Chapter 7 is about testing web application, while Chapter 8 talks about testing the data tier. These, indeed are tough things to handle in real projects, so I like it very much that these chapters made it into the book. However, I think there is a slight focus loss here; these two chapters shouldn’t put that much attention on Spring (MVC and JDBC Template), but rather on general, technology independent problems. Sometimes  I felt like I was reading a book on Spring, with some unit testing and not the other way around.

My favorite parts were the last two chapters. Chapter 9 talks about problems that pop up every single day while fighting huge legacy code bases. Those things described there happen exactly as presented – I encountered almost each and every of them when I was a maintenance guy. The book offers practical solutions on how to overcome these obstacles and get legacy code base under test. This chapter is an awesome one, everybody should know and practice those tricks.

Chapter 10 is about best practices when it comes to unit testing. This chapter is really for the inexperienced, who have just  met unit testing but are not familiar with all the good practices about the framework. This chapter should be a very good starting point for junior programmers at the beginning of their career.

Summary.
Mastering unit testing using Mockito and JUnit has got pretty cool tips and tricks, very thorough analysis of the frameworks and practical applications for everybody out there. One thing I particularly liked is that the book offers a very good overview on all the different reasons why a piece of code becomes hard to test. Nevertheless, I can’t really figure out who is this book for. It is too fast paced for absolute beginners, but somewhat too obvious for experienced engineers – in my honest opinion, some parts may miss the targeted audience.

Having said all these, I’m rating this book 3 out of 5.

Constructor vs. Field injection

I was interviewing a candidate the other day; we were talking about Spring, when I asked him if he preferred constructor or field injection. Typically people pick a side; either the first or the second one, so I was pretty surprised when the candidate told me that it depends on the context. And actually, this is the most awesome answer (in my opinion, of course) one can give to this question.

A lot has already been written about this topic. Most of the articles (and several people I know) state that not injecting all your dependencies through the constructors you are doing it all wrong, as you are hiding your dependencies (This makes perfect sense, but only up to a certain limit). Do these people then actually say that you have no way to write code of good quality based on the EJB technology? There you cannot use constructor injection at all – since you must provide a no-arg constructor that will be called by the container. Can anybody say that every each such system is rubbish and should be thrown away? I’m quite positive that we could find awesome EJB systems without an exhaustive search.

On the other hand, however, in Spring you are free to inject anything through your constructors. Is it than the only one right way to do dependency injection? Should the field based option just left out starting from the next releases of the framework and buried forever?I’d say no – and not only for backwards compatibility reasons. There are many cases when constructor injection produces better results than field injection; but not always. 

Let’s just take two examples. In the first one we are producing the most awesome BDD framework ever. There is only one thing left for us to do, develop a reporting module that is capable of producing test results in various formats (XML, HTM and plain text, for example).  We can come up with something like this:


public class ReportHandler {

  private Reporter reporter;

  public ReportHandler(Reporter reporter) {
    this.reporter = reporter;
  }

  public ReportContents produceOutput() {
    //...
    reporter.getReport()
    //...
  }

  public void dumpOutput() {
    //...
    reporter.persistReport();
    //...
  }
  //...
}

Constructor based injection is clearly the right choice here. With field-based injection we couldn’t even decide what kind of reporter to inject – that is an another level of abstraction.

Let’s now suppose that we are writing a simple text parser utility; it needs to replace placeholders of format #{…} with actual values, replace end of line characters to Linux style and remove all lines that start with three stars. In this case these three responsibilities may very well be factored out to different classes. Now, we have two possibilities:

Nr. 1

public class Parser {

 public Parser(PlaceholderResolver resolver, EndingsReplacer replacer, CommentsDeleter deleter) {
   this. resolver = resolver;
   this.replacer = replacer;
   this.deleter = deleter;
 }

 public Text resolveProperties(...) {
   //...
   Text text = resolver.resolve(...);
   //...
 }

 public Text deleteComments(...) {
   //...
   Text text =  deleter.removeComments(...);
   //...
  }

 public Text replaceEndings(...) {
   //...
   Text text = replacer.replaceEndings(...);
   //...
 }
}

or Nr. 2

public class Parser {

 @Inject
 PlaceholderResolver resolver;
 @Inject
 EndingsReplacer replacer;
 @Inject
 CommentsDeleter deleter;

 
 public Text resolveProperties(...) {
   //...
   Text text = resolver.resolve(...);
   //...
 }

 public Text deleteComments(...) {
   //...
   Text text = deleter.removeComments(...);
   //...
  }

 public Text replaceEndings(...) {
   //...
   Text text = replacer.replaceEndings(...);
   //...
 }
}

The problem with the first version is that we are injecting dependencies through the constructor which are not really dependencies for the whole Reporter object, but for different methods only. This way we are polluting the constructor with dependencies that will be used at only one or two places.

People overly into constructor injection, commonly come up with problems like:

The second version is untestable, as we have no control over the three dependencies. This, in my opinion, is hypocrisy; we’ve all learnt so far that putting in a protected setter just for a unit test is not an evil thing. Having everything tested thoroughly is worth a such a method or two.

“One could call those setters within the package” they argue further… Well, perhaps we should treat each other like professionals who know what they’re doing and not malicious code-monkeys, which try to make the biggest harm possible.

“@Inject, a Spring related dependency is spread in my application”. Well this is not true, as @Inject is in package javax.inject, so this is a javax dependency. Anyway, let’s pretend we have @Autowired instead of @Inject; I’ve never seen a mature application that was ported from Spring to some other IoC container; if you use Spring, you inevitably have it as a dependency. It is, perhaps, not worth the effort to keep Spring-related stuff in the config files only, as it can keep you from reinventing the wheel.

Single responsibility principle is a two ways street. As such, it can be violated two ways: you either create objects with way too many responsibilities, or none. That is, you create your objects so dummy that they have no real logic in them. It’s like someone was like: “Introduce yourself, say that your name is Steven”. Shouldn’t it rather be “Introduce yourself” only, with the responsibility of telling your name left to you? I think it should. Not to mention that in the case of excessive constructor-injection you will -pretty fast- face with monster config files (be it Java or XML) – objects putting together other objects in a long, ugly chain.

In summary, field and constructor injection are two complementary technologies. Using one does not rule out the other; one should, however, apply common sense when dealing with this issue, and should not be overly biased toward one or the another.

Is your organization really that fast-paced?

High-tech companies (and other companies too) publish some indicator numbers from time to time. Those indicators can be very meaningful to shareholders, financial professionals, investors and so on. However, these numbers mean (almost) nothing to the company’s prospective employees. Knowing the stock prices won’t tell you anything about company internals.

Let’s say you’ve got to choose between two job offers. To take money and challenges off the table, let’s just assume that both companies are paying around the same and the work you have to do, seems pretty nice at both places. How do you choose? The only thing you can really rely on is the information you gathered during your interview rounds. Maybe helpful, but way too subjective. What if there were some truly objective indicators out of which you could guess how well-organized the team you’re about to join really is? Would it help you if you were provided numbers like:

  1.  How many days does it take, to get your environment up and running? It can take enormous amount of time to get all the access rights, accounts and many others. Which also means, that during that time you may be completely blocked – trying to get past your 8 working ours per day being bored is sometimes more tiring than actually doing some busy-work.
  2. How long does it take for a new employee to become productive? Most of us like to produce solutions as fast as we can. It could pretty much destroy one’s self-esteem to wait for 2-3 months to actually get something done. Going one step further, this metric would even be able to reflect on some aspects of internal processes (for sure, with pair-programming one catches up much easier with the new technologies and architecture).
  3. How long does it take to test a release? Is it just running a comprehensive test-suit that takes at most a few hours, or do testers have to manually click through the different test cases over and over again?
  4. How long employees stay with the company/team? 

To me, these information would mean much more than the usual “Forbes 500”, “Dynamically growing”, or “fast-paced” stuff. Too bad such metrics are almost never collected. Some companies could easily drop the high part from the high-tech attribute.

Interface abuse

Just a quick word on interfaces, and what they stand for. Probably this is obvious to many people, but I see a recurring problem which I guess is related to some misconception of interfaces.

Program to interface, not to implementation” – old words of wisdom, we’ve all heard a thousand times. However, interface in this context is not necessarily a Java interface – or at least not always. You can find yourself in situations when you are using interfaces and still programming to implementation. Let’s see what exactly is the difference between the two approaches.

Programming to implementation means the complete missing of unification; it means a bunch of if-else if statements, switches, instanceof operations. The following code fragment is clearly programming to implementation, even though it makes use of interfaces.

public interface Clock {
 //...
}

public class NewYorkClock implements Clock{
 //...
}

public class BudapestClock implements Clock {
 //...
}

public class WorldClock {
 //...

 public String getTime(Clock clock) {
 if (clock instanceof NewYorkClock) {
 NewYorkClock newYorkClock = (NewYorkClock)clock;
 Timezone nyTimezone = clock.getNewYorkTimeZone();
 clock.formatNYTime(nyTimezone);
 } else {
 BudapestClock newYorkClock = (BudapestClock)clock;
 Timezone budTimezone = clock.getBudapestTimeZone();
 clock.formatBudTime(budTimezone);
 }
 }
 //...
}

Well, usually it does not come in such obvious forms, but you can be suspicious when you see lots of if-then statements for controlling behavior.

 Programming to an interface means to handle similarly behaving objects in a uniform manner (and that is what interfaces guarantee us: uniformity. No matter who the implementer of that particular interface is, it is always guaranteed that it will conform to the interface it implements).

However, what’s really not programming to an interface (and basically this is why I’m writing this post) is associating an interface with every single class – e.g. having one and only one class implement an interface. This overuse of interfaces does more harm than good. As mentioned above, we use interfaces in order to group together objects with similar behavior. However, when an object does not share similar behavior with any other objects, there is no need for this grouping; that object is already uniform by default.

Extracting an interface from a class just so it has one, has this annoying feature that whenever you ctrl+click a method name in your IDE, you end up in the interface rather than the implementation itself. I see no practical use case in jumping to the signature declaration instead of the implementation itself. It’s annoying, a waste of time, a huge overkill and completely useless, in general.

People usually make excuses like “well, there might be new implementations for this interface in the future, so that’s why”. Which is a pretty bad one; there might not be new stuff to add as well. And even if such a new feature comes along, it’s enough to add the interfaces then – when you actually need them. Don’t fix what’s not broken; don’t add useless code trying to predict the future. Whenever you see such interfaces with only a single implementer, in my opinion, you should just go ahead and delete them. Well, if you delete old unused private methods, why would you keep a type that can be replaced with another one in no time?

After all, the version control will keep track of it anyway, if you need them ever again.

A little less conversation, a little more action, Baby?

Has it ever happened to you, that you forgot to drink water, while in the office?
It happens to me all the time.
 
Have you ever tried putting a bottle of water putting next to you, on your desk? Does the problem above still apply? It does not, in my case. If that bottle is in front of me, it will empty out in the course of the day. I don’t even realize when I drink it, I just realize the empty bottle.

The water cooler is usually located in the kitchen. People are usually sitting in a different room. They are separated from the water with at least one wall. It seems that the wall makes the difference – the wall is the troublemaker that is responsible for your dehydration.

What does this have to do with software development?
It’s easy. Walls don’t just make you thirsty, they do a real good job in absorbing information. Teams separated in different rooms, do a much poorer at communication. Let’s imagine a situation in which a team member is desperately looking for a solution to an incredibly annoying problem (the software can’t be deployed all of a sudden, the build breaks miraculously etc.). This person has already tried everything they could think of, but the thing is still wrong.

Now it’s time for our hero to broadcast the question -everybody does it, eventually-: “Have you guys seen this problem with … ?”. If people are sitting in small rooms, there is a smaller chance there will be an answer for the question. And it turns out, that at least 50% of the people break down at this point, and start over trying to solve the issue on their own. Their understanding is that they are left alone, and nobody knows the answer. They just won’t go to the next room, or the other one for some reason. Walls block them; and that results in a lot of wasted man hours.

In case of co-located teams, this is just not a problem. Every such broadcast question is instantly available to all the team members. If more teams are sitting together in a large open space, it’s even better. The more people are sitting together, the higher the chance for the problems to get sorted out more quickly.

If a group of people are called a TEAM, they should sit together. No matter whether they are 3 or 12. They just have to share the same room, so the information flows efficiently. This might be inconvenient to some team members, but it pays out in the end.

Thoughts on clean code

Back in high school I was taught Pascal. It was a really nice way of learning concepts, basics, programming structures in general. As time went by, I discovered Delphi. Now, Delphi (for those who don’t know) is an object oriented language, based on a Pascal-like syntax. And I was like “wow, I can write applications for Windows, but I’m still doing Pascal”. Continue reading “Thoughts on clean code”