How to throw unexpected checked exceptions

Today I found that it is possible to throw checked exceptions even if they are not declared in throws section.
What did we do when we have need to throw some checked exception? We do:

public void doSomething() throws CannotDoSomethingException {
throw new CannotDoSomethingException();
}

where

public class CannotDoSomethingException extends Exception {
...
}


But we can to throw the checked exception without declaring it at throws section:

public void doSomething() {
Thread.currenThread().stop(new CannotDoSomethingException());
}


I think that this is veeeery bad code

java.lang.String.concat()

Світ класу java.lang.String є чималим. Багато речей заховано глибоко і далеко, чимало просто плавають на верху, але ми їх не завжди бачимо.

Так, наприклад, метод concat() приймає рядок і повертає рядок, який є конкатенацією даного рядка і переданого у вигляді параметра. Рядок-параметр добавляється в кінець даного рядка. Існує, щоправда, виключення, а саме: якщо рядок-параметр є пустим (себто, ""), то тоді метод concat() повертає дану стрічку. В даному випадку економиться час на виконання операції конкатенації для двух рядків. Це є перша відмінність від використання оператора конкатенації рядків "+".

Іншою різницею є те, що якщо рядок-параметр є null, то тоді java.lang.NullPointerException виникає. У випадку ж з "+", null буде замінено на рядок "null", оскільки, String.valueOf(null) повертає "null".

Assertions

Well, one of the most usable feature of safe codding is assertions.
Assertions help to prevent executing code with usafe or unchecked data, for example, with null or wrong parameters, empty strings, too long strings, empty arrays or lists can be unforeseen arguments and must be checked before using.

You may remember the asserts from JUnit. Remember:

assertNotFalse(a > 5, "a cannot be equal or less then 5");

Well, in Apache Commons Lang library you may use the org.apache.commons.lang.Validate class to validate arguments or state in your code. You may use it next:

void saveEntity(Entity entity) {
Validate.notNull(entity);
}

Then, if entity value is then java.lang.IllegalArgumentException is thrown. In other case next code is executed.

There is also overloaded version of such assert methods in Validate class or in JUnit, that helps to describe the assertion:

void saveEntity(Entity entity) {
Validate.notNull(entity, "Entity cannot be null.");
}

I am the fun of the overloaded version of assert methods. Truly say, I think that only version with string description of assertion has right to live. That helps developers to find the source of problem quickly and also it may be used to process the errors.
The other point is to have assert-liked-validation also for state, that will throw the java.lang.IllegalStateException. This type of assertion should used for checking the result of calculation or processing, but not for arguments. So we could have something like:

void saveEntity(Entity entity) {
ArgumentAssert.isNotNull(entity, "Entity cannot be null.");

// create or update the entity,
// then returns entity id, that must be not null value if everything is OK
Integer entityId = dao.save(entity);

StateAssert.isNotNull(entityId, "Entity is not saved, because entity id is null.");
}

The code is not the best, but this shows how StateAssert should be used.

So, if the entityId is null, then StateAssert.isNotNull() method throws IllegalStateException. Before that, ArgumentAssert.isNotNull() method checks whether entity is not null and throws IllegalArgumentException if it is.


And every assert methods, should check whether assertions are enabled, for example, by using system properties.

And what about assert statement in Java?
It should be used, but one type of assertions support must be choosed.

Build Flex with ANT

Ця стаття про виконання білда простої Flex аплікації із використанням ANT.

Мабуть, для того щоб виконати білд простої Flex аплікації слід знати тільки два тарґети:

  • mxmlc - білд mxml у swf файл.

  • html-wrapper - побудова hmtl файлів обгорток для результуючого swf файла.


Нехай, FLEX_HOME - вказує на шлях, де знаходиться на диску сам Flex, тоді, можна підключити в ANT скріпті

<taskdef resource="flexTasks.tasks" classpath="${FLEX_HOME}/ant/lib/flexTasks.jar"/>

Тоді, для того, щоб збілдити swf'ку слід виконати наступний антівський скрипт:

<mxmlc file="${flexApps.basedir}/src/EventsView.mxml"
context-root="/WebAppContext"
keep-generated-actionscript="true"
services="${webapp.basedir}/WebContent/WEB-INF/flex/services-config.xml"
output="${flexApps.output.dir}/EventsView.swf">
<compiler.library-path dir="${FLEX_HOME}/frameworks" append="true">
<include name="${ipcom.basedir}/WebContent/WEB-INF/lib/"/>
</compiler.library-path>
<load-config filename="${FLEX_HOME}/frameworks/flex-config.xml"/>
<source-path path-element="${FLEX_HOME}/frameworks"/>
</mxmlc>


Отже, що собою являють атрибути:

  • file - файл mxml, який представляє собою флекс-аплікацію

  • context-root - назва контексту веб-аплікації, яка використовуватиметься для загрузки флек-аплікаціїю

  • services - файл із описаними сервісами.

  • output - шлях і назва результуючого файла.



А щоб згенерити обгортки:

<html-wrapper file="EventsView.html"
history="true"
template="express-installation"
application="EventsView"
title="Flex Events Viewer"
width="600" height="400"
output="${flexApps.output.dir}"
swf="EventsView"/>

Функціональне програмування

Мабуть важко не замітити, якої потуги набирає функціональне програмування останнім часом. І тому є декілька поважних причин, а саме:

  • використання функціональних мов програмування для написання програм, що використовують конкурентність; іншими словами фукнціональні мови програмування дозволяють писати програми, що можуть працювати і використовувати всі можливості сьогоднішніх багатоядерних процесорів;

  • гнучкісь функціональних мов програмування просто вражає;

  • написання програм за допомогою функціональних мов є досить нескладним, адже вони беруть основу з математичного визначення функції;

  • декотрі функціональні мови програмування (наприклад, Scala) дозволяє використовувати аспекти об'єктно-орієнтованого програмування.

Доречі, від Apache Commons є бібліотека Functor, яка дозволяє використати деякі елементи функціонального програмування в Java. Нажаль, бібліотека ще не в релізі, але будемо надіятися це не надовго. Ця бібліотека дозволить використати такі корисні речі як 1) функції вищого порядку, 2) фільтри, 3) callback функції тощо.


Більш детальнішу інформацію можна знайти там:

  1. Functional programming in the Java language

  2. Functional programming

  3. Functional Programming in the Real World