Monday, December 9, 2013

Let Them Tie Their Shoes

When my son was growing up, one thing I always tried to let him do as much as he was capable of doing. Was this hard? Yes, it was extremely hard, the hardest thing to do is watch someone struggle when you can easily solve the problem for them. At first when I was in a hurry I would watch him try to tie his shoes and especially if I was in a hurry, I would just jump in and do it for him. This got us out the door, but because I was focusing on him, I would take longer myself or forget things. So I changed my approach and allowed him a little time to get ready. I gave him a little time to struggle and learn, and he became independent. Then when we were in a hurry I would trust him to get ready and tie his own shoes so I could focus on things I had to do to get ready. It was a small investment in time at the beginning that paid off over and over again.

Similarly, the project management team must allow the development team to solve their own problems. If they step in and take control when the team is struggling, the team will never realize their potential. Management will second guess the team and in trying to get things done, shift priorities and focus. They team will become dependent on the managers, waiting on instructions instead of self organizing to fix their own problems. The managers will also have little time to focus on doing their job. They will spend the majority of their time and energy "fixing" the team and have little left to plan for future iterations and remove obstacles.

Am I saying they should just leave the team alone? No, I am not, but helping this way looks different and is more guiding than directing. For instance, if the team is struggling with a technical problem, say they are using a new framework and it's really slowing the team down. Management should provide the boundaries of the decision, we have to ship our product by December, or this is all the budget on this project is pretty inflexible. Let the team work within those parameters. One caveat is that they should be boundaries and not just assumptions, if you force false parameters onto a team they will make faulty decisions.

The project management could then facilitate the discussions, provide resources, force the team to make decisions, but don't tell them what that decision should be. Remember facilitate is not directing, its things like taking notes, rephrasing comments and making sure all interested parties have their say. Its very easy at this point to direct conversations or to inject opinions, so be wary of your language and try to be an observer not a participant. Phrases like "you can't possibly be suggesting we do X" or "are we just being lazy here" have a dampening effect on the discussion. Let the team drive and see where it will lead. Time box the discussions and force them to make actionable decisions, but if you let them work on solving their own problems, most times I think you will see, it is a better solution than you could have come up with on your own.


Saturday, September 14, 2013

Use Your Tools - Eclipse Debugging


One of the things I love about pair programming is I get to learn from others on how they use their tools. Some of these are simple, but I wanted to share some of the ones I have found useful.

And since one of the main reasons of using an IDE is to debug code, I decided I would start there.

Drop to Frame. I just discovered this one recently and it makes debugging so much easier. In the debug window if you right click the point where the Thread is suspended you see a menu option Drop to Frame. Its not clear from the name what it does but if you are stepping through the code and want to go back it drops to the beginning of the stack frame. The eclipse notes that not all VMs will support it, but if it does it saves me so much time when I step past my breakpoint.

Attaching source code. I'm surprised at the number of people working with open source code that don't step into the code to find out what its doing. If your jars don't have the source included you can still include it. In the Java Build Path window, go to libraries and expand some of the jars, double click Source Attachment and browse to a path where you have the source code. Just make sure that you are using the same version as the compiled code.

Breakpoint properties. Ever have to set a breakpoint in a loop and step through until you get to the iteration you are interested in. If you right click or Ctrl + double click on a breakpoint and go to properties, you can set a hit count property to break on. You can also set a conditional or break when a value changes. If you need to break on a certain error or when a certain class loads you can set those breakpoints from the Run Menu.

Variables Window. This window is probably the most known, you can see all the variables declared. Some people seem surprised that you can even change the value of variables on the fly here.You can also navigate to the variable type and declaration. There are other options on the view menu for things like showing constants or references.

Display Window. I can't understand why this is not loaded by default, but its not. So go to Window->Show View->Other and Search for Display. I like it because I can use intellisense, inspect variables and even execute code, and then copy and paste working code back into my IDE.

These are just a few of the ones I think are useful, I'm sure there are many more. If you know of any other useful ones feel free to share it in the comments.

Also I'm using Eclipse Juno for this and if you want more details on some of these views or features of the IDE the Eclipse Reference Docs is actually pretty good.

Saturday, July 6, 2013

Let's Retire the Flag

OK, 4th of July is over and it's time to put away the flags. No, I don't mean the Stars & Stripes. I'm talking about using flags in your code.
How do you end up with so many flags in your code? Well you begin innocently enough, you have a controller method that calls to a service and returns a list, so you code up something like this:



@RequestMapping(value = "/person/list/", method = RequestMethod.GET)  
      public String loadList(final Model model) {   
           final Iterable<Person> people = service.findAll();  
           model.addAttribute("personList", people);
    return "list"; 
      }  

Then surprise, the requirements change (You knew that was going to happen, didn't you?). So now we need to also filter the list. OK, no problem, we'll pass a parameter in and filter the list.
      
@RequestMapping(value = "/person/list/", method = RequestMethod.GET)  
     public String loadList(@RequestParam final String filter, final Model model) {   
           final Iterable<Person> people = service.findAll();  
           if(StringUtils.isNotEmpty(filter)){  
                //some sort of filtering here
           }  
           model.addAttribute("personList", people);  
           return "list";  
      }  

But you know what happens next, a new requirement. This time there are different types of filters, so now we start to use our flag variable
      
@RequestMapping(value = "/person/list/", method = RequestMethod.GET)  
     public String loadList(@RequestParam final String filter, final Model model) {  
           final Iterable<Person> people = service.findAll();  
           if(StringUtils.isNotEmpty(filter)){ 
                if("filterA".equals(filter){ 
                    //some sort of filtering here
                }else{
                   //some differnt filtering logic
                }
           }
           model.addAttribute("personList", people);  
           return "list";  
      }  

But now what happens if the filters are additive, like in a search. The nested ifs and the procedural code becomes really hard to maintain. Your methods become large and complex and changes become hard to make. As we add more flags, the combinations make it harder and harder to code. Our tests become hard to write, and "the other developers" you know the ones, copy and paste code, skimp on the the test, etc, etc. Your code starts to break under the pressure until nobody wants to touch the code. You might have seen code like this, you might have even written some yourself to just get something done. So what do we do? Well we have to refactor to have smaller methods that do one thing. By changing the parameter to a path variable we can use the URL to take care of the filter param. We break out our methods and eliminate one level of if statements.
  
@RequestMapping(value = "/person/list/{filter}", method = RequestMethod.GET)  
     public String loadList(@PathVariable final String filter, final Model model) {   
          final Iterable<Person> people = service.findAll();  
          if("filterA".equals(filter){ 
            //some sort of filtering here
          }else{
            //some differnt filtering logic
          }
          return list(model, people);
}      
@RequestMapping(value = "/person/list/", method = RequestMethod.GET)  
      public String loadList(final Model model) {   
          final Iterable<Person> people = service.findAll();  ;
   return list(model, people); 
      }  

private String list(final Model model, final Iterable<Person>) {
  model.addAttribute("personList", people);
  return "list";
 }

We now have a simple private method that just displays the list to the view. We should break our methods up further, such as breaking out the filtering into another method. Depending on how complex this is, we could make use of Apache commons and Predicate classes to abstract our filtering logic into a private method. Note that converting from iterable to a list and back again might not be ideal and we should probably create a service method that gives us what we need. In fact, we might also push the filtering logic back into the service layer, if so we already have the URL mappings and it would be a simple refactoring.
  
private Iterator filter(final  Iterable<Person> people, String filter) {
    Predicate predicate=...some sort of Predicate Factory here....
    Collection<Person> peopleList = new ArrayList<Person>();
    CollectionUtils.addAll(peopleList, (Iterator) people);
    CollectionUtils.filter(peopleList, predicate);
    return peopleList.iterator();
}   

After the refactoring we have much more flexibility, we could multiple filterings on a list or pass the result to a sort routine. Our methods now are small and granular, although not very useful, they are easy to read and understand. In order to make them useful we need to composite them with other methods and expose them as part of the API. This might be URLs or it could be a formal interface such as the service layer API. If we keep the methods small and specific it makes our code so much easier to read and should allow us to respond to change so much easier. So the next time you find yourself reaching for the flag, ask yourself if you really need it, or is a bit of refactoring in order.

Sunday, March 3, 2013

A Little (JUnit) Help

When you do one of those Code Katas, or have a green field project the tests are easy to write. Writing the tests as you code it makes it pretty easy to write the tests. In fact, if the tests start becoming hard to write you probably need to re-look at your code.

Unfortunately, we usually don't have this luxury, because we have the dreaded legacy code. So I've always looked for some way to help me get started on writing my unit tests. First, no I don't want something to write my tests for me, but it would be nice to be able to create some of the setup that makes it easier to get started.

So I was pretty excited when a developer on a project I was just on told me about JUnit Helper. It's an eclipse plugin that take some of the grunt work out of creating tests for legacy code. It has some options to change the mocking libraries and some of the structure of the tests. These are set by going to Windows->Preferences->JUnit Helper. The readme in the github directory has a pretty good explanation of the project so I won't go into that, instead I will show you an example of how it works.

This is a typically Spring MVC Controller with a service wired in

package org.daneking.profile.web.controller.person;

import org.daneking.profile.domain.person.Person;
import org.daneking.profile.service.PersonService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class TestController {

    private static final Logger LOGGER = LoggerFactory.getLogger(TestController.class);

    @Autowired
    private PersonService service;

    public void setService(final PersonService service) {
        this.service = service;
    }

    @RequestMapping(value = "/person/add/", method = RequestMethod.GET)
    public String loadAdd(final Model model) {
        LOGGER.info("Get Request to add");
        return add(model, new Person());
    }

    private String add(final Model model, final Person person) {
        model.addAttribute("person", person);
        return "add";
    }

    @RequestMapping(value = { "/person/add/{id}" }, method = RequestMethod.POST)
    public String save(@Validated final Person person) {
        LOGGER.info("Saving a person");
        final Person persistedEntity = service.save(person);
        // Verify persons was saved
        Assert.notNull(persistedEntity);
        LOGGER.info("Save Person");
        // Post Redirect Pattern to prevent double submits
        return "redirect:/person/list/";
    }

}
And here is the test it generated

package org.daneking.profile.web.controller.person;

import org.daneking.profile.web.controller.person.TestController.*;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import org.junit.Test;
import static org.mockito.BDDMockito.*;

import java.util.Iterator;
import org.daneking.profile.domain.person.Person;
import org.daneking.profile.service.PersonService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
public class TestControllerTest {

    @Test
    public void type() throws Exception {
        // TODO auto-generated by JUnit Helper.
        assertThat(TestController.class, notNullValue());
    }

    @Test
    public void instantiation() throws Exception {
        // TODO auto-generated by JUnit Helper.
        TestController target = new TestController();
        assertThat(target, notNullValue());
    }

    @Test
    public void loadEdit_Accepts_Long_Model() throws Exception {
        // TODO auto-generated by JUnit Helper.
        TestController target = new TestController();
        // given
        Long id = null;
        Model model = mock(Model.class);
        // e.g. : given(mocked.called()).willReturn(1);
        // when
        String actual = target.loadEdit(id, model);
        // then
        // e.g. : verify(mocked).called();
        String expected = null;
        assertThat(actual, is(equalTo(expected)));
    }

    @Test
    public void loadAdd_Accepts_Model() throws Exception {
        // TODO auto-generated by JUnit Helper.
        TestController target = new TestController();
        // given
        Model model = mock(Model.class);
        // e.g. : given(mocked.called()).willReturn(1);
        // when
        String actual = target.loadAdd(model);
        // then
        // e.g. : verify(mocked).called();
        String expected = null;
        assertThat(actual, is(equalTo(expected)));
    }

    @Test
    public void save_Accepts_Person() throws Exception {
        // TODO auto-generated by JUnit Helper.
        TestController target = new TestController();
        // given
        Person person = mock(Person.class);
        // e.g. : given(mocked.called()).willReturn(1);
        // when
        String actual = target.save(person);
        // then
        // e.g. : verify(mocked).called();
        String expected = null;
        assertThat(actual, is(equalTo(expected)));
    }

    @Test
    public void loadList_Accepts_Model() throws Exception {
        // TODO auto-generated by JUnit Helper.
        TestController target = new TestController();
        // given
        Model model = mock(Model.class);
        // e.g. : given(mocked.called()).willReturn(1);
        // when
        String actual = target.loadList(model);
        // then
        // e.g. : verify(mocked).called();
        String expected = null;
        assertThat(actual, is(equalTo(expected)));
    }

    @Test
    public void filteredList_Accepts_String_Model() throws Exception {
        // TODO auto-generated by JUnit Helper.
        TestController target = new TestController();
        // given
        String filter = null;
        Model model = mock(Model.class);
        // e.g. : given(mocked.called()).willReturn(1);
        // when
        String actual = target.filteredList(filter, model);
        // then
        // e.g. : verify(mocked).called();
        String expected = null;
        assertThat(actual, is(equalTo(expected)));
    }

    @Test
    public void deleteById_Accepts_Long_Model() throws Exception {
        // TODO auto-generated by JUnit Helper.
        TestController target = new TestController();
        // given
        Long id = null;
        Model model = mock(Model.class);
        // e.g. : given(mocked.called()).willReturn(1);
        // when
        String actual = target.deleteById(id, model);
        // then
        // e.g. : verify(mocked).called();
        String expected = null;
        assertThat(actual, is(equalTo(expected)));
    }

    @Test
    public void details_Accepts_Long_Model() throws Exception {
        // TODO auto-generated by JUnit Helper.
        TestController target = new TestController();
        // given
        Long id = null;
        Model model = mock(Model.class);
        // e.g. : given(mocked.called()).willReturn(1);
        // when
        String actual = target.details(id, model);
        // then
        // e.g. : verify(mocked).called();
        String expected = null;
        assertThat(actual, is(equalTo(expected)));
    }
   @Test
   public void setService_Accepts_PersonService() throws Exception {
 // TODO auto-generated by JUnit Helper.
        TestController target = new TestController();
 // given
 PersonService service = mock(PersonService.class);
 // e.g. : given(mocked.called()).willReturn(1);
 // when
 target.setService(service);
 // then
 // e.g. : verify(mocked).called();
   }

}
 
 OK, what did this give us and what's left to do. Well first these tests probably won't pass. For instance, the controller makes a call to save, but because the save method is not mocked it would fail. Also, to get the service to mock I had to change the default preferences to mock setter methods. I would also move the creation of the controller and the mock service to a setup. But it actually got a lot of my setup done I just have to move it around.

I'm still playing around the plugin and with some of the preference modifications. One thing I did was change the default Accepts, Throws and Returns and set my mocking preference. One gotcha I discovered is if you import a project into your workspace, for instance a github project, it will try to create the test in your workspace and not where the project is. This is mostly minor stuff though, and for getting some legacy code test cranked out it seems pretty useful.

Thursday, February 28, 2013

Why Did You Go And Make It So Complicated?

We usually add complexity because we want things to be flexible or reusable  But sometimes are drawn to make things more complicated. How many times have you heard after you present a design or a solution to a problem, yeah that's great but what if they change X or Y?  Why is flexibility and complexity our default option?

In the book Java Application Architecture Kirk Knoerschild talks about this use/reuse paradox. When we make things simple and usable with few dependencies the aren't very reusable. But they are easy to change and maintain. If we try to make things reusable, they become more complex and have more dependencies. Simply put flexibility leads to complexity which costs both time and money and makes the code harder to use.

So what is a developer to do? Well one way that Martin Fowler recommends is to build the system and evolve the flexibility through refactoring into common code or frameworks. I think that's great on systems that you get a chance to evolve or where refactoring time is hard to come by.

One thing that I've had some success with is make small usable components and composite them into more complex flexible components. This is not a perfect strategy, it actually takes some discipline to just focus on small components. However because you are relying on underlying simple components the cost of changing it is somewhat easier. You are also more likely to be able to easily rearrange the components to create other complex components.

We did this on JSP tags on my last project and it went well for the most part. There were sometimes when we didn't follow the pattern completely, but I think it created a decent framework for easily creating our Web pages. As I become more comfortable with doing this, I think there are more opportunities to use this kind of pattern, I've recently started to look at ATDD and I think the step definitions could be written in this manner.

We have to resist the push for flexibility and complexity. We need to communicate how, for instance, having a complex validation for a field increases coding and testing time and makes fixing defects and changes in the future harder. I think if we present the costs of the flexibility in this way, we can be more intentional when we choose to add complexity to our application and it will make our lives much more simpler.


Tuesday, January 8, 2013

The Reluctant JavaScript Developer

If  you are like most of the Java developers I know, you know "just enough" JavaScript to get by. You might not consider JavaScript a real language and would rather concern yourself with OOP and SOA and a host of other acronyms. JavaScript is indeed a language and a dynamic, flexible and very powerful one at that. Those same traits can also make it complex, hard to debug and error-prone. The good news is some of the same principles of OOP that you have learned over the years can also apply to JavaScript and by using a few simple techniques make your front-end code more manageable and hopefully save you from pulling too much of your hair out.

While I'm not suggesting you have to be an expert in everything you do, at least you should try to avoid it being a glaring weakness, especially if you make your living writing Web apps. I had the good fortune to work with some really good UI developers that have really helped me understand the front-end portion of web developing. The main thing they taught me is that with just a little studying and  practice can save you alot of headaches in the long run.

We might as well start at the beginning. Most beginners code everything into the page with a script block that looks something like this. This isn't all bad, I sometimes like to write my code in the page to get it to work like in step one before I re-factor.

 <html>  
 <body>  
 <script>  
 function one_test(){  
      alert('this is cool');  
      }  
 function two_test(){  
      alert('you bet it is');  
 }  
 </script>  
 </body>  
 </html>  

While that certainly works it is less than ideal. One problem with this is your web page becomes very hard to read and hard to change. And just like we  re-factor our Java code out into other classes we need to pull Javascript into external files. This has a few advantages like make code reusable, testable and being able to control when it is loaded in the DOM.

 <html>  
 <head>  
 <script src="my_file.js"></script>  
 </head>  
 <body>  
 <script>  
    one_test();  
    two_test();  
 </script>  
 </body>  
 </html>  

And my file (my_file.js).....


 function one_test(){  
      alert('this is cool');  
      }  
 function two_test(){  
      alert('you bet it is');  
 }  


Great now everything is in an external file and we're done!!! No, not quite. One problem we have is name spacing. Everything we declare is global and available everywhere. If we have another script and it has a function with the same name we will have a problem. As good Java developers we know this is not a good solution, and if you have ever had to debug something like this in some complex code with dynamically loaded pages it can be a real pain.

So what do we do? Well, just like Java gives us classes to encapsulate our code, JavaScript gives us something to encapsulate our code. The first one I will talk about is the Object Literal. And its coded like this.

 var myobject={  
      one_test:function(){  
           alert('this is cool');  
      },  
      two_test:function(){  
           alert('you bet it is');  
      }  
 }  

We are wrapping our functions, separated by commas, between brackets {..} and setting the result equal to a variable. And we change our HTML code to this

 <html>  
 <head>  
 <script src="my_file.js"></script>  
 </head>  
 <body>  
 <script>  
   myobject.one_test();  
   myobject.two_test();  
 </script>  
 </body>  
 </html>  

Now we could have another function called two_test but wrapped in another object and they wouldn't conflict, just like in Java if we have a method called foo() and its called from 2 different classes we could expect it to call different code.

You may also note that I now have two script blocks, one declaring the file and one calling. This is not really ideal and I'm doing it this way just for this example. Best practice is to use an external library to 'decorate' things like links and buttons and anything else with our JavaScript behavior so we could eliminate the second script block, but I'll save that for another post.

To a Java developer the best way to think of this is a Map and everything inside the Object Literal is a key value pair. That is why the syntax is name function pairs are separated by a comma, if we wanted a variable it would be similar
 var myobject={ 
      x:'test', 
      one_test:function(){  
           alert('this is cool');  
           return 'what is happening';  
      },  
      two_test:function(){  
           alert('you bet it is');  
      }  
 }  
And we would call it like
 <html>  
 <head>  
 <script src="my_file.js"></script>  
 </head>  
 <body>  
 <script>  
      alert(myobject["x"]);
 </script>  
 </body>  
 </html>  

So if we call the object with our key it will return a function and then the () will execute the function. So myobject is our reference to the map and one_test is the key which returns the function and the () executes it. To really see this, change the line myobject.one_test() to document.write(myobject.one_test), this will print out the body of the function to the DOM.

So, now all our functions are encapsulated and we are happy. Most of us stop here and that's OK. Just wrapping in Object Literals is often enough. However there is one more re-factoring we could do. We can wrap the Object Literal in a function. I know the abstractions are getting ridiculous a function wrapped in a function and if you are using a library like JQuery, you are probably wrapping it another function. Well the problem is everything in our Object Literal is public. We can't declare private variables or private functions. What we need is something like an interface, fortunately JavaScript gives us the ability to do that. Also the good news is that the calling code from the HTML will be the same. In this case our interface is going to return the same Object Literal that we were already referencing with some slight changes to the internal references.

Our final version will look like this

 var myobject=function(){  
      var my_str="--- really, really cool";
      function internal_one(){  
           alert('this is cool' + my_str);  
      }  
      function internal_two(){  
           alert('you bet it is' + my_str);  
      }  
      return{  
      one_test:internal_one,  
      two_test:internal_two  
      }  
 }(); 

Some things to note, I added () last lines of the function, this is to call the function so it will return the Object Literal into the global namespace. If I don't do this I have to change the calling code to myobject().one_test().

The return portion is the same as my Object Literal, and notice now I call the private variables from my functions and reference the private functions with internal names. Without getting too complicated, Javascript is able to take those internal references, bundle them up and pass them along with the Object Literal. This is known as a closure and it contains all the things from the execution environment to make the calls back into the functions.

So while these methods seem complex and hard to understand, with a little practice they do become common place. By applying these simple re-factorings to your JavaScript code, it will make it easy for the next developer to read and debug your code and you never know, that next developer just might be you.