Posts by Arthur Arts

Scala Snippet: How to filter a list in Scala

Posted on by  
Arthur Arts

In Scala, filtering and processing collections is easy and elegant. There are many filtermethods available, but the most used will probably the basic filter method. Here's a code example of some filtering on my (ex)camera collection. The filter method will not only work on Lists, but on any Scala collection.

object MyCameraCollection02 {

  case class Camera(brand: String, model: String, sensorType: String, yearBought: Int) {
    override def toString: String =
      s"$brand $model \t\t $sensorType \t($yearBought)"
  }

  def main(args: Array[String]) {
    val canon5dmarkIII = new Camera("Canon", "5D MkIII", "FF", 2013)
    val canon5dmarkII = new Camera("Canon", "5D MkII", "FF", 2009)
    val canon6d = new Camera("Canon", "6D", "FF", 2014)
    val canon550d = new Camera("Canon", "550D", "APS-C", 2010)
    val canon40d = new Camera("Canon", "40D", "APS-C", 2008)
    val canonIXUS330 = new Camera("Canon", "IXUS 330", "1/2.7", 2001)
    val canonIXUSZ90 = new Camera("Canon", "IXUS Z90", "APS-C", 1999)
    val panasonicGM1 = new Camera("Panasonic", "GM1", "M43", 2014)
    val panasonicFZ20 = new Camera("Panasonic", "FZ20", "1/2.5", 2005)
    val sonyrx100 = new Camera("Sony", "DSC-RX100", "1\"", 2013)
    val sonynex5 = new Camera("Sony", "NEX-5", "APS-C", 2011)
    val sonyr1 = new Camera("Sony", "DSC-R1", "APS-C", 2005)

    val myCameras = List(canon5dmarkIII, canon5dmarkII, canon6d, canon550d, canon40d, canonIXUS330, canonIXUSZ90, panasonicGM1, panasonicFZ20, sonyrx100, sonynex5, sonyr1)
    val canonCameras = myCameras filter (_.brand == "Canon") // Every Canon camera I ever owned
    val sonyCameras = myCameras filter (_.brand == "Sony") // Every Sony camera I ever owned
    val pansonicCameras = myCameras filter (_.brand == "Panasonic") // Every Panasonic camera I ever owned


    // apscCamera's only
    val apscCameras = myCameras filter (_.sensorType == "APS-C")
    println("==APS-C camera's owned==")
    apscCameras foreach println
    println()


    // Canon camera's which are not full frame. You can filter, filtered lists.
    val canonNonFF = myCameras filter (_.brand == "Canon") filter (_.sensorType != "FF")
    println("==Non-FF camera's owned==")
    canonNonFF foreach println
    println()

    // Filter by boolean expressions on class properties
    val apsBefore2012 = apscCameras filter (_.yearBought < 2012)
    println("==APS-C camera's bought before 2012 owned==")
    apsBefore2012 foreach println
    println()

    // Filter by combining boolean expressions.
    val ffcamerasBefore2012 = myCameras filter (cam => cam.yearBought < 2012 && cam.sensorType == "FF")
    println("==Every FF Camera I ever owned before 2012==")
    ffcamerasBefore2012 foreach println
    println()
  }
}

Continue reading →

Scala Snippet: multiline statements in the Scala REPL console

Posted on by  
Arthur Arts

One of the coolest things a standard Scala install will give you, is the Scala interpreter. Technically speaking, this is not an interpreter. In the background, each statement is quickly compiled into bytecode and executed on the jvm. Therefore, most people refer to it as the Scala REPL: Read-Evaluate-Print-Loop. You can access it by starting a command shell on your system and typing in 'scala'. Do make sure your either run it from the place where scala is installed or have scala on your environment PATH. By using the repl, you can quickly experiment and test out different statements. Once you press ENTER it will evaluate the statement and display the result. Frequently you want to execute multi-line statements and luckily the repl has a solution for that. Simply type in :paste and the repl will accept multiline statements. To exit this mode and evaluate your code, simply type CTRL+D. Example:

$ scala
Welcome to Scala version 2.11.4 (Java HotSpot(TM) Client VM, Java 1.7.0\_75).
Type in expressions to have them evaluated.
Type :help for more information.

scala> :paste
// Entering paste mode (ctrl-D to finish)

class Camera {

//this is a multiline example in the REPL

 val brand:String = "Canon"
 val model:String = "5D mark III"
}

// Exiting paste mode, now interpreting.

defined class Camera

scala> val cam = new Camera
cam: Camera = Camera@bfd117

scala> cam.brand
res0: String = Canon

Continue reading →

Bruce Lee's Top 5 Agile Coaching Tips

Posted on by  
Arthur Arts

When I was a kid, I was a big Bruce Lee fan. I walked around the playground rubbing my nose with my thumb. When I had a piece of rope, I had to do my version of the nunchaku routine from Way of the Dragon and made cat-like noises. Looking back at Lee, I find it quite striking how many of the principles of his fighting style Jeet Kun Do apply to agile practices. Check out these descriptions of the fighting style:

  • "Jeet Kune Do is not fixed or patterned, and is a philosophy with guiding thoughts."
  • "Jeet Kune Do practitioners believe in minimal movements with maximum effects and extreme speed."
  • "The system works by using different "tools" for different situations, where the situations are divided into ranges, which is kicking, punching, trapping, and grappling, where martial artists use techniques to flow smoothly between them. "
  • "Through his studies Lee came to believe that styles had become too rigid and unrealistic. He called martial art competitions of the day "dry land swimming". He believed that combat was spontaneous, and that a martial artist cannot predict it, only react to it, and that a good martial artist should "be like water" and move fluidly without hesitation."

Continue reading →

Scala Snippet: Object, Companion Object and Static Methods

Posted on by  
Arthur Arts

If you are a Java developer moving to Scala, one notable difference in terminology that can cause confusion is the term 'object'. In Java an object is always an instance of a class, created by calling a constructor.

In Scala an object is used for defining a single instance of a class with the features you want. In practice this means you will use it:

Continue reading →

Scala Snippet: Case Class vs plain ordinary Class

Posted on by  
Arthur Arts

In Scala there exist the construct of a 'case class'. According to Martin Odersky this supports you to write a "regular, non-encapsulated data structure". It always seems to be associated with pattern matching. So when to use a case class and when to use a 'plain' class? I found this nice explanation stating: _"Case classes can be seen as plain and immutable data-holding objects that should exclusively depend on their constructor arguments. This functional concept allows us to

  • use a compact initialisation syntax (Node(1, Leaf(2), None)))
  • decompose them using pattern matching
  • have equality comparisons implicitly defined

Continue reading →

Scrum Master Tip: Make it transparent!

Posted on by  
Arthur Arts

I am frequently asked by colleagues for advice on how to be a good Scrum Master. I will discuss some of the tips I share in a couple of blog posts. First of all I do like to state that I believe it's best to have a Scrum Master that is able to get his hands dirty in the activities of the team (i.e. coding, analyzing, designing, testing etc.). It will enable him/her to engage and coach at more levels than just overall process. In my opinion one of the most important things a Scrum Master has to do is to make things transparant for the whole team. Now this seems like very simple advice, and it is. However, when you are in the middle of a sprint and all kinds of (potential) impediments are making successfully reaching the sprint goal harder and harder, the danger of losing transparency always pops up. Here are three practical tips:

  • Is it clear for everybody what we as a team should  focus on right now?
  • Is everybody focussing on the things that we should focus on right now?
  • Are we going to reach our sprint goal?

Continue reading →

Mock a superclass method with Mockito

Posted on by  
Arthur Arts

Say you want to test a method from class which extends some kind of superclass. Sometimes you can be dependent on code in the superclass, which is undesirable in a test. Now actually, the first thing you should consider is to refactor your code, because it’s violating the Single Responsibility design principle: there is more than one reason why your class is subject to change. Another advice is to favor composition over inheritence. In this way you can mock the code you are collaborating with. Having said that, sometimes you run into legacy code you just have to work with and aren’t able to refactor due to circumstances. Here’s a trick I found on Stackoverflow to “mock” a superclass method to do nothing with mockito.

public class BaseController {

     public void method() {
          validate(); // I don't want to run this!
     }
}
public class JDrivenController extends BaseController {
    public void method(){
        super.method()
        load(); // I only want to test this!
    }
}

@Test
public void testSave() {
    JDrivenController spy = Mockito.spy(new JDrivenController());

    // Prevent/stub logic in super.method()
    Mockito.doNothing().when((BaseController)spy).validate();

    // When
    spy.method();

    // Then
    verify(spy).load();
}

Continue reading →

The Quick & Dirty Fraud

Posted on by  
Arthur Arts

If you have a car, then every once in a while, you probably have your vehicle checked to see if it's still up to safety and environmental standards. So you take your car to the garage and have it checked. Now, the garage will do some tests and eventually you'll get a nice paper showing what kind of maintenance they have done.

Nowadays, cars are complex, computerized machines. (The days of dad lying under the car to do some fixing with some elemental tools are all but gone.) This means that as a customer, you will have to rely on the professional capabilities and integrity of the garage. You'll have to trust that if the garage says the car is fixed and okay, it really is fixed and okay. Now imagine that you went to the garage, received the paper that your car is okay, go on the road, and your car breaks down. What would be your reaction? You'd probably hold the garage responsible for this, as they are the experts and you paid them to do a good job. What would your reaction be if they told you that they didn't have time to correctly solve your cars problems and did a 'quick fix', without them telling you?

Continue reading →

The Lean-Agile Connection

Posted on by  
Arthur Arts

Most people working in professional IT-driven companies, have heard about Agile, most people in professional companies have heard about Lean. Those who are interested in the subject, have found out that these two very popular phrases are actually closely related. So what is the relation between lean and agile? I'll try to briefly answer this question and will start with a little history.

Contrary to popular belief, the origins of Lean aren't in Japan, but derive from the Ford company in America and the work of the American statistician W. Edwards Deming. The following excerpt states the heart of his philosophy:

Continue reading →

Tasty Test Tip: Test final and static methods with PowerMock and Mockito

Posted on by  
Arthur Arts

Two of the most famous mocking frameworks EasyMock and Mockito, don't offer out of the box support for mocking final and static methods. It is often said on forums that "you don't want that" or "your code is badly designed" etc. Well this might be true some of the time, but not all of the time. So let's suppose you do have a valid reason to want to mock final or static methods, PowerMock allows you to do it. Here's how (example with Mockito):

 <dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>1.4.12</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito</artifactId>
    <version>1.4.12</version>
    <scope>test</scope>
</dependency>

Continue reading →

shadow-left