Between Java and PHP – Arrays

Posted in java, php, programowanie on December 21st, 2012 by Wojciech Soczyński – Be the first to comment

Most PHP developers, that start learning Java face the same shocking issue – Java does not have arrays ! Well it is not completely true, Java has a notion of arrays, but not it the sense that most PHP developers are familiar to.

In PHP, the array is an universal container. It can be used as a map:

Could not embed GitHub Gist 2365217: API rate limit exceeded for (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)

and as a list:

Could not embed GitHub Gist 2365239: API rate limit exceeded for (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)

In PHP arrays are used everywhere, because they are very convenient. There are plenty of awesome functions that operate on arrays, to name just a few:

  • array_map
  • reduce
  • sorting functions
  • array_filter
The last cool feature of a PHP array is that, it remembers the order in which the elements where added.
In Java, things are slightly different. There are several collection types:
  • array – not actually a collection in Java sense, it has a fixed length (similar to SplFixedArray)
  • Map – a typed hash map (similar to PHP’s array, when we use string’s as keys), similar to SPLObjectStorage
  • List – a typed list – a container which remembers the order in which the items was added, similar to SPLDoublyLinkedList
  • Set – a typed collection of unique items

Every collection type is iterable (which means that you can use the for-each loop to iterate over it). All collection types derive from the base abstract Collection class.

The types that I have mentioned above are just interfaces, every one of it has different implementations which have some slightly different properties:

  • Map – implemented by HashMap and LinkedHashMap, the LinkedHashMap retains the insertion order
  • List – implemented by ArrayList and LinkedList, both implementations differ mainly in the speed of the operations – the ArrayList is faster for reading and the LinkedList is faster for writing
  • Set – implemented by HashSet, TreeSet and LinkedHashSet – the LinkedHashSet retains the insertion order, the TreeSet is sorted and the HashSet is the fastests

To even further complicate the notion of collections in Java, every collection type has it’s immutable form :).

To sum it all up, transitioning from PHP to Java in case of Arrays is not that difficult, you must just resolve which collection type you should use in each case. I will show some examples in the next post of this series, so stay tuned.

The Optional type in Google Guava

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

Hi folks ! There was some time ago when I was actively blogging (half of the year or so), so I felt a bit ashamed and decided to write about something interesting. As you probably know I’m working now as a Java developer. Because I’m not a big fan of Java (actually I do hate it) I look from time to time for solutions to over-go Java’s shortcomings.

read more »

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:

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:

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: