Refactoring to Patterns

Joshua Kerievsky

Mentioned 34

Kerievsky lays the foundation for maximizing the use of design patterns by helping the reader view them in the context of refactorings. He ties together two of the most popular methods in software engineering today--refactoring and design patterns--as he helps the experienced developer create more robust software.

More on Amazon.com

Mentioned in questions and answers.

What are the ways to eliminate the use of switch in code?

See the Switch Statements Smell:

Typically, similar switch statements are scattered throughout a program. If you add or remove a clause in one switch, you often have to find and repair the others too.

Both Refactoring and Refactoring to Patterns have approaches to resolve this.

If your (pseudo) code looks like:

class RequestHandler {

    public void handleRequest(int action) {
        switch(action) {
            case LOGIN:
                doLogin();
                break;
            case LOGOUT:
                doLogout();
                break;
            case QUERY:
               doQuery();
               break;
        }
    }
}

This code violates the Open Closed Principle and is fragile to every new type of action code that comes along. To remedy this you could introduce a 'Command' object:

interface Command {
    public void execute();
}

class LoginCommand implements Command {
    public void execute() {
        // do what doLogin() used to do
    }
}

class RequestHandler {
    private Map<Integer, Command> commandMap; // injected in, or obtained from a factory
    public void handleRequest(int action) {
        Command command = commandMap.get(action);
        command.execute();
    }
}

If your (pseudo) code looks like:

class House {
    private int state;

    public void enter() {
        switch (state) {
            case INSIDE:
                throw new Exception("Cannot enter. Already inside");
            case OUTSIDE:
                 state = INSIDE;
                 ...
                 break;
         }
    }
    public void exit() {
        switch (state) {
            case INSIDE:
                state = OUTSIDE;
                ...
                break;
            case OUTSIDE:
                throw new Exception("Cannot leave. Already outside");
        }
    }

Then you could introduce a 'State' object.

// Throw exceptions unless the behavior is overriden by subclasses
abstract class HouseState {
    public HouseState enter() {
        throw new Exception("Cannot enter");
    }
    public HouseState leave() {
        throw new Exception("Cannot leave");
    }
}

class Inside extends HouseState {
    public HouseState leave() {
        return new Outside();
    }
}

class Outside extends HouseState {
    public HouseState enter() {
        return new Inside();
    }
}

class House {
    private HouseState state;
    public void enter() {
        this.state = this.state.enter();
    }
    public void leave() {
        this.state = this.state.leave();
    }
}

Hope this helps.

A lot of people seem to agree, that the Singleton pattern has a number of drawbacks and some even suggest avoiding the pattern entirely. There's an excellent discussion here. Please direct any comments about the Singleton pattern to that question.

My question: Are there other design patterns, that should be avoided or used with great care?

It is simple ... avoid Design Patterns that are not clear to you or those that you do not feel comfortable in.

To name some ...

there are some unpractical patterns, like e.g.:

  • Interpreter
  • Flyweight

there are also some harder to grasp, like e.g.:

  • Abstract Factory - Full abstract factory pattern with families of created objects is not such a breeze as it seems to be
  • Bridge - Can get too abstract, if abstraction and implementation are divided to subtrees, but is very usable pattern in some cases
  • Visitor - Double dispatch mechanism understanding is really a MUST

and there are some patterns that look terribly simple, but are not so clear choice because of various reasons related to their principle or implementation:

  • Singleton - not really totally bad pattern, just TOO overused (often there, where it is not suitable)
  • Observer - great pattern ... just makes code much harder to read and debug
  • Prototype - trades compiler checks for dynamism (which can be good or bad ... depends)
  • Chain of responsibility - too often just forcedly/artificially pushed into the design

For those "unpractical ones", one should really think about before using them, because there is usually more elegant solution somewhere.

For the "harder to grasp" ones ... they are really great help, when they are used at suitable places and when they are implemented well ... but they are nightmare, when improperly used.

Now, what's next ...

A complement to Spoike's post, Refactoring to Patterns is a good read.

I am going to be giving developers at my company a crash course on design patterns (after coming across some scary code recently).

One of the most important things I want to put across is that they save time in both the long and short term (which they really do!) - as developers here are put under quite a bit of time strain. All in all I need to demonstrate the every day benefits - things that will let them go home early.

Telling them that it might mean less bugs probably isn't going to hit home. I need stuff that is going to sink in.

I will probably do three to four sessions of an hour each. Do you guys have any suggestions on what to touch on/to do?

Head First Design Patterns would be a great place to start. It covers the mainstream design patterns.

Refactoring to Patterns might also be of interest.

If you can't buy a book for every developer, buy a few and spread them around.

You are in a unique position for a course-giver: you know the developers and you know the code that they are working with.

A possible approach would be to look at some of the scary code, and go along the lines of "How could we go about improving this? As it happens, there's a design pattern called Observer...."

This might end up being a mix of design patterns and refactoring. But that might be appropriate, given that you're trying to reach developers working on an existing code base.

Good opening slides for any education course in my opinion are:
1) Why are we here? (Where has the need for this course been identified?)
2) What do I expect to learn?
3) Who should take this course? (What are the intended students, prerequisites, etc?)
4) When can I apply what I’ve learned?
5) Expectations of you (Participation, homework, tests, minimum classes to attend, etc)

For design patterns I could expect several visual tools or "job aids".

I would follow a structure similar to the Elements of Reusable Object-Oriented Software book:

1) UML – Class Diagram Overview
2) OOP – Abstraction, Encapsulation, Polymorphism, Inheritance
3) Cohesion and Coupling
4) What is a design Pattern? – Pattern Name, The Problem, The solution, The consequences
5) Why are design patterns so hard to learn?
6) Why use design Patterns?
7) How to Select a Design Pattern
8) How to Use a Design Pattern
9) Cover various GoF design patterns with examples – Show examples of code before applying a design pattern, and how it looks after like Vince Huston does in his examples.
10) Conclusion

As already mentioned, design patterns are really ideas, so when teaching you must convey the idea. If they understand the problem, solution and consequences of the design pattern, then they will be far better off than trying to force patterns into the code (and that will become a nightmare). Recognition of where and what patterns (if any) can be applied is the real goal. The Huston examples are really good for putting out an example of code to the class and seeing if they can identify a pattern to improve it. Hope this helps.

In The Guerilla Guide to Interviewing Joel says that guys who want to get things done, but are not smart will do stupid things like using a visitor design pattern where a simple array would be sufficient.

I find it hard to detect, if the design pattern suggested by the Gang of Four should be applied.

Therefore, I would like some examples from Your work experience

  • When is a simple approach (fixed size array) sufficient?
  • What is the minimum size of a piece of software that justifies the use of the GoF patterns?
  • When to refactor from simple-minded to GoF? Can this be done in a sensible way?

I often find that using test driven development helps guide me when faced with these questions.

  • When is a simple approach sufficient? It is always sufficient to use the simplest approach to get the next test to pass. But knowing when/how to refactor is the real art form.
  • What is the minimum size of a piece of software that justifies the use of the GoF patterns? A rule of thumb I once read is that when you code something once, fine, when you duplicate that code somewhere a second time, make a note and move on. When you find a need for the same code a third time, it's time to refactor to remove duplication and simplify, and often that involves moving to a design pattern.
  • When to refactor from simple-minded to GoF? I like what @anopres said - it's time when you feel the pain of not having the design pattern in place. The pain (or code "smell") may manifest itself in several ways. Code duplication is the most obvious. Refactoring books like Fowler's Refactoring or Kerievsky's Refactoring to Patterns list many such pain points/code stenches.
  • Can this [refactoring] be done in a sensible way? The trick to refactoring is to have a suite of unit tests in place which you have confidence in, and then to refactor without causing any of those tests to fail. Refactoring, by definition, does not change the functionality of your code. Therefore, if your tests continue to pass, you can have a pretty good feeling that you didn't break anything. Although it can be difficult, I actually enjoy this part of TDD, it's almost like a game to make changes without breaking any tests.

In summary, I would say that TDD helps guide me to write the code that is sufficient at the time, and perhaps more importantly helps me to make the changes later when inevitably requirements change, more functionality is required, etc.

I have inherited a monster.

It is masquerading as a .NET 1.1 application processes text files that conform to Healthcare Claim Payment (ANSI 835) standards, but it's a monster. The information being processed relates to healthcare claims, EOBs, and reimbursements. These files consist of records that have an identifier in the first few positions and data fields formatted according to the specs for that type of record. Some record ids are Control Segment ids, which delimit groups of records relating to a particular type of transaction.

To process a file, my little monster reads the first record, determines the kind of transaction that is about to take place, then begins to process other records based on what kind of transaction it is currently processing. To do this, it uses a nested if. Since there are a number of record types, there are a number decisions that need to be made. Each decision involves some processing and 2-3 other decisions that need to be made based on previous decisions. That means the nested if has a lot of nests. That's where my problem lies.

This one nested if is 715 lines long. Yes, that's right. Seven-Hundred-And-Fif-Teen Lines. I'm no code analysis expert, so I downloaded a couple of freeware analysis tools and came up with a McCabe Cyclomatic Complexity rating of 49. They tell me that's a pretty high number. High as in pollen count in the Atlanta area where 100 is the standard for high and the news says "Today's pollen count is 1,523". This is one of the finest examples of the Arrow Anti-Pattern I have ever been priveleged to see. At its highest, the indentation goes 15 tabs deep.

My question is, what methods would you suggest to refactor or restructure such a thing?

I have spent some time searching for ideas, but nothing has given me a good foothold. For example, substituting a guard condition for a level is one method. I have only one of those. One nest down, fourteen to go.

Perhaps there is a design pattern that could be helpful. Would Chain of Command be a way to approach this? Keep in mind that it must stay in .NET 1.1.

Thanks for any and all ideas.

I just had some legacy code at work this week that was similar (although not as dire) as what you are describing.

There is no one thing that will get you out of this. The state machine might be the final form your code takes, but thats not going to help you get there, nor should you decide on such a solution before untangling the mess you already have.

First step I would take is to write a test for the existing code. This test isn't to show that the code is correct but to make sure you have not broken something when you start refactoring. Get a big wad of data to process, feed it to the monster, and get the output. That's your litmus test. if you can do this with a code coverage tool you will see what you test does not cover. If you can, construct some artificial records that will also exercise this code, and repeat. Once you feel you have done what you can with this task, the output data becomes your expected result for your test.

Refactoring should not change the behavior of the code. Remember that. This is why you have known input and known output data sets to validate you are not going to break things. This is your safety net.

Now Refactor!

A couple things I did that i found useful:

Invert if statements

A huge problem I had was just reading the code when I couldn't find the corresponding else statement, I noticed that a lot of the blocks looked like this

if (someCondition)
{
  100+ lines of code
  {
    ...
  }
}
else
{
  simple statement here
}

By inverting the if I could see the simple case and then move onto the more complex block knowing what the other one already did. not a huge change, but helped me in understanding.

Extract Method

I used this a lot.Take some complex multi line block, grok it and shove it aside in it's own method. this allowed me to more easily see where there was code duplication.

Now, hopefully, you haven't broken your code (test still passes right?), and you have more readable and better understood procedural code. Look it's already improved! But that test you wrote earlier isn't really good enough... it only tells you that you a duplicating the functionality (bugs and all) of the original code, and thats only the line you had coverage on as I'm sure you would find blocks of code that you can't figure out how to hit or just cannot ever hit (I've seen both in my work).

Now the big changes where all the big name patterns come into play is when you start looking at how you can refactor this in a proper OO fashion. There is more than one way to skin this cat, and it will involve multiple patterns. Not knowing details about the format of these files you're parsing I can only toss around some helpful suggestions that may or may not be the best solutions.

Refactoring to Patterns is a great book to assist in explainging patterns that are helpful in these situations.

You're trying to eat an elephant, and there's no other way to do it but one bite at a time. Good luck.

I'm starting on a fresh new project--should I look at my spec and decide which design patterns to apply, or just come up with a general idea of organization and allow the patterns to emerge organically through refactoring?

In your experience, which technique will be most productive and have a greater chance of leading to clean elegant code?

I'm also wondering if there are design patterns out there that aren't defined by the GoF, but could be just as valuable? If so, what are some useful resources for informing myself about these?

I'd stay away of patterning your coding too much by upfront design pattern usage. It is better to just make simple code and when needed refactor towards a design pattern that then captures your requirements best.

I've googled a lot and can't find what I look for.

I look for some architecture practice. I mean there are a lot of books about Design Patterns, but I want something like analysis of common mistakes in architecture of EE applications. All I've found - antipatterns like string concatenation or something else that can be found with help of FindBug or Sonar.

How I figure it out:

  1. Book with next steps: task definition, wrong decision, why it is bad, right decision.
  2. Educational resources. I heard there are such resources for testers. Some applications are opened for testing and each who want to learn testing can test it; and after some period discuss own result with other people or see the percent of bugs he has found.
  3. Maybe other ideas?

Why I think Design Pattern books are not suitable for me:

A developer may know many design patterns from such books, but can be incapable of selecting the correct one for the specific situation. IMHO, this is because these books don't give you any practice, and fail to educate the reader as to which design pattern(s) should be applied to any situation. Those books just get you a ready solution.

EDIT:

There aren't any answers any more. So I want to expand my question:

I believe, no I'm certain that exist courses dedicated to improve architecture skills, show the common mistakes in designing of web applications and so on. Also I know that there are a lot of conferences linked with this subject.

Advice me where should I look for them, please.

Can I assume that you know how to create independent objects using Dependency Injection? If not, this would be an excellent are in which to cultivate reuse and create a more robust architecture. Using DI would be an excellent way to re-architect an existing solution. (Contrast that with much evolved code, which becomes brittle because of interdependency.)

While you're not looking toward Design Pattern books, I'd ask you to glance at Refactoring to Patterns by J. Kerievsky.

Kerievsky takes you through some real-life refactorings which have titles like "Move Creation Knowledge to Factory." (It's "real-life" in that he uses actual code, not a contrived example.)

Finally, I have been encouraged in our recent use of Spring Integration as an Enterprise Integration Pattern. If you architect and implement even a modest project in Spring Integration, you'll get quite a lot of experience with both DI and EIP.

To me design patterns look like solutions to isolated problems. In real practice we have to deal with combinations of problems, which are highly dependent. I have never seen any pattern used purely. I can recommend one book which gives a wider view of software architecture: Domain-Driven Design: Tackling Complexity in the Heart of Software. It says how to approach to software design, instead of giving a set of common tools. With some examples it explains how to solve a set of problems in combination.

One more book gives an explanation on how to design classes and their collaboration: Interface Oriented Design: With Patterns. To write good understandable and maintainable code. It explains a lower level approaches rather then DDD.

I was just going through Design Patterns Questions on Stackoverflow and everyone mentioned about GoF- Design Pattern book and Head First Design Patterns book to learn them.

My questions is how can we learn where and when can we apply particular Design Pattern.

Are there any books or online resources which imparts this knowledge or what steps we need to follow in making our decision of where and when we should use particular Design Patterns ?

I would recommend sourcemaking.com. It provides a general discussion on how and when to use the GoF design patterns. And how you can combine them for the best result.

Also Joshua Kerievsky's book Refactoring to patterns might be a valuable resource.

Recently I came about this concept of Design Patterns, and felt really enthusiastic about it. Can you guys suggest some resources that help me dive into Design Patterns?

You know, for me, one of the best books out there is Head First Design Patterns. I personally like the style that they use to communicate the material.

The gang of four design patterns book is the standard. I recommend it if you're comfortable with C++.

Head first design patterns is good too, especially if you like visual aids and want to feel like you're learning design patterns in a '50s diner. Examples are in Java.

There are sometimes multiple ways to implement patterns in a given programming language (for example see this discussion of options for implementing the Singleton pattern in C#), so it might be worth getting one book to succinctly describe the common patterns, and another to suggest the best way to implement them in your favorite language.

Martin Fowler's website has plenty of information: http://martinfowler.com/articles.html. Much of this is covered also in his book, Patterns of Enterprise Application Architecture.

I find Design Patterns Explained to be a good introductory text. The Gang of Four book is a reference for those who already understand patterns.

Wikipedia, the Gang of Four book, and if you're specifically interested in C# implementations there's a decent site here.

Refactoring is the process of improving the existing system design without changing its behavior.

Besides Martin Fowler's seminal book "Refactoring - Improving the design of existing code" and Joshua Kerievsky's book "Refactoring to Patterns", are there any good resources on refactoring?

Working Effectively with Legacy Code focuses on dealing with existing code-bases that need to evolve to be testable. Many techniques are used in the book to accomplish this, and is an excellent resource for refactoring.

I would recommend reading Working Effectively with Legacy Code, then Refactoring - Improving the design of existing code. Martin Fowler's book is more like a receipt book for me, it explains how. Working effectively with legacy code, explains the why in my opinion.

below is some other books relating to refactoring:

antipatterns refactoring software architectures and projects in crisis

refactoring in large software projects performing complex restructurings

refactoring sql applications

Prefactoring

As a junior developper, i'm a bit confused about some design patterns. Sometimes, i just don't know which to use in which context.

For exemple, on creational patterns, i don't really know when to use:

  • Factory
  • Prototype
  • Builder

Actually, i see some differences; but i also see that you can use multiple solutions like:

  • Calling a factory that calls the appropriate builder that clones a prototype.
  • Calling a factory that clones the appropriate prototype
  • Calling a builder with the appropriate director
  • ...

I mean, the result of these creations is at the end the same: you get your object instance.

I just wonder what kind of design you would use on different contexts (i guess it could be depending on performence needs, objects complexity, coupling...)

Also, I don't really see a big differences between a facade and a mediator, except the mediator calls different interfaces.

Same for chain of responsability, don't really understand why all implementations i see use chained lists. Can't this pattern be implemented with a simple List of handlers that we call successively?

That's why i'd like people to tell me in which concrete context you would use a GoF pattern, and also why you wouldn't use any of the other patterns that could have fit to the given problem (but probably in a less elegant way).

Thanks

Initially, I found the easiest way to learn patterns was to come across a situation that needed help (too complex to understand at a glance) and then implement it. It's difficult to understand why a pattern is beneficial until you have a problem that really calls for it.

An excellent resource for this is 'Refactoring to Patterns' by Joshua Kerievsky.

I tend to successfully write compact applications that can encapsulate many business logic in a simple and non-redundant way. I tend to create small methods, but over time I arrive to methods that have too many parameters. I know every code requires its design, but I see an anti-pattern in my behavior and I am not sure which would be the best way to fight against it.

A typical situation would be something like:

   public loanStructure CalculateSomeComplicatedInterestRate(enum clientType, 
        int totalAmout, bool useTaxes, bool doYearlySummary, bool doNotReloadClient, etc)
   {
        loanStructure ret = new loanStructure();
        if (doNotReloadClient) ... ;
        ...
        if (doYearlySummary) GroupResults(ret);
        return ret;
   }

and inside the method, a tree of calls forwards the boolean settings (doYearlySummary, doNotReloadClient, etc) to different business rules that acts on the calculation.

I.E., the problem does not reside on the fact that all parameters could be encapsulated into an object (bigParameterStructure)... I am not comfortable with the masterMethod pattern, but making overloads such as CalculateSomeComplicatedInterestRateMonthly and CalculateSomeComplicatedInterestRateYearly would just hide a private CalculateSomeComplicatedInterestRate.... some problem!!

Of coarse object-orienting design would help... but I still end-up having this kind of methods somewhere on my objects...

Well guys... any help is welcome.

Pablo.

When I face code smells I scan Refactoring: Improving the Design of Existing Code and Refactoring to Patterns. This books are plenty of useful advice to refactor code.

i have a hashMap which i would like its data to be viewed in a JTable how ever i am having trouble getting the hashMap amount of columns and rows and the data to be displayed.i have a hashmap which takes a accountID as the key and a object of students in which each students have their data like name,id, age, etc.however referring to the JTable docs, it says i would need ints for the row and column and a multidimension array of type Object. how can i do it? can i change my hashMap into a multidimenion array?

--Edit i have edited my question so it could be more clear , i am fairly new to Java i do not really get what some of you have posted, especially since the work i am doing is quite related to OO and grasping OO concepts is my biggest challenge,

/I have a dataStorage class, the registered user is added to the HashMap with a Key input of his Username, which is getUser ./

import java.util.*;

public class DataStorage 
{
    HashMap<String, Student> students = new HashMap<String, Student>();  
    HashMap<String, Staff> staffMembers = new HashMap<String, Staff>();  
    //Default constructor
    public DataStorage(){
    }

    public void addStaffMember(Staff aAcc) 
    {
     staffMembers.put(aAcc.getUser(),aAcc);
    }

    public void addStudentMember(Student aAcc)
    {
     students.put(aAcc.getUser(),aAcc);
    }

   public Staff getStaffMember(String user)
   {
   return   staffMembers.get(user);
   }

   public Student getStudent(String user)
   {
    return students.get(user);
   }

   public int getStudentRows()
   {
        return students.size();
   }


}

/**** This is a student class which extends Account***/

public class Student extends Account {

    private String studentNRIC;
    private String diploma;
    private String gender;
    private double level;
    private int credits;
    private int age;
    private boolean partTime;
    private boolean havePc;
    private boolean haveChild;

    public Student(String n, String nr, String id, String dep, String user, String pass)
    {
        super(n, dep, user, pass, id);
        studentNRIC = nr;
    }

    public void setPartTime(boolean state)
    {
        if(state == true)
        {
            partTime = true;
        }
        else
        {
            partTime = false;
        }
    }

    public boolean getPartTime()
    {
        return partTime;
    }

    public void setHavePc(boolean state)
    {
        if(state == true)
        {
            havePc = true;
        }
        else
        {
            havePc = false;
        }
    }

    public boolean getHavePc()
    {
        return havePc;
    }

    public void setHaveChild(boolean state)
    {
        if(state == true)
        {
            haveChild = true;
        }
        else
        {
            haveChild = false;
        }
    }

    public boolean getHaveChild()
    {
        return haveChild;
    }
    public void setDiploma(String dip)
    {
        diploma = dip;
    }

    public String getDiploma()
    {
        return diploma;
    }

    public void setCredits(String cre)
    {
        credits = Integer.parseInt(cre);
    }

    public int getCredits()
    {
        return credits;
    }

    public void setGender(String g)
    {
        gender = g;
    }

    public String getGender()
    {
        return gender;
    }

    public void setAge(String a)
    {
        age = Integer.parseInt(a);
    }

    public int getAge()
    {
        return age;
    }
    public void setLevel(String lvl)
    {
        level = Double.parseDouble(lvl);
    }

    public double getLevel()
    {
        return level;
    }
    public void setStudentNRIC(String nr)
    {
        studentNRIC = nr;
    }

    public String getStudentNRIC()
    {
        return studentNRIC;
    }

}

/**** This is a the Account superclass***/

public class Account {

    private String name;
    private String department;
    private String username;
    private String password;
    private String accountID;
    public Account()
    {
    }   
    public Account(String nm,String dep,String user,String pass, String accID) 
    {
        name = nm;
        department = dep;
        username = user;
        password = pass;
        accountID = accID;

    }

    public void setName(String nm)
    {
        name = nm;
    }

    public String getName()
    {
        return name;
    }

    public void setDep(String d)
    {
        department = d;
    }

    public String getDep()
    {
        return department;
    }

    public void setUser(String u)
    {
        username = u;
    }
    public String getUser()
    {
        return username;
    }

    public void setPass(String p)
    {
        password = p;
    }

    public String getPass()
    {
        return password;
    }

    public void setAccID(String a)
    {
        accountID = a;
    }

    public String getAccID()
    {
        return accountID;
    }
}

Your DataStorage is like the StudentRegistration is used in the sample code.

 // TIP: It can be handy to place the student in some order in the Map 
    //      (therefore using the sorted map).
    private SortedMap students = new TreeMap();  
    // QUESTION: Why not use argument name 'student'?
    public void addStudentMember(Student aAcc)
    {
        students.put(aAcc.getUser(),aAcc);
    }
    // Updated implementation
    public void addStudent(Student student)
    {
        students.put(student.getAccID(), student);
    }
 // QUESTION: Would a method name 'getNumberOfStudents' not be better?  
    public int getStudentRows()

For me it is a little unclear why Student extends from Account. The account identification, is that an unique-id, through the hole system? Do staff (users) and student (users) all have that as unique identification? Where / who creates them? If not the system self, it can never be guranteed that they also enter correctly into your system. Even when checking on uniqueness within your system, helps. But who say not someone else (by accedent) used someone else his/her unique id? (How are the student and staff (accounts) created? If these id's are indeed unique, why not use those for placing the student into a SortedMap? If the sorting is not important. Why not just use a List of students?

Is the name parameter unique (by which you place the student in the Map)?

Programming is little more then learning a programming language. As once understanding the OO-language Java it is good to read some more general programming books. In your specific case I would say start with Domain Driven Design. And then continue with books like these Test Driven Development, Refactoring to Patterns and Design Patterns.

I'm going to create the comparison table of existing automated C++ refactoring tools as well as explore an ability of creation of such tool, free and open-source.

My question is: what refactorings do you really use in your everyday work? There are obvious things like renaming variable/class/method, but is there something specific for C++, like dealing with templates, STL, copy constructors, initializers, etc., etc?

I'm interested in building of realistic picture of all that little problems that C++ developer is facing each day in his coding and that could be automated at least in theory. I'm talking to my colleagues but that's probably not enough.

Thanks in advance.

Take a look in Martin Fowler's Refactoring: Improving the Design of Existing Code and Refactoring to Patterns by Joshua Kerievsky. These in turn reference the GoF Design Patterns book so get that too.

If you can beyond the basic Rename Feature and Extract Function then you might be onto a winner.

I'm reading a lot about good and bad practices in OOP design. It's nice to know your design is bad, or good. But how do you get from bad to good design? I've split the interface (xaml) and codebehind from the main businesslogic class. That last class is growing big. I've tried splitting it up into smaller classes, but I'm stuck now. Any ideas on how to split large classes? The main class has 1 list of data of different types. I'm doing calculations on the total, but also on the individual types. I've got methods to perform these calculations which are called from events handled in the codebehind. Any ideas where to go from here?

Additional Info:

We are already about 6 months into this project. I've worked with object oriented laguages for years (first c++, java and now c#), but never on a large project like this one. I believe we've made some wrong turns in the beginning and I think we need to correct these. I can't specify any details on this project at the moment. I'm going to order one or two books about design. If I separate all the classes, how do I stick them back together? Maybe it's even better to continue this way to the first release and rebuilt parts after that, for a second release?

I highly recommend picking up Code Complete. It's a great book that offers tons of good advice on questions like yours.

To give you a quick answer to your question about how to split large classes, here's a good rule of thumb: make your class responsible for one thing, and one thing only. When you start thinking like that, you quickly can identify code that doesn't belong. If something doesn't belong, factor it out into a new class, and use it from your original class.

Edit: Take that thinking down to the "method" level, too - make your methods responsible for one thing, and one thing only. Helps break large (>50 line) methods down very quickly into reusable chunks of code.

Refactoring by Martin Fowler is an excellent book about how to change the design of your software without breaking it.

Design Patterns works similarly to algorithims but tells you how to combine objects to perform various useful tasks.

Finally Martin Fowler has a variety of useful design pattern for applications. For example Passive View

Michael Feathers's "Working Effectively with Legacy Code" is supposed to be very good, but I'll confess that I haven't read it myself.

Same goes for "Refactoring to Patterns."

Is there any website where people share and discuss good examples of object-oriented design?

Ideally such website should be populated with posts of the following structure:

  • Concise description of the problem, including definitions, links, etc.
  • Several attempts of OO design, diagrams, pseudocode listings (voted up/down by users)
    • Comments (also voted by users)

Currently I'm looking for a source of inspiration.

http://www.amazon.com/Object-Oriented-Software-Construction-Prentice-Hall-International/dp/0136291554

Object Oriented Software Construction - Betrand Mayer

He's the man that originated the Eiffel language, the most complete analysis of OO software construction I've read.

Well I can't point you to web sites, but I can refer you to some great books :

Of course, those are C++ books, but a lot of concepts in them applies to much more than just C++

I've been hearing and reading about cases when people had come across cases of overused design patterns. Ok, missused design patterns are understandable phenomenon. What does it actually mean overused design patterns?

Do you have any examples and why do you think there are too many patterns?

I guess Singleton gets easily overused (though it certainly has its legitime uses).

Addiction to the Singleton pattern is called Singletonitis. :) Symptoms include, at least, unnecessarily high coupling, and testing becoming more difficult.

Edit: As a prescribed cure for Singletonitis, you could try Inline Singleton, described in Refactoring to Patterns by Joshua Kerievsky.

Edit 2: For a good discussion on Singletons, see this older question: What is so bad about Singletons

Before I ask my "general" question, I wanted to present some quotes to my high-level general understanding of the business delegate pattern:

"You want to hide clients from the complexity of remote communication with business service components."

"You want to access the business-tier components from your presentation-tier components and clients, such as devices, web services, and rich clients."

Lets say you have large J2EE web application. When I mean large, I mean that the application has been developed for several years and by many different people and departments. The system wasn't designed well for growth. Right now, lets say the application is configured with one web application.

It would have been great if the application were more modular. But it isn't. One piece of code or library can bring down the entire system. Testing and other means are used to prevent this, but ideally this is just one monolithic web application.

Here is my question; how do you normally avoid this type of design with J2EE apps, where the application grows and grows and one separate application can bring down everything.

I am not familiar EJBs and don't plan on using them for anything too serious. But, the concept of the Business Delegate and Service Locator Pattern seems like a good fit.

Lets say you have a shopping cart screen (same web app) and a set of screens for managing a user account (same web app). In your web-tier (some kind of MVC action method), it seems you could have a Locator that will get the business specific interface, invoke those interfaces per module and if something goes wrong with that module then it doesn't kill other code. Lets say the shopping cart module fails (for whatever reason), the user account screen still works.


The best way to improve a system like this is to slowly make it better. If your system is anything like the systems I've worked on, changing the code often leads to bugs. Automated tests are a way to reduce the chance of introducing new bugs, but often the code wasn't written with testing in mind, and changing the code to make it easier to write tests can lead to bugs.

The way around this problem is to introduce some automated integration tests, and use those tests as a safety net as you carefully refactor the code and introduce tests at a lower level. Making code more testable often results in introducing interfaces and abstractions that make the code easier to work with. It also often requires separating business logic from presentation logic (since testing both together is painful) and breaking out our code into modules (since classes with many dependencies can be hard to test).

When you write new code for your system, try to write unit tests while you write the code. This is much easier (and therefore less frustrating) than writing tests for legacy code, and gives you a chance to see where you might go when you refactor your legacy code.

I know of two excellent bugs on this subject: Working Effectively with Legacy Code by Robert C. Martin and Refactoring to Patterns by by Joshua Kerievsky.

Finally, consider using a dependency injection framework, like Spring or Guice. Dependency injection makes it easier to make your code testable with unit tests. It also makes it easier to follow good design practices like the Dependency Inversion Principle and the Interface Segregation Principle.

Duplicate:

Learning implementing design patterns for newbies

I have been a developer for years and have my way of developing and have always kept up with the latest techologies. I want to start using a design pattern in the hope it will improve my development speed but I need to find one to apply and I need to find a full open source sample that demonstrates it.

I use and have an application that uses LINQ to SQL and .net 3.5 I tried to apply the repository pattern but found the structure complex and having to hack my way through it.

Any advice for someone who wants to better their programming style?

Two books that I would suggest reading are:

Refactoring: Improving the Design of Existing Code (ISBN: 0-201-48567-2) and Refactoring To Patterns (ISBN: 0-321-21335-1)

Both are great books that will help you, at a high level, understand the when's and why's to applying patterns to your code. In addition, they are great reference material for some of the most commonly used patterns out there.

To be clear, these books are by no means the "complete library" of design patterns.

Do you know any resource/s that teaches design patterns by scenario.

Ex : One day x person needs a converting A/C tool between different country resources.....

Answer : Adapter Pattern .. because....

Thanks.

Design Patterns, Gang of Four.

In a language agnostic point of view, you should buy definitely this (easy to learn through examples):
http://www.amazon.com/First-Design-Patterns-Elisabeth-Freeman/dp/0596007124

or Refactoring To Patterns for a more cause-and-effect approach:
http://www.amazon.com/Refactoring-Patterns-Joshua-Kerievsky/dp/0321213351

Hi I have an assignment to teach a team the subject of design principle. As a final exercise to this mini course, I thought to give them an exercise in design pattern, in Java. My idea is to give them a code written badly, and they should refactor it using several design patterns. I didn't find anything similar to that in my search (both in the web and in stack overflow).

Any references to something similar to what I'm looking for?

Thanks

Refactoring to Patterns

This has alot of code filling the bill. The author, Joshua Kerievsky, is also the founder of Industrial Logic, which has (as Nix noted in his response) good material on this topic, drawn from and augmenting this book.

I am wondering about correct definition for such construction:

class A {
 public static A create() {
    return new A();
 }

 private A() {
 }
}

In Effective Java (Item 1) and on wikipedia article I found that this is called Static Factory Method (some kind of Factory Method).

But during reading of Refactoring to Patterns (Chapter 6) I met the same construction called Creation Method. Also, there is a note that it should not be messed up with a Factory Method pattern.

Where truth is?

Have a read of this discussion of Factory Method.

FactoryMethodPattern is different from FactoryMethod or CreationMethod.

I'd like to modify my compiler's code generator to use visitor pattern since the current approach must use multiple conditional statement to check the real type of a child before generating the corresponding code. However, I have problems to get children attributes after they're visited. For instance, in binary expression I use this:

LHSCode := GenerateExpressionCode(LHSNode);
RHSCode := GenerateExpressionCode(RHSNode);
CreateBinaryExpression(Self,LHS,RHS);

In visitor pattern the visit method is usually void, so I can't get the expression code from LHS and RHS. Keeping shared global variables isn't an option since expression code generation is recursive thus could erase previous values kept in the variables.

I'll just show the binary expression as this is the most complicated part (for now):

function TLLVMCodeGenerator.GenerateExpressionCode(
  Expr: TASTExpression): TLLVMValue;
var
  BinExpr: TASTBinaryExpression;
  UnExpr: TASTUnaryExpression;
  LHSCode, RHSCode, ExprCode: TLLVMValue;
  VarExpr: TASTVariableExpression;
begin
  if Expr is TASTBinaryExpression then begin
    BinExpr := Expr as TASTBinaryExpression;
    LHSCode := GenerateExpressionCode(BinExpr.LHS);
    RHSCode := GenerateExpressionCode(BinExpr.RHS);
    case BinExpr.Op of
      '<': Result := FBuilder.CreateICmp(ccSLT, LHSCode, RHSCode);
      '<=': Result := FBuilder.CreateICmp(ccSLE, LHSCode, RHSCode);
      '>': Result := FBuilder.CreateICmp(ccSGT, LHSCode, RHSCode);
      '>=': Result := FBuilder.CreateICmp(ccSGE, LHSCode, RHSCode);
      '==': Result := FBuilder.CreateICmp(ccEQ, LHSCode, RHSCode);
      '<>': Result := FBuilder.CreateICmp(ccNE, LHSCode, RHSCode);
      '/\': Result := FBuilder.CreateAnd(LHSCode, RHSCode);
      '\/': Result := FBuilder.CreateOr(LHSCode, RHSCode);
      '+': Result := FBuilder.CreateAdd(LHSCode, RHSCode);
      '-': Result := FBuilder.CreateSub(LHSCode, RHSCode);
      '*': Result := FBuilder.CreateMul(LHSCode, RHSCode);
      '/': Result := FBuilder.CreateSDiv(LHSCode, RHSCode);
    end;
  end else if Expr is TASTPrimaryExpression then
    if Expr is TASTBooleanConstant then
      with Expr as TASTBooleanConstant do
        Result := FBuilder.CreateConstant(Ord(Value), ltI1)
    else if Expr is TASTIntegerConstant then
      with Expr as TASTIntegerConstant do
        Result := FBuilder.CreateConstant(Value, ltI32)
    else if Expr is TASTUnaryExpression then begin
      UnExpr := Expr as TASTUnaryExpression;
      ExprCode := GenerateExpressionCode(UnExpr.Expr);
      case UnExpr.Op of
        '~': Result := FBuilder.CreateXor(
            FBuilder.CreateConstant(1, ltI1), ExprCode);
        '-': Result := FBuilder.CreateSub(
            FBuilder.CreateConstant(0, ltI32), ExprCode);
      end;
    end else if Expr is TASTVariableExpression then begin
      VarExpr := Expr as TASTVariableExpression;
      with VarExpr.VarDecl do
        Result := FBuilder.CreateVar(Ident, BaseTypeLLVMTypeMap[BaseType]);
    end;
end;

Hope you understand it :)

In visitor pattern the visit method is usually void, so I can't get the expression code from LHS and RHS. Keeping shared global variables isn't an option since expression code generation is recursive thus could erase previous values kept in the variables.

You need to get child attributes when they're visited, hold onto any attributes you need and ensure that you still have them when you need them. That may make the internal structure of your visitor a bit more complex, but it's certainly feasible. Code generation is definitely a common use of the Visitor pattern.

Usually you don't have to hold on to attributes, but you do need to hold onto intermediate results and combine them into other intermediate results in visits to other objects. I think this is the case here, but the interaction is complex enough to be a bit confusing.

I'm not an expert on Object Pascal, so rather than trying to write actual code, I'll just describe how I would handle it.

In this case, I would probably use a stack holding onto intermediate results.

Traversal order can be driven in the nodes' accept methods or in the visitor's visit methods or in an external iterator. For simplicity, I'll assume its in the accept methods.

In the accept method of the simple objects, you would simply do the standard visitor.visit(this) (however you say that in Object Pascal).

In the visit method for simpler objects like your TASTBooleanConstant you would call the appropriate method, in this case FBuilder.CreateConstant with values that you pull from the object and push the result of that method onto the visitor's stack.

In the accept method of a more complex object like your TASTBinaryExpression, you would first call the accept methods on the children and then do the standard visitor.visit(this), ensuring that the children are visited first.

Then, since the children were visited first, their results should be on the stack when the visit method for the complex object is called. In that visit method, you would pop the appropriate results off the stack into local variables, call the appropriate FBuilder.CreateXxx method based on which operator you have, passing those values as parameters, and put the result onto the stack.

For the TASTUnaryExpression objects it would be similar, but with only one child to worry about in the accept method, and only one intermediate result to pop off the stack and use in the visit method.

In your client code, you create the visitor and call the accept method of your top node passing the visitor as argument. After all the recursion is done, the stack should contain only the final result, and the visitor class should provide a getResult method allowing the client to retrieve it.

Sorry this is so long-winded - it might be clearer in code, but hopefully this gives you an idea of how to deal with this.

A good resource for learning how refactor to introduce patterns in existing code like this is Joshua Kerievsky's book Refactoring to Patterns.

I'm new to TDD and I have a question with concept. It's said in TDD no code is written without writing test first. We usually need Repository pattern to mock objects and to be able to implement testing. My question is: should we first implement Repository pattern ? If yes, what happens to writing test first ? If no, how can we mock objects without using Repository pattern ?

I would appreciate your taking time.

If you intend to develop using TDD there is no doubt that you have to create your tests first.

It will let you implement the repository pattern naturally and will make your life easier as the repository pattern will make unit testing less painful.

Even the TDD test cycle enforces this order:

  1. Write a failing acceptance test
  2. Write a failing unit test
  3. Make the failing test pass
  4. Refactor
  5. Repeat steps 2-4 until the failing acceptance test passes

The repository pattern would be introduced in steps 3 and 4. when you actually write your code.

While I prefer those patterns to be introduced in step 4, some other people would just jump ahead and implement it in step 3. It's a matter of style, but I prefer the more complex code to be introduced once the unit test passes.

If you want to get a deeper understanding of this topic, there are some formidable books about refactoring, but one might be especially interesting for you as it logically binds refactoring and design patterns. Refactoring to Patterns

I have implemented the repository pattern in TDD development myself a few months ago and it worked out just fine.

I think this is an excellent question, so thanks a lot for asking it.

I'm presented with a need to rewrite an old legacy desktop application. It is a smallish non-Java desktop program that still supports the daily tasks of several internal user communities.

The language in which the application is both antiquated and no longer supported. I'm a junior developer, and I need to rewrite it. In order to avoid the app rewrite sinkhole, I'm planning on starting out using the existing database & data structures (there are some significant limitations, but as painful as refactoring will be, this approach will get the initial work done more quickly, and avoid a migration, both of which are key to success).

My challenge is that I'm very conflicted about the concept of Keep It Simple. I understand that it is talking about functionality, not design. But as I look to writing this app, it seems like a tremendous amount of time could be spend chasing down design patterns (I'm really struggling with dependency injection in particular) when sticking with good (but non-"Group of Four") design could get the job done dramatically faster and simpler.

This app will grow and live for a long time, but it will never become a 4 million line enterprise behemoth, and its objects aren't going to be used by another app (yes, I know, but what if....YAGNI!).

The question

Does KISS ever apply to architecture & design? Can the "refactor it later" rule be extended so far as to say, for example, "we'll come back around to dependency injection later" or is the project dooming itself if it doesn't bake in all the so-called critical framework support right away?

I want to do it "right"....but it also has to get done. If I make it too complex to finish, it'll be a failure regardless of design.

yes, KISS, but see http://www.amazon.com/Refactoring-Patterns-Joshua-Kerievsky/dp/0321213351 and consider refactoring towards a design pattern in small steps. the code should sort of tell you what to do.

Will it be easy for a C++ developer to read Refactoring: Improving the Design of Existing Code

Is there any other book that I should read about refactoring? Feel free to add any articles on refactoring.

Read a book called Refactoring by Martin Fowler.

I'm the author of Refactoring to Patterns. I have recently completed work on a multimedia album about Refactoring (in C++, Java, and soon, C#).

You can look at samples of this album here:

In addition, if you want to get good at recognizing what kind of code needs refactoring, you can consider studying my album on Code Smells as well. See

If you work with legacy code then it may be worth getting Working Effectively with Legacy Code by Michael Feathers.

Refactoring to Patterns by Joshua Kerievsky

Language used in the book shouldn't matter, the concept is what is important. This book is a practical approach to refactoring.

I might inherit a somewhat complex multithreaded application, which currently has several files with 2+k loc, lots of global variables accessed from everywhere and other practices that I would consider quite smelly.

Before I start adding new features with the current patterns, I'd like to try and see if I can make the basic architecture of the application better. Here's a short description :

  • App has in memory lists of data, listA, listB
  • App has local copy of the data (for offline functionality) dataFileA, dataFileB
  • App has threads tA1, tB1 which update dirty data from client to server
  • Threads tA2, tB2 update dirty data from server to client
  • Threads tA3, tB3 update dirty data from in memory lists to local files

I'm kinda trouble on what different patterns, strategies, programming practices etc I should look into in order to have the knowledge to make the best decisions on this.

Here's some goals I've invented for myself:

  1. Keep the app as stable as possible
  2. Make it easy for Generic Intern to add new features (big no-no to 50 lines of boilerplate code in each new EditRecordX.cs )
  3. Reduce complexity

Thanks for any keywords or other tips which could help me on this project.

For making these kind of changes in general you will want to look at Martin Fowler's Refactoring: Improving the Design of Existing Code (much of which is on the refactoring website) and also Refactoring to Patterns. You also might find Working Effectively with Legacy Code useful in supporting safe changes. None of this is as much help specifically with multithreading, except in that simpler code is easier to handle in a multithreading environment.

I'm reading a book called Refactoring to Patterns, and in this book there is a section titled: Extract Composite (page 214).

What it suggests is that if a bunch of subclasses have common functionality you should extract that functionality to a new superclass. This sounds pretty straight forward.

What is the difference between Extract Composite and Extract Superclass?

Well, according to the reading and the diagrams... the composite should be a new superclass to your child classes. See the following diagram:

enter image description here

Question: What is the purpose of creating a new "CompositeTag" superclass? Why wouldn't you want to just move the code-duplication to its original base class (Node)?

I wish I had my copy handy, but I would say thet "Extract Composite" is a special case of "Extract Superclass" A composite is a specific type of inheritance relationship, and I guess the author felt it needed to be called out separately. The diagram does indeed illustrate the kind of operations often done with composites. I think in the example given, not all subclasses are composites though, so that functionality cannot be pulled into the base class. Still, it does feel a bit like the author was just padding the book a bit :)

I am using Junit 4.12 with PowerMock 1.6 with Mockito. I have also used PowerMockRule library as described here. I am trying to execute initialization code for all of my test cases exactly once as described in this SO Thread. Its executing the initialization code exactly one time however, if I do ServiceInitializer.INSTANCE inside test method it returns me new object. I am not able to understand this behavior. Does anyone have any idea why this is happening? If I execute my code without PowerMockRule Library and run my test with PowerMockRunner then it works fine but in that case my ClassRule is not getting executed.

    public class ServiceInitializer extends ExternalResource {
      public static final TestRule INSTANCE = new ServiceInitializer();
      private final AtomicBoolean started = new AtomicBoolean();

      @Override protected void before() throws Throwable {
        if (!started.compareAndSet(false, true)) {
          return;
        }
        // Initialization code goes here
        System.out.println("ServiceInitializationHelper:"+this); //Print Address @3702c2f1
      }

      @Override protected void after() {
      }
    }




    class BaseTest{
            @Rule
            public PowerMockRule powerMockRule = new PowerMockRule();

              @ClassRule
              public static final TestRule serviceInitializer = ServiceInitializer.INSTANCE;

              @Before
              public final void preTest() {
                // some code
              }

              @After
              public final void postTest() {
                //some code
              }
    }


@PrepareForTest({MyClass.class})
public class MyTest extends BaseTest {
      @Test
      public void testMethodA_1(){
            System.out.println(ServiceInitializer.INSTANCE);//Print Address @54d41c2b
      }
}

Update

I printed the classloader for the classes and it turns out for first print statement the classloder was sun.misc.Launcher$AppClassLoader and for the second print statement the classloder was org.powermock.core.classloader.MockClassLoader. How can I solve this?

Edwin is correct; this is an issue with PowerMock creating a new ClassLoader for every test. I strongly recommend refactoring your code so it can be tested without PoeerMock and switch to Mockito.

These books may be helpful

In the mean time, you can reference ServiceInitializer from your base class:

    public class ServiceInitializer extends ExternalResource {
      public static final ServiceInitializer INSTANCE = new ServiceInitializer();
      private final AtomicBoolean started = new AtomicBoolean();

      @Override protected void before() throws Throwable {
        if (!started.compareAndSet(false, true)) {
          return;
        }
        // Initialization code goes here
        System.out.println("ServiceInitializationHelper:"+this);
      }

      @Override protected void after() {
      }
    }




    class BaseTest{
            @Rule
            public PowerMockRule powerMockRule = new PowerMockRule();

              @ClassRule
              public static final ServiceInitializer serviceInitializer = ServiceInitializer.INSTANCE;

              @Before
              public final void preTest() {
                // some code
              }

              @After
              public final void postTest() {
                //some code
              }
    }


@PrepareForTest({MyClass.class})
public class MyTest extends BaseTest {
      @Test
      public void testMethodA_1(){
            System.out.println(serviceInitializer);
      }
}

I'm sorry to ask such a localized question but until I get confirmation I don't feel confident moving on with my project.

I have read lots about the template pattern, Wikipedia has a good example.

It shows that you create the basic virtual methods and then inherit the base class and override where you want. The example on the site is for Monopoly and Chess which both inherit the base class.

So, my question is, if you had an application which was only going to be Chess and never anything else, would there be any benefit in using the template pattern (other than as an education exercise)?

The template pattern is used in specific situations. It is used when you want to sketch out an algorithm but let the specific steps differ.

This could be useful in a Chess application. However, you should not start developing an application with the idea 'I'm going to use this pattern and that one and..'. Instead, you develop the code and you discover that you need certain patterns.

This is where a Test Driven Development approach is really handy. It allows you to refactor your code each step of the way.

A nice book that explains this is Refactoring To Patterns.

I need to process a big set of files that at the moment are all loaded into memory on a List.

i.e:

List(FileClass) Files;

Use:

Reader.Files; //List of files of the type

File Class has one attribute to match each FileInfo object property i.e: Name,CreateDate,etc. Also has a List of Lines of the type (LineNumber, Data).

Now I need to create an logic to interpret these files. They all have different logic interpreteations and they will be loaded on to their correspondent Business Object.

i.e:

Model model = new Model()

.emp => Process => Employee Class
.ord => Process => Order Class

model.AddObject(emp);
model.AddObject(ord);

My question what is the best design pattern for a problem of this sort.

All I can think of is... something like this:

public ProcessFiles(List<Files> Files)
{

Model model = new Model()
var obj;

        foreach(file in Files)
        {
                    switch (File.GetExtension(file))
                    {
                        case "emp":
                           obj = BuildEmployee(file) //returns Employee class type
                            break;
                        case "ord":
                            obj = BuildOrder(file) //returns Order class type
                            break;
                    }

         model.AddObject(obj);

        }

}

Is there a better way to approach this? This solution looks procedural to me, is there a better Object Oriented Approach to it?

Cheers

UPDATE:

I've come across a few options to solve this:

1)- Use of Partial classes for separation of concerns. I have a data model that I don't want to mix File processing, Database use, etc (Single Responsibility)

DATA MODEL:

public partial class Employee 
{ 
   public int EmployeeID; 
   public string FirstName; 
   public string LastName; 
   public decimal Salary; 
}

INTERPRETER/FILE PARSER:

This partial class defines the logic to parse .emp files.

         // This portion of the partial class to separate Data Model 
          from File processing
         public partial class Employee 
         { 
            public void ProcessFile(string FileName)
            { 
               //Do processing
            } 

            ... 
         }

Intepreter Object

 public class Interpreter : IInterpreter
     {

     foreach(file in Files)
      {

       switch (fileExtension)
        {
          case .emp
             Employee obj= new Employee();
          case .ord
             Order obj = new Order(file);
        }


        obj.ProcessFile(File)
        Model.AddObject(emp)
      }

     }

2)- Perhaps using some sort of Factory Pattern... The input is the file with an extension type. This drives the type of object to be created (i.e: Employee, Order, anything) and also the logic to parse this file. Any ideas?

Well, it seems that you want to vary the processing behaviour based on the file type. Behaviour and Type being keywords. Does any behavioural pattern suit your requirement?

Or is it that the object creation is driven by the input file type? Then creation and type become important keywords.

You might want to take a look at strategy and factory method patterns.

Here is something from the book Refactoring to Patterns:

The overuse of patterns tends to result from being patterns happy. We are patterns happy when we become so enamored of patterns that we simply must use them in our code. A patterns-happy programmer may work hard to use patterns on a system just to get the experience of implementing them or maybe to gain a reputation for writing really good, complex code.

A programmer named Jason Tiscione, writing on SlashDot (see http://developers.slashdot.org/comments.pl?sid=33602&cid=3636102), perfectly caricatured patterns-happy code with the following version of Hello World. ..... It is perhaps impossible to avoid being patterns happy on the road to learning patterns. In fact, most of us learn by making mistakes. I've been patterns happy on more than one occasion.

The true joy of patterns comes from using them wisely.

I will describe a simplified example of such "dependency hell".

Imagine a video player with "play/pause" and "mute/unmute" buttons. Pausing the video should pause sound but not mute it, so that unpausing the video should unpause audio.

Then imagine we are downloading audio and video in separate files, so we have four success/error callbacks. Imagine video can play without audio but not conversely. Now imagine how many changes should be made to the code if the requirements update so that video and audio should wait for each other.

Currently I'm dealing with this using callbacks and boolean variables. I have a feeling this is stone age, because something like this:

if (videoShouldPlay && audioShouldPlay && isAudioPlaying && isVideoDownloaded && isAudioDownloaded) {

or 4 similar callbacks:

audio.onload = function () {
    if (isVideoDownloaded)
       .....
    } else { ...
}

is neither readable nor maintainable. The number of dependencies grows exponentially with the number of components, but I should not track every dependency when I can define some general rules .

I'm sure computer science has solved this problem already.

It looks like to me you need a state machine. Let's take for example the states "playing" and "paused". The rule for the transition "playing" ➜ "paused" would be what you write: "Pausing the video should pause sound but not mute it", etc. It's hard to tell more about it without seeing the actual problem you have at hand.

I would recommend Chapter 29 State from Agile Software Development, Principles, Patterns, and Practices and Replace State-Altering Conditionals with State from Refactoring to Patterns. I personally find the famous Design Patterns: Elements of Reusable Object-Oriented Software book somewhat difficult to read, nevertheless it is the State pattern in it.

Which is the best tutorial to understand java design patterns? I am not new to java programming, so basics of java need not be required.

you may find these useful :

(but the last two are a bit advanced)

Joshua bloch's book Effective Java is useful even thought its not about design patterns but it's a must read.

You must read Head First Design Pattern.

Though not specific to Java, I seriously recommend you to go for, Design Patterns by Gamma, et al (a.k.a. the Gang of Four, or simply, GoF)

If you are not new to programming you have probably already used a lot of them without realizing it. Design patterns are not language specific, try not to think of them as 'Java' patterns or 'Python' patterns etc. A really good book is Design Patterns: Elements of Reusable Object-Oriented Software.