30 November 2011

Stanford online courses

Stanford University offered several of their most popular computer science courses to the public this fall, online for free. The courses were so popular that Stanford’s doing it again in January.

Design and Analysis of Algorithms
http://www.algo-class.org/

Computer Security
http://www.security-class.org/

Computer Science 101
http://www.cs101-class.org/

Machine Learning (one of the offerings this past fall)
http://jan2012.ml-class.org/

Software as a Service
http://www.saas-class.org/

Human-Computer Interaction
http://www.hci-class.org/

Natural Language Processing
http://www.nlp-class.org/

Game Theory
http://www.game-theory-class.org/

Probabilistic Graphical Models
http://www.pgm-class.org/

Cryptography
http://www.crypto-class.org/

And here is an interesting link to the MIT Free online Course Materials and an article about them

13 November 2011

Pomodore Technique - Can you focus for 25 minutes?

by Staffan Noteberg
(Java2Days 2011)

The Pomodoro technique is an interesting approach for improving your focus while working. The technique is based on several concepts:
  • the conditional reflex - having an established rhythm is important as it establishes a safe and expected environment and thus improves focus
  • the attention deficit trail - humans aren't actually able to do multitasking;the workbech and archive example illustrates that - the mind can only work on one thing at a time and whenever you change the task you need to access the archive in order to move the new task on the workbench and store the results from the old task to the archive; bottom line is that when doing more than one thing at a time you actually do a very expensive switching;

What the technique offers is a self improving process based on the Deming cycle:
  • Act phase - when you work on improving the process by analysing the data received from the check phase
  • Plan phase - when you plan the next iteration of work (according to list of tasks, their priorities and dependencies)
  • Do phase - the phase where you actually do your work :) according to the plan and technique established by the previous two phases
  • and finally the Check phase - where various data about performance of the current process of work is recorded for the use of the act phase

The resulting technique is described very well on the following graphic:


It is quite self explainatory, but in case you want any more help you can check up Staffan's web site.

Other lectures from the Java2Days conference

Modern Annotation - Based Code Generation with Jannocessor
by Nikolche Mihajlovski

JAnoccessor is basically a very powerful code generation framework that is entirely configurable via annotations. Some of the cool stuff mentioned is very clean generated code, built on top of the Java APT and also very sophisticated template engine.

Taking your Application to the Cloud
by Josh Long from SpringSource

The lecture was basically a presentation of VMware CloudFoundry. Some of the interesting points was the cloud developer's bill of rights and the example of how CloudFoundry is used. Some of the pros of using a cloud development platform:
  • instant access as long as there is Internet access
  • distributed applications need distributed data
  • much easier configuration - no need to environment specific variables etc.
  • data store management in a cloud way, abstraction from actual database implementation

What's new in the Spring Integration Framework 2.1
by Oleg Zhurakousky from VMware

The book Enterprise Integration Patterns by Gregor Hohpe was identified as the primary inspiration behind the Spring integration framework. The framework build up on messaging and uses the above mentioned book as a specification.

The architecture is build around the three basic notions - that of a endpoint (also referred as filter), that of a channel (also referred as pipe, both point-to-point and publish-subscribe) and another of payload (using a key-value map for header).

Endpoints could be one of the following types:
  • Transformer - such an endpoint that converts the payload
  • Filter - discarding messages based on a certain conditional statement
  • Router - determining a new channel for the different payloads
  • Splitter - generating more than one message from one input message
  • Aggregator - assemble one message from several other

One thing to note is that the framework completely embraces the newly introduced Java future methods.

For more detailed example I highly recommend the video tutorials on the web site of the Spring Integration framework.

Domain-specific languages
by Igor Stoyanov from VMware

Again a good source of reference is the book Domain Specific Languages by Martin Fowler.

The discussion started by giving an example with the hammer and nail problem : "If you have a hammer you intend to see every problem as a nail". In terms of programming languages using a specific programming language shifts the focus from the actual problem that needs to be solved. On the other hand using a very generic language would mean reinventing the wheel most of the time.

The curve of abstraction is another very interesting overview of how the modern languages are changing.

What is important for DSLs is that context is the King - a very good example was given by the Starbucks orders shortening, e.g. whenever you ask for a specific product and its specific contents the order would be given in a very short way, that would otherwise have no meaning, but since it is in this context it would improve readability. From this perspective any DSL would be heavily reliant on the context it is used in.

A very good definition was given for why successful DSLs are successful - basically what they do is combine example execution with program execution.

There was also a short note about Language oriented programming - which is something I am very familiar with. In short this is the topic of using a general purpose language to define a more narrow DSL. From my perspective this is an excellent solution for providing non-technical QA specialist a way to do automation testing without having to increase their specialization in development.

You can follow Igor by subscribing to his blog.

07 November 2011

Java FX 2.0

by Michael Heinrichs from Oracle
(Java2Days 2011)

"Simple and powerful"

This talk gave a very good incite of the latest release of the Java FX framework. The framework itself has an impressive release timeline. The 2.0 version is a new start - it was decided that is would be a "pure Java" framework in order to reduce the learning curve.

Each JavaFX application has a strict hierarchical structure (scene graph). The leafs of the graph are shapes, images, text, web view (an interesting feature allowing to embed web content such as for instance a Google Maps view), media, controls and charts (a great emphasis here, as charts are very sophisticated). The parent nodes on the other side are components that allow grouping (invisible to the user, allowing to treat several components as one), regions (the same but including a border with some color), layouts (vertical, horizontal, etc) and animation (that is typically applied on a parent container).

The animation API is quite sophisticated - animations could be played in loops, grouped in a sequence, played in parallel or a combination of these techniques. There is also a feature called timeline that provides all the required utilities for a very complex animation. The framework would calculate the complex movement that is described by a simpler definition (see example here).

Also worth mentioning is the very easy to use media API and nice (but limited) UI controls. The good news here is that the Java FX framework is going to become open source with some custom UI components already being created by the community.

An interesting note here - Java FX, as well as Flex, also supports CSS (which is something I am still not really sure I understand).

Lastly, but probably with the most importance is the very advanced binding model that Java FX supports. It builds on top of the typical Java POJO getter / setter concept, but the framework takes it even further by providing wrapper objects for each common data type. These wrappers contain listeners that allow for both unidirectional and bidirectional bindings.

You can follow the author by subscribing to his blog.

06 November 2011

Enterprise Java in 2012 - a Spring Perspective

by Jürgen Höller from SpringSource
(Java2Days 2011)

The presentation was centred around what the recent trends in Cloud computing and Java are and how this affects the future of the Spring framework. So what's new in 2011? In 2011 several new server releases were brought out : the Glassfish 3, JBoss 7, WebSphere 8 and Tomcat 7 (Servlet 3 based). There were a number of cloud platforms released, including Google App Engine (Jetty ++ based), Amazon Elastic Beanstalk (Tomcat ++ based) and VMware CloudFoudry (Tomcat ++ based).

From a Spring perspective there were challenges in several key areas:
  • Datastores are now more diverse, there is hardly any standardization and the concept of a distributed cache is very widely applied. Relational databases are no longer the main choice here and would probably become just one of the possible solutions.
  • Web clients have also changed quite a lot. Client side technologies have overwhelmed the old server side approach and now very few applications store any UI state. Even more - JSF is no longer the a great fit - more and more applications use a very lightweight JAX-RS / JAX-WS back end with the combination of some robust client side technology.
  • Concurrent programming has radically changed. If the challenges before were handling requests from multiple sources(and thus having to do synchronization, state handling, etc.), now the focus is rather the multicore world and being able to handle great loads on multiple processors. The new Java 7 released in the summer of 2011 provides the java.util.concurrent.ForkJoinPool class that could be used in these cases.
  • Scala & Akka are a new generation of programming languages that combine both OOP and functional development and are very suitable for the new concurrency model
  • Java EE 6 is no longer relevant as it takes care of yesterdays problems due to the slow expert group process. Even worse - the adaptation of the technology also takes time and as a result it is outdated, but the industry itself is undertaking rapid changes : cloud vs dedicated servers, alternative datastores vs relational databases, etc.
Java EE 7 tries to take tackle these issues by bringing in many updates and having a main focus on the cloud. The timeline for the umbrella specification is Q4 of 2012 and the full specifications would probably be ready no sooner than 2013.

It would allow activation of beans in specific environments (e.g. profiles) by the means of profile annotations. This would ideally help in cache abstraction, having specific cache set-up for each environment.

The Servlet 3.0 specification would finally allow for the removal of the XML configuration files (such as web.xml and even persisntece.xml) and would also support asynchronous request processing.

As a result Sping 3.1 & Spring 3.2 would have Java 7 as it's driver. It would make best use of the Java 7 JDK and also provide support for JDBC 4.1. There would be a fork/join framework with the use of a typical Spring style ForkJoinPoolFactoryBean. Even better - the fraemwork would be build up with having Java 8 in mind - closures and single abstract method (SAM) types would be considered.

03 November 2011

Engineering Systems in the Cloud

by Falk Kukat from Oracle
(Java2Days 2011)

In this presentation that was quite focused on the Oracle product line* (both in terms of hardware and software) Mr. Kukat gave a high level overview of what value and importance a cloud environment could have for a corporation. There was also a good graph of the usual steps that need to be taken in order to achive the goal of having such infrastructure.

The starting point of the lecture was the all to well known question about the actual meaning of a cloud. The answer to this question was given from the National Institute of Standards and Technology (NIST) definition of cloud computing that identifies several key criteria such as:
  • on demand self service
  • resource pooling
  • rapid elasticity
  • etc.

Another thing mentioned was cloud standards such as interoperability, provisioning, etc.

The emphasis of the entire presentation however (besides the whole pleiades of Oracle products presented) was the roadmap to a platform-as-a-service (PaaS). The roadmap suggested that each company needs to go through four distinct phases:
  • standartization - achieving better operation cost
  • consolidation - standartized toolset; better utilization;
  • improvement & performance - better resource management
  • actual cloud environment - the actual goal
The effort required to reach each of these phases is exponential - the major step for a company being reaching the improvement & performance phase.

There was also some talk about the infrastructure underneath. The message was clear - do not put effort into something you can buy at the same or lower price. An analogy was given with buying a car - one could easily buy the best parts that make up a car, but putting them together would not necessarily make a good car for a good price.

* I've intentionally left out all the topics related to Oracle products

16 September 2011

Coming up the next few days ...

... a few thoughts on OpenSDK becoming the official Java SDK reference implementation
... as well as what's new in Java 1.7
... and lots more! Stay tuned!

For the time being check up this cool way to attach icons to anything with CSS

30 June 2011

IceFaces (JSF) issue with PopupPanel and cancelling

Soem of you might have had the issue that a popup panel would not reset it's values after you hit the cancel button. Typically the cancel button would have an immediate="true" flag to discard any validations.

As a side effect, though, it would not update the values of the components inside the form and the next time the panel is shown the values would remain the same (even if you've cleared them in the backing bean).

There are two solutions for this issue:
1. One is to bind the components to the backing bean using the binding attribute
2. Another is to use the code below

    /**
     * Return the parent form of the given component.
     * 
     * @param component
     * @return the parent form or null if no parent form is found.
     */
    public static UIForm getParentForm(final UIComponent component) {
        UIComponent parent = component;
        while ((parent != null) && !(parent instanceof UIForm)) {
            parent = parent.getParent();
        }
        return (UIForm)parent;
    }

    /**
     * Recursively traverse the {@link UIForm} and clear the data of all the components in it
     * 
     * @param uiForm the {@link UIForm} to clear
     */
    public static void clearSubmittedFormValues(UIForm uiForm) {
        clearSubittedFormValuesRecurse(uiForm);
    }

    private static void clearSubittedFormValuesRecurse(UIComponent uiComponent) {

        if (uiComponent instanceof UIInput) {
            // in case this is an input then clear it's value and mark it as "not submitted"
            UIInput uiInput = (UIInput)uiComponent;
            uiInput.setSubmittedValue(null);
        }

        // check all the immediate children of this component
        for (UIComponent component : uiComponent.getChildren()) {
            clearSubittedFormValuesRecurse(component);
        }

        // check any facets (in case this is a PopupPanel for example)
        for (Entry facetEntry : uiComponent.getFacets().entrySet()) {
            clearSubittedFormValuesRecurse(facetEntry.getValue());
        }
    }


I find the second solution somewhat easier and more clean, otherwise you would need to substantially modify the logic of your bean.

29 June 2011

Law of Demeter (LoD) or Principle of Least Knowledge

Have you heard of this principle? In case you haven't here is what I know about it.

Short intro

The whole idea is to make objects aware only about the properties of object they interact directly with. Unfortunately the reasons are not explained in very good detail and I've found only a few good examples of that. I will try to illustrate this issue with a simple example.

The simple example
Suppose we have two relatively independent entities such as a customer and a seller. They could easily be part of different libraries or modules in real life applications.

Suppose we handle a transaction. The customer would have a credit card and the seller would have a laptop (the item he is selling). Now to illustrate where we might have a conflict with the LoD principle :

class Seller{
    Account account;
    public void executePayment(Customer customer, int sumToWithdraw){
        // assume we get some status of the withdrawal in the form of a boolean
        boolean isWithdrawn = customer.getCreditCard().withdraw(sumToWithdraw);
        if(isWithdrawn){
            account.addSum(sumToWithdraw);
        }
    }
}

Notice the issues (aside from my bad choice of variable naming)? The typical LoD principle violation is the presence of more than one ".", e.g. the call an inner object.

Why? Why is this an issue
  • The first and most important problem is that the Seller class should not be interested in the specifics of the Customer class. If the customer had a method "withdrawMoney()" then the inner implementation would not matter and you would achieve better decoupling. Better decoupling would mean that you'd be free to change the way the user pays (via cash, via check) and this would not reflect the users of this class. Otherwise you would need to modify the Seller class each time you need to change the way of payment.
  • Another issue is the fact that you don't really know the specifics about the credit card manipulations in the Seller class. What if, in order to make a payment, the Customer had to firstly make a check about his current balance? You'd need to know this in order to make withdrawals from the credit card. Not only is this code not supposed to be in the Seller class, but it would mean potential duplications (in case other classes also use the same class). And with duplications comes the possibility of bad code change propagandation.

Solution

The solution is quite simple.

class Seller{
    Account account;

    public void executePayment(Customer customer, int sumToWithdraw){
        // assume we get some status of the withdrawal in the form of a boolean
        boolean isWithdrawn = customer.withdraw(sumToWithdraw);
        if(isWithdrawn){
            account.addSum(sumToWithdraw);
        }
    }
}

class Customer{

    CreditCard card;
    Cash cash;
    Check check;

    public void withdraw(int funds){
        if(cash.hasMoreThan(funds)){
            cash.withdraw(funds);
        } else if(card.hasMoreThan(funds)){
            card.withdraw(funds);
        } else {
            check.write(funds);
        }
    }
}

Now only the Customer class is aware of how the funds are extracted and handles any potential issues with them. The seller is completely unaware of what the logic behind this transaction is. This would mean the Seller would not be affected in any case if the code changes and it would also not have to know how the logic of extracting the funds should look like in the first place.

Side note

I personally believe that the measurement of how many dots a line has is not very accurate in terms of determining if there is a violation of the LoD. In some cases the logic should be able to go deep into the nested objects, but we should always be cautious to not tangle the different objects too much and also place the right logic in the right place.

This principle is more of an abstract idea, than an arithmetical rule.

References

Article in Wikipedia

Article by Dan Manges

28 June 2011

ToughWorks and company image

I've come across Martin Fowler's article on the three pillars ThoughWorks is built upon as a company. It's a very interesting article, I'd recommend everybody to spent some time reading it.

It made me think about what we do here in Bulgaria in the field of software development and consulting. Actually company culture as a whole.

In my short career I've worked for no less than 4 companies - large and small, purely Bulgarian and foreign. I've seen some attempts to enforce the company vision upon the employees, especially in large companies where the management likes to shorten the distance and make the whole company a single family.

Personally I think that a well motivated employee, that strongly believes in the company aims would have a massive boost to his/her productivity and vision. It's really very logical - we always tend to give our best when we personally believe in what we do.

Unfortunately it is quite hard to make people believe in something, especially if these people are intelligent, well educated professionals who like to think for themselves. It is even harder when this goal is not sincere - managers often tend to speak about ideals they don't personally believe in.

To make a long story short, what I think is that such an ideology should be very simple and easy to agree with. It must come from the management not only as an idea, but as personal goal. If a manager is personally aiming to achieve a certain idealistic goal it would make the job of communicating this ideal much easier. The goal itself must be very simplistic and idealistic, such as the three pillars mentioned in Martin Fowler's article. E.g. it would be really easy to find people that like to not only make money, but do something the right way and for the right purpose.

The idealistic goals of a company are something that makes people commit to something more than the usual 8 hour shift. It would make them more committed, more responsible and more interested in what they do.

This is a lesson most of the foreign companies have taught me, but few of the Bulgarian managers have been able to fully comprehend and communicate. It is a personal trait that I believe each manager should have and if not - should try to develop.

17 June 2011

Good warm up question for an interview

If you'd like to get the developer on the other side of the table to think in front of you ask him this very simple programming riddle:

How would you exchange the values of two variables without using a third one?

It really goes to show how a person thinks. Some people would start thinking of very complex solutions. other would freeze because the question seems to be very simple and the expectations of a quick answer would make them stall.

A quick tip for those of you who haven't thought of the answer yet - it involves 3 operations of addition and subtraction.



a = 5
b = 8

a = a + b
a = 13
b = 8

b = a - b
a = 13
b = 5

a = a - b
a = 8
b = 5

08 June 2011

IE7 and IE8, relative width (100%) and overflow


Another day, another possibility to see how different interpretation could IE have regarding a web page. Both Chrome and Firefox (and I am sure most other browsers) handle this issue properly, but IE has it's own idea about everything.

The issue

Suppose you have a layout with relative width (say a table with width of 100% nested in another that has a width of 50%) and you have a form field (text area, text box, etc.). If you were to enter an extremely long text most browsers would split the word, but IE wont. Instead it would expand the table to fit in the text.

Strangely this would sometimes even happen to separate words (not one long word).

The solution

Applying table-layout:fixed to all tables in the chain until the first non relatively sized container would fix the issue. I saw some suggestions to use the word-wrap: break-word; style, but in my case it was unnecessary.

Thanks to:
fplanque: dev blog, 456bereastreet.com and stackoverflow (as usual).

31 May 2011

Thoughts on catching general exception types

Discussed here and all over the web.

So what are the arguments?

Pros

  • obviously less code, including code repetition when handling several specific types of exceptions requires the same actions
  • as a direct result of less code repetition we have lesser probability of bad code change propagation (changes that need to be made in two similar blocks of code, but are only made to one of them)
Unfortunately, to me, that comes at a very high cost.

Cons
  • improper handling of generic exceptions that would normally indicate a bug (NullPointerException, ClassCastException etc.); these exceptions need to be handled in a different way than NumberFormatException or some application level exception (which might make sence to the user, for instance indicating that the input needs to be numeric)
  • another more subtle and very dangerous problem is exception swallowing; if you enforce the rule to not catch generic exceptions you also avoid swallowing them - even if the developer is unwise enough to make an empty catch block it would only catch the specific exception; on the other hand if he makes an empty catch block that catches Throwable ... you've got a much bigger problem on your hand
  • the above issues are even more serious when the code you are trying to handle the exception in is actually a public library or framework; handling a OutOfMemoryError for example makes no sense whatsoever in this context; normally you would want the client code to receive this exception and perhaps handle it (although it might be even better to not handle it at all because in most cases the application would not be able to recover from such an exception)

Generally speaking

I am not really a fan of strict coding rules. I would actually prefer to not bind the developer too much, but I find this a matter of approach rather than choice. I know that the code is not written in the best way when it handles generic exceptions - a well written application would have a well defined exception handling model. It would have checked exceptions it could handle (display a message or react in some other way) and unchecked exceptions that would normally indicate a bug.

Bugs are unfortunate, but they need to be visible - hiding the actual issue from the user does not remove the bug itself. I mean having your user click on a button and not reacting is no better than displaying an error message. And after all if it is the error message itself that you want to concentrate on - you could always make a generic catch block in your most outer layers of UI and display a friendly error. Much better than having one of your developers loose two days of debugging just to find the following line of code in the storage layer :

try {
   if(entity == null){
       entity.setDirty();
       session.save(entity);
   }
} catch (Exception) {
   // TODO perhaps we should handle this at some point, but not now
}

18 January 2011

Spring remote and IceFaces sessions

The application I am currently working on is using Spring security, IceFaces and an applet that is communicating with the back end using the Spring remote HTTP invokers.

An interesting problem (or side effect, depends on the point of view) with this configuration is that the IceFaces session would always expire while the user is only using the applet. Obviously a solution had to be implemented, that would monitor the user activity in the applet and then send periodic requests to the back end in order to keep the session alive.

While the monitoring itself was not such a challenge (the java.awt.Toolbox allowed for detecting global mouse and keyboard events) the major difficulty came from the fact that a Spring remote bean would not have the FacesContext initialized. I've noticed that the IceFaces provides API's that could be used to touch the monitor responsible, but it requires the current HttpSession and extracting it proved to be more problematic than I initially expected. I was surprised though that the answer was more obvious than I've expected - one could simply inject the session to a session scoped bean using the @Autowired annotation.


So as a result the solution is simple:

On the applet level:
- a global AWTListener that would monitor for the user interactions - example
- a Timer that would execute on a scheduled period (shorter than the timeout period set up in the server) - example
- a TimerTask that would check if the last user action was taken in the same timer cycle and if so then it would call the backend

On the server layer:
- a HTTP remote bean that would receive these requests - example
- this bean should be with a session scope so we can inject the HttpSession object
- the actual code that touches the session would be

@Autowired
private HttpSession session;

...

public void touchSession(){
    SessionDispatcher.Monitor.lookupSessionMonitor(session).touchSession();
}