The 5 SOLID principles of object oriented design

cohesionAs a Team Leader and sometimes as an Instructor I see a lot of people who thinks programming using Object Oriented Paradigm is using classes and create a hierarchy. They think its about organizing code and not thinking in a Object Oriented way. During the learning path as professional developer in Object Oriented languages you start to observe that’s Object Oriented it’s a good thing but creating good software products using this paradigm its not so easy as thought at first. Why? There are a lot of reasons, but the main ones are always with architecture and ironically organizing the code! Then you start to dig into loosely coupled concepts, patterns, cohesion, etc., just to try to give some predictability, conceptual and physical organization to your application in terms of design, layers and tiers.

Nowadays we live in a mix of ways of developing applications, such as functional programming, using JavaScript in several contexts including Server side, keeping using the object oriented way of programming with the inversion of control in mind and so on. However there are main principles in object oriented way that really help to have a good “organization of our code”, they are know as SOLID principles that I describe below.

Single responsibility principle

A class should have a single responsibility.

This principle its very related with the concept of cohesion. You want a class with only a single responsibility and all the methods and properties are always related with that responsibility. The advantages are obvious, you can ask the right questions all the time and know the answer very quickly! What questions? “In what class its implemented some ?” / “I found a problem related with the Shopping Cart” (guess where to search for the cause)

If you have more than one responsibility for a class, as your application grows so the complexity of the class and at some point you will start to see that it’s a better idea to split the class in two, but probably it will not be an easy task, considering possible dependencies and cross logic inside the methods of the class. It brings you ambiguity which is always a bad thing.

You can detect this kind of problems if you have methods in your class that don’t call any others methods or properties of the class, they are isolated from the rest. This applies to cluster of methods too. This clusters, probably they should be classes by them selves.

Open/close principle

All the entities should be open for extension, but closed for modification.

The idea is that you shouldn’t change the behavior of a class when you extends it with other class. The subclass should only extends the behavior not changing it. If you are creating an hierarchy of classes and you change somehow the behavior probably you should create another method instead of overriding one, or you are talking about a class that shouldn’t be a subclass but probably a sibling, because the logic its different.

Consider this example, if you try to create an Object Oriented structure for cats and dogs you will find that almost 95% of the method names and properties are the same, and you will be tempted to create a class that models both. For instance, both will have properties like: number of lets, eyes, color, mouth, head, and methods like: walk, run, eat, play, talk, rest, sleep, .… If you implement for instance the talk method, probably it will be just a change in the MP3 clip. One naive implementation will be to try to create a way to take advantage of one implementation to implement the other, and probably using hierarchy or the same class with some conditional statements. If you try to use subclass you will violate this principle, if you try to use the same class you are removing cohesion from the class, putting more than one responsibility in it. This is just a simple example just to try to show the idea and dangers of not applying this principle. You should have at least 2 classes because they are completely different entities.

Liskov substitution principle

If S is a subtype of T, then objects of type T may be replaced with objects of type S without altering the correctness of the program.

If you implement a subclass its because you are extending the parent one and not changing its behavior (see the Open/Close principle). If you are extending a class the core logic it’s the same, syntactically and in a semantic way you are talking about the same entity, you just improved the previous class. For instance if you create classes for Accounts in a bank you will have a class Account with methods such as: deposit, withdraw and getBalance. You will expect that any subclass will have these methods to do the same thing as this with just a few extensions like an interest rate for special accounts, but the core logic it will always be the same. You will not put the method deposit change others things than the balance, or probably just adding a transaction to a list.

Interface segregation principle

Its better to have several specific Interfaces than a generic one.

This principle is simple to understand. If you have an interface with several methods that are not related between them in some context, it will be very probably that you will implement this interface in class that need only some of the methods, letting some of the methods implementation empty. I have seen a lot of this in some frameworks.

For instance, instead of having an Interface named CustomerOfBank, with methods for manage the customers and his transactions, you should have 2 Interfaces at least: Customer and Account. Now it is easy to change the interface related with customers and the interface related with accounts!

So, its better to have a lot of several tiny interfaces for a specific context than one generic one!

Dependency inversion principle

One should “Depend upon Abstractions. Do not depend upon concretions.

This principle have produced complete books and frameworks but it states that:

– High-level modules should not depend on low-level modules. Both should depend on abstractions.
– Abstractions should not depend upon details. Details should depend upon abstractions.

For instance, the business tier/layer of an application shouldn’t depend about the implementation of a database module. He shouldn’t be dependent of if I will use an Oracle or Sql Server, or Web Services, etc.. (If we try to be very perfectionist and using the Single Responsibility Principle, the business layers shouldn’t be responsible for creating the Database/Integration tier/layer too.)

How is this possible? Using interfaces and others classes with the responsibility to create the instances of the dependent classes (database), and using only interfaces to “coupling”” the layers and tiers.

Example:

– IDatabaseRepository (interface with the signature of the methods and public properties related with database)

– DependencyManagerClass – responsible to create instances and managing their lifetime, so the business layer will call something like:

IDatabaseRepository rep = DependencyManagerClass.GetRepository();

PS: When using “real” frameworks probably when creating the Business Layer the repository was injected in the constructor, so this call will be in another class and the business class will only use the already created reference to the repository.

You cant find any dependency in business layer about the DatabaseRepository, and neither any responsibility to create the repository and so the name:dependency inversion, because its not the business class that its creating the repository but the logic was inverted, some other class already created the class and gave it to the business layer. This inversion (plus the interface) removed the dependency and knowledge about the details, place, etc. of the repository. You can now exchange one repository to another with changing anything in the Business Layer! Great! Isn’t it?

Final thoughts

There are a lot of others principles, but these five are the most common and “solid” in the object oriented paradigm. If you study more deeply these concepts you will observe how related they are, and so the name SOLID!

Happy work!

4 Tools you should have in Visual Studio

MH900398793There are a lot of tools you could install in Visual Studio to get your job done, but from the developers point of view there are 4 that I found very useful and they increase the quality of your work, reducing costs and time, the preferred managers sentence!

These tools they aren’t expensive if you think about the ROI of using them. I have licenses for all of them, they improve the quality of my work, a lot!

Resharper

In one sentence: After you start to use it you don’t want to rollback.

This tools knows a lot about your code, sometimes more than you! A lot of times it suggests improvements to your code that makes you think “Why I have not thought about it before”, it teaches you better ways of developing. It covers a lot about developing, the C# code, Visual Basic .NET, ASP.NET, XAML, JavaScript, CSS, Refactoring (lots of them and suggestions to your existing code), inspections, etc.

The main features are:

  • Project Dependency Viewer
  • Code Templates (yes, you don’t have to write always the same structure for your code, you can create a template for common code patterns, or use templates out of the box, like loops, classes, etc) PS: It seems the version 8 supports Multi file templates
  • A command line Resharper to use in CI Servers or other automated develop tools you have.
  • Lots of refactors
  • XAML support (he knows about XAML more than any of us)
  • You can create plugins to Resharper (develop plugins to a plugin Smile )
  • CSS understanding
  • Unit Testing
  • Configuration of inspection rules, etc

PostSharp

In one sentence: You want clean code, you want this tool.

Everybody knows and talks about Dependency Injection, Aspect Oriented Programming, Clean Code. But have you tried to learn and use this tool?

What if I tell you you can move most of:

  • Logging
  • Try Catchs
  • Transactions
  • Cache
  • Parameters Validations

to their own classes and be reused between all of you application code?

What if I tell you, you can concentrate the creation of most of your objects in one place and just ask for them, and this tool will create the object with all the dependencies in a configurable way?

What if I tell you, this tools can help you to really decouple your tiers in your application?

This is clean code, this is real architecture!

NDepend

In one sentence: You want to understand and visualize you code, you want this tool.

I have already talked about this tools in a previous post here. But, if you want to know about your application, like complexity, code metrics (configurable by you, if you want), diagrams, dependency cycles, etc., this tools will help you a lot. If the quality and maintenance of your code its important in your development you really should take a look at this tool.

NuGet

In one sentence: One tool to rule them all!

NuGet, it’s a package manager, which saves you a lot of time and trouble when installing all kinds of stuff in your Visual Studio. For instance, one of these days I was playing around with developing Windows 8 applications, and after some research it seems SQLite it’s the best database you can use if you need a local database for your app. How to install it and have the DLL references available to use? Install the NuGet Extension in Visual Studio, then use it to install SQLite, and everything its available to use in your project.

Final thoughts

There are others great tools around that you should use too in Visual Studio, but these 4 covers the main dimensions of your developing environment:

  • Resharper, its about code
  • PostSharpt, its about architecture and structure
  • NDepend, its about really visualizing your code
  • NuGet, its about helping you with external stuff to your application

Happy work!

Managers, it is always about people!

types-of-exerciseAfter years of developing, team leader and project management experience I realized that all good decisions, even the technical ones must include all the people. Well, “everybody” knows this, every project manager, team leader, manager,etc. Really?

Lets focus on the team developers.

Imagine you have a project to develop, a software product. You have a team leader and some developers that you will assign to the project. You want to use the new technologies like HTML5, JavaScript and lets add Java, the software product will be an Android app.

The typical decision will be something like this:

1) I have developers and a senior developer team leader

2) They all know Java

3) They all know about HTML5 and JavaScript, because “everybody” knows about HTML and JavaScript. Right?

4) They all know about java and that is the language of the android, and know what is an Android phone, it will be a challenge!

Lets remake the decision looking from outside:

1) You have developers and at least one of them it’s a Senior.

– Great!

2) They all know Java.

– The problem starts here. What they know about Java? The language and some algorithms (even with some years of experience), or they understand how to apply Java in the context of mobile Applications? If this is the first time they will develop mobile applications, they don’t understand the architecture of these applications, how to develop the components, the events, actions, how the hardware responds and send events to the application. The thing here its not the details of the mobile android development, it’s the lack of “mind set” the team will need before start to code, and the result will be most certain a bad quality product, who will need a lot of fixes and rebuilding. (been there)

3) Yes, every developer who have developed before web applications knows about HTML and JavaScript, everybody knows WHAT IS, and the syntax and some tricks, but few, very few understands the JavaScript paradigm and good HTML. Be aware of this before anyone tells that he knows about this subjects. It was only in the least 2-3 years that the JavaScript boom has started seriously, and Senior JavaScript programmers are a very small team. Before this language was only used for events in the HTML, now we have frameworks developed in JavaScript, we even can use JavaScript to create servers like “Node.js”!

4) It will be a challenge!

– No, it will be a disaster for the company and/or for the customers! The lack of know how in the middle of the project will arise and show all the architecture problems not prevented in the analysis phase or by the Senior. And here you will have 2 options: Remake the whole product from the start, which sometimes its not a bad idea (only for project managers), because the team already acquired the know how and know how to develop in a better way and know what to develop. Or fix the architecture, and this for me it’s the real challenge and here I thing “It will be a challenge” makes all sense! Its like trying to fix an already built house into other blueprint, good luck! (you will see its better to destroy and build again)

What’s my point, here?

This was just a simple example, to show that the most common way of thinking can lead to big problems, which by the way are always happening.

Before a great decision to be made in the software industry, first take in consideration the people you will choose. They are people with a specific know how and mind set, and to change that it takes time and it is a process you must consider. You can say, you will put them all in training classes. Great, but don’t expect that some dozen hours will create a miracle and prepare them for big projects. Training just gives you an overview sometimes shallow, other times deep, but after the training the people must play for some time before entering the “competition”. You can see this in sports teams. They are professionals, they play for many years, but when something changes, like others players, tactics (projects), coacher (team leader) they need to practice before the real competition to be successful, or you will ear from supporters “they had no time to practice that’s why they are playing so bad”. Probably you say the same about your sports team. Remember those words in your company and your team.

Once someone said, that 80% of the quality of a product comes from management, not the workers, because they need conditions to develop a quality product or project. These conditions include human resources management, understanding human behavior and acting accordingly!

What to do?

I will not give you a magical solution, from years of experience as a developer, trainer, team leader, architect and project manager, I can help you to take a decision involving all these variables, but as a manager, project manger or whatever manager you must open space for your developers talk about the difficulties and frustrations they have, and not throwing a “it’s a challenge for you guys” like a magic sentence that in the future will bring its fruits (demotivation and consequently quitting), and I will not talk here how much it costs to bring a new member to a team (think about a new player in a team, even expensive he need time paid by the sports team to adjust to the new environment).

If you are a developer, be more open to your managers, and ask them time to practice, to develop small “challenges” besides the training and before starting a big project, it will give you know how, confidence and experience for a bigger project. Your company its not wasting money its an investment. I think it will cost more to rebuild or fix a bad product than to spend time before doing some “virtual work” and then do the real work. A soccer team plays 1-2 times a week, and receive money from the public, but during the week they spend money training.

50 Powerful Statistics About Tech Mega Trends Affecting Every Business

Great Slideshare presentation about present and future mega trends. Contains very useful statistics if you want to understand the future of technology, and above that, now we live in a merged technology social life, so the trend of the technology is the trend of the society.

Do you care about your professional image online?

The Big Brother is WE

You cannot ignore the importance of your presence online. If you are someone trying to find a job, you must be prepared to be “investigated” online even before you arrive for an interview. (I did this as a Team Leader, when I had to analyze someone new to my team, it was a curiosity I had to know who the person was before meeting her/him in real).

The social networking sites have different expected behavior profiles, and so, show different aspects of your life, wills, likes, etc., even the “lie”ones!

Facebook

When someone tries to find you on Facebook, will expect to find private stuff, political preferences, holiday places, friends you have, photos of your personal life, family and friends’ conversations, everything about your private and social life. So, that person will infer some kind of “private” personality about you after observing your Facebook history.

LinkedIn

Everytime I look at a LinkedIn Profile I am trying to know more about the professional details of someone. I don’t expect to find private details that not improve the professional reputation of that the person. You can write whatever you want, but your potential customers, companies and bosses are all there!

Google+

It’s a Social Network that can be used like Facebook or in a more professional way. You have control of circles of connections, so you can choose who is friend or just a professional connection, so you can choose what kind of information you want to expose in a private or professional way. I think Google will use the information in his network and relate them with searches, so… be careful.

YouTube

Well, it’s about video! You can show your jokes, parties, games, music, covers, etc., you can use it in a more professional way, and create video presentations like a Visual CV where you present yourself, a training session, or great tutorials to improve your professional status online, and share in LinkedIn or your own website!

Twitter

I see Twitter as a way to ping to a group of persons saying ‘I am social alive and I want you to know about it’. You can use it to say that you are following an important subject in the internet related or not with your job or professional interests. Or you can use it to share messages with your friends, starting gossips, etc. You can use it to organize great discussions around a subject, there are several Twitter Chats you can participate in the internet!

Pinterest

An image its more important than 1000 words! Be careful with the image you want to pass about yourself when you choose an image.

Instagram

Digital photos are each day with more realistic features and lots of Megapixels, but then you take a big modern photo and transform it in an old photo and post it in the Instagram. Very popular, be careful with the message and the people!

Final thoughts

There are a lot of social networking sites, and in the future probably a lot more. The Big Brother are US everywhere, The most important thing and advice I can give you is:

Just share online only what you think anyone can know, anything you post more than this, you will probably regret in the future! 

Which social network you elect as the most important to your life/business?

View Results

Loading ... Loading ...

Evernote vs OneNote

evernote_vs_onenote

As an IT Enterprise professional I am always trying to find the perfect tool to help me with my daily tasks. I have tried a lot of them, and it comes always to these 2: Evernote and OneNote.

This review its not about which one its the best (I will let you decide that), but as a professional I will tell you how I feel about using each of their features.

First a list of Pros and Cons with the most important features

Evernote

Pros:

  • Great community around it, with several products and The Trunk
  • Cloud service with apps in the major platforms, desktop, mobile and tablets.
  • Free apps and applications for windows and Mac
  • Free cloud service if you don’t use more than 60MB/month.
  • Add-ons for browsers
  • Tags management. Very easy to associate to notes and very easy to use them in searching.
  • Geo Notes, if that’s important to you
  • The search feature its very good
  • Collaboration (at least in the Mac)
  • Online editor
  • Related Notes
  • Attach Multimedia files to notes
  • Reminders
  • Share with social networks
  • The applications are free.

Cons:

  • The notes editor could be better. I don’t like the way the tables are created, and most of the times the bullets creation follows a strange behavior after some clicking in Enter and DEL.
  • In Windows the desktop version uses to many space with information about the notes. Ok, its possible to hide it, but then I will have to open and close to find what I want. (I accept some comments here! Its my UI feel, not a problem.)
  • The “list of notes” doesn’t fit well with my expectations. It doesn’t help me find a note with a simple view., I will always have to use the search.
  • Its only about single notes. You cannot create sections, or sub notes or some kind of marks inside a note.
  • The note follows the pattern of a text editor (like WordPad), you cannot write in any place like a real notebook.
  • Ink Notes just in desktop and the note must be or Ink or Text, you cannot have both at same time in the same note.

OneNote

Pros:

  • Integrates very well in the Microsoft Office family products
  • Cloud service using SkyDrive.
  • Apps for Windows desktop, Windows 8 tablet, iOS and Android
  • The limit online its the limit of SkyDrive (starting from 7GB)
  • Search its very good
  • Search with tags its great (although I think the tags management could be much more improved, here I like Evernote system)
  • Great collaboration. I tried to use OneNote online and at same time using in my tablet and the experience was as expected)
  • Online editor its great, very similar to the desktop edition but with some constraints (well, its online)
  • The desktop editor is a pearl. You write anywhere, how you want it, like writing in a sheet of paper. (if you have a surface you can use it like a paper using the stylus). Great handling of tables. You can integrate, convert or use Excel tables in OneNote.
  • Integrates with Outlook and Excel. The editor has almost all the tools you find in the Microsoft Word.
  • You can integrate multimedia files along the note.
  • You can have Ink and text in the same note. Great to take annotations.
  • The online application its free if you have a SkyDrive account.
  • The price of the final product its not expensive if you consider a one time buy. (The OneNote Metro application its free)
  • You don’t have the concept of a note. You take notes like if you have a notebook. (could be a pro or not, depending of your taste)

Cons:

  • The handling of the tags needs a rebuild. Its a menu with a lot of tags already developed. You can create new ones, but its not easy to manage them like in Evernote.
  • You have to buy the desktop version.
  • The mobile apps they have a limit of notes before you have to pay them, unless you have an Office 365 subscription.
  • Its note a very single simple note system, you start with a Notebook with a section and page, not a note like Evernote. Although you can create a notebook for very simple notes or use OneNote’s single notes system.

Verdict

I have switched a lot of times between these 2 great notebook applications. When I want to take fast notes, save links, create list for shopping, simple to-do, or a lot of integration with third party apps in the mobile eco system, Evernote its first choice that comes to my mind. But if you work in a professional environment, and you have a lot of notes in some subject, and the concept of sections, sub notes its more intuitive for you, I think OneNote shines here.

Evernote its great sharing the notes between all the devices and very good to organize them with tags and Notebooks, but the notes are simple boxes of isolated information contained inside notebooks and associated with tags. Its about single notes, not books of information.

OneNote its great organizing information for enterprise or scholar environments. The notes are not isolated blocks of text, they belong to a section/sections inside a notebook. It works like a tree (or a notebook with bookmarks) in your mind. If you want the project X Notebook, with sections and sub-pages, where all is organized like in one place and very easy to find, the OneNote its for you!

Now I am using OneNote, because most of my time its working in IT Project, and I want that each project or company be in a Notebook, and inside it I divide by sections like configuration, applications, issues, daily log, etc., its very easy to find the information without using the tags (I just use them for TODOs and reminders). The editor its a joy and I can use my stylus in the windows surface, which mix very well with the text.

However, sometimes I miss the simplicity of Evernote. Its very easy to take a note in any device and find it using the notebook and tagging. But I will miss the great text editing capabilities of OneNote.


My advice:

– Evernote its about getting notes, tagging them well and then searching, it gives you a lot of notes managing/organizing freedom. There are a lot of third party apps integrated with Evernote. You can, for instance, do a scan and send the photo to the Evernote from an iPhone.

– OneNote its about notebooks and organize them by project, company or class/course or something similar. Its like having real notebooks. Its great for project enterprise environments. (Did I mention the great text editor?)

An Infinite loop in Java, but not to everyone!

One of the things, after all these years, that keeps me fascinated about coding, it’s finding curiosities in a few lines of code that make me think for a while!

public class JavaPearls {

    public static void main(String… args){

        Integer a = new Integer(10);

        Integer b = new Integer(10);

        for(;a<=b && b <= a && a != b;)

            System.out.println(“.”);                           

    }

}

Great Technical Books I have read in the last months

transferirAs a software architect I must have a broad knowledge of several subjects so I can have several tools in my brain to create the better solutions with the right tools. I’ve read (and still reading!) a lot of books, so this post will show some of my last readings with some comment on each of the books.

In future posts I will show other interesting books, sometimes not directly related with software but they gave me another way of thinking about systems, patterns and algorithms that helped me to be a better professional, as a technician and leader whenever necessary.

Hope it can be helpful to your tech and soft improvement in the software industry.

If you know others books you have read who can enrich my knowledge, I will appreciate your comment!

How many methods you have in your classes with: Logging, transaction, validation, exception management? How about remove the code from those methods, write it in another class(es) and add just attributes (or java annotations) and surprise! Your code its so much cleaned! This book has improved the quality of my code, architecture and thinking about applications!
Dependency Injection its about building great software architectures. Its about building software like a house, its about decoupling and loosely couple. Its about building testable software, its about software with quality.
A great book about NoSql! Not too deep, but with the enough information to understand the NoSql world. Even with years in database systems I’ve learned new ways of thinking in this book.
The reference for programming windows, now for windows 8. You can’t go wrong with this book.
You want to know about SCRUM, agile and how it works, this is a very good book to start.
Best book for android development.
I know C, C# and C++. With this book from these guys, I added Objective C to the Cs languages list!
Great book about iOS development. Starts from the basis and then develops some applications and of course your knowledge.

Learning Node.Js – Using MySql

nodejs-380x300So much buzz about Node.Js I had to give it a try, and let me tell you, I was impressed by the fast results and applicability of this framework (I know… there is a lot of debate about what Node.Js is).

I will not introduce Node.Js or give a tutorial about it, you must know a little about JavaScript and know about request, response and HTTP codes.

This example shows how easy is to develop a http Node.Js server and I can you start using it to access MySql databases with just a few lines of code.

Preparation:

1) Download and install Node.Js (its very simple, download and unzip, that’s it!). http://nodejs.org/download/

2) Install the MySql package to access a MySql database.

I’ve used Windows for my learning but it will work for sure in Linux and other platforms.

Just write “npm install mysql”, and the rest speaks for itself. (npm it’s a package manager easily install “add ons” to Node.Js)

D:\node>npm install mysql
npm http GET
https://registry.npmjs.org/mysql
npm http 304 https://registry.npmjs.org/mysql
npm http GET https://registry.npmjs.org/require-all/0.0.3
npm http GET https://registry.npmjs.org/bignumber.js/1.0.1
npm http 304 https://registry.npmjs.org/require-all/0.0.3
npm http 304 https://registry.npmjs.org/bignumber.js/1.0.1
npm http GET https://registry.npmjs.org/require-all/-/require-all-0.0.3.tgz
npm http 200 https://registry.npmjs.org/require-all/-/require-all-0.0.3.tgz
mysql@2.0.0-alpha8 node_modules\mysql
├── require-all@0.0.3
└── bignumber.js@1.0.1

3) Now we are ready to develop our first web server in JavaScript (don’t worry about being JavaScript, it is written in C/C++ and its very fast. I’ve made simple tests with 500 request per second on my laptop without any flaw).

var http = require('http');
var mysql = require('mysql');

// Create a connection to MySql Server and Database
var connection = mysql.createConnection({
  host : '101.129.108.171',
  port : 3306,
  database: 'mb',
  user : 'user',
  password : 'pass'
});

// Create a simple Web Server to respond to requests
http.createServer(function(req, res){

    // RECEIVED A REQUEST!

    // for this example respond with a HTTP 200 OK
    res.writeHeader(200);

    res.write('Connect to mySql\n');

    // Connect to mySql (if there is an erro, report it and terminate de request)
    connection.connect(function(err){
        if(err != null) {
            res.end('Error connecting to mysql:' + err+'\n');
        }
    });


      // Query the database to some data 
    connection.query("SELECT * from mb.g WHERE ref = '806787088'", function(err, rows){

        // There was a error or not?
        if(err != null) {
            res.end("Query error:" + err);
        } else {
            // Shows the result on console window
            console.log(rows[0]);
            res.end("Success!");
        }

        // Close connection
        connection.end();
    });


// The server will be listen on port 8080 
}).listen(8080);

4) Open a command prompt (console) window and run node for this JavaScript:

D:\node>node testaMySql.js

5) Use a browser or use curl to test it! (If you use curl you simple open another console window)

D:\node>\tools\curl.exe http://localhost:8080

6) And you will see the output in the 2 console windows:

The console output goes to windows which started node. The res calls in the JavaScript goes to the browser or the console running the curl.

This is just a start with some “tutorial” example to access a mysql database. Of course you can increase the quality of the code and implement the web server to listen as a  “REST”/HTTP solution.

Technorati Tags: ,,
del.icio.us Tags: ,,

A bet you don’t know about these in Java!

Double Brace Initialization

Probably a lot of time you whish to initialize a collection in Java with default values at construction time, but without doing the sequence stuff like this one (too many statements):

// Initialize a cars collection
List cars = new ArrayList<>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ferrari");

// call the method
someMethod(cars);

How to do it?

Using a static method asList (probably you know about this one!)

Functional style, fewer lines, very precise, and clear!

// Initialize the collection (fewer statements!)
List cars = new ArrayList<>(Arrays.asList("Volvo", "BMW", "Ferrari"));

// call the method
someMethod(cars);

Using Double Brace Initialization

If you think a little about it you will see nothing knew, but may surprise you this way of initialization!

// Initialize the collection
List cars = new ArrayList(){{
            add("Volvo");
            add("BMW");
            add("Ferrari");
        }};

// Call the method
someMethod(cars);

Is this a hidden feature in Java? No!

If you know something about anonymous classes and anonymous constructors, nothing here is new!

The first “{“ is creating an anonymous subclass of ArrayList, and the second “{“ is used to create an anonymous constructor.

Let me put the code in another way:

// The collection creation!
trickList cars = new ArrayList()
        // The anonymous subclass 
        {
            // The anonymous constructor
            {
                add("Volvo");
                add("BMW");
                add("Ferrari");
            }
        };

// The method call
someMethod(cars);

More clear now?

Java has some hidden gems that they deserve to be found!

del.icio.us Tags: ,
Technorati Tags: ,
43 Things Tags: ,

Bad Behavior has blocked 82 access attempts in the last 7 days.

Hyper Smash