Buscar en este blog....

lunes, 22 de mayo de 2017

Some online programming languages..

For the Code-Catas I'm organizing in the company, I found this site, which allows the users not only to choose a language among a lot of languages, but also to work with projects and files.

This was a "must have" because in the catas we wanted also to try design patterns, and good programming techniques, what sometimes means to use more than just one file.
The idea of using an online tool came because of licensing issues by installing  some languages in the laptops. There were not supposed to be used to develop productive code (code that will be sold) so buying a license just for that was a lot of money and time installing all the languages.

 The page I found is:

https://www.tutorialspoint.com/codingground.htm

Let's see how it work for our purposes!

jueves, 30 de marzo de 2017

A tool with a fool, it's still a tool ;)

a tool with a foolTwo weeks ago a colleague came to me extremely happy, jumping like a happy Bunny to ask me if I could use the only license of NDepend that we have in the firm to get the metrics and the graphics of his new code he was proud of. Eight months back in time, we bought this tool, because I downloaded a trial version that I tried for... well, now I don't remember if it was 14 days or a month. But I was quite satisfied with it, so I asked to get a license. And I was listened. ;)

But the funny part of this story is that at that time, when I first tried it, this colleague came to me (this time not like happy Bunny) a told me "Good programmers don't need tools. I don't mean to offend you, but a fool with a tool, it's still a fool."... Now he's asking if he can get his own license too.

The interesting part of this, it's not in fact to say that "people who lives in glass houses should never throw stones", but to point out the motivational change that I noticed in this person. When he decided to throw his code in a metric tool, he also started thinking about how to write his code better. how to architect his solution, and taking care about dependencies, death code, etc.

NDepend DashboardSo, my conclusion is that when people see how good or bad his code actually is (in this case based on numeric metrics and graphics), they feel more motivated to do it better. Your quality doesn't live in the ether, you can actually see it! By the way, I must say that NDepend is a great tool, that I can fully recommend.

jueves, 16 de marzo de 2017

"How to tell people their code is bad"

While reading the book Microsoft .NET: Architecting Applications for the Enterprise (Esposito & Saltarello, 2nd ed), I find quite interesting when they speak about this topic..

Because let's face it: architecting in an enterprise is much more than just doing the architecture, fighting with inconsistent requisites and meeting deathlines ;). It's -among other things- also about dealing with developers. As architects are some kind of  technical leaders, I've noticed they must be seen as some inspirational developer. Someone who not only knows and leads the coding aspects, but also someone who can guide other developers to enhace themselves, to write better and less dirty code. But we all know how difficult can it be to tell someone that their code isn't good, or even not good enough. In my personal experience, junior developers are open minded to enhancements, but semi-seniors and senior are most of the time very difficult to get through.

bad code programmingWell, what this book says about it is no key of the universe, but very usefull and easy to keep in mind: instead of telling someone that the code he/she wrote it's not good -and here I mean whatever nice way to tell this- it could be much, much better to ask him/her subtly why was the code written in this way. Maybe in a humble way of meaning "I don't really get what you did, but I'm really interested in it."

You can be suprised of knowing what was it, that toke that person to solve a thing that way. It can be lack of time, lack of knowledge or just a new point of view that you dind't consider. If you think it could be better done in other way, you can tell the developer.... but not as a correction, rather as an opportunity to enhance his or her knowledge.

lunes, 6 de marzo de 2017

Little Awful Practices (II)

This time I'm going to continue with the try-catch examples ;) This thing I found in the code, was also a little stinky. Take a look by yourself:

public static void UpdatePersistentData()
{
 try
 {
  PreferencesManager.UpdatePersistentData();
  TestConfigManager.UpdatePersistentData();
 }
 catch (Exception)
 {
  // ignore
 }
}

Why would someone here want to catch en exception and do nothing with it? Well... this is more common as it should. The reason behind this, I want to believe, is that we don't care if some exception occurs, maybe because it's not crucial for the program's workflow.

Nevertheless I wouldn't agree most of the times with this solution because for me exceptions MUST BE CAUGHT and MUST BE HANDLED.

It happened to me a few months ago to be working on the development of a project which had a dependency for a small library, which was also developed by some guy in the company a few years ago. When the user was under certain environmental conditions the software threw always a crash error, that I had never had. I couldn't debug it, so I start looking deep into my code to try to find where the bug was, but I couldn't really find anything rare. The only suspicious part, was a call to this library, because it was the only part I didn't knew how was working inside. So I reopened that library's project and started looking at the code... and what did I found? Yes, a try-catch section where the catch was actually catching an exception but doing nothing with it!! And this was the reason why my piece of code couldn't detect the true error with a correct message to be shown!

So that's for me the most important reason to catch exceptions: if anything happens (and it'll probably do) your software should notice it to come up with the correct message and you, no matter if you're user or developer, can handle the situation in some way. But at least you can have an idea where does the exception comes from. :)

jueves, 2 de marzo de 2017

Little Awful Practices (I)

The first post of this series is about repeating code. We all know that code repetition doesn't smell good, but sometimes we just don't have the time to fix it (which I know, should however be no excuse). But I've recently seen this piece of code, which really annoyed me. Why? Not only because it's a lot of repeated code, but also it was like 70 lines of code instead about the 17 it could be. One must scroll the code over and over to see what is was doing instead of having all in the same screen! I know, that can't hurt anybody, but I still disagree with this smalls things ;)

So, this was the original code:

public static void LoadPersistentData() 
{
  try 
  {
    // load plug-in configurations
    Manager01.LoadPersistentData();
  } 
  catch( Exception ex ) 
  {
    Utilities.Logger.Instance.LogError( ex );
  }

  try 
  {
    // load user preferences
    Manager02.LoadPersistentData();
  } 
  catch( Exception ex ) 
  {
    Utilities.Logger.Instance.LogError( ex );
  }

  // lots of try-catchs...
  
  try 
  {
 // load model configurations
    Manager07.LoadPersistentData();
  } 
  catch( Exception ex ) 
  {
    Utilities.Logger.Instance.LogError( ex );
  }
}


I've change the real name of the objects because of privacy, but they were all "managers". If we just apply some basic refactoring, just look what do we have in the end. Is it worth the "effort"?

public static void LoadPersistentData()
{
 try
 {
  Manager01.LoadPersistentData();
  Manager02.LoadPersistentData();
  /// lots of calls...
  Manager07.LoadPersistentData();
 }
 catch (Exception ex)
 {
  Utilities.Logger.Instance.LogError(ex);
 }
}

I think it's not a big deal to perform such refactoring... And it also doesn't take any time to do it, whether  you have the time or not.

miércoles, 1 de marzo de 2017

Little Awful Practices (Serie)


Although I'm not a perfect developer, it's quite common when I start looking code to find some practices that I don't like at all. And I think that's actually the reason (that I am a normal developer) why I find them so quickly and complain about them. Sometimes is my own code and of course sometimes not.

In most cases, these are pieces of code which actually do what they are supposed to, and they do it fine, but are very complicated to manage. Or.. maybe not THAT complicated but still large, in a way that they use a lot of "code space" disturbing the developer's sight, or maybe they hide some bugs that are very difficult to find later. So the thing is that some of these practices are innocent and the effort doesn't worth it to to don't let them live. But others must be killed, though.

Some of these spawns, I guess, are born as a result of having a lot of thing in mind and just not paying enough attention to a particular section of code. That would be the best case, I guess. But unfortunately some of them are just the product of a lack of knowledge, basic knowledge the most time. As I said before: I'm not the great programmer who never make mistakes, I do it, like everybody, but it worth it to pay attention and fix this small bugs once you've seen them. And tell the other developers if you find their bugs (but carefully, because programmers are very susceptible about own bugs ;))

But I must recognize that there is also the case, where we think we found a bad practice... and it's not a bad practice at all! It's actually a solution that we would have done in a different way. "The grass is always greener on the other side" doesn't apply that commonly in programming ;)

Summarizing, the idea of this series is to post and "keep in mind" such practices, as some kind of "don't do it" remainders.

domingo, 31 de julio de 2016

The Difference (and relationship) between MVC and MVP patterns

I wrote this post like one year ago, but I did it in spanish. Yet I'm trying to write also a little more in english. So here it goes.

I think this topic is normally a bit confusing due to the big amount of information that we can easily find in the internet and the short time we can spend to analyze all this information.

The MVC Pattern (Model-View-Controller) is a well-known design pattern which is being used all around the world. In fact, there's no one in the software development who hasn't hear about it. So I'm not gonna explain it. Nevertheless, not so well known is this other pattern called MVP (Model-View-Presenter), although it has gained more terrain in the last years.

At first view one can be tempted to think "Oh, they only changed the Controller of the MVC for the Presenter of the MVP, so it's almost the same thing, but with another name!".

Well.. nothing more far away from the truth! Absolutely not! So, what is it? What is the real difference between them? While I'm not gonna explain the MVP pattern in detail, because there is A LOT of information in internet, I would like to explain what is the relationship between these two patterns. How I see it.

First of all, let's quickly remember what the MVC is about: to separate an application into three conceptually-different parts, so he have:


  • Model: makes reference to data or, better said, to representation of the information. Depending on how you interpret the pattern, the model can be directly bound to the persistence of this information. But in a wider interpretation, it can also mean the whole state of the system in a given moment. So, in its wider interpretation, we can say it embraces both the state of the system and its persistence.
  • Controller: represents the business logic. The rules on which the systems run..
  • View: represents the user interface.

Here it is worth to mention that I don't particularly agree with the separation between "Model" and "Controller", because I think often is kind of difficult -and expensive in terms of time- to totally exclude the model (the data) from the controller (the business logic i.e. the behaviour). However, I'm not saying it can't be done, but rather consider that there is actually a conceptual separaration between them, althought it might be unnecesary (this will be inherent to each situation and system).

Now let's briefly review the what the MVP pattern is about:



  • Model: this model represents the business model. Violá! It's not the same as the model of the MVC, but rather this model includes both the representation of the data and the business logic. That's why we talk about a "Business Model". That is, this model invovles the Model and the Controller of the MVC together.
  • Presenter: this is the director: on one hand it directs the events of the view to the model and on the other it updates the view with the information coming from the model. This concept does not exists directly in the MVC pattern. I mean directly, because is perfectly valid to affirm that this "Presenter" is a part of the "View" in the MVC pattern. That is, this is the logic that we are used to write into the MVC's View, no matter how basic it is!
  • View: The View, according to the MVP, is the silliest and easy-to-write code that we have.  It's just about a "View" that knows his "Presenter", to whom it delegates absolutely everything that happens in it. This View makes nothing but to delegate. The user clicks, the "View" tells the "Presenter" where did the user click. Or the other way: the "Presenter" tell the "View" to fill a ComboBox, the "View" fills the Combo with the information provided. It just does not have business logic at all!

So having this information, if we analyze it a little, we come to the conclusion that both patterns are not mutually excludent. It is not about predicting "We're using the MVC pattern or the MVP pattern", but it could be interesting thinking in a combination of them. That might lead us to something called VPCM (View-Presenter-Controller-Model).

What?! Does it actually exists?! What are we talking about?

Nothing new, to be honest. Maybe the name it's new, it doesn't even exist. But that's not the point. The point is that we are breaking down the View of the MVC in two parts: a "View" who does nothing (but to delegate) and its "Presenter" who does everything for the view. Those are, the View and the Presenter of the MVP. Something like this:


Another way to see this, is the other way: we take the Model of the MVP and we break it down in two new pieces: a Controller (which has the business logic) and a Data Model (which represents the  information). That is, we've just get the Controller and the Model of the MVC pattern. It looks something like this:



As we can see after this analysis, they are NOT mutually excludent patterns: they complement each other! We could say that one emphasize
the Backend, and the other the Frontend. MVC and MVP respectively.

I would like to have some opinions about this analysis and its conclusion.
Cheers!

domingo, 24 de julio de 2016

Writing your first Aspect with Postsharp in C#

Hi!

As some of you might remember, some years ago I started to dabble in the world of Aspects Oriented Programming. I also wrote three posts explaining what is aspect oriented programming, what are its advantages and I gave an example on how to implement aspects in Java using AspectJ. That was a few years ago. Nevertheless, those posts are more relevant than ever!! So if you don't feel that sure with AOP, I´d recommend you to read a few on what aspects are to understand it before you continuing reading.

But life and likes started taking me to and through the .NET and C# world, so I began to look for new tools. Today there are really a lot of tools and frameworks to support aspects, however I chose the one called Postsharp.

Until now, I must admit that the simplicity of this framework seems wonderful for me when compared with other like Spring.NET AOP, which requires a little more of skills when setting it up. Postsharp doesn't need to be configured!! So this is the first advantage.

That said, let's go to the point and see an example on how this framework works.

Maybe the correct thing would be to start defining some concepts that I didn't clarify in those posts, and which are usefull to understand what we are doing. But no: today we start directly with an example. After that, in other posts, I will clarify these points.


So, lets imagine a very simple scenery. It's about a well-known and complex application called "Hello, World" ;), on which we are going to add an aspect. We are going to create only one aspect, that will be responsible to intercept the program's execution just before calling the method who writes "Hello World" in to the screen.

Step 1: Add Postsharp to the project.

Once we've created an empty project (e.g. Console Application), we add the Postsharp packet to it. The simplest way to do it is, of course, using NuGet. So easy as opening NuGet and searching the framework by its name. Then adding it to the project.

Here it is worth it to mention, that once added to the project, Postsharp asks the user to download an executable to be installed (version VS > 2010). This is meant to install a component that will added to Visual Studio. Postsharp has a free version which is enough to write aspects with total freedom, but it also has two more versions which are not only not free, but very expensive for the single user, but provide already-written and already-working aspects and also the possibility to write complex aspects. I haven't had yet the chance to try them, but I'm gonna do it as soon as possible. But do not be afraid of it: get the Express version (the free one) to continue. This installation needs to be made only once. So its not a problem.

Step 2: Write the "Hello World".

Actually, steps 1 and 2 are interchangeables. It is really the same. We can write first the "base" project (without aspects) and then install Postsharp.

I know it can be difficult, so I'm gonna help you. To create the "Hello World" project, you should call the method WriteLine() to write in the console, in the main class.

using System;

namespace FirstTryWithPostSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
        }
    }
}

I guess you didn't have much more complications in this step! ;) Let's move on!

Step 3: Write the Aspect.

Now the interesting part: an aspect, is nothing else but a class! Yes, that simple! Well.. but actually this class must accomplish two conditions:

  1. It must be ALWAYS serializable. This is achieved applying the "Serializable" attribute as we'll see soon..
  2. It ALWAYS inherits from one Postsharp's class, which give our class the "super powers", to put it in some way. They aren't actually superpowers, but these Postsharp's classes have methods which can be overridento redefine them. Postsharp's Core will insert them in our code during compile time. In our example, it will be inserted just before the call to Main() method.
Ok, lets create the class, which we can call AspectThatInterceptsAMethod and says this:



using PostSharp.Aspects;
using System;

namespace FirstTryWithPostSharp
{
    [Serializable]
    class AspectThatInterceptsAMethod : OnMethodBoundaryAspect
    {
        public override void OnEntry(MethodExecutionArgs args)
        {
            Console.WriteLine("Entering the method: " + args.Method.Name);
        }
    }
}


Briefly I want to say that I assume that we already know where this class is being indicated as Serializable, and that the aspect (the class) inherits from the class  OnMethodBoundaryAspect, which provides the possibility to rewrite some methods. In this case, we chose the method OnEntry() which indicates that whatever we do inside it will be executed just before executing the methods to which this aspect will be applied. But like OnEntry(), there are other methods that you can also redifne: OnExit(), OnSuccess() y OnException(). Lets see how to apply this aspect to the Main() Method.

Another little detail, is that args.Method.Name give us the name of the method that was intercepted. This, and much, much more (like accesing to the parameters, and its values) are part the powerful tools with which we count.

Step 4: Indicate to which methods our aspect will be applied.

So far we've made an aspect as god demands. But it is isolated, i.e. it is not being used! To use it, we just have to apply it as an attribute in the methods we want to be affected by it. This is made incredible easy in the following way:

 [AspectThatInterceptsAMethod]
        static void Main(string[] args)
        {


If we now run the project, we'll see that the aspect's text is showed at first, and then Main method's text. This occurs this way, because the aspect will be executed always before the method. Why? Just because we decided to overwrite the OnEntry() method. If we'd wanted to show the text before AND after the main's method, then we should have overwritten also the OnExit() method inside the aspect. Yes, only that!.

Another interesting tip is, that if we want the aspect to be applied to ALL methods of a class, it's just needed to put the attribute over the class name. Like this:

    [AspectThatInterceptsAMethod]
    class Program
    {

        static void Main(string[] args)
        {


And in this way, any method will be automatically a victim of our aspect ;) Easy, don't?

I invite you to try it by yourself!

This was an introduction to a very simple aspect. The aspects's world is very much extensive and interesting! Many wonderful things can be done but, however, like everything in software, I recommend you: always analyze which are the real advantages and disadvantages of introducing a new practice, framework or whatever. Aspects are not always needed. Remember: "Having a good hammer doesn't means that every problem is a nail".

In my experience, the use of aspects is a growing trend, but because many people is getting used to it and not being afraid of it. I'll try to come back with new things about Postsharp's aspects.