The Java Courseware

If you are planning to do build a career as a software developer, you have to be prepared to get trained and re-trained every couple of years. But how? If you’re lucky, your employer will send you to classes, otherwise you have to spend substantial amount of time self-studying. Back in the nineties I was hungry for the courseware. Going through these thick manuals on hot technologies was the shortest way to master them.

Beside software developers, university professors and contract instructors are also looking for the courseware that would help them to teach the class without major surprises and failures in front of the students. No matter who you are, I’d like to offer you some extra materials that’ll help you in learning or teaching programming in Java and Java EE.

Last year, Wiley/Wrox has published my Java Tutorial. 24-hour trainer. It was already structured as lessons, had homeworks, came with video screencasts and included easily importable Eclipse projects for each lesson. Then, I created a supporting site where you can download solutions for the assignments. Some of my students offered interesting versions of the solutions and I let them upload their projects to the same site.

Then, I started eating my own dog food and taught a number of online Java training classes using this book as a textbook. While doing this I created presentation slides and used them in classes. These slides included new information and tons of links to additional studying materials. Today, I finished uploading the slides, and they are publicly available under the Wiki section on the site with solutions.

Enjoy your Java!

P.S. Currently I’m preparing the courseware for my upcoming one-day master class “JavaScript for Java Developers“. My colleague Victor is working on the materials for a fast track workshop on using the JavaScript-based framework called Ext JS. Any of these training classes can be delivered onsite at your organization.

DI, This Special Design Pattern

Design patterns were not born equal. Some of them are boring, while others are special. Do you remember your feelings after learning what the Data Transfer Object is? Don’t remember? Of course – cause you didn’t have any special feelings about it other than “It’s easy”.

What do you say about Singleton? Yeah, this is kinda interesting pattern which gave you something to talk about. Do we really need it? Can’t we just achieve the same effect with static variables? Does it make your entire application tightly coupled? Lots to discuss and share your opinion in online forums.

How about Visitor? You must have remembered those feelings when you ran into it first time. The day when you understood how the Visitor pattern works was crucial in your career – that was the moment when you realized that you were not junior software developer anymore. From that very moment you can consider yourself a mid-level person. Till when? Till you’ll be able to explain the Visitor pattern to at least three juniors. Continuos Explanation (c) might reveal though that Visitor is not exactly what you originally thought it was, but now you really get it!

But there is one pattern that has a very strange effect on people. It’s called Dependency Injection. Decoupling in action! A Customer class doesn’t need to reach out for its Orders! How cool is that! First, it gets you high just like smoking banana peels. Then it makes you a little depressed when you realize that there is always a price to pay – instead of having two simple classes Customer and Order you need to have an Inversion of Control container and should neverforget to properly annotate the injector and injectee. In the server-side Java, containers are not too bad, really. We are used to them and feel pretty comfy inside.

But then, a senior Java developer starts learning other domain-specific programming languages like ActionScript or JavaScript just to realize that these poor people don’t have any IoC containers yet! Can you believe that? This is when the Java developer gets craving to make the lives of those (not as fortunate) ActionScript or JavaScript developers easier. In other words, such DI addict wants to share the needle with the rest of the world and inject, inject, inject… This results in proliferation of the “lightweight” DI frameworks/IoC containers among UI developers, which they should be using on top of whatever framework you currently use. This will overcomplicate the application design, but will allow you to inject Orders into Customers rather than using this so-nineties-getOrders().

Oh well, why did I poured all this on you? I don’t know. But please don’t try to tell this to people who enjoy living in thes IoC worlds or else they’ll become aggressive again and will make you feel stupid for not realizing that one can’t do a proper unit testing without the DI. Do we need unit testing? OK, OK….I won’t even go there.

Java: Passing by Reference With a Twist

Currently I’m teaching a Java class online, and Vitaly O., one of my students, ran into an interesting situation. He sent me the program below, which, to his surprise, printed 1.

public class Main {

    public static void main(String[] args) {
        Integer t = new Integer(0);
        t=1;
        test(t);
        System.out.println(t);
    }
   
    public static void test(Integer t) {
    	t=2;
    }

}

The topic of passing by value vs by reference is one of the difficult topics to understand for Java beginners. The code above can confuse junior Java developers, because the author of the program above ran into a bouquet of Java features, which I’ll explain (slowly) in this blog.

All Java textbooks (mine included) will tell you that objects are being passed by reference and primitives by value. That’s fine and understandable – nobody wants to copy large objects in memory . But what about the variables that point at an object and are being passed to a method as arguments like in test(t) line above?
First, let’s take care of a simpler case. Let’s replace the Integer with the class Car that looks like this:

public class Car {
   int salesmanWhoHasKeys;
} 

Imagine a tiny car dealership with two salesmen that has a room only for one car. When a customer pops in, one of the salesmen takes the car keys to test drive THE car. The class TestCar will look similar to the class Main, but is not exactly the same.

public class TestCar {

    public static void main(String[] args) {
        Car t = new Car();
        t.salesmanWhoHasKeys=1;
        
        test(t);
        System.out.println(t.salesmanWhoHasKeys);
    }
   
    public static void test(Car t) {
    	t.salesmanWhoHasKeys=2;
    }
}

The program TestCar prints 2. Why? What makes it different from the program Main? Just bear with me for a moment. Let’s completely understand what the phrase “objects are passed by reference” means. There is only one car, remember? And Java doesn’t create a copy of the one and only instance of the object Car just to pass it to the method test(). But it does create a copy of the original pointer t inside the method test for method argument, which (to add to the confusion) is also named t.

Get used to the fact that we have one object in memory with two different pointers to it (t and ttt). To make things easier to understand, modify the method test() to look as follow:

   public static void test(Car ttt) {
    	ttt.salesmanWhoHasKeys=2;
    }

The program still prints 2. So what’s the difference between dealing with the instance of a Car vs Integer? The wrapper class Integer is immutable. This means that you can’t change its value once it was assigned, which is not the case with the Car.
To make things worse for comprehension, the Java feature called autoboxing kicks in and the original program quietly creates instances of new wrapper Integer objects when it sees something like t=2. This line gets converted into t=new Integer(2)! Got it? So the value 2 has been assigned to a different Integer object via a different variable t.

And just to make sure that you clearly understand the whole confusion of the program Main, please answer my final question, “How many instances of the class Integer were created during the lifespan of the program Main?”

Who said two? Mary? Wrong! The right answer is three! The first one had the value of zero, the next line caused the creation of the another instance if Integer with the value of 1, and the third instance was created by the method test() with the value of 2. Don’t believe me? Step through the Main program in a debugger, and you’ll see three different ids assigned to the variable t.

Don’t you love Java? I do.

mailto: an elegant solution with limitations

On my current project (Flex and Java) the client wants to email certain data to certain recipients. If the mail content and recipients wouldn’t require manual processing, I’d written a Java server side program that would retrieve the data and sent it to a predefined list of recipients. This is not the case though. The client wants to see the data in an email client (MS Outlook) and be able to add some text to the email body, edit the To, CC, and the subject fields.

That’s why I decided to go with a client side solution. There is this handy protocol mailto, and if you’ll prepare the URL that starts like “mailto:…”, contains the To, CC, Subject, and Body – your program will obediently open the mail client with all the field pre-populated. In Flex, you need to use the function navigateToURL(), but this solution works for any programming language or HTML links. So far so good. I’ve easily implemented this elegant solution giving the client the best of both worlds – automatic mail generation with the ability to massage the text.

But my happiness didn’t last long, cause there was yet another innocent requirement – the data should be formatted. Nothing fancy – like columns in the grid. For example, the email body could have contain the following part:

John Smith                5,678
Mary Lou                        12
B Ramalinga Raju          101

Not a rocket science, right? I also though so and quickly wrote two functions to pad a string with spaces from the left and from the right to a certain length. Then I formed each line concatenating the right-padded 20-char long name with the left-padded 10-char long number. Quick test with printing the result in the console of my IDE – it works! What a great programmer I am, aren’t I?

After passing the same data to the mailto, it opened MS Outlook, and the mail body looked similar to this:
John Smith            5,678
Mary Lou                      12
B Ramalinga Raju         101

My perfect alignment went down the drain. And the worst part is that there is no solution to this problem. The mail client was using a font that allocated different width to each characters and my padding was resulting in different width depending on what characters presented in the name of the person. If I could pass HTML to the mailto URL, this would solve my issue. I could have used HTML Table with cell alignment. But mailto allows to pass only simple text (URL encoding didn’t help either).

I hit the wall. What’s next? Will tell the client, “I give you an elegant and flexible solution, but I can’t align the text. Either manually change the font of the data to one of the monospace font, or set Courier to be a default font in MS Outlook “. I’ve implemented lots of non-trivial solutions for this client, but hey, technology has its limits too.

What if the client answers, “No, I need perfectly aligned report and I hate Courier font?” I’ll answer, “No problem, everything can be fixed. I can certainly come up with a custom solution. It’ll take me N days to implement” After multiplying my daily rate by N the client may reconsider and agree to live with my monospace font solution. This is is good example of a situation, when there is a huge price difference between 100% and 99% automated solution.

P.S. If you run into a similar problem in the Flex TextArea component, the solution is the same – set the fontFamily attribute to use one of the monospace solutions, for example:

<s:TextArea fontFamily=”_typewriter”/>

Pandora Radio, Blacks, and Whites

Presently I work for a client that has an open floor setup, which means that lots of noises and conversations are happening at any given moment. But I prefer listening to the music while developing software, and  the Internet radio Pandora really helps. I’ve created several radio stations, and based on my mood, I listen to a hard rock, jazz, blues or other genre.

Since there is no free lunch, Pandora used to insert audio commercials between the songs. No problems here. I understand. This morning, I noticed that Pandora got a facelift, and it seems that the main reason was to free some screen real estate for visual advertisement. Now it’s getting annoying.

All of a sudden, my browser’s window became fool  of women. This is no good. I’m working here, guys.There are people around me. They pay me well for developing software. And what do they see? Are we paying Yakov for having fun staring at all these women?

But things got even more interesting.  I noticed that all these beautiful ladies were black. This got me thinking why would Pandora assume that I’m specifically interesting in black women? The title on the top of the screen read something like “Find local black women in your area.” This is when having analytical thinking helps. At the time, I was listening to the radio station that  was playing reggae music. Got it?

After a while, I switched to another radio station that was playing Joane Osborne and the likes. Guess what? The browser’s window got filled with the faces of white women.

I suspect that Pandora is trying to be smart in showing context-sensitive ads targeting the proper audience.Do they assume that people listening to reggae are most likely into black women and fans of Joanne Osborne are whites?

So far it’s just my assumption, and would require a lot more hours spent listening to various types of music. I like women. I really do. There are gorgeous white, black and latino women (the rumor has it that J. Lo is available again). My question is, what kind of radio station should I create to see all of them at once and not in a into-your-face manner? If I won’t find the answer, I’m going to have to shell out 36 bucks for a year of ad-free Pandora.

Oops…It’s getting even more interesting…Here comes a large banner offering me “High Quality Generic Viagra”. Guys, I may lose this contract with my client, and won’t have money to buy high quality blue pills from your sponsors.

 

The Axe Soup, Cake Mixes, and Frameworks

I always get excited when I see another person questioning the use of frameworks that ask you to either replace one language with another or write additional code as a life support to sustain the framework’s functioning. This time my kudos to Christin Gorman, who did a great job explaining why using the Hibernate framework over SQL is a bad choice.  Watch this video , where Christin uses the Cake Mix metaphor to deliver her message loud and clear.

In the past I was using a different metaphors. One was about the goat and rabbi. The other one is about the Axe Soup a.k.a. Stone Soup.  I remember this story about a soldier returning back from war. He was very hungry, and, when reached some village, he asked a women living there to give him some food. She rejected. Then he asked for a pot of water so he could cook a soup form his axe. She became curious and agreed. After placing the axe in a boiling water he asked if she had just one small potato to add some flavor to the Axe Soup. She gave the potato. Than he asked the woman about a small onion, and on and on and on.  When the soup was ready, he removed the axe from the pot and fed himself with a tasteful soup.

This is pretty much the situation in many enterprise IT shops that blindly prefer using frameworks to the programming language itself.  If you didn’t get the analogy, Hibernate ORM framework is an axe. Add it to the project (the pot), then write some HQL queries, which is a replacement of SQL, learn and use a couple of dozen annotations, and after all this is done you won’t need to worry about JDBC.

Well, you may need to fine tune the HQL,  but it’s later…But now we are covered. We are hibernating as everyone else, yay!  If something will ever go wrong, we can always remove Hibernate from our code, right? Sure, the same way as the soldier pooled out the axe from the soup, when his project was complete.

I really like many improvements that made Java EE 6 light , easy, and really helpful. I like the concept of pruning, which means gradually getting rid of the useless JSRs. But if you ask me, I’d pruned JPA 2.0 without thinking twice. The goal of this 500-page spec is to replace SQL with another language. Why? I don’t know.

Cristin is right, professional chefs never use cake mixes. But, unfortunately, the modern IT shops are more like the fast food chains than Michelin restaurants.

Java, Soviet Union, and Job Interviews

Back in the seventies, I was taking entry exams to the Kiev Politechnic Institute (KPI). I lived in Ukraine, which was a part of the Soviet Union. At that time people of the Jewish descent had really hard time in getting into most of the colleges and universities. Typically, there were four entry exams for the engineering majors: the verbal math, the written math, the verbal physics, and essay. There were no such things as multiple choice tests ndash; we had to solve problems.

Being a Jewish boy myself, I was raised knowing that getting into college will be extremely difficult for me, and I had to be much better prepared than regular Ukrainian and Russian kids. I was strong in math (can’t say this about the Physics though).

Anyway, during the first written test at KPI, there was a problem with the purposely wrong description. Each of the four hundred people that were taking this test had to solve it. I caught the trick in that problem, and my written math grade was 4 out of 5. Two hundred and twenty people got 2 out of 5, which meant that they wouldn’t even accepted to the second exam.

At the verbal math exam, each applicant had to randomly pick a sheet (a.k.a. ticket) with different written problems. Everybody was sitting in a large auditorium preparing their answers followed by the face-to-face conversation with a professor. He or she was reviewing your solutions and could ask additional questions.

I glanced at my sheet – all problems were easy for me. I quickly wrote the answers, then helped to a girl sitting next to me (this was her 5th attempt to get admitted) and wrote all the answers to the guy in the military costume – guys who server in the army had a preferential treatment (you may be surprised, but helping other people during the tests was considered a noble thing to do in the USSR). Each of them had a face-to-face before me and each of them got a quick 4 without any additional questions. I said to myself, that if they got 4, I could expect getting 6 out of 5.

Then was my turn. All answers for the ticket problems were correct, and then the professor started to ask me additional questions. After answering 11 (!) questions correctly, he asked me the next one from trigonometry, “What’s the difference between the graphs of functions arcsine and arccosine”. Piece of cake. I started answering “The function arcsine looks the same as arccosine,  …” He didn’t let me finish or draw the graphs. “Stop. So you think that arsine and arccosine look the same? Your grade is 2 (failed). ” This meant the end of my exams. No i understand, that I should have selected each word more carefully, but getting 2 after seeing how people who know nothing are fetting 4?

I was speechless for a moment… He didn’t let me finish the sentence! I started mumbling that I was awarded a second place in the math Olympiad of the central borough of Kiev. Then I pooled out the award certificate… He just said, “Apparently your math was better back then, but now you have a serious gap in trigonometry ”

Two months later I went to Novocherkassk, Russia, which was a town 600 miles away from home, got two easy fives on both math tests, 4 on essay and 3 on physics, and got admitted to the Applied Math major.

Several years ago, I was browsing books on Amazon and found a pretty interesting one – “You Failed Your Math Test, Comrade Einstein “. The authors compiled many tough math problems that were prepared specifically for the Jewish students applying to the Soviet “ivy league ” universities. I bought this book to show my respect to the authors for their work. People who live in Ukraine now, tell me that this practice is gone, and everyone has equal opportunities on entrance exams…I wish all the best to the people of Ukraine.

So what does all this have with Java and job interviews here in the USA? These days I often interview people who apply for jobs. A face to face interview is similar to that entrance verbal exam. The only difference is that in the USA people are graded based on their skills rather than ethnicity.

But let’s imagine for a moment that you are conducting a technical interview on Java programming and need to have a special question to ensure that the person you don’t like won’t pass. I ‘m going to arm you with one.

After years of interviewing enterprise Java developers of different levels, I can attest that 90% of them don’t bother learning new features of the language and just get by using whatever they learned some time in their past. For example, nine out of ten people still believe that there are only two way of creating a Java thread ndash; subclass a Thread or implement Runnable. You also thought so? I know. The “new way rdquo; was introduced to Java only six years ago. You want to learn another way? Get my recent book “Java Programming. 24-hour Trainer. ”

Here’s the killer question that 95% of the Java programmers won’t answer correctly. “Give all examples of usage of the keyword final”.

The candidate sits quietly for 30 seconds just to show that he ‘s thinking about the best way of answering this easy question, then he writes the following on a piece of paper:

– If a method declared final, this method can’t be overridden.

static final double convertToCelsius(double far){

return ((far – 32) * 5 / 9);

}

–  If a class is declared final, you can “t be subclass (extend) it

final class Tax { …};

– The value for the final variable can be assigned only once

static final int BOILING_TEMP = 212; // in Fahrenheit

Say politely, “Great, this is correct. Are these all uses of the keyword final that you can recollect? ” As I said earlier, the chances that the candidate knows the fourth use are about 5%. He goes, “Java has no any other use of the final keyword, I ‘m positive.” At this point you thank him for giving you great answers and say that an HR person will be in touch shortly. This is one of the major differences between the USA and USSR. We don’t say give the final answers while the candidate is still here. The phrase “Your answer is wrong ” or “You have a serious gap in trigonometry” could lead to unpredictable reaction of the candidate. We don’t want any conflicts. Let him leave in peace.

The mission is accomplished – he failed the job interview!

Recently released Java 7 has a new feature called final rethrow. In my opinion, it’s a pretty useless feature you can live without. Besides, it makes the code more difficult to read. Now, it’s legal to write something like this:

private void throwExceptions() throws A, B, C {

try {

throwAccordingToIndex(new Random().nextInt(2));

} catch (final Exception e){

System.out.printf( “Caught %s and rethrowing…%n “, e);

throw e;

}

}

To make things even more confusing, writing the keyword final here is not mandatory. But hey, the candidate didn’t know about this use, which means that his skills on Java are not current. And our team of sharp developers don’t need people with rusty skills. For the next several years this question will help you eliminating the candidates you don’t want to have beer with. No one will use this feature, and Java practitioners won’t have a chance to see it in anyone’s code.

Do you like my strategy? Neither do I. I’ll remember that episode with arcsine till I die, and will never apply such techniques while interviewing candidates. So why did I write this blog? To be honest with you, I don’t know. For some reason, when I learned about this feature, I couldn’t find any other use for it other than a secret weapon for the dirty interviewers.

Update. After re-reading this blog, I realized that it didn’t cover an important use case: what if the job applicant knows about this fourth use of the final? Ask what he thinks about this new feature. If he has any opinion about this feature, hire him. He follows the latest developments in the Java language and cares to form an opinion.

How Many Frameworks Does It Take To Retrieve Orders?

I don’t like most of the Flex MVC frameworks cause they force me to write more code. I do like frameworks and tools that let me write less code. But there is no free lunch and, at some point, even productive frameworks, tools, and libraries reach critical mass and the finger pointing game begins.

Today, I’ve been working on an application that was supposed to display a list of orders form a relational DBMS. Not a rocket science. But let’s go over the languages, libraries, tools, and frameworks I had to use for this.

First, I wrote a 20-lines SQL Union statement and tested it in Oracle’s SQL Developer. Then I generated 80% of the code and wrote the other 20% manually. Here’s what I was using:

1. Eclipse IDE for Java EE Developers (Eclipse Foundation), which comes with the WTP plugin

2. CRUD code generator Clear Data Builder (Farata Systems). It generated the initial application written in Java, ActionScript, MXML. It also generated ANT build script

3. Configured Apache Tomcat (Apache Foundation) to run from inside Eclipse – this is where my rich Internet application is deployed.

4. Added to the project the libraries of MyBatis (Clinton Begin and Apache Foundation). This is a light-weight data mapping framework. You map manually written SQL to a Java DTO, which eliminates the need to write JDBC.

5. Spring Framework (Spring Source) was used to simplify wiring of MyBatis into my Java applications.

6. BlazeDS framework (Adobe) is being used for efficient serialization of the server-side Java into client-side ActionScript objects and back via AMF protocol. This exchange happens between the peer ActionScript/Java DTOs.

7. The ActionScript DTOs where automatically generated based on their Java peers by the DTO2FX tool (Farata Systems)

8. Most of the Java code was generated, but I had to write small fragments to be called for data manipulations via SQL/MyBatis

9. The latter would engage the Oracle driver and DBMS (Oracle)

Everything’s ready. Start the server, run the Flex app, and…instead of data I’m getting this error: ” org.springframework.jdbc.ArchiveSQLException : Error setting null parameter. Most JDBC drivers require that the JdbcType must be specified for all nullable parameters. Cause: java.sql.SQLException: Invalid column type”.

This error message is misleading. I do insert parameters to the SQL Select, but they are not nulls. I don’t insert anything into the database. The worst part is that there is nothing left to debug. Everything up to the last SQL-annotated Java method declaration works fine. But you can’t debug a method signature, can you? Who is to blame? Oracle driver? Or should I get the source code of MyBatis trying to find the line of the code that blows up?

Enough for today. Going home. I don’t know what’s causing this issue, but I’ll find the solution. The only question is how much time I’m going to spend on it. Do all these productivity frameworks and tools really save time in the long run? Would I be better off writing JDBC code manually? AS a matter of fact I like MyBatis a lot better than Hibernate, but still… Where are the time savings?

Java for Blondes

A couple of years ago I went with my friends to a regular trip for salmon fishing on the Lake Ontario.  The captain who we usually hire said that it was a busy season, people like ourselves were coming non-stop, and he didn’t have a day off for 40 consecutive days. He concluded that next week he’d to take a couple of days off. When I asked him what he was planning to do, he said, “Not sure…probably will go fishing somewhere.”

Somewhat similar has happened to me today. After spending a couple of hours writing the next lesson to my new Java tutorial I got tired, and decided to relax and have some fun. During the next half an hour I recorded the first podcast in a new series of audio lessons “Java for blondes”.

After this recording I felt refreshed and relaxed and went back to work.

The practical use of the mediator design pattern in GUI design

Any complex screen, more or less, of a business application consists of a number of layout containers (Panel, Canvas) and controls (Buttons, data grids, Comboboxes). In the best case scenario, a UI designer gives you a nice-looking screen prototype that s/he put together without bothering too much about which UI components you are going to select to implement the required functionality. Now what? Just look at this screen below that consists of a number of nested components and containers, which I numbered for easier reference. For simplicity (or should I say for better abstraction?) I did not use the actual components such as panels and dropdowns, but I’m sure you can extrapolate this image to your real-world business screen.

Mediator

A simple (but wrong) approach is to just put all these components in one container (1), program the business logic and communication between these components and be done with it. This would produce a monolithic application with tightly coupled components that know about each other, and the removal of one component would lead to multiple code changes in the application. Talking about a string attached…

The better approach is to create loosely coupled custom components that are self-contained, do not know about the existence of each other, and can communicate with the external world by virtue of sending and receiving events. In this post I use code samples from Adobe Flex,which is a good framework for creating event-driven applications, and it has all you need for the creation of custom components. But the same principle can apply in any other programming language or a framework.

At this point, I could have just explained to you the essence of using custom components, but I’d rather make this essay more solid by introducing a little theory about object-oriented programming and explain the use of the design pattern called Mediator. People say that these days some smart employers are asking questions about design patterns during job interviews. So let’s get armed with this Mediator Pattern.

We’ll start with a definition of this pattern from Wikipedia:

“The mediator pattern is a software design pattern that provides a unified interface to a set of interfaces in a subsystem.”

Not clear? I know. Keep reading.

“The mediator pattern addresses this problem by promoting looser coupling between these classes by being the only class that has detailed knowledge of the methods of other classes. Classes send messages to the mediator when needed and the mediator passes them on to any other classes that need to be informed.”

This does not get much better either.

Okay, to put it simply: if you have Lego parts, they don’t know about each other and they don’t have any idea that some boy (a.k.a. Mediator) has decided to use these particular components to build a toy house. And tomorrow, the Mediator will decide to use the same components in a boat. You know where I’m going to with all this.

I would expect that some impatient readers have already scrolled down this article to see if I’ll ever show you some concrete code examples. I will. Promise.

In the diagram above, containers play the role of the Mediator. The top-level mediator is the container 1, which is responsible for making sure that components 2, 3, and 6 can communicate if need be. On the other hand, the number 2 is a mediator for 4 and 5. The number 3 is the mediator for 7 and 8.

Being a mediator is a very honorable mission, but it comes with responsibilities as you need to listen to events from one of your Lego parts and, possibly, fire the event on the other one.

For example, in the online store scenario, the number 6 can be a control where you select an item; number 4 is the button “Add To Shopping Cart”, and 5 is a shopping cart. Let’s forget about number 6 for a moment and look at the content of the mediator number 2. The button 4 has a specific look and feel and can do just one thing: broadcast the event “AddItemClicked”. To whom? To whomever is interested in receiving such an event. So expect to have the code:

dispatchEvent(new Event( &quot;AddItemClicked&quot;));

somewhere inside the component 4. If the mediator 2 is interested in receiving of this event (and it is, otherwise why even bother including number 4?) it will define an event listener for it, which will get the event and in turn will dispatch another event right on the number 5:

addEventListener( &quot;AddItemClicked&quot;, addItemClickedEventHandler);

...

private function addItemClickedEventHandler(): void{

Number5.dispatchEvent(new Event(&quot;Add3ShoppingCart&quot;));

}

Please note, that in the pseudo-code above, the mediator is choreographing how its little components will communicate. It’s time to get to the nitty-gritty coding details. Just read an article about creating custom components in Flex.

I’d like to stress that in the above example number 4 is shooting an event up in the sky: whoever wants to hear can listen. On the other hand, number 5 is just sitting quietly and listening to the incoming event. From whom? It has not an idea. This is what I mean by loose coupling of components. Number 4 does not know about number 5, but they talk anyway through the mediator.

However, as a developer of this screen, you have to take care of mediator-to-mediator communications as well. For instance, if number 6 is a widget where you can select your Sony TV, mediator 1 will be notified about it and need to talk to mediator 2, which in turn will arrange the flow between 4 and 5.

The Bottom Line

Don’t even think of starting to code UI unless you’ve identified your mediators, custom reusable components, and all communication between them via events.