答: Companies often hire those recommended by their employees. If you network in your own geographic area by attending code camps and other dev related meetings, you can find out from employees of other companies what their conditions are like in what is far more likely to be an honest fashion than in an interview. Then you know who to apply to. And you also have people who work there who will recommend you.</p>

Title: How can I thoroughly evaluate a prospective employer?

Body:
We hear much about code smells, test smells, and even project smells, but I have heard no discussion about employer "smells" outside of the Joel Test.  After much frustration working for employers with a bouquet of unpleasant corporate-culture odors, I believe it's time for me to actively seek a more mature development environment.

I've started assembling a list of questions to help vet employers by identifying issues during a job interview, and am looking for additional ideas.   I suppose this list could easily be modified by an employer to vet an employee as well, but please answer from the interviewee's perspective.

I think it would be important to ask many of these questions of multiple people to find out if consistent answers are given.  For the most part, I tried to put the questions in each section in the order they could be asked.  An undesired answer to an early question will often make follow-ups moot.

Values

What constitutes "well-written" software?

What attributes does a good developer have?  Same question for manager.  Who are your most valued employees/managers, and why?

Process

Do you have a development process?

How rigorously do you follow it?

How do you decide how much process to apply to each project?

Describe a typical project lifecycle. Ask the following if they don't come up otherwise:

Waterfall/iterative: How much time is spent in upfront requirements gathering? upfront design?

Testing

Who develops tests (developers or separate test engineers?)

When are they developed?

When are the tests executed?

How long do they take to execute?

What makes a good test?

How do you know you've tested enough?

What percentage of code is tested?

Review

What is the review process like?

What percentage of code is reviewed?  Design?

How frequently can I expect to participate as code/design reviewer/reviewee?

What are the criteria applied to review and where do the criteria come from?

Improvement

What new tools and techniques have you evaluated or deployed in the past year?

What training courses have your employees been given in the past year?  What will I be doing for the first six months in your company (hinting at what kind of organized mentorship/training has been thought through, if any)

What changes to your development process have been made in the past year?

How do you improve and learn from your mistakes as an organization?  What was your organizations biggest mistake in the past year, and how was it addressed?

What feedback have you given to management lately?  Was it implemented? If not, why?

How does your company use "best practices?"  How do you seek them out from the outside or within, and how do you share them with each other?

Ethics

Tell me about an ethical problem you or your employees experienced recently and how was it resolved?

Do you use open-source software?  What open-source contributions have you made?

Follow-Ups

I liked what @jim-leonardo said on this Stack Overflow question:

Really a thing to ask yourself: "Does this person seem like they are trying to recruit me and make me interested?" I think this is one of the most important bits. If they seem to be taking the attitude that the only one being interviewed is you, then they probably will treat you poorly. Good interviewers understand they have to sell the position as much as the candidate needs to sell themselves.

@SethP added:

Glassdoor.com is a good web site for researching potential employers. It contains information about how specific companies conduct interviews...


问:
Why is naming a table's Primary Key column "Id" considered bad practice?
My t-sql teacher told us that naming our PK column "Id" is considered bad practice without any further explanations.

Why is naming a table PK column "Id" is considered bad practice?

答:
ID is common enough, that I don't think it would confuse anyone. You're always going to want to know the table. Putting fields names in production code without including a table/alias is a bad practice. If you're overly concerned about being able to quickly type ad hoc queries, you're on your own.

Just hope no one develops a sql database where ID is a reserved word.

```<code>CREATE TABLE CAR (ID);
</code>```

Takes care of the field name, primary key, and auto increments by 1 starting with 1 all in one nice little 2 character package. Oh, and I would have called it CARS but if we're going to save on key-strokes and who really thinks a table called CAR is going to only have one?

ContentLicense: CC BY-SA 3.0

Body:
ID is common enough, that I don't think it would confuse anyone. You're always going to want to know the table. Putting fields names in production code without including a table/alias is a bad practice. If you're overly concerned about being able to quickly type ad hoc queries, you're on your own.

Just hope no one develops a sql database where ID is a reserved word.

CREATE TABLE CAR (ID);

Takes care of the field name, primary key, and auto increments by 1 starting with 1 all in one nice little 2 character package. Oh, and I would have called it CARS but if we're going to save on key-strokes and who really thinks a table called CAR is going to only have one?


问:
Should we use Entity Framework?
We currently have the following stack :

VS 2005

Web forms

SQL Server 2005

IIS 6

We are planning on transitioning to this :

VS 2010

MVC and Web Forms

SQL Server 2008

IIS 7

My question is, when we move to MVC with VS 2010, should we use Entity Framework( or another ORM), a micro ORM (like Massive), or just plain SQL?

All the tutorials I've read about VS 2010 are all geared towards using Entity Framework for data transactions, but is that going to be around for the foreseeable future (5+ years)?

If it matters, our client's applications can have anywhere from 10 - 1,000 active users.

答:
Entity Framework is a productivity tool.  Unless you have a good reason not to (E.G. you are on SQL 2000 or have no time to ramp up on the technology), then use the best tools at your disposal.

That being said, I find the concept of Entities to translate very well to the MVC pattern's Model.  While having a 1:1 relationship with Models and tables is a bad practice, thinking in terms of Entities tends to produce clean designs, easy to read code (especially with LINQ).

Entity Framework is actively supported by Microsoft.  No one has a magic crystal ball to say "support will last X years".  I see no reason to believe Entity will die in the next 5 years.

Title: Should we use Entity Framework?


问:
How can I thoroughly evaluate a prospective employer?
We hear much about code smells, test smells, and even project smells, but I have heard no discussion about employer "smells" outside of the Joel Test.  After much frustration working for employers with a bouquet of unpleasant corporate-culture odors, I believe it's time for me to actively seek a more mature development environment.

I've started assembling a list of questions to help vet employers by identifying issues during a job interview, and am looking for additional ideas.   I suppose this list could easily be modified by an employer to vet an employee as well, but please answer from the interviewee's perspective.

I think it would be important to ask many of these questions of multiple people to find out if consistent answers are given.  For the most part, I tried to put the questions in each section in the order they could be asked.  An undesired answer to an early question will often make follow-ups moot.

Values

What constitutes "well-written" software?

What attributes does a good developer have?  Same question for manager.  Who are your most valued employees/managers, and why?

Process

Do you have a development process?

How rigorously do you follow it?

How do you decide how much process to apply to each project?

Describe a typical project lifecycle. Ask the following if they don't come up otherwise:

Waterfall/iterative: How much time is spent in upfront requirements gathering? upfront design?

Testing

Who develops tests (developers or separate test engineers?)

When are they developed?

When are the tests executed?

How long do they take to execute?

What makes a good test?

How do you know you've tested enough?

What percentage of code is tested?

Review

What is the review process like?

What percentage of code is reviewed?  Design?

How frequently can I expect to participate as code/design reviewer/reviewee?

What are the criteria applied to review and where do the criteria come from?

Improvement

What new tools and techniques have you evaluated or deployed in the past year?

What training courses have your employees been given in the past year?  What will I be doing for the first six months in your company (hinting at what kind of organized mentorship/training has been thought through, if any)

What changes to your development process have been made in the past year?

How do you improve and learn from your mistakes as an organization?  What was your organizations biggest mistake in the past year, and how was it addressed?

What feedback have you given to management lately?  Was it implemented? If not, why?

How does your company use "best practices?"  How do you seek them out from the outside or within, and how do you share them with each other?

Ethics

Tell me about an ethical problem you or your employees experienced recently and how was it resolved?

Do you use open-source software?  What open-source contributions have you made?

Follow-Ups

I liked what @jim-leonardo said on this Stack Overflow question:

Really a thing to ask yourself: "Does this person seem like they are trying to recruit me and make me interested?" I think this is one of the most important bits. If they seem to be taking the attitude that the only one being interviewed is you, then they probably will treat you poorly. Good interviewers understand they have to sell the position as much as the candidate needs to sell themselves.

@SethP added:

Glassdoor.com is a good web site for researching potential employers. It contains information about how specific companies conduct interviews...

答:
Make sure you are associating yourself with quality people who are under managment that recognizes they are quality people. I know that's subjective and so is your preference for where you want to work. You'll have to determine what you think is important. You can have a long list of questions, but you'll probably be able to figure out the people on your own. We tend to be able to smell our own kind.

They may not be implementing the best practices, but are capable of doing it and are in the process of improving. Are you going to pick a company that wins on the Joel Test by a couple of points only to find out they are all set in their ways and have not desire to improve? I personally would have a problem with that. Even a perfect score won't last forever if they can't continue to attract quality people.


问:
Which GOF design patterns work well with TDD, and which do not?
The GOF Design Patterns book rarely mentions the test-ability of each pattern. I'm aware that there are patterns such as Singleton that would lead to code for which it is difficult to write unit tests, and some such as Strategy that help with TDD.

Which patterns promote TDD, and which hinder TDD?

答:
Test-ability of any code can be determined with the following:
 - is there any global state? (singleton has)
 - are there any hidden dependencies in the code? (IoC and dependency injection make your code testable)
 - is your class using new operator to create objects inside functions/constructors? if yes, code is not testable. </p>

<p>A rule of thumb would be to just check usage of new. More new you see in code, less testable the class is. </p>

Body:
Test-ability of any code can be determined with the following:
 - is there any global state? (singleton has)
 - are there any hidden dependencies in the code? (IoC and dependency injection make your code testable)
 - is your class using new operator to create objects inside functions/constructors? if yes, code is not testable.

A rule of thumb would be to just check usage of new. More new you see in code, less testable the class is.


答:
I recently switched from using in-line SQL queries to using EF and here's what I've found:

Pros

Much faster to build the DAL (love not writing the SQL queries!)

Much easier to maintain

No longer need to remember to parse my input before building an in-line sql statement, which means less chance of a SQL injection attack (of course, it's still possible depending on your queries, but much less likely)

Cons

Cannot span multiple databases... at least not easily

All entities (tables, views, etc) need a primary key

If you want to update a single column in a 100+ required columns table (not my table design), you have to pull down all 100 columns to make the update. Or use a Stored Procedure.

I've had issues with some default values defined on SQL server not getting pulled into the entity model after a new record gets added. Usually this is with computed values, or values that get added in an INSERT Trigger

On occasion, the SQL queries get badly written and are slow to execute. If you have a slow-running query, run a SQL trace to see what EF is doing. It's possible you can re-work that query as a SP or View. This doesn't happen that often though.

I've had a few issues with trying to create an association between tables that do not have a Foreign Key defined in SQL Server. Usually it's because I'm trying to create a 1:0-1 relationship where EF wants to use a 1:0-*

I'm no EF expert though, so I probably missed some things. These are just the items I know I've encounted in the past when switching from inline SQL to Entity Framework. I am glad I made the switch, but there have been times when I've really hated EF due to its quirks.

Title: Should we use Entity Framework?

Body:
We currently have the following stack :

VS 2005

Web forms

SQL Server 2005

IIS 6

We are planning on transitioning to this :

VS 2010

MVC and Web Forms

SQL Server 2008

IIS 7

My question is, when we move to MVC with VS 2010, should we use Entity Framework( or another ORM), a micro ORM (like Massive), or just plain SQL?

All the tutorials I've read about VS 2010 are all geared towards using Entity Framework for data transactions, but is that going to be around for the foreseeable future (5+ years)?

If it matters, our client's applications can have anywhere from 10 - 1,000 active users.


答:
You have to make an architectural decision based on the problem and existing solution. As with any technology there are advantages and disadvantages.

I personaly would normally use the entity framework for new development but not rewrite working existing code. You then get the speed for future delelopment but dont have to invest lots of time converting code. The downside of that approach is it reduces consistancy.

Title: Should we use Entity Framework?


问:
Are there any jobs in the programming field that don't require you to sit at a desk all day?
I'm new in the field of programming. I really enjoy it as a career, but I'm not sure I can handle sitting at a desk for eight hours a day. I don't mind it for short stretches of time of course, but I can't do it day in and day out.

Is there a field of programming that possibly has jobs that require less time spent at the desk?

答:
Join the One Laptop per Child project.

It is a worldwide development project. They need system technicians as well as administrators to take care of their servers and general infrastructure. Which means you need to be where the laptops/servers are being used to give good technical support which would mean a lot of travelling and discovering other cultures.

Plus, if you don't feel challenged enough, you can always develop open source software or go for a hike.


答:
Wolfger already mention PLC programming. There are many programmers who work in automation in general programming PLC, robots (what I do), PACs, PCs, and embedded.

You do spend time behind a desk, some of it programming, some of it customer support. You also spend a lot of time in the field with the equipment. Often there is considerable travel involved. My office covers North and Central America. I also occasionally travel to Europe for meetings at the division headquarters.

Title: Are there any jobs in the programming field that don't require you to sit at a desk all day?

Body:
I'm new in the field of programming. I really enjoy it as a career, but I'm not sure I can handle sitting at a desk for eight hours a day. I don't mind it for short stretches of time of course, but I can't do it day in and day out.

Is there a field of programming that possibly has jobs that require less time spent at the desk?


问:
Ramping Up On Legacy Code
When starting to work on a project with an existing code base, the first thing that needs to be done is usually to understand the application & existing code.  Let's assume that the existing code is legacy code; referring to Michael Feathers' definition of "code with no tests".

I am sure that there are many different ways to handle this ramp-up phase. The most straightforward way is to go through the UI of the application (if there is one) and simultaneously debug the application to understand what is happening at the code level. This is a very time-consuming approach and also it is very easy to forget what you learn in a debugging session. Furthermore, there is no real way to share (among the team) what you learn during debugging.

Understanding the down-sides of this approach, I have tried another approach for my most recent project. What I did was to write a kind of API layer that sits on top of the existing code base. This API contained the functionality of pretty much what a user would do in the UI.

To be more specific, let's assume that the existing application is a typical transactional application with orders, items and shopping carts. My API turned  out to something like this:

```<code>public class OrderAPI{
    public Order createOrder(customerName);
    public boolean deleteOrder(orderID);
    public List<Order> getOrdersForCustomer(customerName);
}

public class OrderItemAPI{
    public OrderItem createOrderItem(order);
    public boolean deleteOrder(orderID);
    public List<OrderItem> getItemInOrder(order);
}

public class ShoppingCartAPI {
    public ShoppingCart createCart(customer,order);
    public boolean addItemToCart(cart, item);
    public boolean removeItemFromCart(cart, item);
}
</code>```

The methods in the API correspond to the actions that the user would perform at the UI level. Within these methods, the calls to the existing codebase are made.

Writing this API by itself, of course, doesn't mean much. So, I have written tests (I guess they automatically become integration tests) to ensure that the API works well; proving that I got an understanding of how the legacy code works.

After all this introduction, comes my question: Can you define (possibly in software engineering terms) what I have done? When taking this approach, I have gone completely with my intuition. At some point, I remember being extremely confused; working on the API, then working on my tests, fixing my API, then my tests. I wasn't sure anymore if my main objective was to learn the existing code base or come up with a stable API layer.

I would greatly appreciate any kind of explanation; I am sure that this must be a practice that other people have already experimented with. I just need the right guidance to point me to the appropriate discussions/resources.

答:
The API is a Facade/Wrapper right?  Feathers might also call it creating a Seam.  I call it "Getting the System under Test".

If possible, you now want to take the UI layer and integrate it so it works through this new API.  At that point you have real integration tests, and have some confidence of the system's behavior from the API down.  If you leave it as is, I would characterize them as Learning Tests, which can still be useful for hunting regressions.

Learning Tests were featured in Clean Code, but I don't know who invented the term.  Here are some links for more info:

http://c2.com/cgi/wiki?LearningTest

http://c2.com/cgi/wiki?CharacterizationTest

http://www.renaissancesoftware.net/blog/archives/tag/learning-tests

http://my.safaribooksonline.com/book/software-engineering-and-development/agile-development/9780136083238/boundaries/ch08lev1sec4

Title: Ramping Up On Legacy Code


答: I customise ERP systems, this involves quite a bit on onsite work but you may or may not want to have to deal directly with customers.</p>


问:
How to test the tests?
We test our code to make it more correct (actually, less likely to be incorrect). However, the tests are also code -- they can also contain errors. And if your tests are buggy, they hardly make your code better.

I can think of three possible types of errors in tests:

Logical errors, when the programmer misunderstood the task at hand, and the tests do what he thought they should do, which is wrong;

Errors in the underlying testing framework (eg. a leaky mocking abstraction);

Bugs in the tests: the test is doing slightly different than what the programmer thinks it is.

Type (1) errors seem to be impossible to prevent (unless the programmer just... gets smarter). However, (2) and (3) may be tractable. How do you deal with these types of errors? Do you have any special strategies to avoid them? For example, do you write some special "empty" tests, that only check the test author's presuppositions? Also, how do you approach debugging a broken test case?

答:
For #1 and #3: Unit tests should not contain any logic, if you do then you are probably testing more than one thing in your unit test. One best practice for unit testing is to only have one test per unit test.

Watch this video by Roy Osherove to learn more on how to write unit tests well.

ContentLicense: CC BY-SA 2.5

Title: How to test the tests?


问:
How often to release in Scrum sprint
How often to you release during a sprint. Only at the end of the sprint or every time a feature is ready. And how to you handle bugfix releases?</p>

答:
TL;DR: Release whenever appropriate

We do releases whenever there is value in doing a release. Sometimes that means doing a release after a single feature or bugfix is completed.  Sometimes that means releasing a collection of features and/or bugfixes.

This doesn't mean we often have "emergencies" that require fast releases.  It means we've worked hard to make releases easy. Our code is tested, tagged and packaged with every build.  We use automated acceptance tests and as a result we have developed a high amount of confidence in the code that passes it's tests.  Since our packages are immediately available via a local yum repo deploying a release is trivial.

Title: How often to release in Scrum sprint


问:
Is object pooling a deprecated technique?
I am very familiar with the concept of object pooling and I always try to use it as much as possible.

Additionally I always thought that object pooling is the standard norm as I have observed that Java itself as well as the other frameworks use pooling as much as possible.

Recently though I read something that was completely new (and counter-intuitive?) to me.

That pooling actually makes program performance worse especially in concurrent applications, and it is advisable to instantiate new objects instead, since in newer JVMs, instantiation of an object is really fast.

I read this in the book: Java Concurrency in Practice

Now I am starting to think if I am missunderstanding something here since the first part of the book adviced to use Executors that reuse Threads instead of creating new instances.

So has object pooling become deprecated nowadays?

答:
It is deprecated as a general technique, because - as you noticed - creation and destruction of short lived objects per se (i.e. memory allocation and GC) is extremely cheap in modern JVMs. So using a hand-written object pool for your run-of-the-mill objects is most likely slower, more complicated and more error-prone than plain new.*

It still has its uses though, for special objects whose creation is relatively costly, like DB / network connections, threads etc.

*Once I had to improve the performance of a crawling Java app. Investigation uncovered an attempt to use an object pool to allocate millions of objects... and the clever guy who wrote it used a single global lock to make it thread safe. Replacing the pool with plain new made the app 30 times faster.


答: I do not know if there is a changing trend here but its certainly going to be the case that it depends. If your Java class is managing an external resource, such as an RMI connection or loading a resource file etc - then certainly the costs for object instantiation can still be high (though those resources may be pooled for you already!). As a general practice I'd agree with the book.

Title: Is object pooling a deprecated technique?

Body:
I am very familiar with the concept of object pooling and I always try to use it as much as possible.

Additionally I always thought that object pooling is the standard norm as I have observed that Java itself as well as the other frameworks use pooling as much as possible.

Recently though I read something that was completely new (and counter-intuitive?) to me.

That pooling actually makes program performance worse especially in concurrent applications, and it is advisable to instantiate new objects instead, since in newer JVMs, instantiation of an object is really fast.

I read this in the book: Java Concurrency in Practice

Now I am starting to think if I am missunderstanding something here since the first part of the book adviced to use Executors that reuse Threads instead of creating new instances.

So has object pooling become deprecated nowadays?


答: Robotics. Not only will you have to cut code, but you will have to talk to hardware guys, and get out into the field and observe your cute little T-800 prototype doing its thing :) </p>


答:
Measure

It completely depends on your use case, size of your objects, your JVM, your JVM options, what GC you have enabled and a whole host of other factors.

In short: measure it before and measure it after.  Assuming you're using an object pooling framework (like from Apache) then it shouldn't be too painful to swap between implementations.

Extra performance testing tip - let the JVM warm up a bit first, run the tests on a running JVM a number of times, it can behave differently.


问:
how to prove the complexity of an algorithm mathematically
I know the fundamental algorithms and it's complexities. for e.g if Binary Search has Complexity O(log n), then how I can mathematically prove this?</p>

答:
For Binary Search Only!

Here is my way of doing it:

To implement binary search on a sorted list that contains N elements, we keep dividing the list in halves until we 'corner' the key. This tells us that the problem size decreases by half, [Eg. 100 : 50 : 25 : 12 : 6 : 3 : 1], until it reaches (worst case) 1!

This gives us Geometric progression with a Common ratio = 1/2 and the Nth term being 1.

GP formula is:

An = A1rn-1
which leads to

1 = A1(1/2)n-1

It gets easier after this: Divide both sides by A1, Multiply by Log 2 and solve for N!

Should give you the number of steps to reach An which is Log 2A1 + 1 which in turn is O(log n)


问:
How can I prevent users from creating multiple accounts on a web site?
I'm building a site that needs to guarantee user reputation scores are accurate by preventing users from creating more than one account, at the cost of decreased user signups. So far, the only solutions I have thought of are allowing users to:

Link to their (verified) PayPal account through PayPal Account Authentication

Provide their PGP public key, and checking that the MSD (a metric of trustworthiness) is below a certain value

Of course, even these methods aren't bulletproof, but are likely to make creating a sock-puppet account very difficult. Are there any others I haven't considered?

答:
Give users a range of options to verify? Combine a good "user policy" ("We won't share your information with third parties", etc) with a good behind-the-scenes "points" scheme give points for stuff like:

  - Verified phone number (SMS them a code that they enter)

  - Facebook

  - OpenID

  - Paypal

  - etc

Give each option a point value (Paypal is worth more than a GMail account, for example)... and let them choose how to get enough points to become "verified". Make this information available to the "owner" of the account.

If the account changes hands, the new owner now has that personal information... if the information changes (new email address) you can increase/decrease the "verified score", make the re-verify phone numbers or whatever.  Fishy activity on an account can increase the needed "verified" score.

I'd do something like this, combined with the aforementioned IP/usage tracking to try and identify bad behavior and "gamificaton" to reward good behavior.

OwnerDisplayName: Alek Storm


问:
Delegate vs Interfaces-Any more clarifications available?
After reading the article-
When to Use Delegates Instead of Interfaces (C# Programming Guide),
I need some help  understanding the below given points, which I found to be not so clear (for me).
Any examples or detailed explanations available for these?

Use a delegate when:

An eventing design pattern is used.

It is desirable to encapsulate a static method.

Easy composition is desired.

A class may need more than one implementation of the method.

Use an interface when:

There are a group of related methods that may be called.

A class only needs one implementation of the method.

My Questions are,

What do they mean by an eventing design pattern?

How the composition turns out to be easy if a delegate is used?

if there is a group of related methods that may be called,then use interface-What benefit it has?

if a class only needs one implementation of the method,  use interface-how is it justified in terms of benefits?

答:
Your question on events has already been nicely covered. And it is also true, that an interface can define multiple methods (but actually needn't), while a function type only ever puts constraints on an individual function.

The real difference however is:

function values are matched to function types by structural subtyping (i.e. implicit compatibility to demanded structure). That means, if a function value has a signature compatible to the function type, it is a valid value for the type.

instances are matched to interfaces by nominal subtyping (i.e. explicit use of a name). That means, if an instance is a member of a class, that explicitly implements the given interface, the instance is a valid value for the interface. However, if the object only has all members demanded by the interfaces, and all members have compatible signatures, but does not explicitly implement the interface, it is not a valid value for the interface.

Sure, but what does this mean?

Let's take this example (code is in haXe since my C# isn't very good):

```<code>class Collection<T> {
    /* a lot of code we don't care about now */
    public function filter(predicate:T->Bool):Collection<T> {
         //build a new collection with all elements e, such that predicate(e) == true
    }
    public function remove(e:T):Bool {
         //removes an element from this collection, if contained and returns true, false otherwise
    }
}
</code>```

Now the filter-method makes it easy to conveniently pass in just a small piece of logic, that is unaware of the internal organisation of the collection, while the collection doesn't depend on the logic given to it. Great. Except for one problem:

The collection does depend on the logic. The collection inherently makes the assumption, that the function passed in is designed to test a value against a condition and return the success of the test. Note that not all functions, that take one value as an argument and return a boolean are actually mere predicates. For example our collection's remove method is such a function.

Assume we called c.filter(c.remove). The result would be a collection with all the elements of c while c itself becomes empty. This is unfortunate, because naturally we'd expect c itself to be invariant.

The example is very constructed. But the key problem is, that the code calling c.filter with some function value as argument has no way of knowing whether that argument is suitable (i.e. will ultimately conserve the invariant). The code that created the function value may or may not know, that it will be interpreted as a predicate.

Now let's change things:

```<code>interface Predicate<T> {
    function test(value:T):Bool;
}
class Collection<T> {
    /* a lot of code we don't care about now */
    public function filter(predicate:Predicate<T>):Collection<T> {
         //build a new collection with all elements e, such that predicate.test(e) == true
    }
    public function remove(e:T):Bool {
         //removes an element from this collection, if contained and returns true, false otherwise
    }
}
</code>```

What has changed? What has changed is, that whatever value is now given to filter has explicitly signed the contract of being a predicate. Of course malicious or extremely stupid programmers create implementations of the interface that aren't side-effect free and thus aren't predicates.

But what can no longer happen is that someone ties up a logical unit of data/code, which mistakenly get's interpreted as a predicate because of its outer structure.

So to rephrase what was said above in just a few words:

interfaces mean using nominal typing and thereby explicit relationships

delegates mean using structural typing and thereby implicit relationships

The advantage of explicit relationships is, that you can be certain of them. The disadvantage is, that they require the overhead of explicitness. Conversely, the disadvantage of implicit relationships (in our case one function's signature matching the desired signature), is that you can't really be 100% sure that you can use things this way. The advantage is, that you can establish relationships without all the overhead. You can just quickly throw things together, because their structure allows it. That's what easy composition means.

It's a bit like LEGO: you can simply plug a star wars LEGO figure onto a LEGO pirate ship, simply because outer structure allows it. Now you might feel that that is terribly wrong, or it might just be exactly what you want. Nobody is going to stop you.

Body:
Your question on events has already been nicely covered. And it is also true, that an interface can define multiple methods (but actually needn't), while a function type only ever puts constraints on an individual function.

The real difference however is:

function values are matched to function types by structural subtyping (i.e. implicit compatibility to demanded structure). That means, if a function value has a signature compatible to the function type, it is a valid value for the type.

instances are matched to interfaces by nominal subtyping (i.e. explicit use of a name). That means, if an instance is a member of a class, that explicitly implements the given interface, the instance is a valid value for the interface. However, if the object only has all members demanded by the interfaces, and all members have compatible signatures, but does not explicitly implement the interface, it is not a valid value for the interface.

Sure, but what does this mean?

Let's take this example (code is in haXe since my C# isn't very good):

class Collection<T> {
    /* a lot of code we don't care about now */
    public function filter(predicate:T->Bool):Collection<T> {
         //build a new collection with all elements e, such that predicate(e) == true
    }
    public function remove(e:T):Bool {
         //removes an element from this collection, if contained and returns true, false otherwise
    }
}

Now the filter-method makes it easy to conveniently pass in just a small piece of logic, that is unaware of the internal organisation of the collection, while the collection doesn't depend on the logic given to it. Great. Except for one problem:

The collection does depend on the logic. The collection inherently makes the assumption, that the function passed in is designed to test a value against a condition and return the success of the test. Note that not all functions, that take one value as an argument and return a boolean are actually mere predicates. For example our collection's remove method is such a function.

Assume we called c.filter(c.remove). The result would be a collection with all the elements of c while c itself becomes empty. This is unfortunate, because naturally we'd expect c itself to be invariant.

The example is very constructed. But the key problem is, that the code calling c.filter with some function value as argument has no way of knowing whether that argument is suitable (i.e. will ultimately conserve the invariant). The code that created the function value may or may not know, that it will be interpreted as a predicate.

Now let's change things:

interface Predicate<T> {
    function test(value:T):Bool;
}
class Collection<T> {
    /* a lot of code we don't care about now */
    public function filter(predicate:Predicate<T>):Collection<T> {
         //build a new collection with all elements e, such that predicate.test(e) == true
    }
    public function remove(e:T):Bool {
         //removes an element from this collection, if contained and returns true, false otherwise
    }
}

What has changed? What has changed is, that whatever value is now given to filter has explicitly signed the contract of being a predicate. Of course malicious or extremely stupid programmers create implementations of the interface that aren't side-effect free and thus aren't predicates.

But what can no longer happen is that someone ties up a logical unit of data/code, which mistakenly get's interpreted as a predicate because of its outer structure.

So to rephrase what was said above in just a few words:

interfaces mean using nominal typing and thereby explicit relationships

delegates mean using structural typing and thereby implicit relationships

The advantage of explicit relationships is, that you can be certain of them. The disadvantage is, that they require the overhead of explicitness. Conversely, the disadvantage of implicit relationships (in our case one function's signature matching the desired signature), is that you can't really be 100% sure that you can use things this way. The advantage is, that you can establish relationships without all the overhead. You can just quickly throw things together, because their structure allows it. That's what easy composition means.

It's a bit like LEGO: you can simply plug a star wars LEGO figure onto a LEGO pirate ship, simply because outer structure allows it. Now you might feel that that is terribly wrong, or it might just be exactly what you want. Nobody is going to stop you.


问:
How to decrease errors before testing?
During last year, several of the projects of the company where I work failed.

We develop web software, that are not especially complicated (the most are CRUDS and search form about this data).

One of the problems that management has identified is the test phase.

Putting simple, our protocol is:

Analysis of the requeriments

Development

When construction is over, upload the executable to a server

Execute test plan

Repair the errors

Execute the test plan, to check if errors persist.

If all is ok -> Send to the client.

The problem is that when we finish phase 3 and start phase 4, the number of errors is to damn high, that the execution plan takes to much time, and we get an interminable list of things that we have to repair.

Until arrive to the test plan we are on time, but after this we spend more hours that were planned and then "fail" the project. We deliver with enought quality for the client but spend more hours repairing bugs.

The management is looking for a solution, and is planned a meeting to ask us for ideas to improve the quality before the first test plan. Any idea?

答:
Use Test Driven Development.  This way you continually test and integrate functionality.  In CRUD based development, I like to use a iCRUD interface.  This makes it easy to setup my tests.  Just create ConcreteItemX which implements iCRUD and setup the 4 tests (Create, Read Update Delete).  Implemenent until all tests pass.

Rinse and repeat.

Its fine to have testing later down the pipe.  You just cannot wait until that late in the process to actually begin any real testing due to the fact that the cost to fix a bug increases dramatically over time.

Title: How to decrease errors before testing?


答:
The first thing to do is figure out where you defects are being injected and where they are being detected. Although you know that too many are slipping through into the testing phase, you don't know where they are coming from. Applying Defect Removal Effectiveness tracking techniques can help here. Simply, create a matrix of phases (given what you said, your phases would probably be requirements, design, implementation, testing, and field). Whenever you find a defect, track where you found it and where it came from. For each phase, track the percentage of defects that have been identified and removed.

Once you know which specific phases are problematic, you can introduce changes. Examples of quality techniques include requirements, design, and code reviews. Cause and effect analysis can also be used to determine why a defect was injected and what can be done to prevent it. Checklists can be employed to ensure repeatibility across your processes. There are a number of quality tools out there, but until you know where your problems are and what is causing them, doing anything might be a waste of resources.

I would recommend reading Stephen Kan's Metrics and Models in Software Quality Engineering. This was the textbook used in my university's Software Engineering Process and Product Quality course, and it's a very good book when it comes to understanding and improving quality at both the product level and the process level.

Title: How to decrease errors before testing?

Body:
During last year, several of the projects of the company where I work failed.

We develop web software, that are not especially complicated (the most are CRUDS and search form about this data).

One of the problems that management has identified is the test phase.

Putting simple, our protocol is:

Analysis of the requeriments

Development

When construction is over, upload the executable to a server

Execute test plan

Repair the errors

Execute the test plan, to check if errors persist.

If all is ok -> Send to the client.

The problem is that when we finish phase 3 and start phase 4, the number of errors is to damn high, that the execution plan takes to much time, and we get an interminable list of things that we have to repair.

Until arrive to the test plan we are on time, but after this we spend more hours that were planned and then "fail" the project. We deliver with enought quality for the client but spend more hours repairing bugs.

The management is looking for a solution, and is planned a meeting to ask us for ideas to improve the quality before the first test plan. Any idea?


问:
What defines an encapsulation properly?
I find the encapsulation concept a bit confusing. So far I have read that the members of the class should be private and any access to private members must be through getter and setter methods, which are public. Are these the only properties which define a properly encapsulated class?

If yes, what about protected class members? We can access protected members in the same package through an object reference — are classes containing protected members improperly encapsulated?

Please give clarification.

答:
Encapsulation is properly defining access to the members of an object and protecting the internal state of the object.

The first part, defining access, is done through the access specifiers (public, private, protected, and so on). Typically, a well encapsulated class limits access as much as possible. If only the current class (or an instance of that class) needs access to it, make it private. If subclasses also need access to it, then it's a protected member. Note that this applies equally to variables and methods.

The second part is to protect the internal state of the object from ever being invalid. This is one of the driving factors behind accessor and mutator methods. You can use these methods to always ensure the validity of the state of the object. For example, if you have a member variable that can only contain specific values, you can validate before changing the state of the object if you require the use of mutator methods, but can't with a public variable.

Title: What defines an encapsulation properly?


答:
Jobs are really what you make them.  You could spend the entire time coding at your desk but software development is so much more than coding.

A previous job of mine involved building the internal software for a testing company.  While not very glamorous, the job did involve a fair bit of travel though the conditions were poor at times (you don't get dual monitors and a comfy chair on site).  The perk was short feedback loops because I was literally in the next room and I got to work with a variety of people (oil & gas and agriculture testers).

At my primary site(s), I could do laps to all the areas to see how everything was working and get first-hand critiques of the apps.  It beats surveys.

When interviewing at non-software development companies, be sure you know what you're getting into because oftentimes the leaders have very ignorant views of software development because they aren't software developers.


答:
Depending on who is teaching that concept, encapsulation can have soooo many definitions that it is essentially a buzzword to be defined with a tens of other buzzwords, sometimes even going to the ridiculous statement like your reported "So far i have read that the members of the class should be private and any access to this private members must be through getters and setters methods which are public".

The need of encapsulation typically arise when you represent an object by aggregating a number of components whose values are each other related, and hence cannot be changed each other independently, without making the object invalid or clueless or meaningless or pantless or whatever you want to call it.
In those case you -an only you- assume the responsibility to manage those subvalues, making those component hidden (or unaccessible ... is much a matter on how the language works), and providing the aggregate with public methods that modifies the inner values properly.

-Edit-
Everything else is just "purism over-construction" that doesn't really implement anything, apart ... satisfying OOP zealot teachers.

-Edit-
P.S.: I have to sorry to all OOP teachers, but 30 year of experience in the industry makes me really wonder abut the damages of certain "uncritical" way to teach "rules" rather than concepts and relations between them!
You can downvote, if you want, but I would like to see a practical demonstration I am wrong!
The world is full of (really bad) books teaching bad things like

```<code>class A
{
private:
   int x;
public:
   void set_x(int x_) { x=x_; }
   int get_x() const { return x; }
};
</code>```

That didn't encapsulate anything, since it lets you do anything you want with x.

Title: What defines an encapsulation properly?

Body:
I find the encapsulation concept a bit confusing. So far I have read that the members of the class should be private and any access to private members must be through getter and setter methods, which are public. Are these the only properties which define a properly encapsulated class?

If yes, what about protected class members? We can access protected members in the same package through an object reference — are classes containing protected members improperly encapsulated?

Please give clarification.

Body:
Depending on who is teaching that concept, encapsulation can have soooo many definitions that it is essentially a buzzword to be defined with a tens of other buzzwords, sometimes even going to the ridiculous statement like your reported "So far i have read that the members of the class should be private and any access to this private members must be through getters and setters methods which are public".

The need of encapsulation typically arise when you represent an object by aggregating a number of components whose values are each other related, and hence cannot be changed each other independently, without making the object invalid or clueless or meaningless or pantless or whatever you want to call it.
In those case you -an only you- assume the responsibility to manage those subvalues, making those component hidden (or unaccessible ... is much a matter on how the language works), and providing the aggregate with public methods that modifies the inner values properly.

-Edit-
Everything else is just "purism over-construction" that doesn't really implement anything, apart ... satisfying OOP zealot teachers.

-Edit-
P.S.: I have to sorry to all OOP teachers, but 30 year of experience in the industry makes me really wonder abut the damages of certain "uncritical" way to teach "rules" rather than concepts and relations between them!
You can downvote, if you want, but I would like to see a practical demonstration I am wrong!
The world is full of (really bad) books teaching bad things like

class A
{
private:
   int x;
public:
   void set_x(int x_) { x=x_; }
   int get_x() const { return x; }
};

That didn't encapsulate anything, since it lets you do anything you want with x.


问:
Stuff every programmer needs while working
I've been tasked with creating a fun and relaxing environment, one thing I know that I want is ergonomic mice and keyboards, others have suggested exercise balls and bands.

What is it that every programmer needs while working? What might not be necessary but would be nice to have anyway?

Note: this question was asked previously, but has been recommended to be posted here. See this link for the previous responses: https://stackoverflow.com/questions/3911911/stuff-every-programmer-needs-while-working-closed

答: A rubik's cube

Body: A rubik's cube


问:
When do I need web services?
Are there any general guidelines to understand when I should consider using (as a eat-your-own-dogfood) and providing web services, and when I shouldn't worry about them? Or, any reading materials you can point me to?

My project is in PHP but I don't mind if it's language agnostic.

答:
There is no all encompassing answer to this - it depends on many variables.

In general, one should implement a web service when there is a need to provide an API (internally and/or externally) that will have multiple users (as in different applications) and that should be consumed over the network (using HTTP).

If there is only one application that will use the API (or at least the only expected one), there is not much point in making a web service (I would question the need for an API in such a case).

Title: When do I need web services?


答:
The answer to the concrete question: 'Is object pooling a deprecated technique?' is:

No. Object pooling is widely used in specific places - thread pooling, database connection pooling etc.

General object creation has never been a slow process. Pooling in itself consumes resources - memory and processing power. Any optimization is a trade-off.

The rule is:

Premature Optimization is Evil!!!

But when is a given optimization premature?

Premature optimization is any optimization done, before you have uncovered a bottleneck via thorough profiling.


答:
P. Brian Mackey is right about TDD being useful - and any unit tests will improve things dramatically.  As a tester, I can tell you that a thorough unit test suite dramatically decreases the number of bugs, and limits the remaining functional bugs to mostly a few predictable areas where I can focus my testing (mostly integration points / environmental interactions).  This simplifies test coverage and makes testing go faster.

Other ideas:

Get QA involved ASAP.  If you don't have at least one QA specialist sitting on all or nearly all of the meetings, starting with the design stage, you are missing a lot of value.  Senior testers can help find design flaws, bring up small features that will greatly speed up testing, and can start planning test strategy sooner when they are involved in design meetings.

Get good, solid requirements, get them early, and get QA to review them.  A good QA specialist will find holes in the requirements that no one thought to address.  Sometimes things that are minor details to devs are huge blockers to QA (e.g., the specifics of business rules; dev can build the framework for rules and then add the actual rules later with little effort, but tests can't be written until the specifics are known).  The worst test cycles I've seen have been when the BA folks didn't get clear requirements, got them late, or communicated modifications to requirements verbally to developers without notifying QA.  Also, test automation can't be developed concurrently with product development without good requirements up front.

Develop more incrementally.  Don't throw the entire product to QA, but deliver pieces throughout the development cycle as they are finished for component testing and component integration testing.  Agile development techniques are great for reducing the test cycles and distributing them more smoothly throughout the project so you don't have a huge snarl at the end.

If you have developers or testers who read code working in QA, have them do code reviews as well as developers (so one dev, one QA reviews each major code change).  This both helps QA learn the code base and system, and also provides a quality-focused perspective on the code.

Use more automation in your QA process.  Limit manual testing to a few well-defined areas.  Automated tests can be developed before the development on the component is finished, can be run at night, and require relatively few resources once developed.  Although you will probably invest more test resources overall into automation, a lot of the tester time will happen before the 'test bottleneck', when tester time is cheap.

Ensure that developers make working with and unblocking testers a high priority through the entire development cycle.  When you discourage a tester from asking questions, learning the system, and generally doing their job, you acquire technical debt.  Developers might not realize this because you don't pay interest on that debt until you get to the test phase; the cost is externalized from the developers.

Automate test environment setup.  It's time-consuming, and most testers need to do it at least daily to keep up with bug fixes.  A tester should be able to install the entire product(s) with a single command.

Title: How to decrease errors before testing?


答:
Though my job as an in-house Windows Forms programmer does involve a lot of deskwork. I'm often at other people's desks watching them demonstrate a bug or expressing a desire for a new feature of some sort. Sometimes I have the option of just watching them work, and when doing so I can see how they use the application, so I can think of ways to make them better able to do it their way, instead of the way I was thinking when I developed that particular feature.

As a lot of my work also involves integration and interop with third-party hardware and software. I'm often in the lab fiddling with various gizmos and watching how the programs react. My last job was in web programming, and there wasn't much "lab work", so yes, that job was sitting at a computer coding heads-down for most of the day.

Programming is quite simply a knowledge job, meaning it's mostly a desk job. If you want to go beyond that, then you need a job that isn't just programming, but other elements of the SLDC including analysis and design. That gets you out of your cube and into face-to-face meetings with the people who will benefit from the new programming work, or at least the people paying the bills.


答:
Basically, you should implement a web service when you have functionality that, for whatever reason, requires centralization on a computer you control, but that needs to be directly accessed by consumers on many machines that you may not control.

Typically, the reasons for such centralization are:

The functionality requires access to a large dynamic data store that would be infeasible to distribute in its entirety to all users.

The functionality requires serious computational muscle that, again, would be infeasible to provide to all users or to expect them to have available.

The functionality exists to provide some sort of controlled access to confidential information or features. You simply cannot trust anything on the remote end of an Internet connection.

The functionality must be platform-independent so that it can be consumed by programs run on a variety of platforms. No one programming language is 100% platform-independent, but many communications layers (such as WSDL/SOAP and HTML/HTTP) are.

In all cases, it is necessary to distinguish the functionality being talked about as being more involved than serving up web pages. The actual mechanism used is actually very similar, but the intended recipient is not a browser (and thus an end user simply needing a UI), but code (which will use the results of your service in its own program for its own purposes).

To do this, you expose your functionality as a web service, which clients can send requests to and to which you can choose, if everything seems kosher, to respond.

Title: When do I need web services?

Body:
Are there any general guidelines to understand when I should consider using (as a eat-your-own-dogfood) and providing web services, and when I shouldn't worry about them? Or, any reading materials you can point me to?

My project is in PHP but I don't mind if it's language agnostic.


答: In situations where you want to avoid garbage collection entirely, I think object pooling is the only viable alternative.  So no, it is absolutely not a deprecated technique.</p>


问:
Is there a standard, formal name for an object or class that behaves as if it is a given object?
I have an app in Django that expects to get a record with the fields email, first_name, and last_name.

However, sometimes I want to be able to send it something that isn't actually a record but behaves like one (in that it has the necessary fields as attributes), like so:

```<code>class FakeRecord(object):
    def __init__(self, email, first_name=None, last_name=None):
        self.email = email
        self.first_name = first_name
        self.last_name = last_name
</code>```

I'm wondering if there is a standard name for this kind of object or if FakeRecord works as the name for this class.

More generally, is there a name for a class that stands in for or behaves similarly to another class? Is there a standard implementation/design pattern?

Further clarification

For the purposes of my app, basically I have a utility function that sends an email to a recipient. The recipient can be any Django record so long as it has an email address, a first name, and a last name.

However, sometimes the app sends a one-off mailing to some given e-mail address that doesn't have a record. In those cases, I simply create a FakeRecord with the email address (and first name/last name if available), and send that in instead.

Since the utility function itself doesn't do anything with the record other than retrieving the attributes, none of the other db functionality of a Django record object is needed.

答:
It sure looks like a Mock.

While often used for testing, it's also sensible in a Duck-typed language to mock other class definitions.

You've got two classes which are both implementations of a common interface.  This is polymorphism in action.  There's not much of "standard formal" name for it because it's just OO programming.

In Python, because there's no formal requirement for a separate interface class, these are just polymorphic classes.

You could call them "Polymorphs" or "Alternative Implementations".


问:
Why is naming a table's Primary Key column "Id" considered bad practice?
My t-sql teacher told us that naming our PK column "Id" is considered bad practice without any further explanations.

Why is naming a table PK column "Id" is considered bad practice?

答:
This thread is dead, but I would like to add that IMO not using Id is a bad practice. The Id column is special; it is the primary key. Any table can have any number of foreign keys, but it can have only one key that is primary. In a database where all primary keys are called Id, as soon as you look at the table you know exactly which column is the primary key.

Believe me, for months now I've spent all day every day working in lots of big databases (Salesforce) and the best thing I can say about the schemas is that every table has a primary key called Id. I can assure you I absolutely never get confused about joining a primary key to a foreign key because the PK is called Id. Another thing that people haven't mentioned is that tables can have long silly names like Table_ThatDoesGood_stuff__c; that name is bad enough because the architect had a hangover the morning he thought up that table , but now you are telling me that it's bad practice not to call the primary key Table_ThatDoesGood_stuff__cId  (remembering that SQL column names aren't in general case sensitive).

To be honest, the problems with with most people who teach computer programming are that they haven't written a line of production code in years, if ever, and they have no idea what a working software engineer actually does. Wait until you start working and then make up your own mind what you think is a a good idea or not.


答:
According to Martin Fowler, fake is pretty accurate:

Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production (an in memory database is a good example).

http://martinfowler.com/articles/mocksArentStubs.html#TheDifferenceBetweenMocksAndStubs

Title: Is there a standard, formal name for an object or class that behaves as if it is a given object?

Body:
I have an app in Django that expects to get a record with the fields email, first_name, and last_name.

However, sometimes I want to be able to send it something that isn't actually a record but behaves like one (in that it has the necessary fields as attributes), like so:

```<code>class FakeRecord(object):
    def __init__(self, email, first_name=None, last_name=None):
        self.email = email
        self.first_name = first_name
        self.last_name = last_name
</code>```

I'm wondering if there is a standard name for this kind of object or if FakeRecord works as the name for this class.

More generally, is there a name for a class that stands in for or behaves similarly to another class? Is there a standard implementation/design pattern?

Further clarification

For the purposes of my app, basically I have a utility function that sends an email to a recipient. The recipient can be any Django record so long as it has an email address, a first name, and a last name.

However, sometimes the app sends a one-off mailing to some given e-mail address that doesn't have a record. In those cases, I simply create a FakeRecord with the email address (and first name/last name if available), and send that in instead.

Since the utility function itself doesn't do anything with the record other than retrieving the attributes, none of the other db functionality of a Django record object is needed.


答:
Characterization tests is the term that Michael Feathers uses to write tests that try to understand and characterize what an unknown code base does. It seems that, to get to these tests, you were forced to also create this API, a wrapper or facade (as mentioned by Steve Jackson) that tries to expose a coherent set of functionality at the right level of abstraction without going through the UI. It's hard to test without good separation and coherence.

So to me, this API seems like necessary scaffolding to be able to write some characterization tests. It might be interesting to consider evolving it and incorporating it in the application itself, so that you don't have competing views of the same system, what might backfire and turn out to be a source of duplication (and maintenance headaches).

Other related terms that might be of interest include:

To build test data:

Test data builders

Object mothers

Big refactorings:

Strangler application

Design patterns:

Facade

Principles (on levels of abstraction):

Single Level of Abstraction Principle

Interface Segregation Principle (pdf)

Title: Ramping Up On Legacy Code

Body:
When starting to work on a project with an existing code base, the first thing that needs to be done is usually to understand the application & existing code.  Let's assume that the existing code is legacy code; referring to Michael Feathers' definition of "code with no tests".

I am sure that there are many different ways to handle this ramp-up phase. The most straightforward way is to go through the UI of the application (if there is one) and simultaneously debug the application to understand what is happening at the code level. This is a very time-consuming approach and also it is very easy to forget what you learn in a debugging session. Furthermore, there is no real way to share (among the team) what you learn during debugging.

Understanding the down-sides of this approach, I have tried another approach for my most recent project. What I did was to write a kind of API layer that sits on top of the existing code base. This API contained the functionality of pretty much what a user would do in the UI.

To be more specific, let's assume that the existing application is a typical transactional application with orders, items and shopping carts. My API turned  out to something like this:

```<code>public class OrderAPI{
    public Order createOrder(customerName);
    public boolean deleteOrder(orderID);
    public List<Order> getOrdersForCustomer(customerName);
}

public class OrderItemAPI{
    public OrderItem createOrderItem(order);
    public boolean deleteOrder(orderID);
    public List<OrderItem> getItemInOrder(order);
}

public class ShoppingCartAPI {
    public ShoppingCart createCart(customer,order);
    public boolean addItemToCart(cart, item);
    public boolean removeItemFromCart(cart, item);
}
</code>```

The methods in the API correspond to the actions that the user would perform at the UI level. Within these methods, the calls to the existing codebase are made.

Writing this API by itself, of course, doesn't mean much. So, I have written tests (I guess they automatically become integration tests) to ensure that the API works well; proving that I got an understanding of how the legacy code works.

After all this introduction, comes my question: Can you define (possibly in software engineering terms) what I have done? When taking this approach, I have gone completely with my intuition. At some point, I remember being extremely confused; working on the API, then working on my tests, fixing my API, then my tests. I wasn't sure anymore if my main objective was to learn the existing code base or come up with a stable API layer.

I would greatly appreciate any kind of explanation; I am sure that this must be a practice that other people have already experimented with. I just need the right guidance to point me to the appropriate discussions/resources.


问:
How do I handle projects in which my project manager is the same as the client?
I am a freelance worker taking on a new project with a company I'm already familiar with. My boss (the company owner) previously gave me a website project to work at while he also assigns a project manager to review the progress. But with my latest project, the setup here is a little different.

My boss assigned to me this project as well. He's only in the office two days out of a week. After the first meeting with the client, I wondered who was the PM since I wasn't introduced to him/her. When I told my boss that in most cases, I'd rather report to the PM because it's easier and more accessible, that's when he informed me there that my PM is the same person as the client! I was a bit shocked. I didn't want to tell him right out that I find something very wrong with that arrangement, but I'm stuck with this project for now.

So I end up being in direct contact with the client once a week, which is good in a few cases, but am responsible for meeting him for extended periods while my boss only sits in for a few minutes. Especially for a project of a scope which will last for a few months, I feel like I'm doing the job of both a project manager and programmer.

I didn't quote him for the project- the PM/client sent the quote to my boss, and my boss is handling my payouts based on that.** He also controls the schedule for the project. So I'm trying to tread carefully with completing the goals so I don't get short-changed.

My biggest concern, though, is the lack of good communication. The PM/client is not very technically inclined, sometimes states goals that are subtly different from what I perceive, and asks for things that are beyond the means of the tools I'm working with. My boss is better at explaining the situation in a broad sense, but like I said he's not always available, and pretty slow at responding online.

Basically, there's a lack of a dedicated PM and there is sparse communication among me, my boss and the PM/client. How would I track my own progress and ensure better performance, and avoid misinterpreting the tasks for the project? I want to stay on a good pace with the communication I receive without feeling stuck or overwhelmed.

I prefer face to face contact. Everyone else in the office updates their progress by discussing with PMs working in the office on a daily basis, and their projects go more smoothly. My boss isn't interested in having one of them work on this project because he says it'll take a lot of time away from their current work. I want to force in more communication in this project but my boss isn't doing much to help.

[Edit] Well, here's an update. What ended up happening is that our client was demanding other features that turned out to be out of scope, and the CMS that we had to use didn't permit addition of these features so easily. My boss and I struck out some of his demands in the essence of time and budget, and last week the client/PM ended up being dissatisfied and cancelled the project indefinitely.

In the future I will stay away from such arrangements with the client doubling as a PM. I think it gives someone far too much control over the direction of a project.

答:
You should create a list of tasks to be completed for this project and manage it in a project management system such as Redmine. You should then give all necessary parties access to the project management system and have them add/edit tasks as necessary. With this, they can track your progress and ensure that all requirements for the project are listed and completed.

It's not the face-to-face contact you would prefer, but you definitely need to have something written down and able to be tracked. Otherwise, expectations will not be addressed from all sides and your project will likely suffer.


答:
I don't know enough about your project. In addition to other answers already posted, Web services allow data consumers to access data across the internet without knowing how the data is stored or where it is stored or even the format of the storage. The contract between the client and the service is all you need to know.

If you expect that your application will be used by many systems and you don't want to expose either your data model or the logic used to access this data for whatever reason to these other systems and still want them to get some or all of the data, Web Services is a good candidate for that.

Web Services is the core of SOA. SOA allows your system to be easier to integrate and integrate with. For the service consumer, it is always easier to just use the service than to build the mechanisms for it.

Web Services are platform independent.So you could call the service to get the data regardless of the technology of the service. However, both the service consumer and the service must agree on the data exchange format, etc.

"There are currently two schools of thought in developing web services: the traditional, standards-based approach (SOAP) and conceptually simpler and the trendier new kid on the block (REST)." See Rest vs SOAP

Web Services are good choice when you accessing data on different databases since it abstracts the data sources.

Web Services is used by data stores that use NoSQL, such as Amazon SimpleDb and others. Web Services are used by Business Process Modeling tools to create processes from BPM flows.

Web Services and SOA are large subjects in IT today. There are entire books devoted to these subjects.

The site Many Videos has lots of videos on the subject.

Title: When do I need web services?


问:
Is there such a thing as a "when" statement?
Is there a language or language feature that can handle "when" cases? That is, whenever some condition becomes true, in any scope or context, that extra code could be specified to execute?

Note that this is different from a simple if, which must be in a particular scope and explicitly written. This when clause would almost be like an if that applied to every case in the execution of the program after it.

答:
What you are asking for is called Reactive Programming.

It is a paradigm of programming where the variables are aware of the expression they've been assigned and whenever a component of the expression changes, the variable reacts by re-evaluating the expression, possibly triggering other similar re-evaluatoins down the chain of dependencies.

Usually this reactive behavior is achieved through clever use of observer pattern, where a reactive value registers itself as a listener to a set of events that trigger the re-evaluation of the value.

To the best of my knowledge, there does not exist a programming language that would entirely embrace reactive programming in it's core, but there are plenty of libraries in many languages offering benefits of reactive programming in one way or another.

Most of the data binding frameworks can be considered implementations  of reactive programming.

There is a nice paper on called "Deprecating the observer pattern", that will probably explain much better than I ever could, what the reactive programming is all about and what would an implementation of it offer over and above already existing techniques.


问:
How much does your company spends on books?
It seems to me that buying and reading books is one of the most important investments a developer can make, and one of the most important investment a company can spend on a developer. There were a lot of times when I was confronted with a tricky problem, and what I did was to flip through an algorithm book and I would stumble upon an answer. And there were a lot of times when I tackled a problem head-on without first doing a literature search, only to find out later that my solution sucked and a proper solution had already been written down elsewhere.

But it also seems to me that a lot of companies view books as an expense and thus must be cut down and "budgeted". Sad, but true.

How much your company spends on books?

答:
For the two startups I worked for recently (one of them funded by Sequoia), the feel is that the CEO and/or managers want us to buy ZERO books.

When I first got hired, the CEO knew I didn't know PHP at that time (I knew C, Java, Python, and Ruby), and I asked him what might be good books to read up on PHP when I first started, and he mentioned, "what is it... [pause for a few seconds] it is http://www.php.net"   At the same time, when he tried to persuade people to join our company, on the phone, he will say, "We are funded by Sequoia; we are given unlimited amount of money to succeed."  But none of the developers I knew at the company buy any book and/or expense it to the company.  So I bought close to 20 books that year, on PHP, CSS, Javascript, Prototype.js, jQuery, all out of my own pocket.

At the same time, the CEO will talk about working long hours, having us work from Monday to Friday and come back on Sunday for a "strategy meeting", and give us free $5 food for lunch so that we can work at the desk for extra 45 minutes and not walk outside the building for sunshine, for fresh air, or for a little exercise (our wage was probably about $45 to $75 per hour), and give us free $7 dinners two days out of the week at 8pm, so we would all stay till 8pm and would feel embarrassed to "eat and leave" and so after eating, put in 30 to 45 minutes or more for the company.

And all that, with the other founder, the CTO addicted to the Transformer, and a plastic truck that can transform to a robot, and all the plastic shooting he likes even when we are fixing bugs to release in the next 2 hours, hiring college buddy as the database guy (and storing all the millions of users' passwords in plain text in the DB), the girlfriend as the senior program manager, the girlfriend's brother as head of tech support when he had no tech support experience, and so that they can all be the "royalties" and have an attitude and look down on us, with all that, the allowed money to buy books for us, was zero.


答:
Where it's possible for the developers to write unit tests, during them development stages, I would definitely agree with P.Brian.Mackey's advice to use Test Driven Development.

However, we've recently also got a lot of value from having users write down what they would do to test the system before development even starts: these are known as User Acceptance Tests.

Each UAT starts off as a short bulleted list, describing what the user does, and saying what will happen. They'll also record things like where to find sample input files.

As the functionality is implemented, the UAT gets fleshed out with more detail, so they are a sort of "living document". For this reason, we've ended up storing them on simple internal wiki pages, rather than any document management system.

These have turned out to be valuable in a surprisingly wide range of situations:

They tell the developers exactly what the expected behaviour is, before writing the code

This saves time being spent on implementing incorrect functionality, only to be told that "no, that wasn't what was wanted - please fix it"

They serve as a kind of instruction manual during development:

for real users, to allow software to be tried out during the development stage

for developers who are new to a project

They prompt all sorts of useful questions about the what's required, before work even starts - allowing us to work out what decisions we need to make, before development starts

They give developers a better understanding of the chunk of work, earlier on - this making it much easier to estimate roughly time will be required for each stage.

And of course, they make it easier for the system to be tested, as well.

Title: How to decrease errors before testing?


答:
First of all, good question. I admire your focus on utility rather than blindly accepting "best practices". +1 for that.

I've read that guide before. You have to remember something about it - it is just a guide, mainly for C# newcomers who know how to program but aren't so familiar with the C# way of doing things. It's not so much as a page of rules as it is a page that describes how things are already usually done. And since they're already done this way everywhere, it might be a good idea to stay consistent.

I'll get to the point, answering your questions.

First of all, I assume you already know what an interface is.
As for a delegate, it's enough to say that it's a structure containing a typed pointer to a method, along with an optional pointer to the object representing the this argument for that method. In case of static methods, the latter pointer is null.

There are also Multicast delegates, which are just like delegates, but may have several of these structures assigned to them (meaning a single call to Invoke on a multicast delegate invokes all of the methods in its assigned invocation list).

What do they mean by an eventing design pattern?

They mean using events in C# (which has special keywords for sophistically implementing this extremely useful pattern). Events in C# are fueled by multicast delegates.

When you define an event, such as in this example:

```<code>class MyClass {
  // Note: EventHandler is just a multicast delegate,
  // that returns void and accepts (object sender, EventArgs e)!
  public event EventHandler MyEvent;

  public void DoSomethingThatTriggersMyEvent() {
    // ... some code
    var handler = MyEvent;
    if (handler != null)
      handler(this, EventArgs.Empty);
    // ... some other code
  }
}
</code>```

The compiler actually transforms this into the following code:

```<code>class MyClass {
  private EventHandler MyEvent = null;

  public void add_MyEvent(EventHandler value) {
    MyEvent += value;
  }

  public void remove_MyEvent(EventHandler value) {
    MyEvent -= value;
  }

  public void DoSomethingThatTriggersMyEvent() {
    // ... some code
    var handler = MyEvent;
    if (handler != null)
      handler(this, EventArgs.Empty);
    // ... some other code
  }
}
</code>```

You then subscribe to an event by doing

```<code>MyClass instance = new MyClass();
instance.MyEvent += SomeMethodInMyClass;
</code>```

Which compiles down to

```<code>MyClass instance = new MyClass();
instance.add_MyEvent(new EventHandler(SomeMethodInMyClass));
</code>```

So that's eventing in C# (or .NET in general).

How the composition turns out to be easy if a delegate is used?

This may easily be demonstrated:

Suppose you have a class that depends on a set of actions to be passed to it. You could encapsulate those actions in an interface:

```<code>interface RequiredMethods {
  void DoX();
  int DoY();
};
</code>```

And anyone who wanted to pass actions to your class would first have to implement that interface. Or you could make their lives easier by depending on the following class:

```<code>sealed class RequiredMethods {
  public Action DoX;
  public Func<int> DoY();
}
</code>```

This way the callers only have to create an instance of RequiredMethods and bind methods to the delegates at runtime. This is usually easier.

This way of doing things is extremely beneficial under the right circumstances. Think about it - why depend on an interface when all you really care about is having an implementation passed to you?

Benefits of using interfaces when there are a group of related methods

It's beneficial to use interfaces because interfaces normally require explicit compile-time implementations. This means that you create a new class.

And if you have a group of related methods in a single package, it's beneficial to have that package be reusable by other parts of the code. So if they can simply instantiate a class instead of building a set of delegates, it's easier.

Benefits of using interfaces if a class only needs one implementation

As noted earlier, interfaces are implemented in compile time -- which means they are more efficient than invoking a delegate (which is a level of indirection per se).

"One implementation" might mean an implementation that exists a single well-defined place.

Otherwise an implementation might come from anywhere in the program which just happens to conform to the method signature. That allows for more flexibility, because methods need only to conform to the expected signature, rather than belong in a class that explicitly implements a specific interface. But that flexibility might come at a cost, and actually breaks the Liskov Substitution principle, because most times you want explicitness, because it minimizes the chance for accidents. Just like Static Typing.

The term might also refer to multicast delegates here. Methods declared by interfaces can only be implemented once in an implementing class. But delegates can accumulate multiple methods, which will be called sequentially.

So all in all, it looks like the guide is not informative enough, and merely functions as what it is - a guide, not a rulebook. Some advice might actually sound a bit contradictive. It's up to you to decide when it's right to apply what. The guide seems to only give us a general path.

I hope your questions have been answered to your satisfaction. And again, kudos for the question.

Title: Delegate vs Interfaces-Any more clarifications available?

Body:
After reading the article-
When to Use Delegates Instead of Interfaces (C# Programming Guide),
I need some help  understanding the below given points, which I found to be not so clear (for me).
Any examples or detailed explanations available for these?

Use a delegate when:

An eventing design pattern is used.

It is desirable to encapsulate a static method.

Easy composition is desired.

A class may need more than one implementation of the method.

Use an interface when:

There are a group of related methods that may be called.

A class only needs one implementation of the method.

My Questions are,

What do they mean by an eventing design pattern?

How the composition turns out to be easy if a delegate is used?

if there is a group of related methods that may be called,then use interface-What benefit it has?

if a class only needs one implementation of the method,  use interface-how is it justified in terms of benefits?

Body:
First of all, good question. I admire your focus on utility rather than blindly accepting "best practices". +1 for that.

I've read that guide before. You have to remember something about it - it is just a guide, mainly for C# newcomers who know how to program but aren't so familiar with the C# way of doing things. It's not so much as a page of rules as it is a page that describes how things are already usually done. And since they're already done this way everywhere, it might be a good idea to stay consistent.

I'll get to the point, answering your questions.

First of all, I assume you already know what an interface is.
As for a delegate, it's enough to say that it's a structure containing a typed pointer to a method, along with an optional pointer to the object representing the this argument for that method. In case of static methods, the latter pointer is null.

There are also Multicast delegates, which are just like delegates, but may have several of these structures assigned to them (meaning a single call to Invoke on a multicast delegate invokes all of the methods in its assigned invocation list).

What do they mean by an eventing design pattern?

They mean using events in C# (which has special keywords for sophistically implementing this extremely useful pattern). Events in C# are fueled by multicast delegates.

When you define an event, such as in this example:

class MyClass {
  // Note: EventHandler is just a multicast delegate,
  // that returns void and accepts (object sender, EventArgs e)!
  public event EventHandler MyEvent;

  public void DoSomethingThatTriggersMyEvent() {
    // ... some code
    var handler = MyEvent;
    if (handler != null)
      handler(this, EventArgs.Empty);
    // ... some other code
  }
}

The compiler actually transforms this into the following code:

class MyClass {
  private EventHandler MyEvent = null;

  public void add_MyEvent(EventHandler value) {
    MyEvent += value;
  }

  public void remove_MyEvent(EventHandler value) {
    MyEvent -= value;
  }

  public void DoSomethingThatTriggersMyEvent() {
    // ... some code
    var handler = MyEvent;
    if (handler != null)
      handler(this, EventArgs.Empty);
    // ... some other code
  }
}

You then subscribe to an event by doing

MyClass instance = new MyClass();
instance.MyEvent += SomeMethodInMyClass;

Which compiles down to

MyClass instance = new MyClass();
instance.add_MyEvent(new EventHandler(SomeMethodInMyClass));

So that's eventing in C# (or .NET in general).

How the composition turns out to be easy if a delegate is used?

This may easily be demonstrated:

Suppose you have a class that depends on a set of actions to be passed to it. You could encapsulate those actions in an interface:

interface RequiredMethods {
  void DoX();
  int DoY();
};

And anyone who wanted to pass actions to your class would first have to implement that interface. Or you could make their lives easier by depending on the following class:

sealed class RequiredMethods {
  public Action DoX;
  public Func<int> DoY();
}

This way the callers only have to create an instance of RequiredMethods and bind methods to the delegates at runtime. This is usually easier.

This way of doing things is extremely beneficial under the right circumstances. Think about it - why depend on an interface when all you really care about is having an implementation passed to you?

Benefits of using interfaces when there are a group of related methods

It's beneficial to use interfaces because interfaces normally require explicit compile-time implementations. This means that you create a new class.

And if you have a group of related methods in a single package, it's beneficial to have that package be reusable by other parts of the code. So if they can simply instantiate a class instead of building a set of delegates, it's easier.

Benefits of using interfaces if a class only needs one implementation

As noted earlier, interfaces are implemented in compile time -- which means they are more efficient than invoking a delegate (which is a level of indirection per se).

"One implementation" might mean an implementation that exists a single well-defined place.

Otherwise an implementation might come from anywhere in the program which just happens to conform to the method signature. That allows for more flexibility, because methods need only to conform to the expected signature, rather than belong in a class that explicitly implements a specific interface. But that flexibility might come at a cost, and actually breaks the Liskov Substitution principle, because most times you want explicitness, because it minimizes the chance for accidents. Just like Static Typing.

The term might also refer to multicast delegates here. Methods declared by interfaces can only be implemented once in an implementing class. But delegates can accumulate multiple methods, which will be called sequentially.

So all in all, it looks like the guide is not informative enough, and merely functions as what it is - a guide, not a rulebook. Some advice might actually sound a bit contradictive. It's up to you to decide when it's right to apply what. The guide seems to only give us a general path.

I hope your questions have been answered to your satisfaction. And again, kudos for the question.


问:
Should we use Entity Framework?
We currently have the following stack :

VS 2005

Web forms

SQL Server 2005

IIS 6

We are planning on transitioning to this :

VS 2010

MVC and Web Forms

SQL Server 2008

IIS 7

My question is, when we move to MVC with VS 2010, should we use Entity Framework( or another ORM), a micro ORM (like Massive), or just plain SQL?

All the tutorials I've read about VS 2010 are all geared towards using Entity Framework for data transactions, but is that going to be around for the foreseeable future (5+ years)?

If it matters, our client's applications can have anywhere from 10 - 1,000 active users.

答:
Another potential solution is to use an alternative Entity Framework Library that is not the one supplied with V.S. There are a few out there on the web.

The Entity / 3 layers framework concept, has been out there for a while, and have work with several custom libraries, like many other developers, before Microsoft released its own "official" framework.

Pros

Have the benefits of the Entity (D.A.L.) framework, without been stuck with Microsoft constant libraries / framework changes.

Adding features to a library that are maybe not available to the existing official library, like using several dtabase brands.

Cons

Have to support the library or tools. Its very common to have a Entity generator code tool to generate the enitites.

Title: Should we use Entity Framework?


问:
What's the advange of JRuby (or any other language ported to JVM)? Why would one use it?
Let's say I really like Ruby and I know Java. What's the deal behind these J* and Iron* languages that allow you to use the syntax of a foreign language to compile them into JVM or .NET bytecode?

Basically, what's the advantage? Is it just because you like the runtime of one language, but not the syntax?

Please advise!

答:
It moves the burden of maintaining a lot of native platforms away from the language to the JVM.  This makes it easier for the language maintainers to handle multiple platforms plus provide excellent performance for the dull, boring tasks of e.g. writing a good garbage collection etc.

The herculean amount of work to provide a good underlying infrastructure is usually not easily seen from the "outside" but it is quite big.

Also the JVM essentially mean that new platforms are almost free to port to.  In my job we run Java code on a non-mainstream IBM platform - any well written Java program runs out of the box.


答:
The point is, once you get one language to properly run on a given platform and interface with it, you can basically leverage all existent libraries for that platform (with little to no effort depending on the platform).

Much like having Ruby call down to C libraries, you can have JRuby call down to Java libraries. And you might prefer that, for a number of reasons:

Java enforces memory safety. So when calling down to Java instead of C, there's less reason for concern

Whatever tool/library you want to use is only (or best) implemented for Java.

You want to extend an existing Java based system with a language as Ruby.

You just like Java.

In short, the Java platform is a huge and rich ecosystem. And being able to leverage it with one of many popular languages instead of being tied to Java is both good for the platform and the communities of other languages.

Your choice of language and platform no longer really depend on each other. That means you won't have to write in a language you don't like to leverage a badly needed platform feature, or that you won't lock yourself out of some platform just by your language choice.

Please note, the above of course applies to .NET, although the Iron-stuff doesn't really seem to have taken off yet as far as I can tell. But given there's F# and Nemerle and the fact that C# also allows for terser programming than Java (with Linq for example) and that despite Mono the .NET eco-system has strong ties to Windows, who knows if it ever will.

Title: What's the advange of JRuby (or any other language ported to JVM)? Why would one use it?

Body:
Let's say I really like Ruby and I know Java. What's the deal behind these J* and Iron* languages that allow you to use the syntax of a foreign language to compile them into JVM or .NET bytecode?

Basically, what's the advantage? Is it just because you like the runtime of one language, but not the syntax?

Please advise!


问:
What are the available tools for creating cross-platform, cross-browser multiplayer online commercial games?
HTML5+Javascript is not viable as the client-side code will be visible and, thus, stealable. Flash is not viable since it's not supported on ipads and thus not cross-platform. Said that, what are the available tools for creating cross-platform, cross-browser multiplayer online commercial games?</p>

答:
HTML5 and Javascript is the only option if you must have your game playable in a browser, and be 100% cross platform such that it'll work on otherwise closed platforms like the iPad (in the iPad browser).  There's ways to obfuscate the client side code so that it isn't easy to steal, and there's other tricks that can be used to prevent outright theft.  As a side note, Flash is just as easy to steal as obfuscated Javascript, so if you're really that worried, then that option is out.

One option is Unity3d, given that there's a way to compile for iOS, and since Unity works in the browser, it only requires a plugin.  I do believe support is limited/non-existent in Linux, though, so depending on how cross platform you want, that could be a problem.  Unity also compiles for Android, though being able to do all of this will cost money.


答:
HTML5 and Javascript is the only viable tool to create a truly cross-platform game. To ensure it cannot be stolen, ensure the gameplay relies on your service - something that would be difficult to replicate.

For example, many multi-player online games currently out there now may have a client that you can download. Some people create private servers for them. But the original creators provide a service (the main server/s) where the majority of players are on. The creators remain a viable business even though the client may have been taken by other people.

Your business proposition shouldn't rely on the client never being taken or copied by other parties. Instead, ensure your service remains attractive for players to stay on.

Title: What are the available tools for creating cross-platform, cross-browser multiplayer online commercial games?

Body: HTML5+Javascript is not viable as the client-side code will be visible and, thus, stealable. Flash is not viable since it's not supported on ipads and thus not cross-platform. Said that, what are the available tools for creating cross-platform, cross-browser multiplayer online commercial games?</p>