Category: Architecture & Developing

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!

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).

















































 

 

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):

How to do it?

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

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

Using Double Brace Initialization

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

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:

More clear now?

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

 

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

Five advanced Java Synchronizers you probably don’t know

 

Besides the common synchronize which is based in the lock bit that every Java object has, you have more sophisticated synchronizers in java, such as:

  • Semaphore – Use the concept of a permit to indicate a max number of allowed threads in a place. When you use the value 1, the behavior its similar to synchronize, also called binary semaphore. There is however a big difference here, you acquire a permit on the semaphore, not a locking object, its just a variable to count when a thread acquires a permit and when a thread releases a permit, some kind of a counter. The only thing you really have are threads locking until a permit be available. In the example below, we define 3 as the number of permits, so after 3 acquires the 4 thread will wait for a release before continue its execution.

    • CountDownLatch – Initialize this class with a number (to countdown), and when reaches 0 the thread waiting unblocks and follows its way. (After the await the latch cannot be reused)

 

 

 

  • CyclicBarrier  – This class behaves somehow as the inverse of the CountDownLatch. After N await() the threads blocked can follow their way. (A CyclicBarrier can be reused)

 

  • Phaser – Very complex synchronizer, a mix of CountDownLatch and CyclicBarrier, with lots of customized options. If you need a behavior similar to 2 previous synchronizers but they were not enough you want to deep into this one. It behaves like a CyclicBarrier but you can register a set of threads and at any time deregister, achieving a level of customization not possible with the other synchronizers. Think about the need to wait for threads to arrive before you can continue or start another set of tasks. More information about this at Oracle website:

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Phaser.html

 

  • Exchanger – The best explanation comes from Oracle doc itself: “A synchronization point at which threads can pair and swap elements within pairs”. One thread wants to send information to other thread and blocks awaiting to send the data, and in EXCHANGE receives what the other thread wants to send too! This behavior happens to both sides!

 

photo credit: My Buffo via photopin cc

NDepend – You must have this tool!

 

I’m a .NET developer since v1.0 at 2002, and as you may guess, I’ve used a lot of tools to help me doing my job. How many times you realize that you are always doing the same thing over and over, in the same way, and sometimes you don’t even notice that you are letting some “little” bugs or “little” bad practices that in the long run will damage your code? And, how about projects with lots of assemblies, methods, complex behaviors, is this familiar to you? If it is, you want to check this tool NDepend

The first thing you probably note it’s the name, which lead us to think that this tool its about dependencies between components, assemblies, methods. Well, its true! But its much more than that! How many of us don’t need to visualize the dependencies from all angles in our project? How much do you value seeing the relations between your classes, assemblies, methods? How great its to know which method it’s the more complex, or more used, or more critical? Probably this “.net method” should be the more unit tested and optimized! In a team, a tool like this has great value, either for developers either for team leaders who want to know how the technical aspects of the project are going.

But this tool, its not only about dependencies, its about code complexity, metrics and very good warnings and advices to improve your code quality, too. In some tests I’ve made with this tool in one of my projects, I discovered that some of my code should be improved (almost saying fixed!), NDepend has show where there was some source code problems and why they were problems! I’m learning from this tool, besides my senior professional experience as a team leader, developer and Certified Trainer!

In NDepend you will find a lot of interactive visual graphs, matrix, trees of your code and its relationships, but besides the visual features of this tool, which are great, you have access to an advanced tool CQLinq(Code Query Linq) which allows you to build Linq queries to query YOUR CODE! Yes, querying your code!

I think it’s a beautiful feature, and a pertinent add-on to any tool which aspires to analyze code.

An example:

A Linq query to return all my public methods with more than 30 lines of code!

You can use all the Linq operators, such as Take, Except, and have access to a very rich API to query your code by a lot of different metrics, such as:

What are the 10 most complex methods?

As a first experience with this tool, I was very impressed, it’s a very productive tool, improves the quality of my code and of my team developers too. This tools its used by a lot of great companies like: ThoughtWorks, Microsoft, HP, Siemens, Google, Redgate and hundreds of others, they are not wrong about choosing it!

I’ will keep exploring this tool for my projects, my first impressions were great, so, why stop? If you are a professional developer I think you should give yourself an opportunity to improve the quality of your projects trying this wonderful tool! You can use it as either a Visual Studio Extension or as an Application outside Visual Studio.

For now I’m really enjoying what I have seen so far. In the future, I will certainly dig more deeply in specific features of this tool and post about my experiences,

Android SDK Tips

Little simple things where I lost some time finding out the resolution when developing for Android.

Emulator with PANIC error:

PANIC: Could not open: C:\Users\

This error happens all the time in windows environment. The most cause is because your username has some non-english characters like “éáç…”, and Android SDK uses your home folder in the operating system as a default to create the emulators.

Possible solution:

make a copy of the avd folder and configure the ini file to point to the new folder.

  1. Go to the emulator folder (for instance: c:\users\usernamewithnonenglishlike-áéíç\.android\avd\)
  2. Copy the “avd” folder to another folder without non-english characters (c:\myAvds\…")
    1. Don’t remove the original
  3. In the original folder open the “init” file: (for instance: c:\users\usernamewithnonenglishlike-á\.android\avd\AVD_for_2_7in_QVGA.ini)
  4. Change the path value to the new folder:
    1. path=newFolderWithoutNonEnglishCharacters\avd\AVD_for_2_7in_QVGA.avd
  5. Start the emulator, it must work now!

PS: Another way is creating manually the AVD and place it in a custom folder:

 

Associate the resource layout (xml file) with the Activity java class:

In the activity java file just add a line to link to the resource file.

Create your resource file or “design file” at res\layout\your_resource.xml

    1. use only lowercase characters combined with numbers and “_”
  1. In the Activity Java Class, in the “onCreate” method, use “setContentView(R.layout.your_resource) like the code below.











 

 

 

Can’t configure Android SDK in IntelliJ 12 when creating a new project

Intellij doesn’t have configured any jdk, so we must configure at least one!

  1. Create the project without the Android SDK configured.
  2. Add some jdk (1.5, 1.6, 1.7) in File->Project Structure
  3. Then choose Android SDK for your project!

 

 

Singleton Pattern without explicit “if” and initialization!

One of the most elegant features of Java are the anonymous initializers! They came in two flavors, static and instance. These kind of initializers are anonymous because they are run by the JVM, at “load byte code” time for static initializers, and at “construction time” for the instance initializer.

The Singleton pattern its very easy to implement, we just have to hide the default constructor (writing it as private) and create a way to call it, usually using a public static method which verifies with a local field if it has already created an instance or not. If so, then ignores the creation, else it creates the instance and returns it. With this, we have only one instance possible in all the application.

Well, with static initializer you don’t need to verify the construction of the object, lets give this job to the JVM at load time! The static anonymous block runs when the JVM loads the class, which is the perfect time to create the instance! After this initialization, when calling any method of this class we are certain the instance already exists and we don’t have to develop any “if” to verify that.

An example of a very simple singleton below.

 

 

There are other ways to create the object without using the “if” (sometimes called lazy instantiation), like declaring the static field with an instance of the class:

but this solution doesn’t allowing me (in a elegant way) to run any other code at “load byte time”, so I really prefer the “static initializer way”.

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

Hyper Smash