Blog about my personal and professional experiences with the Java programming language in its different flavors.
Sunday, January 27, 2013
CLOJUG - First meeting
Saturday, January 12, 2013
Book Review: Oracle ADF Enterprise Application Development Made Simple
| Book cover from http://www.packtpub.com |
The latest release of the framework (as of today) is 11gR2 (11.1.2.3.0) and you can develop using Oracle JDeveloper or Eclipse with the Oracle Enterprise Pack for Eclipse (OEPE) plugin. Oracle ADF is not free, but there is a smaller version of the framework that is free to develop and free to deploy (even on production) and is called ADF Essentials.
In this post, I'll be reviewing the book "Oracle ADF Enterprise Application Development Made Simple" written by Sten E. Vesterli and published by PACKT. I have to say that this book is not for beginners in the Oracle ADF field, it is aimed at Sr. Java developers or those with ADF background willing to take the next step or even Java architects, as it is not focused on development tips and tricks but on the set of tools and configurations that you need in order to manage the development lifecycle of an ADF application.
Chapter 1, ADF Proof of Concept, shows the steps you should follow in order to prove that ADF is the framework your team should use for that next project. It first briefly introduce you to ADF architecture and components that you should know in order to build your enterprise applications. Then it shows a case study that leads you to create a proof of concept from design to development. Again, this is not a development book, so it doesn't dive on some development concepts.
Chapter 2, Estimating the Effort, presents you a way to measure the cost and how long it will take to build the enterprise application using ADF. It describe some of the common techniques that some companies apply such as use cases or user stories and it states that the user is a critical success factor for the project. It presents three scenarios (optimistic, likely, pessimistic) and shows you the estimation for the case study presented on chapter one.
This chapter also presents a nice software to create UI designs before development called Balsamiq. The good thing about this software is that it produces a "hand-written" look so everyone knows that it is not the final design and that it can change.
Chapter 3, Getting Organized, teaches you that before start coding, you need to think about the skills and the team you need in order to create enterprise applications with ADF. Then it talks about the programming tasks you should be aware of when building such applications and presents you some third party tools you may use in order to enhance collaboration and control the development lifecycle. It finishes showing you how to structure your application so you don't end up with one big workspace but with small ones that you can then integrate.
Chapter 4, Productive Teamwork, introduces you to the Oracle Team Productivity Center, its advantages and quick configuration steps you should follow in order to install and start using this tool inside JDeveloper. I have to say that this tool is a must if you are working in teams and are developing ADF applications.
Chapter 5, Prepare to Build, tells you the basic libraries you need to build in order to make your application extensible in the future. This is a good chapter, because you start building the base structure of your application.
Chapter 6, Building the Enterprise Application, this is where the real development of the application begins. This chapter guides you to the several steps you should follow in order to start working with JDeveloper and the other integrated tools. The mentioned steps are detailed and applied to the case study. It gives you a real sense of what is to be made during development.
Chapter 7, Testing your Application, shows you several libraries and software you can use in order to create tests for your Business components, User Interfaces and for Stress/Performance tests. It gives you examples based on the case study built through out the book. Really easy to follow step by step tutorial and it gives you the tips to configure the tools to work with ADF.
Chapter 8, Look and Feel, guides you to defining the appearance of components without affecting their functionality. As you are building a modular ADF application, it shows you how easy it is to change the look and feel of your application based on Skinning.
Chapter 9, Customizing the Functionality, this is an advanced topic. It tells you how you can customize the same application for several clients. There is some theory about how it works and then hands on simple example that shows you what you need to do in order to customize your application.
Chapter 10, Securing your ADF Application, this chapter is about the many easy-to-use security features built into ADF. It shows you all the configurations you can make in order to have a fine-grained security in your ADF applications. IMPORTANT: the smaller version of ADF, ADF Essentials, is not bundled with this security mechanism, but you can use the Java EE security instead (more about this in future post).
Chapter 11, Package and Deliver, finally, the last step of the development cycle shows you what you should be considering when deploying your applications: cleaning your code, database connections, etc. And it gives you a list of application parameters you should set for a production environment. At the end, it illustrates you in how you can automate the process of compiling, running tests and deploying to the application server using Ant. Great tips for improving your software development process.
Appendix A, Internationalization, shows you the configurations you need in order to have your application available for other languages and zones. Again, easy to follow step by step tutorial.
As you can see, it is a complete book that goes through all the phases when developing applications using ADF, although, several concepts apply to other technologies. I really enjoyed this book, I'm and experience ADF developer and it helped me in architecting several projects, a 100% recommended. One more thing, the book is published in a lot of formats: printed book, kindle, PDF, ePub, so you have many options to read it. I have the kindle edition and it looks great on my kindle, paragraphs are well formatted and the source code is easy to read. There's only one thing, some tables does not fit the page on the kindle version, so you cannot read the last column.
For more information about this book go to:
http://www.packtpub.com/oracle-adf-enterprise-application-development/book
See ya!
Thursday, December 27, 2012
What's for Java in 2013?
- A new Java User Group will be born in Cali, Colombia. So if you are around stay tuned. This is my contribution to the community, hopefully we'll get many active members and lots of hackathons, meetings and information sharing.
- Java SE 6 End-Of-Life (EOL) is estimated for February 2013. It means that you won't get any other update for your Java SE 6 (unless you buy the Java SE Support), but it doesn't mean that Java SE 6 will disappear, you can still download this version in the Java Archive, but you are encouraged to update to Java SE 7, which has been around since July 2011.
- Oracle will be promoting the Oracle Java Embedded Suite: a full suite for embedded devices which consists of Java SE Embedded 7 runtime, Java DB, Glassfish Server and Jersey WS Framework. You can install this suite on the Raspberry Pi for your projects... nice!
- JavaFx will continue its development. There's lot of documentation online to learn this technology and you can even install JavaFx apps on embedded systems like the RaspberryPi, check this post by Stephen Chin.
- Java EE 7 will be released on the first quarter of 2013, around April. Great new features, check them out!
- Java 8 will be here! The new release of the Java SE will be announced during the second semester of the year, so you better start using Java SE 7 before you get outdated...
- Java One 2013 Save the Date: now we have dates for the conferences around the globe, I guess Java One LAD (Brazil) will be held on December at São Paulo.
Happy new year!
Wednesday, December 26, 2012
Iterator Pattern and Java
The Iterator Pattern provides a way to access the elements of an aggregate object sequentially without exposing its underlaying representation.
Let's check the classic class diagram for the Iterator pattern:
- Aggregate: This is the base class (or interface) of our data structures, you can think of it as the java.util.Collection interface, which defines a lot of methods for the collection classes.
- ConcreteAggregate: This is the concrete data structure that we'll be iterating, for example, java.util.ArrayList, java.util.Vector, etc.
- Iterator: Base class (or interface) for iterators. You can find one in Java at java.util.Iterator. You can notice that the Java version has different methods that we'll be discussing later in this post. Here you define de methods you need in order to traverse the data structures.
- ConcreteIterator: As you want to traverse different data structures you need different iterators. So a concreteIterator is an Iterator for the data structure you want to traverse.
Now, let's take a look at the Java implementation of the Iterator Pattern. The following diagram was generated using Architexa's Free Tool for Understanding Code and it shows the relations between some classes of the Java Collections Framework where we can see a structure similar to the classic class diagram:
The above diagram shows only one implementation of the pattern in Java, there are a lot more, but they always use the java.util.Iterator interface; this is the interface you should use in your implementations of the Iterator Pattern when coding in Java. Let's compare both diagrams:
You can't see this class in the JavaDocs, but it is there in the source code: java.util.Itr
Notice that the methods of the Iterator object in the Java example are different from the methods in the classic class diagram:
- There is no +First() method. If you need to go to the first element, you have to instance a new iterator.
- The +IsDone() method has been renamed to +hasNext().
- The +Next() and +CurrentItem() has been merged into +next().
- The +remove() method has been added.
So, if you ever have to work with different data structures and need a uniform way to traverse them and/or access their items, think about the Iterator Pattern:
//... in a class
/**
* Traverse a list, hashtable, vector, etc. what ever that implements
* the Iterator Pattern
*/
public void traverse(Iterator iter)
{
while(iter.hasNext())
{
System.out.println(iter.next());
}
}
Of course, you will always have to create the ConcreteIterator class for your data structure, but if you are using classes from the Java Collections Framework, it's already done.
One last thing, remember the most important OO Principle of all: Always use the simplest solution that meets your needs, even if it doesn't include a pattern.
Wednesday, December 12, 2012
JavaOne LAD (Brazil) 2012 Days 2 and 3
The second one was a robot created by Vinicius Senger which uses Raspberry Pi and Glassfish Server so you can control the robot using REST WS, awesome!!
There were no Oracle stores.
Tuesday, December 4, 2012
JavaOne Brazil 2012 Day One
Hello all, today I had the opportunity to attend JavaOne LAD (Brazil) 2012.
I'm writing this post right from my mobile device, so I'll be brief.
The community keynote was hosted by several java luminaries and Java Champions from Brazil such as
Fabiane Nardon, Yara Senger, Vinicius Senger, Bruno Souza and a special guest from jFokus. The talk was about getting involved with the java community: Jugs, Java Champions, JCP, etc. Inspiring.
The next conference was about The Internet of Things... Really interesting. You can find more about this at: Things-API.org
Unfortunately I was confused and I left early, missing the java technical keynote... Can't believe it!! grgr
Anyway, tomorrow is another day full of conferences and I'll be posting about the ones I like the most.
See ya!
Thursday, November 1, 2012
Duke's Choice Awards 2012 LAD nomination extended
Sunday, October 14, 2012
Java 7: Meet the Fork/Join Framework
![]() |
| Free clip art from http://www.freepik.com |
According to Wikipedia, Parallelism is the "simultaneous execution of some combination of multiple instances of programmed instructions and data on multiple processors" and Java has classes and interfaces to achieve this (sort of...) since DAY 1. You may know them as: java.lang.Thread, java.lang.Runnable, etc... What Concurrency Utilities (java.util.concurrent package) does is simplify the way we code concurrent tasks, so our code is much simpler and cleaner. As developers we haven't had to do anything when running our applications in machines with higher processing resources, obviously, the performance of our applications will improve, but are we really using the processing resources to the maximum? The answer is big NO.
This post will show you how the Fork/Join framework will help us in using the processing resources to the maximum when dealing with problems that can be divided into small problems and all the solutions to each one of those small problems produce the solution of the big problem (like recursion, divide and conquer).
The Basics
The Fork/Join framework focuses on using all the processing resources available in the machine to improve the performance of the applications. It was designed to simplify parallelism in Divide and Conquer algorithms. The magic behind the Fork/Join framework is its work-stealing algorithm in which work threads that are free steal tasks from other busy threads, so all threads are working at all times. Following are the basics you should know in order to start using the framework:
- Fork means splitting the task into subtasks and work on them.
- Join means merging the solution of every subtask into one general solution.
- java.lang.Runtime use this class in order to obtain the number of processors available to the Java virtual machine. Use the method +availableProcessors():int in order to do so.
- java.util.concurrent.ForkJoinPool Main class of the framework, is the one that implements the work-stealing algorithm and is responsible for running the tasks.
- java.util.concurrent.ForkJoinTask Abstract class for the tasks that run in a java.util.concurrent.ForkJoinPool. Understand a task as a portion of the whole work, for example, if you need to to do something on an array, one task can work on positions 0 to n/2 and another task can work on positions (n/2) +1 to n-1, where n is the length of the array.
- java.util.concurrent.RecursiveAction Subclass of the abstract task class, use it when you don't need the task to return a result, for example, when the task works on positions of an array, it doesn't return anything because it worked on the array. The method you should implement in order to do the job is compute():void, notice the void return.
- java.util.concurrent.RecursiveTask Subclass of the abstract task class, use it when your tasks return a result. For example, when computing Fibonacci numbers, each task must return the number it computed in order to join them and obtain the general solution. The method you should implement in order to do the job is compute():V, where V is the type of return; for the Fibonacci example, V may be java.lang.Integer.
When using the framework, you should define a flag that indicates whether it is necessary to fork/join the tasks or whether you should compute the work directly. For example, when working on an array, you may specify that if the length of the array is bigger than 500_000_000 you should fork/join the tasks, otherwise, the array is small enough to compute directly. In essence, the algorithm you should follow is shown next:
if(the job is small enough)
{
compute directly
}
else
{
split the work in two pieces (fork)
invoke the pieces and join the results (join)
}
OK, too much theory for now, let's review an example.
The Example
Blurring an image requires to work on every pixel of the image. If the image is big enough we are going to have a big array of pixels to work on and so we can use fork/join to work on them and use the processing resources to the maximum. You can download the source code from the Java™ Tutorials site.
Once you download the source code, open NetBeans IDE 7.x and create a new project:
Then select Java Project with Existing Sources from the Java category in the displayed pop-up window:
Select a name and a project folder and click Next >
Now, select the folder where you downloaded the source code for the Blur on an image example:
And select the file ForkBlur.java then click finish:
The source code will be imported and a new project will be created. Notice that the new project is shown with erros, this is because Java 7 is not enable for default:
To fix this, right click on the project name and select the option Properties. On the pop-up dialog, go to Libraries and select JDK 1.7 from the Java Platform ComboBox:
Now, go to the option Sources and select JDK 7 from the Source/Binary Format ComboBox:
Last but not least, increase the memory assigned to the virtual machine when running this application as we'll be accessing a 5 million positions array (or more). Go to the option Run and insert -Xms1024m -Xmx1024m on the VM Options TextBox:
Click OK and your project should be compiling with no errors. Now, we need to find an image bigger enough so we can have a large array to work on. After a while, I found some great images (around 150 MB) from planet Mars, thanks to the curiosity robot, you can download yours from here. Once you download the image, past it on the project's folder.
Before we run the example, we need to modify the source code in order to control when to run it using the Fork/Join framework. In the ForkBlur.java file, go to line 104 in order to change the name of the image that we are going to use:
//Change for the name of the image you pasted //on the project's folder. String filename = "red-tulips.jpg";
Then, replace lines 130 to 136 with the following piece of code:
ForkBlur fb = new ForkBlur(src, 0, src.length, dst);
boolean computeDirectly = true;
long startTime = System.currentTimeMillis();
if (computeDirectly) {
fb.computeDirectly();
} else {
ForkJoinPool pool = new ForkJoinPool();
pool.invoke(fb);
}
long endTime = System.currentTimeMillis();
Notice the computeDirectly flag. When true, we'll NOT be using the fork/Join Framework, instead we will compute the task directly. When false, the fork/join framework will be used.
The compute():void method in the ForkBlur class implements the fork/join algorithm. It's based on the length of the array, when the length of the array is bigger than 10_000, the task will be forked, otherwise, the task will be computed directly.
Following you can see my 2 processors when executing the Blur on an image example without using the Fork/Join framework (computeDirectly = true), it took about 14s to finish the work:
You can see that the processors are working, but not to the maximum. When using the Fork/Join framework (computeDirectly = false) you can see them working at 100% and it took almost 50% less time to finish the work:
This video shows the complete process:
I hope you can see how useful this framework is. Of course, you cannot use it all around your code, but whenever you have a task that can be divided into small tasks then you know who to call.
For more tutorials and information about concurrency in Java, check the Java™ Tutorials site.
see ya!
References:
Available on Internet: http://docs.oracle.com/javase/tutorial/essential/concurrency/
[accessed on October 10 2012].
Available on Internet: http://photojournal.jpl.nasa.gov/catalog/PIA16101
[accessed on October 10 2012].
Monday, October 8, 2012
ADF Essentials
- 150 Ajax-enabled JSF components.
- Support for Skinning.
- Visual and declarative development.
- Free to develop and deploy.
- Glassfish server officially certified, check the ADF Essentials product certification page.
- Includes ADF Faces, ADF Data Visualization Tools (DVT), ADF Controller, ADF Model, ADF Share, and ADF Business Components. Check this page for a complete list of components included.
- For more information and other benefits visit the ADF Essentials product home page.
The framework is built over JSF 2 so if you have previous experience in building Web applications using JSF you are likely to start developing with ADF Essentials pretty fast. On the contrary, if you are just beggining with Web development, the visual and declarative development this framework offers will let you build the application in a fast pace. Either case, there are tons of documentation online: books, tutorials and videos to help you.
What you will need:
I've been using ADF Faces (which is the complete version of the framework) for the last 3 years and I can tell how easy it is to develop RIA (Rich Internet Applications) with it. In future posts I will show you how to deploy a Web application developed with ADF Essentials on Glassfish server and even on Tomcat (which is not yet officially supported).
Two things before we finish:
- ADF Faces is the complete framework (which is free to develop but not free to deploy) and ADF Essentials is a subset of ADF Faces and is free to develop and deploy.
- Check the following video from ADF Insider Essentials's channel on youtube so you can see the framework in action:
see ya!
References:
Available on Internet: http://www.oracle.com/technetwork/developer-tools/adf/overview/adfessentials-1719844.html
[accessed on October 06 2012].
Friday, October 5, 2012
My "Make the Future Java" Tool Kit arrived!
Make the Future Java motivates each of us to share our knowledge and to inspire future technologists to learn more about Java. You can order your Tool Kit too, is FREE. For more information, please visit the program website.
So what's inside? According to Oracle: "The Make the Future Java Tool Kit contains both learning resources and Java branded materials to give your outreach project more impact". It comes with a nice T-Shirt, postcards, posters and DVDs with the following:
- Latest Java Magazine issues
- Beginner Tools such as Alice, BlueJ and GreenFoot
- Java Tutorials (JEE, Java SE, JavaFx)
- Hands on Lab (Java, JavaFx)
- NetBeans IDE
All the tools, tutorials and HOL (Hands On Lab) are available online as well. I'll be posting about our JUG meetings and events where we Make the Future Java. Remember, You can help too, order your Tool Kit and inspire others!
see ya!!
Friday, September 28, 2012
Decorator Pattern and Java
Classes should be open for extension but closed for modification.Designs must be flexible and opened for behavior extension but without modifications to existing code. That way, you avoid introducing new bugs to previous tested and reliable code. Let's check the definition of the Decorator pattern, according to the Head First Design Patterns book:
Attach additional responsabilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.And the basic class diagram for this pattern is as follows:
Let's review each class from the above diagram:
- Component: Most of the time it's an abstract class with abstract methods. Represents the base class of the hierarchy.
- ConcreteComponent: Concrete class that implements the methods from the abstract Component class, during the implementation of the methods you should define default behavior. It's the real class you want to decorate. You may have as many ConcreteComponent classes as you need.
- Decorator: Base class for decorators, it's abstract so decorators are required to implement the abstract methods. It's composed with a reference to the Component class, so decorators may access the object they are decorating. Notice that both ConcreteComponent and Decorator subclass the Component class, that way decorators may be transparent to you, I mean, you are going to have a reference to a Component object and it may or may not be decorated, you just don't know (or care).
- ConcreteDecorator: A concrete decorator that implements the methods from the abstract Decorator class. It's the class that executes the real job of decorating. It can access the object it is decorating. You can have as many ConcreteDecorator classes as you need.
OK, that's kind of confusing, I know. Let's see a real example of the Decorator pattern in action so you can understand the concept. If you have used the java.io API you have already used this pattern, just think about opening streams from a file:
//in a class...
public void printLines(String file) throws Exception
{
DataInputStream rin = null;
rin = new DataInputStream(new FileInputStream(file));
//more code...
}
The last piece of code is making use of the Decorator Pattern, it is decorating a java.io.FileInputStream so we can read primitive Java data types instead of bytes. Let's review the most important points:
- java.io.InputStream: Reads bytes. Base class of the input-streams of bytes hierarchy. This is our Component class. It is not present in our code.
- java.io.FileInputStream: Reads bytes from a file. This is our ConcreteComponent class as it extends the java.io.InputStream.
- java.io.FilterInputStream: Base class for decorators. It is not present in our code.
- java.io.DataInputStream: Reads primitive Java data types.
As you can see, every decorator adds behavior to a component (in this case to a FileInputStream so it can read primitive Java data types). The following diagram was generated using Architexa's Free Tool for Understanding Code and it shows the relations between the input-stream classes we were talking about (and some others) and we can see the exact same structure of the Decorator Pattern:
Something to be aware of is that every decorator is another class in your design, so if you have a lot of decorators, your design will have a lot of small classes and it may become complex.
One last thing, remember the most important OO Principle of all: Always use the simplest solution that meets your needs, even if it doesn't include a pattern.
See ya!
References:
Wednesday, September 26, 2012
Observer Pattern and Java
According to Head First Design Patterns book, this is the definition of the Observer pattern:
Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.Sounds familiar? Have you ever worked with Swing? Looks like the event handling mechanism is using the Observer Pattern. Let's think about it, suppose you have a JButton and you want other objects to be notified when the button is pressed... have you done that? sure! The other objects are not asking all the time to the button whether it is pressed or not, they only wait for a notification from the button. Swing does it using the java.awt.event.ActionListener, but in essence it is using the Observer Pattern, even if we are not using interfaces like java.util.Observer or classes like java.util.Observable...
Now, talking about observers and observables, this two exist since JDK 1.0 and you can use them to implement the Observer Pattern in your applications. Let's see the how to do it:
The objects you want to be waiting for notifications are called Observers, they implement the interface java.util.Observer. This interface defines only one method: +update(Observable,Object):void which is called whenever the observed object is changed. The first parameter, an Observable, is the object that changed. The second parameter may be used as follows:
- If using PUSH notifications, the Object parameter contains the information needed by the observers about the change.
- If using PULL notifications, the Object parameter is null and you should use the Observable parameter in order to extract the information needed.
When to PUSH or PULL? It's up to your implementation. The Object you want to be observed is called the Observable and it has to subclass the java.util.Observable class. Yes, subclass. That's the dark side of the built-in implementation of the Observer Pattern in Java, sometimes you simply can't subclass, we'll talk about this in a minute... Once subclassed, you will inherit the following methods, among others:
- +addObserver(Observer):void which adds the Observer passed in as parameter to the set of observers.
- +deleteObserver(Observer):void which deletes the Observer passed in as parameter from the set of observers.
- setChanged():void which marks the Observable as having been changed. This method is protected, so you can only call it if you subclass the java.util.Observable class. Call it before notifying your observers.
- +notifyObservers():void which notifies the registered observers using PULL. It means that when the +update(Observable,Object):void is invoked on the Observer, the Object parameter will be null.
- +notifyObservers(Object):void which notifies the registered observers using PUSH. It means that when the +update(Observable,Object):void is invoked on the Observer, the Object parameter will be the same parameter passed in the +notifyObservers(Object):void .
So, what happens if the class you want to be the Observable is already subclassing another class? Well, then you have to write your own Observer Pattern implementation because you can't use the one built-in Java. The following diagram shows you the basic concepts of the Observer Pattern, so you can built your own implementation:
One last thing, remember the most important OO Principle of all: Always use the simplest solution that meets your needs, even if it doesn't include a pattern.
See ya!
References:
Duke's choice award 2012 is coming to LAD
The program looks for the most compelling implementations of Java technology. Innovation is the only criteria. The nomination form can be found on the Duke's Choice Java.net site
Winners will be announced on stage during JavaOne LAD (Brasil) December 4th through 6th, and will also be featured in the January/February issue of Java Magazine. Winners will receive a free JavaOne LAD full conference pass and a Duke's Choice Award Statue.
So, you are in Latin America (LAD) and have an innovative Java project? what are you waiting for? The end date for nominations is October 30th, 2012.
Don't you know if you got what it takes? Check the 2011 winners (when there was only one global program).
more info: Duke's Choice Java.net site
see ya!
Monday, September 10, 2012
Java 7 conference for ASUOC
The information of my presentation is as follows:
| Language | Spanish |
| Where | ICESI University Auditorio Varela S.A. Cali, Colombia |
| When | September 13th 2012 16:00 - 17:30 (GMT-5) |
More info (in spanish):
Colombia Oracle Users Group
ICESI University
See ya!
Thursday, August 23, 2012
Head First Design Patterns Book Review
| Book cover from http://www.headfirstlabs.com |
As others "Head First" titles, this book is well written, easy and funny to read, it has a lot of graphics, jokes, examples in the book and on the web site to be downloaded... I just loved it! Click here to know why Head First books are great.
The book covers the following design patterns:
- Observer: Subscribe to receive updates when object's state changes.
- Decorator: Wraps an object to provide new behavior.
- Factory: When you want to encapsulate instantiation.
- Singleton: Ensures one and only one of a kind.
- Command: Encapsulates a request as an object.
- Adapter: Wraps an object and provides a different interface to it.
- Facade: When you need to simplify the interface of a set of classes.
- Template Method: Subclasses decide how to implement steps in an algorithm.
- Iterator: Allows to traverse a collection without exposing its implementation.
- Composite: When you need to treat collections of objects and individual objects uniformly.
- State: Encapsulates state-based behaviors and uses delegation to switch between behaviors.
- Proxy: When you need to control access to an object.
- Some other patterns: Bridge, Prototype, Interpreter, Chain of responsibility, mediator, etc.
Each pattern is explained in detail using an application sample in what they have called "ObjectVille". They also give you examples of its use in real life and its class diagram. Each chapter has a summary at the end (they've called it "Tools for your Design Toolbox") with the most important concepts and definitions.
Many of the above patterns were discovered by the Gang of Four (GoF), who were the first ones in writing about this topic back in 1995. Since then, new patterns have been discovered (yes, they are discovered not created), this book guides you to other reading materials where you can find more design patterns, shows you how looks the formal documentation of a pattern and describes the steps you should consider if you discover new ones.
But it is not all about design patterns, the book also explains the Object Oriented Design Principles (OODP) that every software engineer must know in order to design extensible and maintainable software:
- Encapsulate what varies
- Favor composition over inheritance
- Program to interfaces, not to implementations
- Strive for loosely coupled designs between objects that interact
- Classes should be open for extension but closed for modification
- Depend on abstractions. Do not depend on concrete classes
- Only talk to your friends
- Don't call us, we'll call you
- A class should have only one reason to change
Something really important I learned with this book is: Always use the simplest solution that meets your needs, even if it doesn't include a pattern. So don't try to fill your design with patterns all around, first try using the Object Oriented Design Principles (OODP) then, if necessary, make use of patterns.
One more thing, the book is published in a lot of formats: printed book, kindle, PDF, so you have many options to read it. I have the kindle edition and it looks pretty much the same as in PDF. The kindle edition is available only on Kindle Fire, iPad, PC and Mac (not the portable kindle device).
In future posts I'll write about these patterns and how they are applied in the Java API.
See ya!!
Tuesday, June 26, 2012
Campus Party Colombia 2012 - CPCO5
The information of my presentation is as follows:
| Language | Spanish |
| Where | Corferias Innovation/Development Section Bogotá, Colombia |
| When | June 28th 2012 9pm-10pm (GMT-5) |
More info (in spanish):
Colombia Java Users Group official web site
Campus Party Colombia
See ya!
Sunday, February 5, 2012
JavaCup 2012 - Java Hispano
You do not have to create the graphics or write the code to render the match, the framework does it for you!
Here is a presentation of the tournament:
References:
Available on Internet: http://www.javahispano.org/
[accessed on February 3rd 2012].
Available on Internet: http://javacup.javahispano.org/
[accessed on February 4rd 2012].
Tuesday, January 24, 2012
Java 7 - Project Coin Decompiled
//suppose the classes City and Customer exist ... Map<City,List<Customer>> map = new HashMap<City,List<Customer>>(); ...
//suppose the classes Country, City and Customer exist ... Map<Country,Map<City,List<Customer>>> map = new HashMap<Country,Map<City,List<Customer>>>(); ...
Now, it starts to be very hard to read, right? What if you also need to group by Region?
//suppose the classes Region, Country, City and Customer exist ... Map<Region,Map<Country,Map<City,List<Customer>>>> map = new HashMap<Region, Map<Country,Map<City,List<Customer>>>>(); ...
So what do you think? It's not easy at all to read code like that. Fortunately, the new Diamond Operator helps a lot in the readability of code. The last code can be recoded in Java 7 like this:
//suppose the classes Region, Country, City and Customer exist ... Map<Region,Map<Country,Map<City,List<Customer>>>> map = new HashMap<>(); ...
A lot better!
Strings in Switch
I've been waiting for this a lot!!! I remember the days when I was starting in the Java world and I really needed to use Strings in switch. Well, my waiting is finally over. In earlier versions of Java you had to write something like this:
//in a class
...
public void stringToNumber(String str)
{
if(str.equalsIgnoreCase("one"))
{
System.out.println(1);
}
else if(str.equalsIgnoreCase("two"))
{
System.out.println(2);
}
else if(str.equalsIgnoreCase("three"))
{
System.out.println(3);
}
}
...
In Java 7 you can write it like this:
//in a class
...
public void stringToNumber(String str)
{
switch(str)
{
case "one":
System.out.println(1);
break;
case "two":
System.out.println(2);
break;
case "three":
System.out.println(3);
break;
}
}
...
Even NetBeans has an option to convert it automatically:
Try with resources and Multi Catch
This is a nice enhancement in this version, now you don't have to worry about closing those ResultSets, Statements, FileInputStreams...etc. You just need to use the new try structure and the compiler will care about it for you. You can even create your own classes to be Closeable (this is a new interface) by the new try structure. Following is a classic file access via streams:
//in a class
import java.io.*;
...
public static void copyFile(String path)
throws IOException, NullPointerException
{
File file = new File(path);
FileOutputStream fout = null;
FileInputStream fin = null;
try {
try {
fout = new FileOutputStream("file.dat");
fin = new FileInputStream(file);
byte[] bytes = new byte[1024];
int leido = 0;
while ((leido = fin.read(bytes)) != -1) {
fout.write(bytes, 0, leido);
}
} finally {
if (fout != null) {
fout.close();
}
if (fin != null) {
fin.close();
}
}
} catch (NullPointerException ex) {
ex.printStackTrace();
throw ex;
}catch (IOException ex) {
ex.printStackTrace();
throw ex;
}
}
...
If you notice, in order to be sure that the opened Streams are being closed once they finish, you have to code a try/finally block and close them by yourself. In Java 7, you can achieve the same behaviour in a better way and with less lines of code using the new try structure and the new NIO.2 classes:
//in a class
import java.nio.file.*;
import java.io.*;
...
public static void copyFile(String src)
throws IOException, NullPointerException
{
Path path = FileSystems.getDefault().getPath(src);
try (FileOutputStream fout = new FileOutputStream("file.dat")) {
Files.copy(path, fout);
} catch (NullPointerException | IOException ex) {
ex.printStackTrace();
throw ex;
}
}
...
Binary literals and underscores in literals
Now you can express an integer as a binary literal, this is ideal when programming low-level APIs, also you can use underscores in order to make your values more readable:
//in a class
...
public static void coin()
{
int binaryNum = 0b10; //This is number 2 in binary code
double value1 = 1000000000; //hard to read?
double value2 = 1_000_000_000; //Easy to read with Java 7
double value3 = 0b101010110111; //hard to read?
double value4 = 0b1010_1011_0111; //Easy to read with Java 7
double pi = 3.14_15_92; //another example of readability
}
...
So, less code, more productivity and a better code readability that's what Project Coin is about! (Among other things not seen here).
That's it for PART I of this post, in PART II we are going to see what's the compiler doing when we Decompile the code we have seen here.
References:
Available on Internet: http://netbeans.org/kb/docs/java/javase-jdk7.html
[accessed on January 22 2012].




























