Monday, July 26, 2010

Factory Method

Imagine that your application is very complicated and it happened that you use two logging providers - one is Log4J and another is Java Logging. Your co-worker got great idea to have specification of which of the providers to use in configuration file. As you wrap all logging logic behind some ILogger interface, you also want to hide exact logging provider from client code and pass creating logic to some separate class.

FACTORY METHOD

For me this design patter is the most familiar and easiest. I'm sure that most of the readers have seen it many times. So the intent of the Factory Method is to hide exact class that should be created basing on some conditions.
In our example classes that should be created are Log4J or JavaLogging, they both implement interface ILogger, that is widely used in your application.

public interface ILogger {
    void LogToDatabase(String message);
    void LogToFile(String message);
    void LogToConsole(String message);
}

As you already guess it might be that in future you will decide to use another logging provider. As we already described in our scenario we read which logging provider to use from some configuration. For not exposing exact classes we delegate this work to LoggerProviderFactory. Here is usage:


    public void Run(){
        LoggerProviderFactory.LoggingProviders providerType =
                getTypeOfLoggingProviderFromConfigFile();

        ILogger logger = LoggerProviderFactory.GetLoggingProvider(providerType);

        logger.LogToConsole("Hello Factory Method Design Pattern.");
    }

    private LoggerProviderFactory.LoggingProviders getTypeOfLoggingProviderFromConfigFile() {
        return LoggerProviderFactory.LoggingProviders.Log4J;
    }

What we are getting back from GetLoggingProvider method is interface. Factory Method decides which of the concretes return basing on the input parameter, which in our case is enum.

Here is implementation of Factory Method:

public class LoggerProviderFactory {

    public enum LoggingProviders{
        JavaLogging,
        Log4J
    }

    // this is our factory method...
    public static ILogger GetLoggingProvider(LoggingProviders logProviders)
    {
        switch(logProviders){
            case JavaLogging:
                return new JavaLogging();
            case Log4J:
                return new Log4J();
            default:
                return new JavaLogging();
        }
    }
}

Because my hardcoded configuration logic returns me Log4J and since implementation of LogToConsole of Log4J concrete logger looks like:


    public void LogToConsole(String message) {
        System.out.println("Log4J: " + message);
    }

I'm getting this as output: Log4J: Hello Factory Method Design Pattern.

Here is my drawing try:

If you liked or disliked this blog post, just let me know.

Check out my Design Patterns Table.

Sunday, July 25, 2010

Interview

I’m not going to write comprehensive article on how to successfully pass Interview. I would like to share some recent thoughts on it. Might be that in one year term you will see another article with same title.

First of all, and as per me, interviewers ask mainly those things that they know well

So if you are candidate for junior position, range of questions that interviewer has could be dramatically wide for you. But once again, if you are junior, he will ask you basics in which he is guru. This means that slight inaccuracy in your definition will just highlight that you are new incomer. This shouldn’t make you sad.

If you are candidate for mediate position, you already are competent in some areas. This means that two things might happen, either your interviewer is competent in them also or either not. In first variant you will need to prove that you are really competent, and after you are done with that, probably general questions will go smoothly. In second variant it doesn’t matter how good you are in those things, everything will depend on other questions. But anyway try to highlight your strength areas.

Regarding senior positions I have almost nothing to say, because I’m still intermediate developer. I think that in this case company finds some resources that are super-competent and everything looks like in med variant, just on another level, or maybe they take candidate basing on his general applicability to this position.

For Junior
Try to show that are able to learn everything, that you are passionate about learning new technologies and can think out of the box. (One friend gave me this hint.) Generally they take juniors for their growth capabilities. That is like investment.

For intermediate
Be confident in things you know and ready for the questions you don’t know answers. Show readiness to solve problems and be honest when answering.

Interview and candidate attitude to work
Also I think that while interviewing someone company lost one very-very important thing – his/her attitude to work. That is something that could not be easily evaluated during interview. I assume that there are guys with good knowledge, but for some reason they are not interested in career growth or orientation for the results. These guys still could pass interview and then bring less value to company, then it was expected. I do not say they do little work, but this is like you’ve got good looking sport car with engine from motorbike. On one blog I read very interesting article motto of which is “Don’t hire for knowledge, hire for attitude!”

Remember that you are also interviewing
Ask about the processes they have and use. Don’t forget general questions about work conditions, like timing schedule, conditioners, vacations, and so on.
Ask deeply about the project, they are going to have you working on. For example, ask if they are doing Agile, if they write Unit Tests for their projects, which kind of duties they want you to execute and if you will have chance to do more. If it is possible ask them to see some source code. I believe that if you are good in programming you will see with whom you gonna work.
The most important for me is to know if they are looking forward to see your professional growth and if they will be glad to promote you because of that. If they really want you to grow and do not expect you to be working horse on one project, this might be good company.

Did I have one recently?
I think that you are very interesting if I have had some interview(s) in recent time. Yes, I had, but I’m not constantly looking for new job, I just accept invitations if they could bring me some value. I would say if they ask for interview, go and see where you stand in current labor market. You will see if you are losing technology tendency at your work or if you are banally losing money, because indeed you worth much more.

I’m not throwing you to send resumes and go to dozen interviews, but I recommend having one interview at least once a year, just to know if you need to pay more attention on learning something or improving something.

I am not afraid to say above, even if my current employer will read this blog post or if company who asked me for interview will read this. Why? Because if I stay, this means that current company satisfies me with conditions it gives me and this should make it happy that resources are not going away. If I move, this means that another company finds me more valuable than current, and this means only one – I was losing something at my work.

Guys, that all is about how much you cost. And I know answer for this question:
You cost exactly as much as you are getting right now!
Just think about that for a while, and you will get deep meaning of it.

Saturday, July 24, 2010

Prototype

Have you worked with Outlook calendar or any other mature calendar, that allows you copy some events from day to day?
For example your friend scheduled small beer party for Friday, 23 July where he listed his friends, also he allocated time from 7pm till 3 am and put high priority, he also described that it is great to have party on Friday after work in the comments. As you were invited, party went extremely well. In the end of party your friend decided to schedule similar party for the next Friday, but since he had already drunk too much it was complicated for him to populate all of the fields of the event in calendar. Which kind of enhancement would you propose for the calendar, your friend uses? Probably copy-paste functionality.

PROTOTYPE

Prototype is design pattern, that allows us create complete copies of instances already defined in design (list of possible types of events) or either run-time(Friday's event), so we no longer need reinstantiate them from A to Z. Already defined instances are called prototypical instances.

As we already described one applicability of Prototype for copying instances specified at run-time, this design pattern could be also used for reducing number of subclasses in the system. For example instead of having subclasses like "5 floors apartment block with 3 rooms flats", "9 floors apartment block with 2-3-4 rooms flats" and "12 floors apartment block with 1-2-3 rooms flats" you may have 3 instances of ApartmentBlock initialized with needed properties, and then you just copy one of them when you need to build new building somewhere in the city. In other words no need to write either this "new ApBlockWith9FloorsAnd234Flats()" or this "new ApartmentBlock(){Floors = 9; FlatsDic = {2,3,4}}".

What you need is something like "_9FloorsApBlock.Clone()". Of course you can combine this with FactoryMethod, so you will have something like "GetMe9FloorsAppBlock()", which inside calls cloning of prototypical instance.


Example

Let's now take a look at Prototype, which defines clone() method for our prototypes.

public class CalendarPrototype implements Cloneable{
    @Override
    public CalendarPrototype clone() throws CloneNotSupportedException{
        CalendarPrototype copyOfPrototype = (CalendarPrototype)super.clone();
        return copyOfPrototype;
    }  
}

My concrete Prototype class is calendar event, which looks like this:

public class CalendarEvent extends CalendarPrototype {

    ArrayList<Attendee> _attendees = new ArrayList<Attendee>();
    Priority _priority; // priority is reference variable  
    Date _startDateAndTime = new Date();
   
    //setters and getters here
}

Client code
is executed, when my friend wants to open calendar, right click on event and paste it into other location, therefor changing start/end date & time.

Take a look on this process:

public class PrototypeDemo {

    public CalendarEvent getExistingEvent(){
        CalendarEvent beerParty = new CalendarEvent();
        ArrayList<Attendee> friends = new ArrayList<Attendee>();
        Attendee andriy = new Attendee();
        andriy.FirstName = "Andriy";
        andriy.LastName = "Buday";
        friends.add(andriy);
        beerParty.set_attendees(friends);
        beerParty.set_startDateAndTime(new Date(2010,7,23,19,0,0));
        beerParty.set_priority(Priority.High());

        return beerParty;
    }

    public void Run() throws CloneNotSupportedException {

        CalendarEvent beerParty = getExistingEvent();
        CalendarEvent nextFridayEvent = (CalendarEvent) beerParty.clone();
        nextFridayEvent.set_startDateAndTime(new Date(2010,7,30,19,0,0));

        // we will talk about further code a bit later
        nextFridayEvent.get_attendees().get(0).EmailAddress = "andriybuday@liamg.com";
        nextFridayEvent.get_priority().setPriorityValue(0);      
       
        if(beerParty.get_attendees() != nextFridayEvent.get_attendees())
        {
            System.out.println("GOOD: Each event has own list of attendees.");
        }
        if(beerParty.get_attendees().get(0).EmailAddress == nextFridayEvent.get_attendees().get(0).EmailAddress)
        {
            //In this case it is good to have shallow copy of the attendees.
            System.out.println("GOOD: If I updated my e-mail address it will be updated in all events.");
        }
        if(beerParty.get_priority().isHigh() != nextFridayEvent.get_priority().isHigh())
        {
            System.out.println("GOOD: Each event should have own priority object, fully-copied.");
        }
    }
}

As you can see my friend got copy of the existing event and by grag-drop changed its date. But after that I noticed that I can change my address in his attendees list, so I did that, also after we got another beer and felt sick we decided to lower priority to neutral with this line: nextFridayEvent.get_priority().setPriorityValue(0);

Looks like we've got what we want - copy of the existing event, with attendees, priority, etc. But it turns out that when I open old event I see that priority is now neutral, not high. As you already guessed that is because we executed shallow copy.

Shallow copy copies only direct value field and keeps same references.
Deep copy copies whole graph of objects, so they all have different addresses in heap.

CLONE

For Prototype we can implement clone() our own way, so for example I can have partially deep copy, so my new address should be the same in all events, but priority should keep different.

In Prototype design pattern we implement clone method. Sometimes we may need complete deep copy which can be archived by manual copying which is cumbersome, by reflection, which could be slow, or by serializing and deserializing to new object, which is also expensive. But sometimes you need partial deep copying like in our example. That is why programming languages introduces Cloneable interfaces to be implemented by our own. Suitalbe for our example could look like:

    @Override
    public CalendarPrototype clone() throws CloneNotSupportedException {
        CalendarEvent copy = (CalendarEvent)super.clone();
       
        // this allows us have another list, but same attendees there
        ArrayList<Attendee> copiedAttendees = (ArrayList<Attendee>) this.get_attendees().clone();
        copy.set_attendees(copiedAttendees);

        // we also would like to copy priority
        copy.set_priority(this.get_priority().clone());

        return copy;
    }
   
I already wrote console outputs that say we are ok. But also here is screenshot from debug mode to prove that I do not cheat:



Hope this article wasn't boring and brought more understanding of Prototype design pattern. Please let me know what you think about it!


Here is my Design Patterns Table.

Friday, July 23, 2010

Team Work: Am I complaining bitch

I've been writing e-mail to my co-workers, notifying them about changes I did in sprint backlog. Then I switched to people avaliability and continued about complaining why do we allocate only 6 hours per day for tasks and then did unexpected - shared my thoughts on being result oriented.

EMAIL:


[Something about my changes...
complains-complains-complains- sorry could not share them - complains-complains-complains - complains looks like "we have X hour for this and that where then other Y go?"]
 
I understand what you may think about me after this, but root of our being behind the schedule is our attitude to work.
 
I would like to see sprint backlog populated with tasks we really do and fulfilled to meet our allocation per day.

If we are agile team, that want to meet project success, why don’t everyone commit himself equally with others.
If we are professionals who what to achieve career picks and earn something valuable for our lives we need to be result oriented.

All my complains above could be discounted if we all want make customer happy and get it DONE. I want! And you?

Looking forward to hear from you?


Now I think about the consequences that my e-mail will bring. Indeed it looks like I'm too concerned about my project or either I'm emotional, since complained about those things.

Really would like to hear from you about your opinion on this.


Maybe:
I'm complaing bitch
I do not understand that people have other life priorities
I'm too young
I'm bad team worker, I need to start playing from other side
I should become lazy :)
This will have:
Good consequences and they will like my e-mail
Neutral
Bad consequences and will simply make barrier between me and them

Please share other variants, that is really something, I'm interested in to hear from you, readers!

Thursday, July 22, 2010

Developer's Meeting: AutoMapper

Today I performed developer's meeting on AutoMapper. I would say that it went good, but I did not really enjoy it and will explain why. But I do not regret doing this presentation and will explain why.

Why am I upset of today's presentation delivery?

Not so many people got interested in theme, that I've decided to present. There were about 10 or less developers in conference room. I really expected to have bigger audience and had prepared to speak to other division of our software business unit. But I believe there are some reasons why I did not get many listeners.

Few important thoughts for presenters that encounter the same

Never be disappointed by the number of attendees.. at least at the beginning, so this will not decrease quiality of your speach.

If topic of you speech is not really popular it doesn't mean that you should discount its value.

If topic is indeed simple don't neglect your preparations. For some reason I even wasn't a bit nervous before presentation, as I'm usually are and I don't find this to be good.

Take a look around, you probably will see those who are interested in topic and those who are simply excited by your presentations. Special thank to today's attendees, without you I would have to talk to walls.

For future pay more attention on actuality and popularity of the topic. I personally going to create monkeysurvey to get that information.

With smaller audience you get more feedbacks. Why? Easily, they feel more relaxed and you have more time to allocate to each of them. In today's presenation I got so many interesting questions and figured them out for myself and for audience online, while writing code. That was amazing.

Try to understand those who did not participate. Probably they counted to be more reasonable to spend that hour on some urgent issues or they discounted topic, since they are sure that will not need AutoMapper. And if they even will need it, it is quite possible to learn it in amount of couple of hours.

Still be proud of yourself. This is must be, otherwise you will lose confidence which costs a lot.

Presentation

For my presentation I've used already existing posts on AutoMapper, also for the end of presentation I had real world usage examples.

And here is presentation itself:


View more presentations from Andriy Buday.

Don't forget to check out my article on AutoMapper here.

Sunday, July 18, 2010

Book Review: MCTS exam 70-505 Windows Forms Application Development Training Kit

Oh! Yet another training kit on Microsoft exam. This time it is Windows Forms Application Development (exam 505).
It was extremely boring to read this book.

Book talks on different Windows Forms related stuff. From the beginning it tries to teach me how to create simple forms app and add controls to it, but hey with my experience developing applications it is too boring. In advanced WinForms controls it talks on ListBox, TreeView, CheckBoxes and so on :) After so complex things it leads me to ADO.NET and how to work with connection Strings and how to even read data from DataReader. In advanced topics on Windows Forms Development it talks on how to create MDI application. OMG, i knew how to do them on my 3rd year in university. In asynchronous operations it talks on how I can use BackgroundWorker and even what is Thread and how to synchronize two of them. Maybe the most interested chapter was Deployment, at least because I never really used it either at work or in university.

But you know what is the most funny about all of this? - Possibility that I will not pass this exam. Why? - Because these entry ms exams are kind of exams for con. It require simple knowing of names of classes and functions. But on other hand I understand, that they couldn't make it different.

You just need to read this kit to pass this exam, almost no way to do it different.
I understand that if you have no experience working with Windows Forms book could bring lot of value for you. For example, do you know how to create not rectangular button or how to print documents programmatically.

Fact that I read this book means only one - which I'm going to schedule exam for next Friday and spend my evenings trying tests from book, and maybe MeasureUp. Also researching over internet how to prepare myself fot it.

So, wish me good luck on passing this exam.

Few bestowals

Being software developer is often pleasure, except of money it sometimes could even bring gifts.



VS 2010 Bag I've got at 3rd Lviv .Net User Group meeting. This bag isn't really of good quality, but it brings me pleasure to use it, since now Visual Studio 2010 covers my back :)

Working Effectively with Legacy Code came to me from USA and I'm really looking forward to read it soon. It looks that this is going to be my first non-electronic book in English that I will read full-length.

Book on Silverlight 4 (also got at Lviv .Net UG) isn't something that I hurry to read, because I'm sure that I will start with articles on Silverlight when I'll get to it.

Friday, July 16, 2010

Firefox 3.6.6 update dialog :)

Today Firefox asked me for update, of course I approved.

When it started downloading updates very quickly I got this picture:



Readers, do you see anything wrong with it? :)

I never thought that guys from Firefox could do such fun and stupid bug, but this proves that we all are human, still not ideal robots.

Thursday, July 15, 2010

Lviv .NET User Group: My presentation on NHibernate

Hello, as many of you know yesterday I spoke to NHibernate at local .NET User Group.

I won 20 beers, because we've got > 30 attendees

It was group's 4-th meeting and it went extremely well. Above 40 people participated and for me it was biggest audience I ever had to talk to during one hour or so. For another speaker - Derik Whittaker - I'm sure that this is not biggest audience he had, but maybe the biggest foreign language speaking audience. If I'm wrong please correct me.

Audience asked questions

People were asking me lot of questions and I tried to answer quickly and easily, but keeping in mind that I should continue and be in time, since it is bad practice to overtime speech.

I asked questions

To my own surprise flow of delivering this presentation was so smooth and harmonic with audience. Asking people simple questions, making them shaking their hands and keeping attention, because maybe another time I'll ask exactly someone from them.

I'm proud for my presentation skills

From day to day I become better in my ability to talk easily to technical audience. This time I've got the most sophisticated audience I ever had. They all had good experience working on different projects. So it was not like talking to university guys, who are very "green" in their understanding of technology and how things should look like.

Presentation itself

You could take a look at my presentation below.


View more presentations from Andriy Buday.

Not enough time to finish my second demo

For my second demo I allocated about 20 minutes, but it turned out, that I got about 10 and also talking to it and coding takes longer than sitting with my own keyboard and typing it at light speed. So sorry guys for not showing what I planned there.
What was planned and I did not show is: demoing lazy loading, chasing, complex Criteria API, and maybe the interesting - implementing own UnitOfWork and NHibernate repositories, approaches to build domain model with NHibernate.
BTW: I'm also going to have another blog post on NHibernate itself.


Really looking forward to get your feedback! Please leave your comments!

Thursday, July 8, 2010

Resharper: Plan for Developer's meeting

Resharper

Resharper is code refactoring and productivity extension to Visual Studio. While you are typing it analyzes code and highlights errors, suggests quick-solutions and hints on code completion. It allows you generate lot of code, perform code clean-up and do different refactorings. Resharper saves your time.

My reasons why to use Resharper
  • Productivity boost
  • Automate routine tasks if you need
  • IntelliSense that "thinks" instead of you
  • Great with Unit Tests
  • Chance to become light-speed guru
Why not to use Resharper (*)
  • You are not using Visual Studio
  • You are not going to pay for it
  • You are not going to be productive and earn more time/money
  • You are afraid of performance drawback

Developer's meeting

Finally I've decided to provide developer's meeting on Resharper. Long time ago (1.5 years) we had developers meeting provided for our team (about 50 people) on regular bases. We've lost that process because guy providing those has moved to Austria. Now we have those meetings quite rarely, mainly me trying to provide a lot of them. Help me, post some feedback here.

What you may need to be prepared for such kind of meeting?

It is obvious that we could not have PowerPoint pretension for this topic, so you will need write code illustrating Resharper. Second thing is that you should have some scenario to proceed with. You cannot simply go and create code on the flow, because it may happen that you will fall in wrong corner. So this post represents short plan for meeting and kick-off tutorial for my co-workers if they will like my talk.

Plan Of Attack

Introduction

I would need give some general definition to what Resharper is and show where from we can download it.
As it is recommended good approach is to know your auditory. Few questions? Ask who knows some hotkey, say Ctrl+Alt+G. This is very common hotkey, but not as much as Alt+Enter and answer for this question should allow you see how deeply they know Resharper and how quick you should be with core functionality in Resharper.

SetUp Resharper

Once you have installed Resharper, you may go and change keyboard layout under Resharper->Options->Visual Studio Integration
As I figured out almost each active user of Resharper uses IntelliJ IDEA keyboard layout and I would recommend it for you.


Besides, you may leave some of the VS native shortcuts - first time you are going to use F12 for example it will re-ask you if you want use Resharpers (navigate to error) or VS (go to definition) one. This way you may save most commonly used keys from VS. You can download keymap pdf file from here.

Also it is possible to save all of your configuration in xml file and share with others.

Damn It! Let's write some code.

KeyboardJedi

For the meeting you will need demonstrate hot-keys you are pressing. For this I'm using KeyboardJedi by Roy Osherove.
On following screenshot we can see that I've pressed Shift+F6 and got renaming dialog box. Please note KeyboardJedi at the left.


I renamed file to be Calculator.

Introducing Alt+Enter

This hotkey is the most commonly used. It shows available quick-fixes and context actions. Showing how we can change visibility of class with this. So guys start with learning this hotkey!

Templates usages


Pushing Members Up and Down


We even could mark something as abstract when pushing down.


So this gives us change in 3 different files simultaneously.

    public interface IOperation
    {
        double GetResult();
    }
    public abstract class OperationBase : IOperation
    {
        public abstract double GetResult();
    }
    public class OneOperandOperation : OperationBase
    {
        public override double GetResult()
        {
            return 0;
        }
    }
    public class TwoOperandsOperation : OperationBase
    {
        public override double GetResult()
        {
            return 0;
        }
    }

Learning Generating Code (Alt+Ins)

Generating constructor, properties,  auto-properties, surrounding with some template (Ctrl+Alt+Ins)

Scenario: method needs to be thread-safe, so we surround it with locking (Ctrl+Alt+Ins), and we are refactoring with introducing object lock, then we refactor with introducing field (Ctrl+Shift+R).

Scenario: method has lot of code so we use extract method refactoring (Ctrl+Alt+M).

Navigation (Ctrl+Alt+G)

Navigation is one of the features of resharper that is very important in huge complex solutions. And that is one of my favorite ones. JetBrains did a lot of improvements in navigating through solution.
From any part of code you could easily navigate to whatever you want by pressing: Ctrl+Alt+G.

Navigate to type (Ctrl+N)

When showing this also good to illustrate on big solution, also mentioning about camel cases. So in picture below, you could see that I just typed "CDS" and I'm able to see few different classes that match what I need.
Scenario: Navigation to declaration, implementation and so on.
Navigation to class members (Ctrl+F12).

Unit Testing
Resharper supports unit testing frameworks, so it could easily work with NUnit as well as MSTests in one solution.

Scenario: Writing UT using live template for test method, debugging UT imitating TDD, creating shortcut for UT run.

Live template
When showing unit testing capabilities we may show how to create template for unit test, or some special kind of UT.

Few other scenarios

Links

Everything needed could be found from this page: http://www.jetbrains.com/resharper/

P.S. Items marked with (*) were added after I had posted this article.

Monday, July 5, 2010

Using NHibernate Profiler with Unit Tests

Today, I've been writing few methods for my DAL classes, of course, I decided to have one or few integration unit tests that hits database and see actual SQLs with NHibernate Profiler.

So in couple of minetes I've got unit tests that had following line in the beggining of each:

 HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();

if you don't know, this line attaches your execution code with NHibernate Profiler, so I'm able to see SQLs NHibernate generates.

When I run bunch of unit tests in my testing file, I've got strange picture with duplicating of queries for each test with arithmetic progression. And N+1 problem, but hold on, I'm sure that I did everything through joins.



Reason is that profiler appends to my code on each new test run and that is why it start thinking that I have multiple selects to get list of something.

Solution, which I would recommend as pattern for writing Unit Tests with NHibernate Profiler is following:

        [SetUp]
        public void SetUp()
        {
            HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();
        }

        [TearDown]
        public void TearDown()
        {
            HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Stop();
        }

Saturday, July 3, 2010

My 100-th blog post: Blogging Pays Off

Hello my dear readers, this post is my 100-th one blog post.

Almost 9 months left since I posted my first words here. I went through different things there. Starting with Design Patterns and different educational stuff, since I was going my Master year, and finishing with different book reviews and tips on how to become successful. But why do I need blog?

First of all I love blogging. It helps me feel that I'm needed in this world and that I bring something valuable to others. Also it takes me closer to my life goals, to become successful world known developer. And even if I shift to some managers position in future I will still be developer of my and people's around lives.

Blogging keeps me concentrate on different topics, I'm describing, helping me understand them better. I would bet that most of the software developers think that they know Gof design patterns, but indeed when you ask them about main concepts they could list only obvious. Ask them research over internet and create own example and bright understanding will come to their mind. Same things happens to me. It is just amazing how something could be clear after you wrote blog post on it.

Sometimes I've been posting short quick tips. They could look useless, but when I come to the same problem I just go to my blog and see the solution. It happened to me few times, and I was really proud that I have this blog.

Blogging helps me differ from other of my colleges. They see that I do the best to keep in touch with new technologies and that I'm trying to self-improve. From another side, sometimes it makes me sad when I see others being much more proactive and productive, as Scott Hanselman (blogging god?), so I'm afraid that I make someone around upset. But from yet another side when I see those active people it drives me to become super active. So I hope I help my coworkers in their passion to became famous.

Blogging increases my visibility. I've been asked few times for meetings outside of my company. Once it was about creating user group, finally it was created without me, but now I'm with those guys, helping them develop best .NET UG in Ukraine. Another time it was job opportunities but I did not leave my company, hope it was right decision.

Finally, blogging pays off! Week ago I had performance appraisal and besides of my usual capabilities like result orientation and knowledge, my blog played evident role in how that meeting went. Now I have possibility to be Senior Developer in my company with higher salary, I hope :). But remember that is not just your blog possibility to lead you to success. It is your hard work and attitude to things you do.

Be directed to your goal and move forward!

Sketching and prototyping with Firefox

I was thinking about what to post and I've got nice twits like this one:

@sbohlen I am quite impressed by this http://bit.ly/ci3fxn Its no #balsamiq but its still amazing (and free); runs in and OUT of your browser

So why not to try that thing. So I installed Pencil add-on.

Here is screenshot of my try:


Toolbar on the left is rich of different shape collections. Sadly I did not find one for UML diagrams, but they could be easily added and that is great.

So this is the simplest way to have light prototyping machine just in your browser.

Few simple mocking scenarios

Are you married? Yeah, quite not usual question for blog post about mocking, but if you are married you probably asked your girl to become your wife.

So you are playing role of PotentialHasband:

    public interface IPotentialHusband
    {
        string AskForHerHandInMarriage();
    }

and she is PotentialWife, taking your ask into consideration and answering you true or false.

    public interface IPotentialWife
    {
        bool GiveHimAnswer(string hisSpeech);
    }

If she is Linda, you would need to have "I love you" in your speech to get her agreement:

    public class Linda : IPotentialWife
    {
        public bool GiveHimAnswer(string hisSpeech)
        {
            return hisSpeech.Contains("I love you");
        }
    }

Btw, if your wife is indeed Linda, you just need  put some comments below :)

What we are going to test is to see that after you asked, she will definitely give you at least some answer and not ignore you. Also if her answer is "YES" we would like to see MarriageService called Marry method.

    public class MarriageService
    {
        public virtual void Marry(IPotentialHusband almostHusband, IPotentialWife almostWife)
        {
            Console.WriteLine("You are now husband and wife!");
        }
    }

Class which we are going to test is named LearningMocking and has constructor that accepts potential husband/wife and marriageService. Whole story takes place in RestaurantDinner method.

First let's test that after you asked she gives at least some answer. Since we are not interested in concrete instances we just generate mocks for our interfaces, and passing null instead of marriage service. I'm using RhinoMocks in this example.


        [Test]
        public void EnsureThatAfterHeAskedSheAnswers()
        {
            var potentialHusband = MockRepository.GenerateMock<IPotentialHusband>();
            var potentialWife = MockRepository.GenerateMock<IPotentialWife>();
            var learningRhino = new LearningMocking(potentialHusband, potentialWife, null);

            learningRhino.RestaurantDinner();

            potentialHusband.AssertWasCalled(x => x.AskForHerHandInMarriage());
            potentialWife.AssertWasCalled(y => y.GiveHimAnswer(Arg<string>.Is.Anything));
        }

This ensured that at least she will give you some answer. In next test we will have some mix and will use concrete class Linda. We have generated Stub for return value of your speech, so instead of writing concrete class for husband we've used stub. This test shows that she will not marry you:

        [Test]
        public void EnsureLindaWillRejectHim()
        {
            var potentialHusband = MockRepository.GenerateMock<IPotentialHusband>();
            var linda = new Linda();
            var marriageService = MockRepository.GenerateStub<MarriageService>();
            var learningRhino = new LearningMocking(potentialHusband, linda, marriageService);
            potentialHusband.Stub(x => x.AskForHerHandInMarriage())
                .Return("Hey lady, would you marry me?");

            learningRhino.RestaurantDinner();

            marriageService.AssertWasNotCalled(x =>
                x.Marry(Arg<IPotentialHusband>.Is.Anything, Arg<IPotentialWife>.Is.Equal(linda)));
        }

Let's use another strategy to ask Linda:

        [Test]
        public void GiveHimAnotherTry()
        {
            var potentialHusband = MockRepository.GenerateMock<IPotentialHusband>();
            var linda = new Linda();
            var marriageService = MockRepository.GenerateStub<MarriageService>();
            var learningRhino = new LearningMocking(potentialHusband, linda, marriageService);
            potentialHusband.Stub(x => x.AskForHerHandInMarriage())
                .Return("Linda, I love you, would you marry me?");

            learningRhino.RestaurantDinner();

            marriageService.AssertWasCalled(x => 
                x.Marry(Arg<IPotentialHusband>.Is.Anything, Arg<IPotentialWife>.Is.Equal(linda)));
        }

Except of verifying that Marry method was called we also verify that it was called with instance of linda and none else with line Arg<IPotentialWife>.Is.Equal(linda). As well you could setup constructor arguments for MarriageService, since it is not an interface. Also with Rhino.Mocks you will need to have method Marry to be virtual. If it is not virtual and you don't have interface for it you may need to extend that class with your own.

In the end we've got this method:

        public void RestaurantDinner()
        {
            string wouldYou = PotentialHusband.AskForHerHandInMarriage();
            if(PotentialWife.GiveHimAnswer(wouldYou))
            {
                MarriageService.Marry(PotentialHusband, PotentialWife);
            }
        }

Nice picture:







Please write down if you would like to see more complex mocking examples.

Book Review: The Goal: A Process of Ongoing Improvement

Last weekend I had a chance to read very interesting book, kind of business novel. I was given this book by my managers after we finished with my performance appraisal. Which (btw) went very well. 


Book talks about guy, who manages plant where he encounter problem of going behind the schedule and his bosses wanted to close out his plant. But he with colleges, using Theory of Constraints and sophisticated thinking, was able to get plant to the new level.

From first pages I was not sure if book is kind of my thing, since I usually don't read novels,  but it turns out that book is only a bit hard going at the beginning. From page to page it was more gripping to read and in the end it just became a real page-turner.


Book forces us to think that everything is possible, you just need to take a look for wider solutions without using any of your stereotypes. Book never gives you ready answers, so it is thought-provoking one. First it states the problem, describing it in details, after that main hero is bombarded with different questions by friends, which provoke us think in pair with him.

Reading book was really-really enjoyable and I would highly recommend it for your reading. Book indeed is exciting for those who are interested in career development and in manager's positions.

P.S. I've changed this post a bit to use more specific words like: interesting, exciting, thought-provoking, a real page-turner, gripping, kind of my thing, hard going at the beginning, gripping. That was English course activity to have review on some book. I'm lazy to write new one.

Memento

If you ever played any shooter game, you probably know what do hot-keys F5 & F9 mean. If you did not play those anyway you should be aware of usefulness of quick-save/quick-load functionality. By pressing F5 you save your current location your health/armor levels and maybe some other information, like how many monsters did you kill already. This defines your state which is going to be saved. On pressing F9 you return to your previous saved state (kind of undo operation).

When you are saving your state you don't wanna it to be accessible by other classes (encapsulation of state), so you will be sure that none will decrease you health level. Also you wanna keep track of savings and maybe you are going to add functionality that will get back through two-three saves by pressing Shift+F9 (+F9).

How can you accomplish this?

MEMENTO

Memento pattern is used when you want do undo operations without exposing internal state of the Originator (Game). Coordination of operations is done by Caretaker, or something that simply lists mementos and therefore remembers states without knowing what are they.

Let's take a look at implementation:

Originator (Game)

public class GameOriginator {
    private GameState _state = new GameState(100, 0);//Health & Killed Monsters

    public void Play(){
        //During this Play method game's state is continuously changed
        System.out.print(_state.toString());
        _state = new GameState((int) (_state.Health * 0.9), _state.KilledMonsters + 2);
    }

    public GameMemento gameSave(){
        return new GameMemento(_state);
    }

    public void loadGame(GameMemento memento){
        _state = memento.getState();
    }

    public class GameMemento {
        private final GameState _state;
       
        private GameMemento(GameState state) {
            _state = state;
        }

        private GameState getState(){
            return _state;
        }
    }
}


So it is able to generate memento instance with current game state, as well it is able to get state from existing memento, BUT none else could get that state, since GameMemento is inner class of Game and methods are private.


Caretaker

Or the guy, who keeps track of your F5/F9th. Currently it is able to load the latest one quick save, but it could be easily enhanced.

public class Caretaker {
    private GameOriginator _game;
    private Stack<GameOriginator.GameMemento> _quickSaves = new Stack<GameOriginator.GameMemento>();

    public Caretaker() {
        _game = new GameOriginator();
    }

    public void shootThatDumbAss(){
        _game.Play();
    }

    public void F5(){
        _quickSaves.push(_game.gameSave());
    }
   
    public void F9(){
        _game.loadGame(_quickSaves.peek());
    }
}



Output

With following usage code:

        Caretaker caretaker = new Caretaker();
        caretaker.F5();
        caretaker.shootThatDumbAss();
        caretaker.F5();
        caretaker.shootThatDumbAss();
        caretaker.shootThatDumbAss();
        caretaker.shootThatDumbAss();
        caretaker.shootThatDumbAss();
        caretaker.F9();
        caretaker.shootThatDumbAss();

our application generates:

Health: 100
Killed Monsters: 0
Health: 90
Killed Monsters: 2
Health: 81
Killed Monsters: 4
Health: 72
Killed Monsters: 6
Health: 64
Killed Monsters: 8
Health: 90
Killed Monsters: 2


Here is quick UML, that I drew for my example:


My Design Patterns Table