Posts Tagged ‘scala’

Gambling with Scala pt.1

Posted in java, programowanie on March 27th, 2012 by Wojciech Soczyński – Be the first to comment

For some time I was eager to write some sample application that will be using Scala and the Akka actors framework. The main problem was to pick up an example, that would make sense to apply both technologies. The idea for the example came to me all of sudden, when I was sitting with my friends after a soccer game. Usually, when you play a game, you are talking about it right after it ends, but this time it was different. My colleagues were talking about poker !

read more »

Wiedz, że coś się dzieje…

Posted in architektura, java, programowanie on March 21st, 2012 by Wojciech Soczyński – 6 Comments

Ostatnimi czasy, mam okazję tworzyć dość duże ilości testów jednostkowych. Zwykle tworze je do cudzego kodu, co pozwala mi w pewnym sensie ocenić jego jakość. Zapytacie może, jak proces pisania testów jednostkowych do istniejącego kodu pozwala ocenić jego jakość ?

Otóż, pewna stara programistyczna fama głosi, że gdy kod jest łatwo testowalny, to prawdopodobnie jego jakość, a przynajmniej architektura będzie wysokiej jakości. Automatycznie na myśl przychodzi takie proste rozwiązanie, że skoro kod ma być łatwo testowalny, to najlepiej by było zacząć jego tworzenie od napisania testów. Takie podejście nazywa się TDD (Test Driven Development). Pewnie wielu z Was słyszało o takim podejściu, natomiast jeżeli pracujecie w typowej firmie wytwarzającej “stronki”, to pewnie nie mieliście wielu okazji by zastosować takie podejście.

Oczywiście nie koniecznie jest to grzech – w prostych projektach zastosowanie TDD może być dyskusyjne ze względu na narzut czasowy jaki generuje. Znając jednak życie, prosty projekt zwykle przeradza się w projekt skomplikowany, którego skali nikt nie przewidział.

Abstrahując jednak od TDD, chciałbym się podzielić z Wami, moimi spostrzeżeniami na temat typowych “wzorców” w kodzie, które znacząco obniżają jego testowalność. Przy okazji zaproponuje sposoby ich rozwiązania poprzez refaktoring kodu oraz omówię konsekwencje jakie niosą za sobą poszczególne antypatterny.

Tak więc, jeżeli spotkasz jeden z podanych poniżej przypadków – wiedz, że coś się dzieje ;)

  1. Testując dany obiekt sprawdzam jego stan po wywołaniu danej metody:
  2. Testując dany obiekt tworzymy mocki obiektów od których jest zależny w sposób łańcuchowy
  3. Testując dany obiekt łapiemy się na tym, że testując metodę publiczną w istocie chcielibyśmy przetestować metody prywatne z których ona korzysta

The Context

Posted in architektura, domain driven design, java, programowanie on March 19th, 2012 by Wojciech Soczyński – Be the first to comment

The inspiration for this post came to me mainly because of the discussion in comments which I had on Sebastian’s Malaca blog. We had a little debate there about the famous “getters and setters” duo. In my opinion, you can peacefully write software, completely avoiding them (with the obvious exception for DTO’s). My interlocutors had a little different point of view – they stated, that although you should avoid them, there are some cases when G&S are a must. I came up with classic example of a Human, which we can image as:

public class Human {
    
    private Legs legs;
    private Heart heart;
    private Brain brain;

    public Human(Heart heart, Brain brain, Legs legs){
        this.legs = legs;
        this.heart = heart;
        this.brain = brain;
    }
    
    public Distance walk(Place origin, Place destination) throws UnreachableDestinationException {
        heart.accelerateRate(150);
        Distance summaryDistance = new Distance(0, Unit.METER);

        while(!origin.equals(destination)){
            if(!brain.canMoveByStep()){
                throw new UnreachableDestinationException(destination);
            }
            Distance stepDistance = legs.moveStep();
            summaryDistance = summaryDistance.add(stepDistance);
            origin = origin.move(stepDistance);
        }
        return summaryDistance;
    }
    
    public void talk(Human interlocutor){
        //some code
    }
    
    public WorkResult work(Task task){
        //some code
    }
}

As we see in this example, you don’t have any getters or setters, all possible actions of a Human are expressed by the methods attached to its class. OK, everything looks beautiful, but what happens if our walking Human gets hit by a car ? If the injury is serious, he will be taken to the hospital. In the hospital he will be medically examined by some (let us hope) skilled medical personnel. If the injury was real worse, the situation may require to perform an operation on an open heart. Unfortunately our properly encapsulated Human doesn’t expose its internal state of which the heart is part of. So, what can (and does) a surgeon ? He just simply breaks the encapsulation by cutting the chest and gets his job done.

If we wanted to translate (model) the actions of a surgeon in Java code, we would write:

public class Surgeon {

    private HashMap<String, MedicalProcedure> knownProcedures;
    
    public Boolean operate(Human patient, String procedureName) throws FamilyDoesNotAllowException {

        Field[] fields = Human.class.getDeclaredFields();
        try {
            List<Organ> organs = new ArrayList<Organ>();
            for (Field field : fields) {
                field.setAccessible(true);
                Organ organ = (Organ)field.get(patient);
                organs.add(organ);
            }
            MedicalProcedure procedure = knownProcedures.get(procedureName);
            return procedure.execute(organs);
            
        } catch (IllegalAccessException e) {
            throw new FamilyDoesNotAllowException();
        }
    }
}

In the above example, Java’s reflection API was used to break the encapsulation of the instance of a Human class. If we dive into the body of the method “operate”, we could see that an exception could be thrown – the IllegalAccessException. This is because the JVM could be configured to ban such usages of the reflection API. In the real world, the family could also disagree to operate the patient.

So much for drawing parallels between the real world and Java code. As we see, we cannot relay on this particular feature of Java’s reflection API. If we want to save our innocent Human being, we have two options:

  1. write getters and setters for the organs
  2. add a new method to the Human class, to let him be operated

Let write some code to see, how could it be implemented:

Język Scala dla programistów PHP cz.5 – implicit conversions

Posted in php, programowanie on July 15th, 2011 by Wojciech Soczyński – 7 Comments

Jedną ze świetnych i unikalnych cech języka Scala, której PHP nie posiada są tzw implicit conversions zwane też przez oficjalną dokumentację “widokami” (views). Podobny mechanizm zaimplementowany jest w C#, chociaż szczegółów szczerze powiedziawszy nie znam ;) . read more »

Język Scala dla programistów PHP – cz.4 case classes i pattern matching

Posted in php, programowanie on June 16th, 2011 by Wojciech Soczyński – 14 Comments

Witajcie ! Jakiś czas minął już od ostatniego wpisu o Scali (3 miesiące), czas więc odświeżyć swoje zainteresowanie i wiedzę na temat tego języka. Dzisiejszym daniem głównym są tzw. case classes. Jest to pewnego rodzaju nowość dla osób przyzwyczajonych do Javopodobnych obiektowych systemów typów.
read more »