问:
What language is used to program nano quadrotor behaviour?
Just watched this fascinating and terrifying video. I'm curious what programming language / paradigm is used to control these beasties?</p>

答:
The term I see most often for the algorithms is decentralized adaptive control.  There are some papers available from the group that designed it, although their site looks like it hasn't been updated in a few years.

According to this electronic design article, the quadrotors are running Robot Operating System (ROS), which has support for both python and C++.  I couldn't find which language is used on this particular project.


问:
Is Learning C++ Through The Qt Framework Really Learning C++
The problem I have, is that most of the C++ books I read spend almost forever on syntax and the basics of the language, e.g. for and loops while, arrays, lists, pointers, etc.

But they never seem to build anything that is simple enough to use for learning, yet practical enough to get you to understand the philosophy and power of the language.

Then I stumbled upon QT which is an amazing library!

But working through the demos they have, it seems like I am now in the reverse dilemma. I feel like the rich man's son driving round in a sports car subsidized by the father. Like I could build fantastic software, but have no clue what's going on under the hood.

As an example of my dilemma take the task of building a simple web browser. In pure C++, I wouldn't even know where to start, yet with the Qt library it can be done within a few lines on code.

I am not complaining about this. I am just wondering how to fill the knowledge void between the basic structure of the language and the high level interface that the Qt framework provides?

答:
Well, I think the best way to learn C++ is by using its own syntax ONLY(Standard C++), so you will be able to use the LANGUAGE stuff, and NOT the Qt(or any other frameworks, libraries ...etc).

Why? because as a beginner, when you look at any C++ code mixed with other Non-C++ code(Qt in this case) you will not be able to see what is C++'s things and what is not, rather it will be more complex process.

ContentLicense: CC BY-SA 3.0


问:
Is it better idea to call an external command-line application or to internalize that application's logic?
I have a "pipeline" sort of process that is essentially just linking together a bunch of existing tools to automate a workflow. For one of the steps, there is an existing command-line tool that already does the meat of what that step needs to do.

The external CLI tool is java-based, and so is my pipeline, so it would be possible to integrate the tool directly into the pipeline step, but the tool is very complex and is currently closely tied to having command-line input (something like 37 config flag options).

The question is: Is it a better idea to simply call out and invoke the external process, or would it be better to integrate the external code within my application?

What are the pros / cons of integrating vs. calling the external process?

答:
It isn't "better" or "worse".  There are simply different costs and benefits.

It is often more expensive to write and maintain a piece of software the larger the number of integration points do to the added complexity.

A function you write has very little integration cost.

A third party library has slightly larger integration cost.

A separate program you have to exec will have and even larger integration cost.

Note these are integration costs which you have to weigh against total cost which includes among other things the cost for writing and maintaining software.

It may be the case that you are a very inexperienced programmer, but a long time power user.

If you were to "shell out" your total cost may be low despite the higher integration cost, because you can mitigate the integration cost with your experience and knowledge.

If you were to write the function yourself your total cost may be quite high despite the low integration cost because of your inexperience programming.

The best way to figure out:

Is it better idea to call an external command-line application or to internalize that application's logic?

Is to calculate the costs for yourself.  The cost will be different for different environments, situations and people.  Most of the time it will cost more to call out to the command line, but not always and the only way to be sure it to do the analysis.


问:
New cloud development workflow using Github, Cloud9ide and CloudFoundry
So time is changing towards cloud development/computing.

I'm trying to get the new "cloud" workflow based on the services I'm going to use: Github, Cloud9ide and CloudFoundry.

Here is what is on my mind:

Github acts like a central (main repo) just like yesterday's local filesystem. Every service will base it service upon this main repo.

Workflow:

Github: I create a new Github repo served as main repo for the project.

Cloud9ide. I open my Github repo and write my tests and implementation (BDD/TDD). When I'm ready I save (commit) it to main repo on Github.

X: A running instance of Jenkins detects someone has committed and fetches the latest commit, builds, deploys, tests (yeti and/or selenium) and reports if the tests were passed or not. If not, I make another commit til all tests are passing.

X: I run the CloudFoundry commands to push the main Github repo to CloudFoundry's server and it will deploy my app automatically.

What I'm still confused about is where this X environment will be. On a local server where I have to install Jenkins? Or could I install it on Cloud9ide (when java is supported) or will it be on another cloud service? Also, that X environment has to be able to fetch (clone) the Github repo and run the build scripts.

And since the concept of Cloud9ide is very new and there haven't been any other predecessors I really wonder how the workflow will look like. We all know Github's workflow. We now know CloudFoundry's workflow (deploy/scale with a restful API/command line tool). But how Cloud9Ide will operate is still somewhat unclear to me. Someone on Cloud9ide mentioned that there will be buttons like deploy so I can deploy with one click. But that I guess will depend on what services that deploy process will hook up into etc.

Could someone enlighten this cloud workflow topic and fill in the gaps.

Thanks.

答:
A running instance of Jenkins detects someone has committed and fetches the latest commit, builds, deploys, tests (yeti and/or selenium) and reports if the tests were passed or not. If not, I make another commit til all tests are passing.

This can be done with travis, which is very simple to setup and very easy to use.

OwnerDisplayName: weng


问:
How do you answer the question, "where do you see yourself in 5 years?"
What do recruiters expect you to answer when they ask, "Where do you see yourself in 5 years?" Something like:

I want to improve my technical skills ... blah-blah-blah ... architect?

Is it just to check your ambitions and if you are not going to leave in a month?

答:
To sync with company’s goals

In one of my interviews, after I completed all the rounds, they told me their long term goals of the project. I was confused because it was more of maintenance than development. During this confusion the interviewer clarified a few things.

We might have to invest a lot in getting you’re trained in our domain.

The application model is complex and it takes close to 6 - 8 months or even 1 year to stabilize.

So please think wisely before you can give us a positive answer because it would be a huge wastage of resources for us if otherwise.

Bottom Line

So basically your goals are basically being synchronized to the goals the company has and they check whether you fit in.

ContentLicense: CC BY-SA 2.5


问:
Dealing with management that does not see value in improvements that are not immediately visible to the user
I can understand schedule pressure.  You want to please your users, as they are the lifeblood of the company. However, it is also true that certain changes will make everything easier down the road. Unfortunately, management in my organization has an instinctive resistance to such changes and this resistance is so strong that it gets in the way of long-term improvements.

For example, Apple recently introduced Automatic Reference Counting for iOS programs.  This is a major improvement over the manual retain/release calls one previously had to use.  The code is easier to write and easier to maintain. The changeover itself is likely to produce some crashes. But once those are worked out, the number of random weird crashes is likely to go down.

I recently mentioned to my boss that I wanted to switch to automatic reference counting.  His response was that he wanted to concentrate on visible improvements. It is likely that this response was in turn driven by pressure he is getting from above him - and probably right from the CEO.

There are a lot of similar examples.  The common thread is that something needs to be fixed but the short-term costs of the fix outweigh the short-term benefits, where "short term" is defined as "within the next few weeks."

How should I handle the situation?

EDIT:  Thanks for the responses.  Keep 'em coming.  Because it is relevant to my situation, I should make it clear that my manager and the CEO are both programmers -- though the CEO may by now have forgotten what this is like.  Apparently their programmer sides have been overwhelmed by other pressures.

答:
Let me tell you about a $2 billion opportunity that nearly slipped through our hands because of management inertia.

Some of us have a point of listening to the voice of the customer, meaning understanding what he wants. It's not always what he asks for, but if you are in a position to have conversations with your customer, you eventually come to a mutual understanding of what he wants. (Then he can explicitly start asking for it.)

That being said, its important to understand who should be having that conversation with the customer. You generally have your business development folks along with some principal designers doing this. If you have any competition, you can expect that the customer is having this conversation with them also.

At the same time, it's important the the developers keep current in their fields, because there will be competition that will beat you if you aren't.

In our situation, we had an existing customer, and a somewhat effective product based on old technology, and the customer needed rapid upgrades. What they really needed was a complete replacement product, but the mindset at our company was that this would immediately force us into a competitive position, whereas modifying the existing product allowed our customer to continue with us without legally being required to make it competitive. Our management thought they owned this market. The problem was they couldn't keep up with the upgrade requests, because the existing product structure was not flexible enough to upgrade.

The customer became impatient and started having conversations with competing sources. We lost our "ownership" of that market and a couple billion dollars in revenue. However, once the market forced us into a competitive position, management had no choice but to either go out of business or compete. (Most of the ones who were roadblocks eventually were fired.) We competed, and were able to recapture the business by the thinest thread.

I said at the start that this opportunity nearly slipped through our hands. We got the business back, for the revenue I mentioned. If we had been more prepared to adapt to the customer's concerns in the beginning, there wouldn't have been any real competition.

The take-away I am offering is this: Always try to stay leading edge in your personal capabilities. Always develop a product that is flexible and can be adapted quickly to what your customer needs. If you work too long for a company that doesn't think like this, you will wither, and your personal motivation will diminish. I have seen it happen.

When you have an idea to improve your product for whatever reason, ask yourself these questions: -- Is this what I think the customer wants? Can I validate my thoughts about the product development against the voice of the customer? Is my company in a position to address the customer needs? If so, how? -- You should then be a in position to make a persuasive case regarding your product development proposals.


问:
S.O.L.I.D., avoiding anemic domains, dependency injection?
Although this could be a programming language agnostic question, I'm interested in answers targeting the .NET ecosystem.

This is the scenario: suppose we need to develop a simple console application for the public administration. The application is about vehicle tax. They (only) have the following business rules:

1.a) If the vehicle is a car and the last time its owner paid the tax was 30 days ago then the owner has to pay again.

1.b) If the vehicle is a motorbike and the last time its owner paid the tax was 60 days ago then the owner has to pay again.

In other words, if you have a car you have to pay every 30 days or if you have a motorbike you have to pay every 60 days.

For each vehicle in the system, the application should test those rules and print those vehicles (plate number and owner information) that don't satisfy them.

What I want is:

2.a) Conform to the S.O.L.I.D. principles (especially Open/closed principle).

What I don't want is (I think):

2.b) An anemic domain, therefore business logic should go inside business entities.

I started with this:

```<code>public class Person
// You wanted a banana but what you got was a gorilla holding the banana and the entire jungle.
{
    public string Name { get; set; }

    public string Surname { get; set; }
}

public abstract class Vehicle
{
    public string PlateNumber { get; set; }

    public Person Owner { get; set; }

    public DateTime LastPaidTime { get; set; }

    public abstract bool HasToPay();
}

public class Car : Vehicle
{
    public override bool HasToPay()
    {
        return (DateTime.Today - this.LastPaidTime).TotalDays >= 30;
    }
}

public class Motorbike : Vehicle
{
    public override bool HasToPay()
    {
        return (DateTime.Today - this.LastPaidTime).TotalDays >= 60;
    }
}

public class PublicAdministration
{
    public IEnumerable<Vehicle> GetVehiclesThatHaveToPay()
    {
        return this.GetAllVehicles().Where(vehicle => vehicle.HasToPay());
    }

    private IEnumerable<Vehicle> GetAllVehicles()
    {
        throw new NotImplementedException();
    }
}

class Program
{
    static void Main(string[] args)
    {
        PublicAdministration administration = new PublicAdministration();
        foreach (var vehicle in administration.GetVehiclesThatHaveToPay())
        {
            Console.WriteLine("Plate number: {0}\tOwner: {1}, {2}", vehicle.PlateNumber, vehicle.Owner.Surname, vehicle.Owner.Name);
        }
    }
}
</code>```

2.a: The Open/closed principle is guaranteed; if they want bicycle tax you just inherit from Vehicle, then you override the HasToPay method and you're done. Open/closed principle satisfied through simple inheritance.

The "problems" are:

3.a) Why a vehicle has to know if it has to pay? Isn't a PublicAdministration concern? If public administration rules for car tax change, why Car has to change? I think you should be asking: "then why you put a HasToPay method inside Vehicle?", and the answer is: because I don't want to test for the vehicle type (typeof) inside PublicAdministration. Do you see a better alternative?

3.b) Maybe tax payment is a vehicle concern after all, or maybe my initial Person-Vehicle-Car-Motorbike-PublicAdministration design is just plain wrong, or I need a philosopher and a better business analyst. A solution could be: move the HasToPay method to another class, we can call it TaxPayment. Then we create two TaxPayment derived classes; CarTaxPayment and MotorbikeTaxPayment. Then we add an abstract Payment property (of type TaxPayment) to the Vehicle class and we return the right TaxPayment instance from Car and Motorbike classes:

```<code>public abstract class TaxPayment
{
    public abstract bool HasToPay();
}

public class CarTaxPayment : TaxPayment
{
    public override bool HasToPay()
    {
        return (DateTime.Today - this.LastPaidTime).TotalDays >= 30;
    }
}

public class MotorbikeTaxPayment : TaxPayment
{
    public override bool HasToPay()
    {
        return (DateTime.Today - this.LastPaidTime).TotalDays >= 60;
    }
}

public abstract class Vehicle
{
    public string PlateNumber { get; set; }

    public Person Owner { get; set; }

    public DateTime LastPaidTime { get; set; }

    public abstract TaxPayment Payment { get; }
}

public class Car : Vehicle
{
    private CarTaxPayment payment = new CarTaxPayment();
    public override TaxPayment Payment
    {
        get { return this.payment; }
    }
}

public class Motorbike : Vehicle
{
    private MotorbikeTaxPayment payment = new MotorbikeTaxPayment();
    public override TaxPayment Payment
    {
        get { return this.payment; }
    }
}
</code>```

And we invoke the old process this way:

```<code>    public IEnumerable<Vehicle> GetVehiclesThatHaveToPay()
    {
        return this.GetAllVehicles().Where(vehicle => vehicle.Payment.HasToPay());
    }
</code>```

But now this code won't compile because there's no LastPaidTime member inside CarTaxPayment/MotorbikeTaxPayment/TaxPayment. I'm starting to see CarTaxPayment and MotorbikeTaxPayment more like "algorithm implementations" rather than business entities. Somehow now those "algorithms" need the LastPaidTime value. Sure, we can pass the value to the constructor of TaxPayment, but that would violate vehicle encapsulation, or responsibilities, or whatever those OOP evangelists call it, wouldn't it?

3.c) Suppose we already have an Entity Framework ObjectContext (which uses our domain objects; Person, Vehicle, Car, Motorbike, PublicAdministration). How would you do to get an ObjectContext reference from PublicAdministration.GetAllVehicles method and therefore implement the funcionality?

3.d) If we also need the same ObjectContext reference for CarTaxPayment.HasToPay but a different one for MotorbikeTaxPayment.HasToPay, who is in charge of "injecting" or how would you pass those references to the payment classes? In this case, avoiding an anemic domain (and thus no service objects), don't lead us to disaster?

What are your design choices for this simple scenario? Clearly the examples I've shown are "too complex" for an easy task, but at the same time the idea is to adhere to the S.O.L.I.D. principles and prevent anemic domains (of which have been commissioned to destroy).

答:
I hate to break it to you, but you have an anemic domain, i.e. business logic outside of objects.  If this is what you are going for that is okay, but you should read about reasons to avoid one.

Try not to model the problem domain, but model the solution.  That is why you are ending up with parallel inheritance hierarchies and more complexity than you need.

Something like this is all you need for that example:

```<code>public class Vehicle
{
    public Boolean isMotorBike()
    public string PlateNumber { get; set; }
    public String Owner { get; set; }
    public DateTime LastPaidTime { get; set; }
}

public class TaxPaymentCalculator
{
    public List<Vehicle> GetVehiclesThatHaveToPay(List<Vehicle> all)
}
</code>```

If you want to follow SOLID that is great, but as Uncle Bob said himself, they are just engineering principles.  They are not meant to be stringently applied, but are guidelines that should be considered.

OwnerDisplayName: David Robert Jones

Body:
I hate to break it to you, but you have an anemic domain, i.e. business logic outside of objects.  If this is what you are going for that is okay, but you should read about reasons to avoid one.

Try not to model the problem domain, but model the solution.  That is why you are ending up with parallel inheritance hierarchies and more complexity than you need.

Something like this is all you need for that example:

public class Vehicle
{
    public Boolean isMotorBike()
    public string PlateNumber { get; set; }
    public String Owner { get; set; }
    public DateTime LastPaidTime { get; set; }
}

public class TaxPaymentCalculator
{
    public List<Vehicle> GetVehiclesThatHaveToPay(List<Vehicle> all)
}

If you want to follow SOLID that is great, but as Uncle Bob said himself, they are just engineering principles.  They are not meant to be stringently applied, but are guidelines that should be considered.

OwnerDisplayName: Gnon


答:
I think that in this sort of situation, where you want the business rules to exist outside of the target objects, testing for type is more than acceptable.

Certainly, in many situations you should use a Strategy patern and let the objects handle things themselves, but that's not always desireable.

In the real world, a clerk would look at the type of vehicle and lookup its tax data based on that.  Why shouldn't your software follow the same busienss rule?

Title: S.O.L.I.D., avoiding anemic domains, dependency injection?

Body:
Although this could be a programming language agnostic question, I'm interested in answers targeting the .NET ecosystem.

This is the scenario: suppose we need to develop a simple console application for the public administration. The application is about vehicle tax. They (only) have the following business rules:

1.a) If the vehicle is a car and the last time its owner paid the tax was 30 days ago then the owner has to pay again.

1.b) If the vehicle is a motorbike and the last time its owner paid the tax was 60 days ago then the owner has to pay again.

In other words, if you have a car you have to pay every 30 days or if you have a motorbike you have to pay every 60 days.

For each vehicle in the system, the application should test those rules and print those vehicles (plate number and owner information) that don't satisfy them.

What I want is:

2.a) Conform to the S.O.L.I.D. principles (especially Open/closed principle).

What I don't want is (I think):

2.b) An anemic domain, therefore business logic should go inside business entities.

I started with this:

```<code>public class Person
// You wanted a banana but what you got was a gorilla holding the banana and the entire jungle.
{
    public string Name { get; set; }

    public string Surname { get; set; }
}

public abstract class Vehicle
{
    public string PlateNumber { get; set; }

    public Person Owner { get; set; }

    public DateTime LastPaidTime { get; set; }

    public abstract bool HasToPay();
}

public class Car : Vehicle
{
    public override bool HasToPay()
    {
        return (DateTime.Today - this.LastPaidTime).TotalDays >= 30;
    }
}

public class Motorbike : Vehicle
{
    public override bool HasToPay()
    {
        return (DateTime.Today - this.LastPaidTime).TotalDays >= 60;
    }
}

public class PublicAdministration
{
    public IEnumerable<Vehicle> GetVehiclesThatHaveToPay()
    {
        return this.GetAllVehicles().Where(vehicle => vehicle.HasToPay());
    }

    private IEnumerable<Vehicle> GetAllVehicles()
    {
        throw new NotImplementedException();
    }
}

class Program
{
    static void Main(string[] args)
    {
        PublicAdministration administration = new PublicAdministration();
        foreach (var vehicle in administration.GetVehiclesThatHaveToPay())
        {
            Console.WriteLine("Plate number: {0}\tOwner: {1}, {2}", vehicle.PlateNumber, vehicle.Owner.Surname, vehicle.Owner.Name);
        }
    }
}
</code>```

2.a: The Open/closed principle is guaranteed; if they want bicycle tax you just inherit from Vehicle, then you override the HasToPay method and you're done. Open/closed principle satisfied through simple inheritance.

The "problems" are:

3.a) Why a vehicle has to know if it has to pay? Isn't a PublicAdministration concern? If public administration rules for car tax change, why Car has to change? I think you should be asking: "then why you put a HasToPay method inside Vehicle?", and the answer is: because I don't want to test for the vehicle type (typeof) inside PublicAdministration. Do you see a better alternative?

3.b) Maybe tax payment is a vehicle concern after all, or maybe my initial Person-Vehicle-Car-Motorbike-PublicAdministration design is just plain wrong, or I need a philosopher and a better business analyst. A solution could be: move the HasToPay method to another class, we can call it TaxPayment. Then we create two TaxPayment derived classes; CarTaxPayment and MotorbikeTaxPayment. Then we add an abstract Payment property (of type TaxPayment) to the Vehicle class and we return the right TaxPayment instance from Car and Motorbike classes:

```<code>public abstract class TaxPayment
{
    public abstract bool HasToPay();
}

public class CarTaxPayment : TaxPayment
{
    public override bool HasToPay()
    {
        return (DateTime.Today - this.LastPaidTime).TotalDays >= 30;
    }
}

public class MotorbikeTaxPayment : TaxPayment
{
    public override bool HasToPay()
    {
        return (DateTime.Today - this.LastPaidTime).TotalDays >= 60;
    }
}

public abstract class Vehicle
{
    public string PlateNumber { get; set; }

    public Person Owner { get; set; }

    public DateTime LastPaidTime { get; set; }

    public abstract TaxPayment Payment { get; }
}

public class Car : Vehicle
{
    private CarTaxPayment payment = new CarTaxPayment();
    public override TaxPayment Payment
    {
        get { return this.payment; }
    }
}

public class Motorbike : Vehicle
{
    private MotorbikeTaxPayment payment = new MotorbikeTaxPayment();
    public override TaxPayment Payment
    {
        get { return this.payment; }
    }
}
</code>```

And we invoke the old process this way:

```<code>    public IEnumerable<Vehicle> GetVehiclesThatHaveToPay()
    {
        return this.GetAllVehicles().Where(vehicle => vehicle.Payment.HasToPay());
    }
</code>```

But now this code won't compile because there's no LastPaidTime member inside CarTaxPayment/MotorbikeTaxPayment/TaxPayment. I'm starting to see CarTaxPayment and MotorbikeTaxPayment more like "algorithm implementations" rather than business entities. Somehow now those "algorithms" need the LastPaidTime value. Sure, we can pass the value to the constructor of TaxPayment, but that would violate vehicle encapsulation, or responsibilities, or whatever those OOP evangelists call it, wouldn't it?

3.c) Suppose we already have an Entity Framework ObjectContext (which uses our domain objects; Person, Vehicle, Car, Motorbike, PublicAdministration). How would you do to get an ObjectContext reference from PublicAdministration.GetAllVehicles method and therefore implement the funcionality?

3.d) If we also need the same ObjectContext reference for CarTaxPayment.HasToPay but a different one for MotorbikeTaxPayment.HasToPay, who is in charge of "injecting" or how would you pass those references to the payment classes? In this case, avoiding an anemic domain (and thus no service objects), don't lead us to disaster?

What are your design choices for this simple scenario? Clearly the examples I've shown are "too complex" for an easy task, but at the same time the idea is to adhere to the S.O.L.I.D. principles and prevent anemic domains (of which have been commissioned to destroy).

OwnerDisplayName: Mystere Man


答:
You might be on the right track. The problem is, as you've noticed, that there's no LastPaidTime member inside TaxPayment. That's exactly where it belongs, although it doesn't need to be publicly exposed at all:

```<code>public interface ITaxPayment
{
    // Your base TaxPayment class will know the
    // next due date. But you can easily create
    // one which uses (for example) fixed dates
    bool IsPaymentDue();
}

public interface IVehicle
{
    string Plate { get; }
    Person Owner { get; }
    ITaxPayment LastTaxPayment { get; }
}
</code>```

Each time you receive a payment, you create a new instance of a ITaxPayment according to the current policies, which can have completely different rules than the previous one.

Body:
You might be on the right track. The problem is, as you've noticed, that there's no LastPaidTime member inside TaxPayment. That's exactly where it belongs, although it doesn't need to be publicly exposed at all:

public interface ITaxPayment
{
    // Your base TaxPayment class will know the
    // next due date. But you can easily create
    // one which uses (for example) fixed dates
    bool IsPaymentDue();
}

public interface IVehicle
{
    string Plate { get; }
    Person Owner { get; }
    ITaxPayment LastTaxPayment { get; }
}

Each time you receive a payment, you create a new instance of a ITaxPayment according to the current policies, which can have completely different rules than the previous one.

OwnerDisplayName: Groo


答:
What I don't want is (I think):

2.b) An anemic domain, which means business logic inside business entities.

You have this backwards.  An anemic domain is one which the logic is outside the business entities.  There are lots of reasons why using additional classes to implement the logic is a bad idea; and only a couple for why you should do it.

Hence the reason why it's called anemic: the class doesn't have anything in it..

What I would do:

Change your abstract Vehicle class to be an interface.

Add an ITaxPayment interface that the vehicles must implement.  Have your HasToPay hang off of here.

Remove the MotorbikeTaxPayment, CarTaxPayment, TaxPayment classes.  They are unnecessary complications/clutter.

Each vehicle type (car, bike, motorhome) should implement at a minimum Vehicle and, if they are taxed, should implement ITaxPayment as well.   This way you can delineate between those vehicles that aren't taxed and those that are... Assuming this situation even exists.

Each vehicle type should implement, within the boundaries of the class itself, the methods defined in your interfaces.

Also, add last payment date to your ITaxPayment interface.

OwnerDisplayName: Chris Lively


问:
Is ageism in software development based on anything other than bias?
I am sure that this question will piss off some people, but that is not my intent. We are all in the same boat - I will be subject to it one day as well.

According to Milton Friedman's view, who was not a theoretician, discrimination in the work place can only go so far, for there will be employers out there willing to pick up the overlooked talent based on their productivity alone, and those who base their hiring/salary decisions on wrong perceptions will be taken care of by smarter competitors. Starting own business is a form of competition.

Age is obviously a huge factor in sports or a job that requires very hard manual labor. What about in software industry? Ageism does exist (or does it not?), but why?
Some straight questions:

Are corporations inherently evil and like to mistreat people just because?

Are employers stupid / unorganized because they still liken software to construction industry?

Are older folks less productive?

Are they not willing to work crazy hours?

Do they demand wages that are too high?

Does it come down to hormones and primal instincts? In monkey societies testosterone is everything. What about in code monkey societies?

Is ageism a myth after all?

Do only the "lazy" ones (those who do not keep up) get lower salaries?

Is it not about one's age but about having family and kids or not having it, thus influencing how much time on can spend keeping up with stuff?

Do employers want to pay young people more because they like the way they look?

Other?

Are my questions not very relevant? If so, then why?

I myself am not married yet, but I do not like to work extra hours. I do find some time to read up on things, but I have other interests as well. At the same time it is hard for me to compare my abilities to that of others of the same age; I have met both geniuses and dummies. I also do not really know how much other programmers, other than a couple of my friends are making. Even if I had a lot of data, how do I prove strictly the presence of ageism and the extent of it?

Finally, what are some good ways for an individual contributor to maintain good salary level through older years?

Thank you for your feedback.

答:
I'm a seasoned developer and I can say this for sure: ageism definitely exists.

This is what I've seen of younger programmers that I interview and hire/fire:

Some are useless.

Some are arrogant little bastards that don't know how to write software and won't learn from senior developers like myself.

A few are OK.

I find that the majority of young programmers don't learn hardware or OS details or complex languages. Consequently, they do NOT learn new languages faster, do NOT know how to develop full systems. They are NOT worth the $ at all. They are also more prone to leaving when the pressure is on because they can't take it and run home to momma.


答:
Why a vehicle has to know if it has to pay? Isn't a
  PublicAdministration concern?

No. As I understand it your whole app is about taxing. So the concern about whether a vehicle should be taxed is no more a concern of PublicAdministration then anything else in the entire program. There is no reason to put it anywhere else but here.

```<code>public class Car : Vehicle
{
    public override bool HasToPay()
    {
        return (DateTime.Today - this.LastPaidTime).TotalDays >= 30;
    }
}

public class Motorbike : Vehicle
{
    public override bool HasToPay()
    {
        return (DateTime.Today - this.LastPaidTime).TotalDays >= 60;
    }
}
</code>```

These two code snippets differ only by the constant. Instead of overriding the whole HasToPay() function override an int DaysBetweenPayments() function. Call that instead of using the constant. If this is all they actually differ on, I'd drop the classes.

I'd also suggest that Motorbike/Car should be a category property of vehicle rather then subclasses. That gives you more flexibility. For example, it makes it easy to change the category of a motorbike or car. Of course bikes are unlikely to be transformed into cars in real life. But you know that a vehicle going to get entered wrong and need to be changed later.

Sure, we can pass the value to the constructor of TaxPayment, but that
  would violate vehicle encapsulation, or responsibilities, or whatever
  those OOP evangelists call it, wouldn't it?

Not really. An object that deliberately passes its data to another object as a parameter isn't a large encapsulation concern. The real concern is other objects  reaching inside this object to pull data out or manipulating the data inside the object.

Body:
Why a vehicle has to know if it has to pay? Isn't a
  PublicAdministration concern?

No. As I understand it your whole app is about taxing. So the concern about whether a vehicle should be taxed is no more a concern of PublicAdministration then anything else in the entire program. There is no reason to put it anywhere else but here.

public class Car : Vehicle
{
    public override bool HasToPay()
    {
        return (DateTime.Today - this.LastPaidTime).TotalDays >= 30;
    }
}

public class Motorbike : Vehicle
{
    public override bool HasToPay()
    {
        return (DateTime.Today - this.LastPaidTime).TotalDays >= 60;
    }
}

These two code snippets differ only by the constant. Instead of overriding the whole HasToPay() function override an int DaysBetweenPayments() function. Call that instead of using the constant. If this is all they actually differ on, I'd drop the classes.

I'd also suggest that Motorbike/Car should be a category property of vehicle rather then subclasses. That gives you more flexibility. For example, it makes it easy to change the category of a motorbike or car. Of course bikes are unlikely to be transformed into cars in real life. But you know that a vehicle going to get entered wrong and need to be changed later.

Sure, we can pass the value to the constructor of TaxPayment, but that
  would violate vehicle encapsulation, or responsibilities, or whatever
  those OOP evangelists call it, wouldn't it?

Not really. An object that deliberately passes its data to another object as a parameter isn't a large encapsulation concern. The real concern is other objects  reaching inside this object to pull data out or manipulating the data inside the object.


问:
How does one determine whether or not to rewrite poorly-designed code?

Possible Duplicate:

  When is a BIG Rewrite the answer?

I'm on a small team that's been handed a poorly-written, half-finished 2D Java game. Our objective is to do as much as we can to make it better in about 11 weeks. I'm pretty sure the code is not maintainable and I need to decide if I should pitch the idea of a rewrite (near rewrite, anyway).

For example, the Main class, which is an applet, has most of the game logic just thrown into it. Keyboard and mouse events are handled with huge if/else blocks, none of it is commented (the only comments are the sections of code that have been commented out), and all of the drawing and animation code is just in one huge chunk. Images are loaded in a separate class that just goes through each file, each on a separate line, and reads the image into a static Image variable. This all seems like poor design.

We have until the end of the semester, roughly 11 weeks, to make the game better than it is right now. It's playable but severely broken in spots. I've currently been assigned a small feature to implement: a clickable main menu instead of one that's controllable by keyboard only. On one hand I know I'm capable of implementing this but on the other I'm afraid to try to add new features because a) the more stuff we add the more likely it is that the program will break because of the bad design choices and b) the more I'll be adding to the mess that's already there.

I took the weekend to try to duplicate the basic game functionality with a different design (to see if it could be done quickly enough). I'm able to load and cache sprites, create game entities and move them, and keep track of the game's state to determine which keyboard input to handle and what to draw on-screen. A spritesheet loader was next on my list (I found out that the game art isn't in sprite sheets but each is in a separate file). A trusted friend said that it might be better to have to maintain the old code but looking at it it's too brittle. We could refactor as we go but I think that would be difficult too.

Our group is meeting this Friday. I planned to discuss the idea of an overhaul and present what I've been working on but now I'm not so sure. I feel like it's a simple-enough 2D Java game that once we put together a solid base that it would be a lot easier to add features but we'd have to redesign the base code pretty quickly, probably in two to four weeks or thereabouts. I'd like to think that we can do it that fast but I'm not completely sure.

I guess you could reduce my question down to this: how do you best determine when to maintain poorly-designed code and when to spend some time starting almost completely from scratch?

答:
Don't write it from scratch. Inevitably, there will be logic that you miss in the rewrite, and the exercise of getting deep and dirty in the code will be worthwhile. Find refactoring tools that can aid you. I know it's in Java, but for example, Visual Studio has refactoring tools that let you extract out functions very easily. Maybe you can try Eclipse and its tools, or find a plugin.

Start with extracting out large blocks that seem functionally related. You may identify logic that can be separated out into classes. Find the dependencies and parameterize them (e.g. deglobalize variables). Ultimately, try establishing better structure around the existing code first.

You might not end up with a shining example of OO perfection, but that's not the goal. The goal is to add maintainability to the project such that you can add functionality without blowing a fuse.


答:
Refactor the existing source code. I know it sucks but if there's a lesson I've learned in development its that you don't just throw away a working project because the code is terrible.

Your game is working. Keep it that way.

Keyboard events are being handled in gigantic if blocks? Spin that off into a class and segregate functionality into methods. You'll be able to reuse most of the code that's been written already.

There aren't any comments? Add them as you refactor specific areas of the code base.

The game isn't using spritesheets? Doesn't have a manager? Concatenate the existing sprites into a sheets and write the manager so that it slots into the existing sprite loading solution.

Drawing and animation are being all mixed in with the game logic? Again, start moving these chunks into their respective classes.

You get my point. There's nothing worse and more depressing than having to untangle a snarled code base but the victory is that much sweeter at the end. Instead of spending 5 weeks rewriting what's already done, you'll have 5 extra weeks to spit and polish and add new features.

Sit down with your team and map out what still needs to be achieved with this project in terms of features. After you have a comprehensive list you can begin making deliberate refactorings that will directly benefit the success of your project.

Title: How does one determine whether or not to rewrite poorly-designed code?

Body:
Possible Duplicate:

  When is a BIG Rewrite the answer?

I'm on a small team that's been handed a poorly-written, half-finished 2D Java game. Our objective is to do as much as we can to make it better in about 11 weeks. I'm pretty sure the code is not maintainable and I need to decide if I should pitch the idea of a rewrite (near rewrite, anyway).

For example, the Main class, which is an applet, has most of the game logic just thrown into it. Keyboard and mouse events are handled with huge if/else blocks, none of it is commented (the only comments are the sections of code that have been commented out), and all of the drawing and animation code is just in one huge chunk. Images are loaded in a separate class that just goes through each file, each on a separate line, and reads the image into a static Image variable. This all seems like poor design.

We have until the end of the semester, roughly 11 weeks, to make the game better than it is right now. It's playable but severely broken in spots. I've currently been assigned a small feature to implement: a clickable main menu instead of one that's controllable by keyboard only. On one hand I know I'm capable of implementing this but on the other I'm afraid to try to add new features because a) the more stuff we add the more likely it is that the program will break because of the bad design choices and b) the more I'll be adding to the mess that's already there.

I took the weekend to try to duplicate the basic game functionality with a different design (to see if it could be done quickly enough). I'm able to load and cache sprites, create game entities and move them, and keep track of the game's state to determine which keyboard input to handle and what to draw on-screen. A spritesheet loader was next on my list (I found out that the game art isn't in sprite sheets but each is in a separate file). A trusted friend said that it might be better to have to maintain the old code but looking at it it's too brittle. We could refactor as we go but I think that would be difficult too.

Our group is meeting this Friday. I planned to discuss the idea of an overhaul and present what I've been working on but now I'm not so sure. I feel like it's a simple-enough 2D Java game that once we put together a solid base that it would be a lot easier to add features but we'd have to redesign the base code pretty quickly, probably in two to four weeks or thereabouts. I'd like to think that we can do it that fast but I'm not completely sure.

I guess you could reduce my question down to this: how do you best determine when to maintain poorly-designed code and when to spend some time starting almost completely from scratch?


答:
The situation you are describing is the same situation you will meet everywhere in the industry concerning so called legacy-code. To get a notion why you probably not should start from scratch I suggest you read this nice article from Joel.

http://www.joelonsoftware.com/articles/fog0000000069.html

Furthermore, I suggest to get a copy of Feathers' book "Working effectively with legacy code", which describes a lot of useful practices how to handle your situation.


答:
I would say that neither a person nor a vehicle should know whether a payment is due.

reexamining the problem domain

If you look at the problem domain "people having cars": In order to purchase a car you have some sort of contract which transfers ownership from one person to the other, neither the car nor the person change in that process. Your model is completely lacking that.

thought experiment

Assuming there is a married couple, the man owns the car and he is paying the taxes. Now the man dies, his wife inherits the car and will pay the taxes. Yet, your plates will stay the same (at least in my country they will). It is still the same car! You should be able to model that in your domain.

=> Ownership

A car that is not owned by anyone is still a car but nobody will pay taxes for it. In fact, you are not paying taxes for the car but for the privilege of owning a car. So my proposition would be:

```<code>public class Person
{
    public string Name { get; set; }

    public string Surname { get; set; }

    public List<Ownership> getOwnerships();

    public List<Vehicle> getVehiclesOwned();
}

public abstract class Vehicle
{
    public string PlateNumber { get; set; }

    public Ownership currentOwnership { get; set; }

}

public class Car : Vehicle {}

public class Motorbike : Vehicle {}

public abstract class Ownership
{
    public Ownership(Vehicle vehicle, Owner owner);

    public Vehicle Vehicle { get;}

    public Owner CurrentOwner { get; set; }

    public abstract bool HasToPay();

    public DateTime LastPaidTime { get; set; }

   //Could model things like payment history or owner history here as well
}

public class CarOwnership : Ownership
{
    public override bool HasToPay()
    {
        return (DateTime.Today - this.LastPaidTime).TotalDays >= 30;
    }
}

public class MotorbikeOwnership : Ownership
{
    public override bool HasToPay()
    {
        return (DateTime.Today - this.LastPaidTime).TotalDays >= 60;
    }
}

public class PublicAdministration
{
    public IEnumerable<Ownership> GetVehiclesThatHaveToPay()
    {
        return this.GetAllOwnerships().Where(HasToPay());
    }

}
</code>```

This is far from perfect and probably not even remotely correct C# code but I hope you get the idea (and somebody could clean this up). The only downside is that you would probably need a factory or something to create the correct CarOwnership between a Car and a Person

Body:
I would say that neither a person nor a vehicle should know whether a payment is due.

reexamining the problem domain

If you look at the problem domain "people having cars": In order to purchase a car you have some sort of contract which transfers ownership from one person to the other, neither the car nor the person change in that process. Your model is completely lacking that.

thought experiment

Assuming there is a married couple, the man owns the car and he is paying the taxes. Now the man dies, his wife inherits the car and will pay the taxes. Yet, your plates will stay the same (at least in my country they will). It is still the same car! You should be able to model that in your domain.

=> Ownership

A car that is not owned by anyone is still a car but nobody will pay taxes for it. In fact, you are not paying taxes for the car but for the privilege of owning a car. So my proposition would be:

public class Person
{
    public string Name { get; set; }

    public string Surname { get; set; }

    public List<Ownership> getOwnerships();

    public List<Vehicle> getVehiclesOwned();
}

public abstract class Vehicle
{
    public string PlateNumber { get; set; }

    public Ownership currentOwnership { get; set; }

}

public class Car : Vehicle {}

public class Motorbike : Vehicle {}

public abstract class Ownership
{
    public Ownership(Vehicle vehicle, Owner owner);

    public Vehicle Vehicle { get;}

    public Owner CurrentOwner { get; set; }

    public abstract bool HasToPay();

    public DateTime LastPaidTime { get; set; }

   //Could model things like payment history or owner history here as well
}

public class CarOwnership : Ownership
{
    public override bool HasToPay()
    {
        return (DateTime.Today - this.LastPaidTime).TotalDays >= 30;
    }
}

public class MotorbikeOwnership : Ownership
{
    public override bool HasToPay()
    {
        return (DateTime.Today - this.LastPaidTime).TotalDays >= 60;
    }
}

public class PublicAdministration
{
    public IEnumerable<Ownership> GetVehiclesThatHaveToPay()
    {
        return this.GetAllOwnerships().Where(HasToPay());
    }

}

This is far from perfect and probably not even remotely correct C# code but I hope you get the idea (and somebody could clean this up). The only downside is that you would probably need a factory or something to create the correct CarOwnership between a Car and a Person


问:
Return Types from Service Interfaces in Service Layer: Mapper required for UI Layer objects?
I am designing a component based system using JSF2 on top of Spring's IoC Container.

It is to employ a service layer between a controller and the domain/business layer (I anticipate the controller is nothing more than the JSF Servlet binding in the web.xml file).

The rationale for the service layer (which conforms to an interface for each service) is to allow for the services to be changeable.

It has occurred to me that the return types of the objects from the service layer objects are likely to be business objects from the business layer, which would then be used in the backing beans for the JSF view to populate the UI components on the pages.

Ideas:

Is it acceptable as a standard practice for these business layers,

say a Customer() object coming back from a FindCustomerService, to

just be passed back to a Presentation Layer backing bean? Can the Presentation Layer know about the Business Objects or are these not a part of the Service/defined for use in the Service Interface and therefore part of the contract for a Service implementation?

Alternatively, should I be thinking about representing components on

the UI using a generic set of UI classes within the backing beans, which are then   mapped to the return types coming back from the Service Layer in another layer between the

Controller and the Service Layer? (This would likely require re-engineering if a Service was changed?)

Perhaps it is a standard practice to return using standard language scalars and object return times from the service layer to avoid the need for a translation layer?

First SOA project. Figured this would make a nice question for archive and links to appropriate patterns would be greatly appreciated.

答:
Your assumptions are sound and are highly similar to my own in projects I am currently working on.

Here is roughly how I perceive the componentized architecture:

```<code> JSF Page (.jsf, .xhtml, etc..) View
</code>```

```<code> Managed Bean - Controller, Presentation Logic
</code>```

```<code> Business Logic Layer
</code>```

```<code> Data Access Layer (Database DAO's, Web Service DAO's)
</code>```

```<code> Database, Web Service, File store persistence, etc...
</code>```

To provide some insight into some of your points:

You are assuming that the web services in question are going to be returning Java objects?  Perhaps they are ordinary Java data objects serialized as XML, perhaps they are not.  If they are truly external from a third party then you cannot make that kind of assumption.  Ideally in your example however that the web service returns a Customer object, you should define and control the Customer class in your project.  If not and you simply pass this object through to the Presentation layer, then your application is exposed to the risk that the external web service may change this object in the future and this would be a point of failure at all layers.

I wouldn't pass a Java object like that where I do not control the source.  In this case a Translation operation should occur on the data being returned from the web service in the Data Access Layer, that will make assumptions about the data being returned from the web service, and translate that data into Java beans that you control and are part of your project.  In this way from the Business Logic layer on up, assuming that your Customer class remains the same, then these layers will be unaffected by a change in the external web service.  The only affected layer will be the Translation layer.  This is typically the way things are done with web services in SOA.

Body:
Your assumptions are sound and are highly similar to my own in projects I am currently working on.

Here is roughly how I perceive the componentized architecture:

 JSF Page (.jsf, .xhtml, etc..) View

 Managed Bean - Controller, Presentation Logic

 Business Logic Layer

 Data Access Layer (Database DAO's, Web Service DAO's)

 Database, Web Service, File store persistence, etc...

To provide some insight into some of your points:

You are assuming that the web services in question are going to be returning Java objects?  Perhaps they are ordinary Java data objects serialized as XML, perhaps they are not.  If they are truly external from a third party then you cannot make that kind of assumption.  Ideally in your example however that the web service returns a Customer object, you should define and control the Customer class in your project.  If not and you simply pass this object through to the Presentation layer, then your application is exposed to the risk that the external web service may change this object in the future and this would be a point of failure at all layers.

I wouldn't pass a Java object like that where I do not control the source.  In this case a Translation operation should occur on the data being returned from the web service in the Data Access Layer, that will make assumptions about the data being returned from the web service, and translate that data into Java beans that you control and are part of your project.  In this way from the Business Logic layer on up, assuming that your Customer class remains the same, then these layers will be unaffected by a change in the external web service.  The only affected layer will be the Translation layer.  This is typically the way things are done with web services in SOA.


答:
how do you best determine when to maintain poorly-designed code and when to spend some time starting almost completely from scratch?

When a simplest change would turn into a colossal task*, then it's better to start refactoring it. But never just throw away your old code (read about it in Joel's 10 things you should never do.

* I assumed the code is tested, and without bugs. If you introduce new bugs, then your task is not finished.


答:
You are both right and both wrong, that's why those issues stick around for long time and create hard feelings.

The reasons why are clearly stated above: management thinks in money; or even more specifically: revenue. To them something which has a cost but no visibility directly to the customer doesn't add revenue so it's a bad plan.

Your vision is also right: it will be good for customers but on longer term. Your actions might generate an even bigger revenue in the future compared to the short term plans.

You are not the manager, you are not the one directly responsible for the revenue (I assume of course). So you are mixing up (that's how it feels for management) with their issues and you are not focussing on your job: further expanding the software.

All hard, clear words but that's how most issues arise, out of communication errors. You both want the same thing but your short term decisions are made differently. All because the developer has a different outlook compared to the manager.

How do you solve this issue? You communicate and understand each other quite well on a number of issues. That will be the focus on customer engagement and satisfaction most likely.

To solve this issue in a stable and future proof method agree on some thing: measure the cost of bugfixing in old code. Measure the time it takes additionally to work with the old software and how it would be with the new codebase.

To prove this you could do for example this quite simple thing: branch the software in your versioning. First do what management wants, so create that feature. You do this but the agreement is you get time to show the different way. Then do the same thing in the new branche but first fix the issues you want to get rid off. Then also develop the solution.

Now you have the same solution but totally developed differently. Create a case from it, put the solutions next to each other including some management info like stability, amount of code needed and the code itself.

Now grab together a coffee and start taking a look, not debating who is right but what would be the influence of both directions for the company. That will create a meeting which is really useful and not a better-worse discussion because that won't generate the atmosphere you both will need. That won't make your product better.

Title: Dealing with management that does not see value in improvements that are not immediately visible to the user

Body:
I can understand schedule pressure.  You want to please your users, as they are the lifeblood of the company. However, it is also true that certain changes will make everything easier down the road. Unfortunately, management in my organization has an instinctive resistance to such changes and this resistance is so strong that it gets in the way of long-term improvements.

For example, Apple recently introduced Automatic Reference Counting for iOS programs.  This is a major improvement over the manual retain/release calls one previously had to use.  The code is easier to write and easier to maintain. The changeover itself is likely to produce some crashes. But once those are worked out, the number of random weird crashes is likely to go down.

I recently mentioned to my boss that I wanted to switch to automatic reference counting.  His response was that he wanted to concentrate on visible improvements. It is likely that this response was in turn driven by pressure he is getting from above him - and probably right from the CEO.

There are a lot of similar examples.  The common thread is that something needs to be fixed but the short-term costs of the fix outweigh the short-term benefits, where "short term" is defined as "within the next few weeks."

How should I handle the situation?

EDIT:  Thanks for the responses.  Keep 'em coming.  Because it is relevant to my situation, I should make it clear that my manager and the CEO are both programmers -- though the CEO may by now have forgotten what this is like.  Apparently their programmer sides have been overwhelmed by other pressures.


答:
I think you're right that the payment period is not a property of the actual Car/Motorbike. But it is an attribute of the class of vehicle.

While you could go down the road of having an if/select on the Type of object, this is not very scalable. If you later add lorry and Segway and push bike and bus and aeroplane (may seem unlikely, but you never know with public services) then the condition becomes larger. And if you want to change the rules for a lorry, you have to find it in that list.

So why not make it, quite literally, an attribute and use reflection to pull it out? Something like this:

```<code>[DaysBetweenPayments(30)]
public class Car : Vehicle
{
    // actual properties of the physical vehicle
}

[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public class DaysBetweenPaymentsAttribute : Attribute, IPaymentRequiredCalculator
{
    private int _days;

    public DaysBetweenPaymentAttribute(int days)
    {
        _days = days;
    }

    public bool HasToPay(Vehicle vehicle)
    {
        return vehicle.LastPaid.AddDays(_days) <= DateTime.Now;
    }
}
</code>```

You could also go with a static variable, if that is more comfortable.

The downsides are

that it will be slightly slower, and I'm assuming you have to process a lot of vehicles. If that is an issue then I might take a more pragmatic view and stick with the abstract property or interfaced approach. (Although, I'd consider caching by type too.)

You will have to validate at startup that each Vehicle subclass has an IPaymentRequiredCalculator attribute (or allow a default), because you don't want it to process 1000 cars, only to crash because Motorbike doesn't have a PaymentPeriod.

The upside is that if you later come across a calendar month or annual payment, you can just write a new attribute class. This is the very definition of OCP.

Body:
I think you're right that the payment period is not a property of the actual Car/Motorbike. But it is an attribute of the class of vehicle.

While you could go down the road of having an if/select on the Type of object, this is not very scalable. If you later add lorry and Segway and push bike and bus and aeroplane (may seem unlikely, but you never know with public services) then the condition becomes larger. And if you want to change the rules for a lorry, you have to find it in that list.

So why not make it, quite literally, an attribute and use reflection to pull it out? Something like this:

[DaysBetweenPayments(30)]
public class Car : Vehicle
{
    // actual properties of the physical vehicle
}

[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public class DaysBetweenPaymentsAttribute : Attribute, IPaymentRequiredCalculator
{
    private int _days;

    public DaysBetweenPaymentAttribute(int days)
    {
        _days = days;
    }

    public bool HasToPay(Vehicle vehicle)
    {
        return vehicle.LastPaid.AddDays(_days) <= DateTime.Now;
    }
}

You could also go with a static variable, if that is more comfortable.

The downsides are

that it will be slightly slower, and I'm assuming you have to process a lot of vehicles. If that is an issue then I might take a more pragmatic view and stick with the abstract property or interfaced approach. (Although, I'd consider caching by type too.)

You will have to validate at startup that each Vehicle subclass has an IPaymentRequiredCalculator attribute (or allow a default), because you don't want it to process 1000 cars, only to crash because Motorbike doesn't have a PaymentPeriod.

The upside is that if you later come across a calendar month or annual payment, you can just write a new attribute class. This is the very definition of OCP.


问:
What functionality does WebStorm contain which RubyMine does not?
I am looking at buying Rubymine as I am doing a small amount of ruby, but a large amount of html5/javascript.

I was going to get Webstorm as I do have a lot of pure html5/js based frameworks/apps that I am working on, however I then read that WebStorm/PhpStorm/Rubymine etc are all based on their IDEA framework, and made out like each framework contained the functionality of WebStorm anyway, other than a few features which were not there out of the box but could be added through plugins.

The main features that interest me about WebStorm are:

JS Unit testing from IDE

JS Lint/Hint coverage within UI

DOM/JS Refactoring/Intellisense

Coffeescript support

SVN/Git integration

FTP and remote sync (although not as important as the rest)

So given the above, would Rubymine provide the above functionality too? as I would rather have 1 IDE which I can do both in, than having 2 IDEs which have a lot of overlapping functionality.

Is there any specific functionality which is ONLY within Webstorm but not in any of the other IDEs?

答: RubyMine has all the features of WebStorm. Note that because of the different release cycles some features may appear first in one IDE, but will be also available in all the other IDEs with the next update. There is no functionality specific to WebStorm that is not available in the other IDEs. See http://devnet.jetbrains.com/message/5466924?tstart=0</p>


答:
I have the latest version of RubyMine (3.2.4), and while I have only used it for doing strictly Ruby projects, on the right side of the startup page I see that it has bundled plugins for Coffescript, CSS, HTML tools, JS Inspection, JavaScript Debugger etc. so I think you're basically right in assuming that it is essentially WebStorm + Ruby.

However the WebStorm feature page mentions support for Node.JS and JSLint/JSHint, which I do not specifically see in RubyMine.  But based on this page, I believe you can install these features as additional plugins.

Since you can download a 30-day free trial of RubyMine, and the same for WebStorm, so you can always download both and compare them.

Title: What functionality does WebStorm contain which RubyMine does not?

Body:
I am looking at buying Rubymine as I am doing a small amount of ruby, but a large amount of html5/javascript.

I was going to get Webstorm as I do have a lot of pure html5/js based frameworks/apps that I am working on, however I then read that WebStorm/PhpStorm/Rubymine etc are all based on their IDEA framework, and made out like each framework contained the functionality of WebStorm anyway, other than a few features which were not there out of the box but could be added through plugins.

The main features that interest me about WebStorm are:

JS Unit testing from IDE

JS Lint/Hint coverage within UI

DOM/JS Refactoring/Intellisense

Coffeescript support

SVN/Git integration

FTP and remote sync (although not as important as the rest)

So given the above, would Rubymine provide the above functionality too? as I would rather have 1 IDE which I can do both in, than having 2 IDEs which have a lot of overlapping functionality.

Is there any specific functionality which is ONLY within Webstorm but not in any of the other IDEs?


问:
Does it make sense to avoid a framework when building a large webapp with PHP?
Being a PHP web application developer for several years now, I've had my share of MVCs and frameworks. At first I thought they were the best thing since sliced bread; everything seemed to be very easy to implement.

Now however, it seems that the more complex the application gets, the more hassle the framework introduces, so I have to develop workarounds to overcome them. Such workarounds are usually pretty daunting and complex since I have to delve down into the framework core code and make changes so that it behaves the way I want.

For example, in one of my projects where I use Slim(C)+Idiorm(M)+Twig(V) (which I believe is very flexible), I have to create a custom function just to display dynamic data in parent templates; without a framework I could have simply executed mysql_query() in the included file.

Okay, frameworks are cool if I'm creating a simple company profile website; I can just whip some code in one night and they're usually ready by the morning, and the amount of good coding practice and design patterns I've learned from them is very valuable.

But really, for a complex web application like an all-in-one web based school management system, frameworks usually get in the way of my business process like in the example above.

So my question is: is it okay to just go back to basics, and use standard PHP code and libaries for doing my next project where there might be a gazillion frameworks and libraries, provided I can sufficiently use good coding practices and follow sensible design patterns like MVC? My development team is pretty small: only 2 programmers and 1 designer. The other programmer agrees with my thoughts above.

答:
In my opinion a framework should only be used if it makes the development process easier for you, and not cumbersome. There's nothing wrong with not using a framework or building your own, especially for small projects.

Obviously you will still need to pay attention to the structure and security aspects, but considering you have been using frameworks for many years you probably already know those aspects inside out.

For larger projects, I agree with the others, meaning that using a framework is probably going to be the best option in the long run.


答:
My experience is pretty much the opposite of yours. When doing small, quick things, a framework can "get in the way" a bit as you need to lay out your code in a certain way and think about things carefully before proceeding. By just jumping straight to mysql_query you can have your prototype up and running much quicker.

But for large, complex sites, carefully laying out code and really thinking about how you write your code is extremely important if you want a site that will be maintainable going forward.

In particular, adding mysql_query calls to random parts of the page cycle are generally a really bad idea. You might have one here and one there to begin with and it's no big deal, but before long you'd got dozen spread all over the place and you're wondering why your pages take 3 seconds just to render. Or you change your schema and seemingly unrelated sections of the site break for unknown reasons.

Title: Does it make sense to avoid a framework when building a large webapp with PHP?

Body:
Being a PHP web application developer for several years now, I've had my share of MVCs and frameworks. At first I thought they were the best thing since sliced bread; everything seemed to be very easy to implement.

Now however, it seems that the more complex the application gets, the more hassle the framework introduces, so I have to develop workarounds to overcome them. Such workarounds are usually pretty daunting and complex since I have to delve down into the framework core code and make changes so that it behaves the way I want.

For example, in one of my projects where I use Slim(C)+Idiorm(M)+Twig(V) (which I believe is very flexible), I have to create a custom function just to display dynamic data in parent templates; without a framework I could have simply executed mysql_query() in the included file.

Okay, frameworks are cool if I'm creating a simple company profile website; I can just whip some code in one night and they're usually ready by the morning, and the amount of good coding practice and design patterns I've learned from them is very valuable.

But really, for a complex web application like an all-in-one web based school management system, frameworks usually get in the way of my business process like in the example above.

So my question is: is it okay to just go back to basics, and use standard PHP code and libaries for doing my next project where there might be a gazillion frameworks and libraries, provided I can sufficiently use good coding practices and follow sensible design patterns like MVC? My development team is pretty small: only 2 programmers and 1 designer. The other programmer agrees with my thoughts above.


问:
Studies on how noise affects productivity of programmers
Does anyone have any links to studies that show how noise affects the productivity of programmers? Specifically I would like to see how/if productivity rises when noise levels decrease.

As pointed in comments, the nature of the programming workflow is such that you go in and out of focus all the time -- so it's likely to be affected by noise differently than other lines of work.

The reason I think that this is programmer specific is that I am also interested in mathematics. In a noisy place, if I start thinking about maths, the noise goes away and I find myself lost in a world of pictures. In fact my favourite place to do maths was always The Copper Kettle cafe, a busy tourist place.

For programming it's completely different. While programming I'm usually thinking verbally, and any talking whatsoever destroys my train of thought. I'm literally incapable of programming anywhere where there is audible conversation.

I've talked to other programmers who don't even notice noise that disables me, and they say that they think mainly in pictures. Which is why I'm wondering whether there are any actual academic studies into whether programming is particularly noise-affected compared to say maths or lawyering.

答:
The book Peopleware has several chapters that cover the subject. You can read a decent summary here.

Studies led by Tom DeMarco & Timothy Lister showed statistically significant results about the correlation between noise and defects.

Here is an interesting part of the summary:

Workplace Quality and Product Quality - Companies that provide small and noisy workplaces explain away complaints as workers campaigning for the added status of bigger, more private space. To determine whether noise level had any correlation to work, we divided our sample into those who found the workplace acceptably quiet and those who didn't. Then, looking at workers within each group who completed the entire exercise without a single defect:

```<code>> Workers who reported that their workplace was acceptably quiet before
the exercise were 1/3 more likely to deliver zero-defect work.
</code>```

As the noise level gets worse, this trend gets stronger:

Zero-defect workers:    => 66% reported noise level OK

1-or-more-defect workers: => 8% reported noise level OK

A Discovery of Nobel Prize Significance - On February 3, 1984, in a study of 32,346 companies worldwide, the authors confirmed a virtually perfect inverse relationship between people density and dedicated floor space per person. If you're having trouble seeing why this matters, you're not thinking about noise. Noise is directly proportional to density, so halving the allotment of space per person can be expected to double the noise. Even if you managed to prove conclusively that a programmer could work in 30 sq. ft. without being hopelessly space-bound, you still wouldn't be able to conclude that 30 sq. ft. is adequate space. The noise in a 30 sq. ft matrix is more than triple the noise in a 100 sq. ft. matrix, which could make the difference between a plague of product defects and none at all.

Check the summary, really, noise is one of the recurring subject in Peopleware.

Body:
The book Peopleware has several chapters that cover the subject. You can read a decent summary here.

Studies led by Tom DeMarco & Timothy Lister showed statistically significant results about the correlation between noise and defects.

Here is an interesting part of the summary:

Workplace Quality and Product Quality - Companies that provide small and noisy workplaces explain away complaints as workers campaigning for the added status of bigger, more private space. To determine whether noise level had any correlation to work, we divided our sample into those who found the workplace acceptably quiet and those who didn't. Then, looking at workers within each group who completed the entire exercise without a single defect:

> Workers who reported that their workplace was acceptably quiet before
the exercise were 1/3 more likely to deliver zero-defect work.

As the noise level gets worse, this trend gets stronger:

Zero-defect workers:    => 66% reported noise level OK

1-or-more-defect workers: => 8% reported noise level OK

A Discovery of Nobel Prize Significance - On February 3, 1984, in a study of 32,346 companies worldwide, the authors confirmed a virtually perfect inverse relationship between people density and dedicated floor space per person. If you're having trouble seeing why this matters, you're not thinking about noise. Noise is directly proportional to density, so halving the allotment of space per person can be expected to double the noise. Even if you managed to prove conclusively that a programmer could work in 30 sq. ft. without being hopelessly space-bound, you still wouldn't be able to conclude that 30 sq. ft. is adequate space. The noise in a 30 sq. ft matrix is more than triple the noise in a 100 sq. ft. matrix, which could make the difference between a plague of product defects and none at all.

Check the summary, really, noise is one of the recurring subject in Peopleware.


答:
Suggest you run a clone detector over the code.  This will let you find where duplicated code that can be abstracted is found, and you will be able to form useful absrtractions (e.g., handling mouse events, etc.).

Our CloneDR tool will find blocks of code that match modulo parameters; it essentially proposes subroutines (OK, this is Java, they are called methods) showing you duplicated code and how it can be paramterized.


问:
How can I track programming productivity on a daily basis?
How can I track that I'm developing software more or less productive than the previous days? </p>

答:
Assume for a moment that being productive is managing your time such that you are utilizing all of your working time to work towards completion of your tasks, and that anything that contributes to wasted time - I.e.: time spent not completing your tasks - is non-productive.

About the only thing that you can really do is to log your time when engaged in various activities throughout your day. Time boxing is a technique used for various purposes, but would suit this effort to log your activity during a day.  Spend 15 minutes on a timer simply doing some task. If the task is something you are supposed to be working on, your time was productive.  If you found yourself editing your blog, reading a news paper, or daydreaming about that nice girl in accounting, then your time was probably unproductive.  Add up your minutes at the end of the day and you'll get a feel for how productive you are...

But there's a catch! What do you do about those other minutes... you know, taking a 5 minute break, going to lunch, having your boss interrupt you to tell you about that big fish he didn't catch on his last fishing trip? Log all of that too. Time spent on a break isn't wasted if it contributes to your mental health and well-being... just so long as you aren't taking a 5 minute break every 10-15 minutes!! As to the rest, interruptions, dealing with other work related issues.. all of this can be tracked.

You can of course find yourself obsessing over this sort of stuff, and god help you if the boss is one of those people who sees you time-boxing and uses that to justify reasons to pile on more work, or criticize your efforts. You see, the problem with obsession over the productive hours is that you can be working for an entire day, and still end up getting nothing of actual relevance done. Some days you can be writing code like it was butter melting right out of your brain, and onto that sandwich that you call your screen... while other days you can have a serious mental block as you try 357 different ways to do the same thing, only to watch it fail.  Many would say continuous "failures" can be unproductive, and that in itself isn't going to be helped no matter how much you time box and log your hours during the day.

The other way to look at it is to simply set yourself a number of goals, to complete during a day and a week, and then work towards completing them. If you actually achieve your goals, you can argue that you've been productive, and if you don't achieve your goals, you may need to understand why you didn't meet them, and decide if you were or weren't productive based on the actual reasons for missing your goals. Ultimately, if you deliver working code when it's needed, and if you can get your tests to pass, and a task completed, then you've been productive.  Measurements will only be of value if there is a legitimate reason for analyzing them statistically later on.


问:
How to stop the development spec from changing in mid development?
Problem: It seems with almost every development effort I'm involved in, no matter how much time is spent planning prior to starting development, there is always a large amount of changes required either midway or towards the end of the project. These are sometimes big changes which require alot of re-development.

I don't work for clients who pay money, this is an in-house development team on in-house development websites. So, it's not like I can charge for it or anything. And at the end of the day, we have to try to hit deadlines.

Questions: What are some of the best ways you guys have found to minimize and prevent spec changes from cropping up midway or after development?

答: An approach I have found that works sort-of OK (not with all managers obviously) is "I think I can do that, yes. It depends - how much extra time are you assigning to this project? It's a fairly major change you are requesting."</p>


问:
Unit of work principle is causing a problem in MVC3 application
I am implementing a website using MVC3, Entity Framework 4.1 and Repositoty pattern, Unit of work principle. But I am facing a big problem while implementing this.

I have developed a static ObjectContext class. This class is used across all the repositories so unit of work pattern is followed. I have e.g. ICustomer, IProduct repositories. I use specifically only one repository in a controller and that too is injected using NInject.

```<code>CustomerController(ICustomer customer)
{
}

ProductController(IProduct product)
{
}
</code>```

Since object context class is static and IProduct, ICustomer have parameterised constructor which accepts the objectContext class, these two will share the same ObjectContext instance.

When the execution is single threaded everything goes fine, but in multi-threading I get an unhandled exception, because of one repository closing the connection which was being used by other. I think if I make ObjectContext class not-static then this will solve the problem(Not tested yet) but then Unit of Work will not be observed.

Can you please suggest a solution for this?

答:
Use reference counting on the connection (and any other shared state which needs special clean up after use).

Whenever an object begins using the connection, increment the reference count.  When the object is finished, decrement the count.  When the count reaches zero, close the connection.

You will want to use a lock to protect the reference count and the connection open / close logic.  There are a few race conditions around connection open / close which will cause problems, otherwise.

More generally, you're going to have to worry about synchronization on any state which is shared amongst multiple threads.  If you keep this design, you need to get in the habit of looking up whether or not classes / functions are thread safe, and adding locks to protect anything which isn't, or which you aren't sure about.  If you have multiple synchronization primitives, you will need to start worrying about acquisition order, and the possibility of deadlock.

This is one of the huge drawbacks of anything static or otherwise shared in a multithreaded application.  Synchronization is really easy to screw up, and leads to difficult-to-reproduce-and-diagnose bugs.  Ensure that you consider this in your evaluation of your design against other designs which don't require shared state.


答:
Here's a meaningful and accurate measure of productivity that involves taking multiple Evidence-based scheduling snapshots:

Once you've gathered a few days' worth of statistics, run your Monte Carlo simulation, and observe the graph, which should look like this:

Then do one more day's worth of work, and run the simulation again. If you were productive that day, the graph should change something like this:

Most importantly, if you were product on that day, the ship date probability on any given date should increase since when you last ran the simulation before that day of work. If it decreases, then you were less productive on that day.

Of course, the accuracy of EBS increases with time and experience, so that can be another reason for the change in the ship date probability value. That's why you want to start doing this at least after a few days worth of sampled work. Even without that, though, if you were significantly more productive on one day or another, the probability should increase quite noticeably.

Title: How can I track programming productivity on a daily basis?

Body: How can I track that I'm developing software more or less productive than the previous days? </p>


问:
Jenkins without Automated Tests
I know that Jenkins is focused on continous building/testing, monitoring of batch jobs about the project. We have a legacy project which such condition :

1)Has a development team.

2)It has SVN for source code management

3)Some cronjobs for some operations.

4)Compile&Build don't take too much time, there is no very complex dependencies.

5)It doesn't have any automated test/junit classes and will not have.

I'd like to ask to experienced users about Jenkins, is it still worth to use Jenkins for central build&management of the project ?

答:
I'd like to ask to experienced users about Jenkins, is it still worth
  to use Jenkins for central build&management of the project ?

Definitely. Even if you don't/won't use Jenkins to run any automated testing, it is still a valuable tool. What you still get out of it is a neutral party that will continuously attempt to build your software and will notify you and your team if it is unable to do so. This is very valuable as it prevents an unstable build of your software from going unnoticed.

Title: Jenkins without Automated Tests


答: It's definitely worth it. One often un-noticed benefit is that it forces you to have your build process automated, which is a huge win just by itself. Regardless of the build stability, simply having it all automated is usually the hardest step, so if using jenkins encourages that and helps tto enforce it, the it's worth it.</p>

Title: Jenkins without Automated Tests

Body:
I know that Jenkins is focused on continous building/testing, monitoring of batch jobs about the project. We have a legacy project which such condition :

1)Has a development team.

2)It has SVN for source code management

3)Some cronjobs for some operations.

4)Compile&Build don't take too much time, there is no very complex dependencies.

5)It doesn't have any automated test/junit classes and will not have.

I'd like to ask to experienced users about Jenkins, is it still worth to use Jenkins for central build&management of the project ?


问:
How to infer my Assumptions I based my time estimate on?
In an answer on how to make time estimates it is said to write down all your assumptions you made when estimating a project. Seems like a good plan.

Problem is, by assuming I already made an ass out of myself without realizing it. Assumptions are those evil things that like to stay hidden, things I took for granted.

So when reviewing my estimate, what techniques can I apply to discover the assumptions I based my time estimate on?

答:
A real example: My boss asked me how long it would take me to deploy the software on a new piece of hardware and run through the manual acceptance test procedure. I'd done the test procedure on other systems before, so I knew the whole thing took about 2 hours. I also know that deployment, installation, and configuration takes about 30 minutes. There are other factors, but let's just take these. I could very well say that it will take me 3 hours to do everything that was asked...assuming that the system was on the network. My assumption was that IT had done their configuration of the machine to put it on the network, and I could just log on and deploy the software. If they hadn't, my estimate would be blown already, since I couldn't do anything until that happened.

Assumptions aren't "evil things that like to stay hidden". They are things that you are counting on to have happened that are out of your control. You can present your estimate with these assumptions that these other things have happened, and outline what exactly you assumed would happen.

By enumerating and making your assumptions known, you didn't make an ass out of yourself. In fact, everyone's now on the same page. If you get into the situation and something didn't happen, you can point to the assumptions that you based your estimate on and then reestimate based on your newly found knowledge that the original assumptions were wrong.

You won't be able to account for everything. Some things will be overlooked. The only thing that you can do is keep track, learn from your mistakes, and get better next time. That's why you (especially at a project level) reestimate frequently - NASA's Software Engineering Laboratory estimates once at the start of the project...and then again 5 times throughout the project, revising based on clarifications, information learned, risk analysis, and assumptions made.


答:
Problem is, by assuming I already made an ass out of myself without
  realizing it.  Assumptions are those evil things that like to stay
  hidden, things I took for granted.

Not true. You need to make assumptions to make any form of estimate, if you knew everything fully beforehand it wouldn't be an estimate. You need to make lots of reasonable assumptions to be an effective programmer.

```<code>So when reviewing my estimate, what techniques can I apply to discover the assumptions
I based my time estimate on?
</code>```

If you made the estimate you should have a good idea of the conditions you need for that estimate to be appropriate. Think through all the dependencies of your project and if they could ever change. For example one assumption could be All my users are using a modern web browser, I don't need to support IE6*. Or My supplier's webservice will have all the order reporting detail i need in one call, I wont need to do any extra data processing

-* That one has got me before. IE6 is widly used in some organisations and its an absolute #### to code for

Title: How to infer my Assumptions I based my time estimate on?

Body:
In an answer on how to make time estimates it is said to write down all your assumptions you made when estimating a project. Seems like a good plan.

Problem is, by assuming I already made an ass out of myself without realizing it. Assumptions are those evil things that like to stay hidden, things I took for granted.

So when reviewing my estimate, what techniques can I apply to discover the assumptions I based my time estimate on?

Body:
Problem is, by assuming I already made an ass out of myself without
  realizing it.  Assumptions are those evil things that like to stay
  hidden, things I took for granted.

Not true. You need to make assumptions to make any form of estimate, if you knew everything fully beforehand it wouldn't be an estimate. You need to make lots of reasonable assumptions to be an effective programmer.

So when reviewing my estimate, what techniques can I apply to discover the assumptions
I based my time estimate on?

If you made the estimate you should have a good idea of the conditions you need for that estimate to be appropriate. Think through all the dependencies of your project and if they could ever change. For example one assumption could be All my users are using a modern web browser, I don't need to support IE6*. Or My supplier's webservice will have all the order reporting detail i need in one call, I wont need to do any extra data processing

-* That one has got me before. IE6 is widly used in some organisations and its an absolute #### to code for


答:
The answer did mention

Make them sit down, read, and agree to your assumptions (or, if you're lucky, get them to give in and give you real requirements).

So this isn't something which should just stay in your head, making assumptions should be a process of taking nothing for granted and continually asking for acceptance of the assumptions, in order to see everyone is on the same page.

Only then you can be sure you have a reasonable time estimate.


问:
How-to convince company to start documenting for legacy software
It has been less than a year since I joined my current company. Their majority of sales have come from a single product that has been alive since the last 10 years. However, there is minimal (if at all) documentation.

Not only do the developers in the company struggle with the lack of documentation but also there is a high amount of turnover, causing everyone to lose their time. This is because experienced developers have left the company and there is less and less resources to communicate/brain storm with.

Without getting into too much detail, I have suggested to the previous manager that there needs to be some sort of documentation (at least an Architecture document) that outlines the product. I also suggested using JavaDoc and other automatic documentation tools. These suggestions were responded to by slight smiles and statements of the sort "We do not have enough time", "We need short-term improvements right now" and even "The code itself should be the documentation" from the programmers themselves.

I have already wasted enough time trying to find out if what I needed per requirement/bug had existed in this big (really) code base. I am looking for any suggestions that you might give regarding the need of documentation. Or, rather, if this is a lost case for this legacy system or organization.

答:
You probably have the crux of why they have a high turnover in your post. You have already raised your concerns with management, make sure you have done so in a formal way pointing out the business reasons for documentation (reduced support costs and wasted resources in trying to figure out the code).

If you have raised your concerns in the correct way and management still ignore you then your choices are a)suck it up b) Look for a new job  (I would recomend b)


答:
I feel your pain.  I've been in this exact position before.

My suggestion is to lead by example.  Start a wiki or document and start making notes.  Make repeated references to this document you're putting together.  If someone asks you a question, make a show of looking at the document for the answer first.  If the question isn't there, add it to the section of unanswered questions.  As it grows, share it with everyone.   Add time to document to your maintenance tasks.

You have to grow this organically.  It needs a champion.  I'm not aware of any developer-driven argument that will make a company that doesn't care about documentation suddenly flip that switch.  Once it's in place, everyone will wonder how they got by without it.  Sadly, once you move on, it will probably become obsolete and die.

Title: How-to convince company to start documenting for legacy software

Body:
It has been less than a year since I joined my current company. Their majority of sales have come from a single product that has been alive since the last 10 years. However, there is minimal (if at all) documentation.

Not only do the developers in the company struggle with the lack of documentation but also there is a high amount of turnover, causing everyone to lose their time. This is because experienced developers have left the company and there is less and less resources to communicate/brain storm with.

Without getting into too much detail, I have suggested to the previous manager that there needs to be some sort of documentation (at least an Architecture document) that outlines the product. I also suggested using JavaDoc and other automatic documentation tools. These suggestions were responded to by slight smiles and statements of the sort "We do not have enough time", "We need short-term improvements right now" and even "The code itself should be the documentation" from the programmers themselves.

I have already wasted enough time trying to find out if what I needed per requirement/bug had existed in this big (really) code base. I am looking for any suggestions that you might give regarding the need of documentation. Or, rather, if this is a lost case for this legacy system or organization.


答:
static ObjectContext class

This is actually even worse than what you think.  The ObjectContext class is not thread safe so even if you manage to get what you think is good synchronization, (without actually locking) you will still be throwing exceptions all the time in a multi-user environment.

The ADO.NET team recommends using a new ObjectContext every time you plan on querying the database.  How else could anyone separate their data access classes from each other if this weren't the case?

I think if I make ObjectContext class not-static then this will solve the problem(Not tested yet) but then Unit of Work will not be observed.

Not true at all.  The unit of work pattern has nothing to do with having a single  repository for an entire application--otherwise, every entity framework tutorial would start you off by showing you how to create your static ObjectContext.

It simply means that if you can't commit the unit of work, the entire commit will be backed out and the entire commit must succeed for it to be successful; it's a single logical transaction.

If you need to keep objects around for the life of the application, look into caching them in a data structure other than an ObjectContext.

Title: Unit of work principle is causing a problem in MVC3 application

Body:
I am implementing a website using MVC3, Entity Framework 4.1 and Repositoty pattern, Unit of work principle. But I am facing a big problem while implementing this.

I have developed a static ObjectContext class. This class is used across all the repositories so unit of work pattern is followed. I have e.g. ICustomer, IProduct repositories. I use specifically only one repository in a controller and that too is injected using NInject.

```<code>CustomerController(ICustomer customer)
{
}

ProductController(IProduct product)
{
}
</code>```

Since object context class is static and IProduct, ICustomer have parameterised constructor which accepts the objectContext class, these two will share the same ObjectContext instance.

When the execution is single threaded everything goes fine, but in multi-threading I get an unhandled exception, because of one repository closing the connection which was being used by other. I think if I make ObjectContext class not-static then this will solve the problem(Not tested yet) but then Unit of Work will not be observed.

Can you please suggest a solution for this?