Asier's thoughts

Blogging about software development


Leave a comment

This site has been migrated

I just migrated this blog to asierba.github.io.

I also changed the dns entry of asierba.net to point there, so you shouldn’t be able to get to this blog through asierba.net. If you are, let me know please.

If you are seeing this post as part of your rss reader that means you are subscribed to the wrong rss feed. Please update it: asierba.net/feed

I won’t be posting any more here (asierba.wordpress.com), so expect this site to die.

 

More info about the migration here: http://asierba.net/2017/02/23/from-wordpress-to-jekyll/

 


Leave a comment

Judge the code, not the developer

I’ve been paying attention recently to conversations we have at work. I can hear people complaining about the code, how bad it is, not readable, difficult to make changes.. They will refer to the people who wrote it. And I do it too! Even if we don’t know who wrote it. It doesn’t matter, is ‘us’ and ‘then’.

  • They wrote this crazy stuff.. why??”
  • somebody had this idea of creating this hierarchy of classes. Look now, how can we extended this class without affecting this other??”
  • “look, a developer added an extra call to the service here. This is making our application not to perform well.”

We are judging the people, instead of the code. This just creates tension between co-workers. It creates a difference between the person who wrote the ugly code and us. We are kind of saying they don’t know how to write code, do they job properly.. ultimately we are just saying they are inferior and that we are better than them. We judge them.

We can just change our aptitude if we detach the code from the people.

  • “this crazy stuff.. why??”
  • “this hierarchy of classes. Look now, how can we extended this class without affecting this other??”
  • “look, there is an extra call to the service here. This is making our application not to perform well.”

We would still be stating the same thing: the code is bad, not readable, difficult to make changes.. BUT we won’t be judging people, our co-workers, our team mates. We will be all in the same boat seeing the same problems and ultimately fixing them together.


Leave a comment

Automocking dependencies in unit tests for C# with AutoFixture

If you have been unit testing for a while you would have come to the following problem:

You have a class that talks to different classes. These dependencies are injected to your class through the constructor. You would have a test like the this:

    [Fact]
	public void SomeTest()
	{
		var dependency1stub = new Mock<IDependecy1>();
		var dependency2mock = new Mock<IDependecy2>();
		dependency1stub.Setup(x => x.SomeQuery()).Returns(2);

		var sut = new SUT(dependency1stub.Object, dependency2mock.Object); 

		Assert.Equal(4, sut.GetDoubleValue(2));
		dependency2mock.Verify(x => x.SomeComand());
	}

I guess you would have more than one test against this class, probably many. Each of them calling to the constructor of the object with its dependencies.

Now, what happens if you change the dependencies? What happens if you add one dependency extra to this class? You will have to go one by one through all the tests and change the line of code where new SUT(…) is present.

var sut = new SUT(dependency1stub.Object, dependency2mock.Object, dependency3mock.Object);

What if you have dozens or hundreds of tests against that class?? That could be kind of painful! I can already heard you saying..

test are slowing me down!

Well, wait! Bear with me.

First thing to notice here is that using the “new” keyword is a code smell and should be avoided when possible. Each time you use new you are coupling that code to a particular implementation. In this case, we are coupling the tests to construction of the system under test and ultimately to the de injection of its dependencies. We should avoid this as much as possible. Let’s see how we can fix this.

The easiest approach would be to create a test setup and move the object initialisation there, this way that code will get shared through all the methods in the test class. If dependencies change we will have to update JUST the code there.

        private Mock<IDependecy1> _dependency1stub;
        private Mock<IDependecy2> _dependency2mock;
        private SUT _sut;

        public Tests() // Test setup in xUnit is the constructor
        {
            _dependency1stub = new Mock<IDependecy1>();
            _dependency2mock = new Mock<IDependecy2>();

            _sut = new SUT(_dependency1stub.Object, _dependency2mock.Object);
        }

        [Fact]
        public void SomeTest()
        {
            _dependency1stub.Setup(x => x.SomeQuery()).Returns(2);

            Assert.Equal(4, _sut.GetDoubleValue(2));
            _dependency2mock.Verify(x => x.SomeComand());
        }

However, with this approach still we will have to change code. It’s not nice, our code is not open for extesion and closed for modification. We are violating the Open-Closed principle.
Also, what if your system under test is called from different test classes? You will still have to change all setups for those test classes.
You can improve things using a SUT factory. But still you will have to change the code inside the factory each time.

A better approach would be to use a external library like Autofixture that can automock and autoinject those dependencies. We will let Autofixture to do the job of object initialisation for us.

        [Fact]
        public void WithAutoFixture()
        {
            var fixture = new Fixture();
            fixture.Customize(new AutoMoqCustomization()); // set up automocking

            var dependency1stub = fixture.Freeze<Mock<IDependecy1>>();
             var dependency2mock = fixture.Freeze<Mock<IDependecy2>>();
            dependency1stub.Setup(x => x.SomeQuery()).Returns(2);

            var sut = fixture.Create<SUT>(); // initialise object with mocked dependencies 

            Assert.Equal(4, sut.GetDoubleValue(2));
            dependency2mock.Verify(x => x.SomeComand());
        }

If you now add a new dependency to the constructor of the SUT this test still will compile and pass. You don’t care any more about object construction and your tests are not fragile any more!
So you can keep doing TDD and stop complaining how tests are slowing you down!

Happy coding! 🙂

PS I know you can also do this in Machine.Specifications with Machine.Specifications.AutoMocking or Machines.Fakes. I highly recommend the last one if you are using Machine.Specifications.


Leave a comment

Standardisation kills innovation

I’ve recently re-watched the video from Spotify about their culture at work. It’s a really cool video, if you haven’t watched it yet you should. I’ll wait.

Part 1

And part 2

It’s been a year since I first watched it. I understand now much better many of the things they talked about. I guess because these are things I have experienced through the last year.

One of the things that stuck in my head is that autonomy is more important than standardisation.

In Spotify teams are quite autonomous. They make their decisions based in their own rules instead of following some general company rules. Rules are not good when you want innovation. Standardisation kills innovation. How can you try new things if each time you want you have to change some rule in the company? How can you learn? How  you grow? Isn’t it better to keep this rules down just to the team? You will just have to convince your team instead of the whole company!

I’ve seen a pattern coming into place in software companies who are changing from product to project teams, they are adopting standards! In these companies teams instead of working in a specific product in a company work in different products all the time. Each product will be changed by more than one team through its lifetime. In order to make everybody’s life easier everybody will have to be on the same page. Therefore the need to standardise everything: which tools to use, frameworks, naming conventions, coding standards, methodologies, ways of testing, branching, deployments, code reviews, how to write a commit message.. You need to have the same rules for every team so changing from one product to another it’s not a pain in the ass..

Now, let’s say you or your team doesn’t like one of these “rules” or just thinks it could be improved. Good luck if you want to change any of that easily.
Standards make change hard, they give no much autonomy to teams and makes continuous improvement difficult. And autonomy it’s important not just for innovation, also for job satisfaction as mentioned in Drive: The surprising truth about what motivates us.


2 Comments

Implicit vs Explicit Waits in selenium

The last few days at work we have been fixing some intermittently failing tests in selenium. In the process I came to learn the difference between implicit and explicit waits.

The needs of waits.
When running a test against an application UI sometimes you need to wait for an element to be present. This could be due to the whole interface taking time to fully load or just a small part of it.

When we jumped to fix these tests we saw that they were doing what they mean-to and that the application was really doing what the tests said, but the problem was down to page or elements or the page loading slower that expected. Waits would be our allies in our battle.

Two types of waits
There are two type of waits you can use in Selenium: implicit and explicit waits.

  • Implicit waits are defined for the whole test suite.
    Every time the selenium driver tries to find an element on a page it will wait a certain amount of time before throwing an element not found error.
    By default the implicit wait is 0, this means the driver won’t wait at all.
    This is how you define the implicit wait of 3 seconds:

    Driver.Manage().Timeouts()
    .ImplicitlyWait(TimeSpan.FromSeconds(3));

    Each time the driver looks for an element (i.e using Driver.FindElement(..)) it will wait 3 seconds before failing. If it finds it before it will continue with the test run.

  • Explicit waits are defined just for a single purpose.
    For example we could wait for a progress bar to finish, a pop up to hide or an element to render.
    This is how you define an explicit wait for the body element of 5 seconds:

    var wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(5));
    wait.Until(d => d.FindElement(By.TagName("body")));

    If the driver doesn’t find the html “body” element in the page within 5 seconds it will throw an exception. If it finds it before it will continue with the test run.

For both cases the driver will constantly check for UI changes. If the the element is present before the time it will continue, it won’t keep waiting.

Favour explicit over implicit waits
By rule of thumbs you should favour explicit waits over implicit. If your tests is failing because certain element takes time to load add a explicit wait for that element. You could also fix the problem adding an implicit wait, but that would affect the whole test suite and make tests slower and you wouldn’t be addressing the underlying problem.
In the other hand, sometimes the whole website could be slow and pages would always take a few seconds to load. In those cases it’s ok to add implicit waits, but I wouldn’t recommend any more than 2-3 seconds.

[+] info:


Leave a comment

Thinking is the bottleneck

I just spend almost two days with a bug fix at work. The fix was just a one line code change!

This kind of things make you think. We as developers spend a lot more time reading and understanding code than writing it. Knowing where and how to do the code change is the important bit, but getting to there is the difficult bit. Specially when you are dealing with code which is hard to understand.

Many managers (and sadly also some developers) don’t understand that in software development typing is not the bottleneck. It is expected from developers to write loads of code, the more the better, if it’s faster even better. But the thing is that we are problem solvers, not code monkeys. The goal of each feature we release is to solve a particular business problem, not to put some code in a server..

Having this in mind is important to take the right approach. Thinking is the bottleneck . Getting to the solution is the hard bit.

That’s why things like pair programming should be taking into account, two people will get to a solution faster working together than separately. Things like keeping your code “clean” matters, if you write code that shows its intent and is inline with the business domain it would be easier to understand and get to the solution faster. It’s also important to have conversations often with the business because it will make you understand the real problem and get to the solution faster. And many more..

The point I am trying to make here is that you shouldn’t think that we are here to write code, we are here to solve problems!


5 Comments

Care

I got to the conclusion that the successful delivery of software is all down to care.

If you have developers who care they will write clean code, with unit test and follow TDD approach. The code will be easy to change, enabling the business to make quick decisions against the market so they can beat their competitors.

If you have product owners (or project managers) who care they will try to bring the best features to their products. They will speak to developers and testers and define together the best possible solutions and refine their features in the process.

If you have testers who care they will try to understand the features that are being request to be developed. They will stablish conversations with business people and developers so they will know which tests to write in order to verify the product is working as expected.

If you have operations people who care they will enable their systems for easy deployments. They will talk with developers and give them the power to easily change their code in production while giving technical advise.

In general, if you have people who care they will try to do their best while looking for ways to improve.

If you are one of that many companies struggling with your software delivery my advise is simple: hire people who care! That would be the first step, after that everything will come together slowly.


Leave a comment

Giving estimates

Why do we estimate?

We, the delivery team, estimate so we can predict the time is going to take us to finish a task. It could be a new feature, a bug fix or whatever. This way business people can have a rough idea of how long is going to take to have a code change in place.

But this is just an estimation. Not a commitment. We can’t say it’s going to take us 3 days and then rate success or failure depending if we met that estimate or not.

We are humans and we are not good making predictions. We are optimistic. Even if we could predict exactly how long a task will take many things could happen in between that we weren’t expecting.

Making predictions for long projects it’s even worse. If we are bad estimating for small tasks imagine adding up all those deviations.. Estimating a whole project it’s wrong. And that’s why we have agile or things like #norprojects. Even #noestimates.

So what do we do?

First, we are aware. Estimates are going to be wrong. So we will tell the business that our estimates are just predictions and tell them we are giving just a guess.

They are going to be wrong specially in the long term. So we will give estimates to the business within a sprint, one week or two weeks should be the longest. If they ask for a feature that it’s not within the scope of the current sprint we will say “Sorry, I don’t know”. If somebody comes and ask “when do you think the project will be finished?” we will say “Sorry, we don’t know. I could give you a day to make you happy but that would be just lying and I don’t want to.”

So we will be honest. We will be professionals and don’t tell lies to our managers or business people just to make them happy for the time being. Managers want to know when things are going to be finished so they can put in place all their figures and budgets and all of that, but using estimates for that it’s just lying. Also if we are working in a feature and we find an impediment which is going to slow us down, we will say it as soon as possible.

We will build trust.


Leave a comment

Learning how to learn

I feel lucky to be a software developer. Things are changing rapidly around us these days. New languages, frameworks, libraries, methodologies, patterns are showing up every day. So quickly that it’s frightening, you have to keep learning all the time! I see this as an opportunity. An opportunity to learn how to learn and get better at it. Here some tricks I’ve been following:

First, failing is learning. So be aware of that. We learn from mistakes. The pain of a failure will make you not to repeat that mistake again, it’s the quickest way to learn. So fail fast. The faster you fail, the faster you will learn.

This reminds me a quote from Batman begins:

Bruce: I wanted to save Gotham. I failed.

Alfred: Why do we fall sir? So that we can learn to pick ourselves up.

But failing is not enough, you have to learn from reflection. Each time you fail observer the failure. Why did it happen? How can I avoid it next time? Don’t get attached to the feeling of failure – this is difficult.

This is not just for failures. Every day, every week, every year look into yourself. What have you achieved? What did you do wrong, what did you do right? Why? Think, observe yourself and learn from it. This is in-line with the great Eastern cultures like Buddhism where contemplation is a big thing.

You have to also explore. In order to learn new things you have to try new things. Obvious, right?  We all are used to doing the same things over and over again every day. We are lazy. We are afraid to fail when trying something new. But that’s silly. You should try to do new things, if not how would you discover them?

To make the best of this your have to get out of the comfort zone. Do things that you wouldn’t do normally because you would be afraid to fail. Failing is learning, so it’s okay if you fail. Explore as much as you can without the fear of failing. Do crazy things if you have to.

Embrace Kaizen philosophy and continuously improve. Always seek for perfection. Fail, reflect, learn and improve. Rinse and repeat. Every time getting a bit better. Be ambitious.

And the most importantly, make it fun. Learning should be fun, find that motivation.

As I said, being a software developer forces me to learn fast and get better at it. The thing is that this is a skill that you can apply not just to software, but to your life in general!


2 Comments

Command returns true/false for success/error

I’ve seen this kind of pattern usually when working with web services.

Imaging the following piece of code:

public bool RunCommand()
{

    // .. Some logic ..

    return true; // success

}

Basically we have a method in a class that executes some logic, if this is successful it returns a true, if not a false. At first you would say this make sense, right?

It kind of reminds me the days when I was learning C 🙂

But this is just over-complicating things. Any client of this method will have to add a check.


if(RunCommand()) {
  // everything good

  // Show user success message

} else {

  // error!

  // show user something went wrong

}

Why not just assume that the method is going to be execute successfully? If not just throw and exception! Then just handle that exception. Simple!

Just adding the true/false return for success/error is basically re-implementing exceptions. Well, it’s even worse. Exceptions are explicit, they mean that something went wrong, they even have a custom error message. A boolean just means that.. a boolean: true or false, it’s open to interpretations. When we get a false it could mean anything, no error message, no custom exception.

Also returning values from command methods is a bad practice. You should have two kind of methods: querys that return values but don’t change anything in your system and commands that change something but return nothing! This is known as CQS or Command and Query Separation.