问:
Building a strong robust client-server system
I need some help with regards to implement a pre-designed system that has 4 components and several constraints. I've spent approximately 50 hours trying to determine the best way to build this system; however, I do not think I have a strong enough solution as of right now.

~~~ The Background Information ~~~

The purpose of this project is to allows for business owners (and their developers) to access data remotely.
It has 4 components.

A Web Service

A Client

A Database For the webservice

A Database For the Client

The user interface must be in the form of a web service as it is one of the design requirements.

The Client is stored on a business owners computer (Which houses their database). It is a local program programmed in the .net platform.

Business owners access the web service which then accesses a client, requests for data and passes that data to the client.

The above is known and unchangeable (as I am not the person who makes the project specification)

~~~ The Real Problem ~~~

The problem is, The Client may not necessarily be at the same place every time, the IP of the client is subject to change. The Client may also simply not be online at the time of the request from the business owner.

~~~ My Present Solution ~~~

My Present solution to this problem is to create a TCP/IP Server on the Client. When the Client is turned on or started, it can "register" its TCP/IP Server credentials (the information needed to contact it) into the server along with some identification information.

~~~Editted for clarity~~~
When the Web Service gets a request, it can open a random TCP/IP connection and let the client  (Remember the TCP/IP Server is on the Client) know it has a request for data. The Client can then get the request, process it and send a response with a 'request Id'.

Based on this request Id, the web service can receive a call, let the client know it has a request, the client can go query the web service for the request, retrieve the request, process the request and send a response back to the web service which can then process the response (extract the request Id from it) and send it back to the appropriate web service caller.

~~~ End Edit ~~~ (wow that sentence is a mouthful to read out loud)

~~~ What I Would Like ~~~

I feel my solution is sketchy and I would really like some feedback as to potential pitfalls that I may not see and better ways of approaching it.

答:
I may be all wet here, but it sounds like the crux of the problem is that you need to initiate a communication from the server to the client.

Your proposed solution (that you are uncomfortable with) is to install a web server on the client machine (the laptop, in my comments) and register the IP address of it with your main server.

Having 2 or more web servers talk to each other on a peer relationship is pretty common and seems to work well.  The issue lies in whether or not you're comfortable with any/all infrastructure needed to get that 2nd web server installed and running reliably, and whether or not you'd have firewall issues (many companies block inbound HTTP requests).

A couple other ideas come to mind:

Simple polling.  Have your client poll the main server periodically.  Not an ideal solution (you may have thousands of poll requests per successful 'hit'), but it could work.  the poll request / 'no' reply could be pretty cheap to implement and should scale well.

Long polling - your client requests some data from the server.  If the server has the data, it returns it.  If it doesn't have it, it either blocks or sends little "keep alive" messages back to the client.

There's a good write up in this SO question

See also the Wikipedia entry on Long polling

You didn't mention any scaling issues - how many clients you expect, how quickly they must respond, how often they'll initiate requests, etc.  Those answers will probably dictate which approach is appropriate.


问:
What is a "task pool"?
I have searched for many websites for a definition of "task pool", but most descriptions are very vague. Anywhere I can find a precise definition of it?

More details.

Are dependencies allowed in task pool?

Can a running task exchange data with other running tasks?

To phrase conversely, are tasks permitted to accept data only prior to start and permitted to publish results only after the task has finished?

What keeps track of the temporary resources (memory, CPU etc) that are used by tasks?

How to define weights that will encourage efficient task assignment?

For example, if one task needs to pass a lot of data to the next task, it may make sense to run the next task immediately following the first task, and as close to the first thread / CPU / machine / cluster (locality) as possible

What about tasks that are not known (do not exist) in the beginning, but were "created" later?

答:
In general, I'd say that a task pool should be made in a way that

all tasks can be executed concurrently, given enough resources (with synchronization on shared resources when necessary)

all tasks can be executed serially, in any arbitrary order

any level of concurrence between 1. and 2. is possible

all possible orders and concurrence levels produce valid results (not necessarily the same)

Given that definition,

Are dependencies allowed in task pool?

Too vague. If you mean tasks depending on other tasks, I'd say no. A system with such dependencies is a rather a queue than a pool.

Can a running task exchange data with other running tasks?

It should not. You cannot rely on another task running at the same time.

To phrase conversely, are tasks permitted to accept data only prior to start and permitted to publish results only after the task has finished?

Not necessarily. Unchanged data (i.e. from an immutable database) can be accessed later. Output can be written at any time, as long as no other tasks depends on it.

What keeps track of the temporary resources (memory, CPU etc) that are used by tasks?

The framework? At least, not the tasks.

How to define weights that will encourage efficient task assignment?
  For example, if one task needs to pass a lot of data to the next task, it may make sense to run the next task immediately following the first task, and as close to the first thread / CPU / machine / cluster (locality) as possible

IMO when such a dependency exists, there should be one task that does both, instead of two tasks

What about tasks that are not known (do not exist) in the beginning, but were "created" later?

Tasks can create new tasks. Those can be executed at any time after creation, possibly concurrently with the task that created them.

ContentLicense: CC BY-SA 2.5

Title: What is a "task pool"?


问:
What is the difference between state and field?
Is state another name for field or is it something different?

For example:

```<code>private int telNumber;
</code>```

can I say about telNumber that it is a state or it is a field?

答:
Let's say I have the following class:

```<code>public class Foo
{
    private int _bar;
    private string _baz;

    public Foo(int bar, string baz)
    {
        _bar = bar;
        _baz = baz;
    }

    public void ChangeBar(int newBar)
    {
        _bar = newBar;
    }
}
</code>```

I can create an instance of the class like this:

```<code>var myFoo = new Foo(3, "Qux");
</code>```

The values for _bar and _baz collectively form myFoo's state.

If I change _bar, like this:

```<code>myFoo.ChangeBar(6);
</code>```

That means that the state of myFoo has changed, because one or more of the fields has changed.

ContentLicense: CC BY-SA 3.0

Body:
Let's say I have the following class:

public class Foo
{
    private int _bar;
    private string _baz;

    public Foo(int bar, string baz)
    {
        _bar = bar;
        _baz = baz;
    }

    public void ChangeBar(int newBar)
    {
        _bar = newBar;
    }
}

I can create an instance of the class like this:

var myFoo = new Foo(3, "Qux");

The values for _bar and _baz collectively form myFoo's state.

If I change _bar, like this:

myFoo.ChangeBar(6);

That means that the state of myFoo has changed, because one or more of the fields has changed.


答:
In layman's words:

No. State is not another name for a field.

The state of an object is the combination of the values of all its fields.

If any field gets changed, it is said that the object's state (as a whole) has changed.

Title: What is the difference between state and field?

Body:
Is state another name for field or is it something different?

For example:

```<code>private int telNumber;
</code>```

can I say about telNumber that it is a state or it is a field?


问:
Mastering a programming language by not programming?
The computer scientist Peter Norvig argued in his essay Teach Yourself To Program in 10 Years that you need about 10,000 hours of practice.

But Jeff Atwood argued in his post How To Become a Better Programmer by Not Programming that he believes the only way to become a better programmer is by not programming.

These articles are in opposition. Is there a scientific evidence to prove the Jeff Atwood approach?

答:
You're missing the point.

Jeff Atwood is saying that being an excellent programmer requires more than just coding skills.  It also requires being a good designer, working well with other people, and in general becoming a better thinker and problem solver.

The greatest missing skill is somebody who's both good at understanding the engineering and who has good relationships with the hard-core engineers, and bridges that to working with the customers.

-- Bill Gates

Peter Norvig's point is that you can't just pick up a copy of "Become a Master Programmer in 24 Hours" and expect that to work.  But that's exactly how many folks who ask questions at Stack Overflow seem to approach programming.  They think they can load up Eclipse, learn a few keywords, and write the next Angry Birds.  It takes a little more than that.


问:
Architecturally speaking, does a database abstraction layer, such as Microsoft's Entity Framework, void the need for a separate Data Access Layer?

The way it was

For years, I have organized my software solutions as such:

Data Access Layer (DAL) to abstract the business of accessing data

Business Logic Layer (BLL) to apply business rules to data sets, handle authentication, etc.

Utilities (Util) which is just a library of common utility methods I have built over time.

Presentation Layer which could of course be web, desktop, mobile, whatever.

The way it is now

For the past four years or so I have been using Microsoft's Entity Framework (I am predominately a .NET dev) and I am finding that having the DAL is becoming more cumbersome than clean on account of the fact that the Entity Framework has already done the job that my DAL used to do: it abstracts the business of running CRUDs against a database.

So, I typically end up with a DAL that has a collection of methods like this one:

```<code>public static IQueryable<SomeObject> GetObjects(){
    var db = new myDatabaseContext();
    return db.SomeObjectTable;
}
</code>```

Then, in the BLL, this method is used as such:

```<code>public static List<SomeObject> GetMyObjects(int myId){
    return DAL.GetObjects.Where(ob => op.accountId == myId).ToList();
}
</code>```

This is a simple example of course as the BLL would typically have several more lines of logic applied, but it just seems a bit excessive to maintain a DAL for such a limited scope.

Wouldn't it be better to just abandon the DAL and simply write my BLL methods as such:

```<code>public static List<SomeObject> GetMyObjects(int myId){
    var db = new myDatabaseContext();
    return db.SomeObjectTable.Where(ob => op.accountId == myId).ToList();
}
</code>```

I am considering dropping the DAL from future projects for the reasons stated above but, before doing so, I wanted to poll the community here for your hindsight/foresight/opinions before I get down the road on a project and discover a problem I didn't anticipate.

Any thoughts are appreciated.

Update

The consensus seems to be that a separate DAL isn't necessary but (making my own inference here) is a good idea to avoid vendor lock in.  For example, if I have a DAL that is abstracting EF calls as illustrated above, if I ever switch to some other vendor I don't need to rewrite my BLL.  Only those basic queries in the DAL would need to be rewritten.  Having said that, I am finding it tough to envision a scenario in which this would happen.  I can already make an EF model of an Oracle db, MSSQL is a given, I am pretty sure that MySql is possible as well (??) so I am not sure if the extra code would ever grant a worthwhile ROI.

答:
I view the EF and DAL as separate components in an Enterprise system. The Data Access Layer is an abstraction that other services use to perform data persistence and management. Typically Entity Frameworks build a nice API around querying, updating, deleting and inserting however at the core they still require a direct connection to the back-end data source. So any type of routing or firewalls will stop the EF from working, thus requiring you to create a EF mediation component.

Here is a high-level example showing where DAL and EF fit in:

```<code>-------------    -------                                    ----------------    ------
| Service A | -> | DAL | -> { LOCAL / LAN / WAN ACCESS } -> | DAL BACK-END | -> | EF |
-------------    -------                                    ----------------    ------
</code>```

It has been my experience that a better design is to never allow the business logic or service implementations direct access to the EF layer. Instead, to provide an abstraction for working with all the persistent data which allows you to ship requests over the wire or perform them locally.

This design introduces some leaky abstractions though. So it should be considered on a case by case basis.

Some questions to ask:

Will all the components accessing your data be able to obtain a Connection to the back-end data store?

Does your EF allow you to aggregate data sets across different types of data stores? For example using a SQL database with MongoDB for documents.

Body:
I view the EF and DAL as separate components in an Enterprise system. The Data Access Layer is an abstraction that other services use to perform data persistence and management. Typically Entity Frameworks build a nice API around querying, updating, deleting and inserting however at the core they still require a direct connection to the back-end data source. So any type of routing or firewalls will stop the EF from working, thus requiring you to create a EF mediation component.

Here is a high-level example showing where DAL and EF fit in:

-------------    -------                                    ----------------    ------
| Service A | -> | DAL | -> { LOCAL / LAN / WAN ACCESS } -> | DAL BACK-END | -> | EF |
-------------    -------                                    ----------------    ------

It has been my experience that a better design is to never allow the business logic or service implementations direct access to the EF layer. Instead, to provide an abstraction for working with all the persistent data which allows you to ship requests over the wire or perform them locally.

This design introduces some leaky abstractions though. So it should be considered on a case by case basis.

Some questions to ask:

Will all the components accessing your data be able to obtain a Connection to the back-end data store?

Does your EF allow you to aggregate data sets across different types of data stores? For example using a SQL database with MongoDB for documents.


答:
Not sure if this is the answer you're looking for.. but here goes.

We do it to keep things separated/organised. Yes, EF/NHibernate are data access.. but we limit its use to its own assembly with a generic repository setup. This assembly also contains all of our NHibernate mappings, Session factory, code for handling multiple databases, etc.

We still refer to it as the "Data Access Layer", because the entire assembly exists to support our ORM.

I should probably note that our main app references 5 databases, has roughly 4-500 domain objects/mappings and various schemas. So, this setup makes sense for us. Perhaps for a smaller app you would skip this assembly but.. I am a sucker for organised code and would probably do it anyway :)

Title: Architecturally speaking, does a database abstraction layer, such as Microsoft's Entity Framework, void the need for a separate Data Access Layer?

Body:
The way it was

For years, I have organized my software solutions as such:

Data Access Layer (DAL) to abstract the business of accessing data

Business Logic Layer (BLL) to apply business rules to data sets, handle authentication, etc.

Utilities (Util) which is just a library of common utility methods I have built over time.

Presentation Layer which could of course be web, desktop, mobile, whatever.

The way it is now

For the past four years or so I have been using Microsoft's Entity Framework (I am predominately a .NET dev) and I am finding that having the DAL is becoming more cumbersome than clean on account of the fact that the Entity Framework has already done the job that my DAL used to do: it abstracts the business of running CRUDs against a database.

So, I typically end up with a DAL that has a collection of methods like this one:

```<code>public static IQueryable<SomeObject> GetObjects(){
    var db = new myDatabaseContext();
    return db.SomeObjectTable;
}
</code>```

Then, in the BLL, this method is used as such:

```<code>public static List<SomeObject> GetMyObjects(int myId){
    return DAL.GetObjects.Where(ob => op.accountId == myId).ToList();
}
</code>```

This is a simple example of course as the BLL would typically have several more lines of logic applied, but it just seems a bit excessive to maintain a DAL for such a limited scope.

Wouldn't it be better to just abandon the DAL and simply write my BLL methods as such:

```<code>public static List<SomeObject> GetMyObjects(int myId){
    var db = new myDatabaseContext();
    return db.SomeObjectTable.Where(ob => op.accountId == myId).ToList();
}
</code>```

I am considering dropping the DAL from future projects for the reasons stated above but, before doing so, I wanted to poll the community here for your hindsight/foresight/opinions before I get down the road on a project and discover a problem I didn't anticipate.

Any thoughts are appreciated.

Update

The consensus seems to be that a separate DAL isn't necessary but (making my own inference here) is a good idea to avoid vendor lock in.  For example, if I have a DAL that is abstracting EF calls as illustrated above, if I ever switch to some other vendor I don't need to rewrite my BLL.  Only those basic queries in the DAL would need to be rewritten.  Having said that, I am finding it tough to envision a scenario in which this would happen.  I can already make an EF model of an Oracle db, MSSQL is a given, I am pretty sure that MySql is possible as well (??) so I am not sure if the extra code would ever grant a worthwhile ROI.


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答: Changing my syntax highlighting colors to match the ones used in the version control system.</p>


答:
The "Not Programming" part should come after a good deal of programming practice.

```<code>the only way to become a better programmer is by not programming
</code>```

You have to be a programmer first before you can become a better one. The first programming language learning barrier will take up a great deal of effort alone and the problem-solving part will be trivial compared to problems you will have to face later on.

UPDATE:

As suggested in the comments, you can still benefit from "not programming aka: (thinking)" when first starting out as a programmer but I would not step away from the keyboard just because someone says I should be doing that to get better, rather you should do it because you know you need to think about it more.

Title: Mastering a programming language by not programming?

Body:
The computer scientist Peter Norvig argued in his essay Teach Yourself To Program in 10 Years that you need about 10,000 hours of practice.

But Jeff Atwood argued in his post How To Become a Better Programmer by Not Programming that he believes the only way to become a better programmer is by not programming.

These articles are in opposition. Is there a scientific evidence to prove the Jeff Atwood approach?

Body:
The "Not Programming" part should come after a good deal of programming practice.

the only way to become a better programmer is by not programming

You have to be a programmer first before you can become a better one. The first programming language learning barrier will take up a great deal of effort alone and the problem-solving part will be trivial compared to problems you will have to face later on.

UPDATE:

As suggested in the comments, you can still benefit from "not programming aka: (thinking)" when first starting out as a programmer but I would not step away from the keyboard just because someone says I should be doing that to get better, rather you should do it because you know you need to think about it more.


问:
How can I use icons under a CC-ND license?
I am developing an open-source Java desktop application and I would like to use some icons in the GUI to indicate various settings, external links, etc. I found a set of free icons that are published under the Creative Commons Attribution-NoDerivs 3.0 Unported license that I would like to use.

My questions are:

Would including such an icon in my application constitute an adaptation or derivative work, and as such be a violation of the license?

The icons are a little too big for my use case. Am I allowed to include scaled-down versions in my application? And would there be a difference between scaling them in photoshop and including these modified images versus including the original images and scaling them down programmatically?

I would like to release my program under the Apache License 2.0. Does this have an effect on whether I can include the icons or not? Would I need to take any extra steps, other than including the original copyright and license information for the icons in my NOTICE file?

Edit:

An ArsTechnica article titled "Creative Commons images and you: a quick guide for image users" states that

More subtle alterations, like cropping an image to make it fit your page width, might seem to be a gray area, but as long as you don't make enough changes so that your version, when taken as a whole, qualifies as an original, copyrightable work in its own right, then you should be safe.

So the second question essentially becomes:

Does a scaled down version of an icon qualify for copyright in its own right?

And if the answer is "no", then it is not considered an Adaptation and therefore not prohibited under the terms of the license.

答:
Most of these questions can only be answered with confidence by a lawyer. I am not one, but I will try to give some insights.

Creating scaled versions of the icons is probably fine. Copyright is awarded for the expression of creativity and it doesn't take any creativity to scale an image. Other transformations, even scaling the width and height differently, are more problematic, because it does take creativity to decide if the result looks good.

The Apache license does not affect anything except the code you explicitly license with it. You need to give the proper attribution and license information for the icons you include, but the Apache license does not impose any additional requirements or problems here.

Distributing the software and the icons in one package is not likely a problem, but to be sure you could contact the copyright holder of the icons to ask if they consider distribution with an application to be the creation of a derived work. If they do, consider distributing it as two packages.


问:
Hashing Algorithm: Deleting an element in linear probing
While using Linear probing method to implement hashing, when we delete and element, the position of the deleted element is declared as a tombstone/ mark it as deleted. Why can't we just shift all the elements from the current position until the next empty element is encountered? Won't this save the time when too many tombstones are encountered later and a rehashing might be required? Am I missing something? Please tell me if I need to clarify my question.

Thanks a lot!

答:
Best explained by counter example:

```<code>HASH(A) = 10
HASH(B) = 10
HASH(C) = 12

myHash.insert(A); // A goes to slot 10

              10   11   12
            +----+----+----+
            | A  |    |    |
            +----+----+----+

myHash.insert(B); // B goes to slot 10, but that is taken, so it sees 11 is empty and inserts there

              10   11   12
            +----+----+----+
            | A  | B  |    |
            +----+----+----+

myHash.insert(C); // C hashes to slot 12 and gets put there

              10   11   12
            +----+----+----+
            | A  | B  | C  |
            +----+----+----+

myHash.remove(B); // We remove B, and shift the ones after it back

              10   11   12
            +----+----+----+
            | A  | C  |    |
            +----+----+----+

myHash.contains(C) == false; // C hashes to slot 12, but there is nothing there.  So therefore the hash does not contain C (but it does CONTRADICTION).
</code>```

Therefore, by proof of contradiction, simply sliding the succeeding elements upon removal will result in incorrectness.

EDIT: C should have said that it hashes to 12

Body:
Best explained by counter example:

HASH(A) = 10
HASH(B) = 10
HASH(C) = 12

myHash.insert(A); // A goes to slot 10

              10   11   12
            +----+----+----+
            | A  |    |    |
            +----+----+----+

myHash.insert(B); // B goes to slot 10, but that is taken, so it sees 11 is empty and inserts there

              10   11   12
            +----+----+----+
            | A  | B  |    |
            +----+----+----+

myHash.insert(C); // C hashes to slot 12 and gets put there

              10   11   12
            +----+----+----+
            | A  | B  | C  |
            +----+----+----+

myHash.remove(B); // We remove B, and shift the ones after it back

              10   11   12
            +----+----+----+
            | A  | C  |    |
            +----+----+----+

myHash.contains(C) == false; // C hashes to slot 12, but there is nothing there.  So therefore the hash does not contain C (but it does CONTRADICTION).

Therefore, by proof of contradiction, simply sliding the succeeding elements upon removal will result in incorrectness.

EDIT: C should have said that it hashes to 12


答:
State is more of a usage pattern than a particular way to define a class's properties.  I would only consider a variable part of the State when, according to DoFactory,

State,

Allow[s] an object to alter its behavior when its internal state changes. The object will appear to change its class.


问:
ASP.Net or WPF(C#)?
Our team is divided on this and I wanted to get some third-party opinions.

We are building an application and cannot decide if we want to use .Net WPF Desktop Application with a WCF server, or ASP.Net web app using jQuery. I thought I'd ask the question here, with some specs, and see what the pros/cons of using either side would be. I have my own favorite and feel I am biased.

Ideally we want to build the initial release of the software as fast as we can, then slow down and take time to build in the additional features/components we want later on. Above all we want the software to be fast. Users go through records all day long and delays in loading records or refreshing screens kills their productivity.

Application Details:

I'm estimating around 100 different screens for initial version, with plans for a lot of additional screens being added on later after the initial release.

We are looking to use two-way communication for reminder and event systems

Currently has to support around 100 users, although we've been told to allow for growth up to 500 users

We have multiple locations

Items to consider (maybe not initially in some cases but in future releases):

Room for additional components to be added after initial release (there are a lot of of these... perhaps work here than the initial application)

Keyboard navigation

Performance is a must

Production Speed to initial version

Low maintenance overhead

Future support

Softphone/Scanner integration

Our Developers:

We have 1 programmer who has been learning WPF the past few months and was the one who suggested we use WPF for this.

We have a 2nd programmer who is familiar with ASP.Net and who may help with the project in the future, although he will not be working on it much up until the initial release since his time is spent maintaining our current software.

There is me, who has worked with both and am comfortable in either

We have an outside company doing the project management, and they are an ASP.Net company.

We plan on hiring 1-2 others, however we need to know what direction we are going in first

Environment:

General users are on Windows 2003 server with Terminal Services. They connect using WYSE thin-clients over an RDP connection. Admin staff has their own PCs with XP or higher. Users are allowed to specify their own resolution although they are limited to using IE as the web browser.

Other locations connects to our network over a MPLS connection

Based on that, what would you choose and why?

答: I will have to recommend you to use WCF for your service layer because of scalability and security. For the presentation layer you can use either Silverlight or ASP.NET, Silverlight is like Flash, but it's hard to understand and have a high learning curve at first, mostly when working with data. ASP.NET is easier to use but you will need a lot of tweaking and javascript to use it efficiently.</p>

Title: ASP.Net or WPF(C#)?


问:
Things to do before going to production
I am finishing up a decently sized Python/Shell project, and I'm wondering if there's a 'best practice' list of things to do when finishing up development.

So far I've done:

pylint

pycallgraph

grep'ed for :TODO: and :FIXME:

find orphan code

some more documentation

install scripts for client and server

make sure comments match the reality (before I forget the finer points)

What other things do you do, generally, or Python-specific?

答:
make sure you have enough automatic tests

run them!

also test things for which you don't have automatic regression tests (for example, your install scripts)

and make sure you have everything checked in into your SCCS (test that by checking everything out on a clean machine and see if there is something missing)

make sure version numbers are up-to-date

update your change log (the document for your client, not the comments in your SCCS)

update your list of open issues / list of requirements for the next release / backlog / issue tracker (whatever you use for this purpose)

And one thing: IMHO some of the things you mentioned should be always in order at the end of the day - adding or correcting comments only before going to production is far too late. Make your comments match reality immediately, whenever you change a function, later you will forget about it.

Title: Things to do before going to production


问:
Should I be commiting code quickly and testing later?
I am a web and software developer involved in the creation of mobile apps. I am currently working on a project with a looming deadline. I am wondering if I should be committing code rapidly and large and testing later, or doing tiny commits and testing each one.

Thank you!

答:
"We test later" always means "we test never", because there's never any time left to do it later. Whenever you have something changed that is worth testing, test it now.

You won't introduce fewer bugs just because you make more commits and fewer tests between the commits. Instead, you will pile bogus code on bogus code which, after n changes, becomes not n times hard to fix, but 2^n times, because you lose the feedback on which of your changes was the root cause for the bug.


答:
Should I be committing code quickly and testing later?

Once a functional piece of code is committed it is a good time to test. In another words, if committed code is testable, do your testing and don't postpone.

Postponing the testing (unit testing or manual one) on a committed code is a bit of an evil. That will potential to catch you up badly later on. As piling up on the commits without testing would not help to progress the project forward.

As mentioned, cutting the corners never ends to be productive. Just try not to skip steps and do your unit testing, before assuming that your task is done.

Related Stack Exchange question and blog post:

Codding Horror - Testing With "The Force"

Is Unit Testing worth the effort?

Title: Should I be commiting code quickly and testing later?

Body:
I am a web and software developer involved in the creation of mobile apps. I am currently working on a project with a looming deadline. I am wondering if I should be committing code rapidly and large and testing later, or doing tiny commits and testing each one.

Thank you!


答:
As others have mentioned, delaying testing often means that testing gets cut - even in the best case, testing far later from implementation leads to less efficient testing.

That said, there are benefits of checking in immediately. Quick check-ins reduce the risk and size of merge conflicts, both for you and your colleagues. If you have a build process that prevents you from breaking it (reject check-ins on build failure or unit test failure is the most common) then feel free to check in.

If you're going that route then once the code is in, then start on the unit tests. Do not delay them, do not get other things out of the way... don't cut corners.

I've seen this at multiple companies and works just fine as long as your team (or team lead) is disciplined enough.

(note: This is not the only way to successfully develop software. Tiny changes that are tested and checked in together will work. Test first development will work. What works best for you will vary significantly on who you are, what you're working on, etc.)


答:
Spend good amount of time on back-up plans to roll-back deployments in the case of failure or un-expected events.

Back-up :

Prepare a checklist and add items to it

Make sure you have a back-up plans for Database roll-back, scripts, etc.

Remove logging code or check the production/testing setting of the app.

Simulate the worse scenario of deployment

Check the failing points of the overall system (network connectivity, firewalls, etc..)

Prepare a roll-back scenario and simulate it

Title: Things to do before going to production

Body:
I am finishing up a decently sized Python/Shell project, and I'm wondering if there's a 'best practice' list of things to do when finishing up development.

So far I've done:

pylint

pycallgraph

grep'ed for :TODO: and :FIXME:

find orphan code

some more documentation

install scripts for client and server

make sure comments match the reality (before I forget the finer points)

What other things do you do, generally, or Python-specific?


问:
How useful are IT headhunters/recruiters when looking for a new job?
Since they exist for several fields with varying degrees of usefulness, I'm curious as to the reputation of headhunters/recruiters that focus solely on IT professionals (e.g. programmers, software engineers, CIOs, etc) when it comes to finding a new job.

Are they actually useful or is it fairly hit or miss? Does the old adage of only working with a limited number apply or can you safely give you resume/CV to several of them?

答:
Don't underestimate the art of dealing with recruiters.  These are all my own generalizations, based on 7 years of consulting work as a java developer.

Recruiters generally are non-technical and deal with buzzwords on resumes or years of programming experience in a language, but most importantly, remember they are sales people.

They work for the CLIENT, not you for the most part.

You are a commodity to them, not a person.

They work all day at negotiating as paid professionals, the programmers generally only deal with this out of necessity and focus on their technical skills.

There is a business reason for hiring women in the recruiting role that could pass for models.  I've read that most developers currently are men, about 80% according to this article.  I've also read that it is for a negotiating advantage for the recruiting company.  See Recruiters are Pretty.  I couldn't locate the original article that I read anymore, but it literally spelled it out this way. Another take is: Why are most recruiters female?, but the statement there was women are just better at it.  Maybe, but there is a lot of young, attractive women in that role, more than one would think.

Anyway, I'm just stating a fact here that was in agreement from my experience, don't read anything else into these comments. I'm giving an opinion and it's still a guess.

There are lots of bad recruiters, those that want to exploit you and your skills.

I realize I'm being blunt here, but my experience is that developers are generally poor negotiators, so we are generally outclassed in dealing with the recruiters.  A sad, but true fact.  It is further exacerbated by the willingness of foreign developers who will agree to do most anything to get a position, including taking much less pay and working for free on contract work above their 40 hours, which puts rate pressure on American developers.  This comment can also be misconstrued.  I've seen American developers do the same, it just seems more common with the foreign developers in my experience.

Add to all this that it's not always easy selling your skills to a non-technical manager who doesn't always see your market value.

Knowing these things helps give you a slight advantage because it makes you more cautious in dealing with the recruiters.  If you need further proof, read your employment contracts.  We take most of the risk, but the recruiter holds most of the cards.

For example, just this week a co-worker (contractor) told me he got a lower rate the day he went to sign up for the position.  The recruiter said it was the client that did it, but why would the client change the rate the day he was signing?  The client sets the rate up front, before the selection process begins.  Then after 90 days he gets a letter, again from the recruiter saying his contract was terminating early due to funding issues.

The truth was, the recruiter cut the consultants rate, but kept the same bill rate, then raised the bill rate after 90 days to the client, in hopes that they would pay it.  I've confirmed that this has also happened to an IT Manager who is a friend of mine, so while it may not happen every time, apparently it's not a random thing either.

The moral of the story is that rate changes are allowed by the recruiter in some of the employment contracts I've seen, though not in wording that would alarm a programmer, if they even read it.

The bottom line to all this is, yes recruiters are very useful and you can get jobs using a recruiter, just understand the risks I've mentioned and other risks I haven't even brought up.  I use them each time I look for a new contract, but I prefer to work with ones I've dealt with before.

What has helped me is to develop a business relationship with a recruiter based on some edge I have in the market, a security clearance, expertise in a hard to find skillset, etc..  That way, in a sense it's a win-win for them to really help me as I have something of value to them that the average developer may not have.


问:
How to write a syntax checker
How is a syntax checker for a programming language written? I am guessing a grammar has to be written first. How to then proceed?

Motivation

I'm using a programming language (Apex for Salesforce) that is compiled in the cloud and a list of errors is sent back to the basic Eclipse editor. I'd like to skip the process for simple typing mistakes and just check for them locally.

答:
You're right so far.  In all cases, you have to have a rigorous description of the syntax of the language (a "grammar") before you can build something that can take something allegedly in that language and determine if it complies with the syntax rules (a "parser").

The parser is the front end of a compiler.  Code generation is the back end.

There are dozens of books out there on compiler construction.  Most of them go into great detail on parsing techniques.  Some deal only with the back end.

The best and most accessible book I've found for a beginner is Nicklaus Wirth's "Compiler Construction".  Available free.  You'll have to translate his source code from Oberon (a simple descendant of PASCAL and Modula-2) into your language of choice.

Jack Crenshaw's series, "Let's Build A Compiler", although incomplete, is almost as good, and just as accessible.

There are other tools.  ANTLR is popular.

Title: How to write a syntax checker


问:
MVP Implementation at the UserControl Level
I'm trying to figure out how MVP should be implemented at the UserControl level. I thought I had it, but I ended up reading a blog post that pretty much shut me down. Now I'm back at the start and with no idea how to proceed.

Let's say my UserControl is something simple like two TextBoxes and a ComboBox. This gets invoked from a main form (which has its own View and Presenter). Now, the way I understand MVP is that the Main Form Presenter is supposed to invoke a second presenter to handle all communication with the UserControl that gets dropped there.

And this is where I get completely lost. My past implementations of UserControls (before I learned MVP) always incorporated the logic behind the control (e.g. ComboBox selection will change text label related to TextBox1). As such, implementation of the UserControl is done by dragging it onto the designer, and then calling commands like UserControl1.Update() or UserControl1.DisplayData(data).

In any third-party UserControl, all commands to the UserControl are performed by commands to the control. There is no "presenter" that needs to be invoked, for instance, when I drop a ComboBox, or a ListView, or any other WinForms control onto my form. Yet they have internal logic that dictates how they display, and in the essence of testing, it should have a "presenter" separation to it somewhere.

I thought that a good solution would be that the constructor of my UserControl would create a Presenter. Any commands to the UserControl would delegate straight to the Presenter. This would allow my UserControl to have its own presentation logic separated from its "view", such that I can test it, and such that the implementer (the Main Form) need only drop in the UserControl and perform data sends and receives as part of its local presentation logic. The UserControl has its own presentation logic left invisible to the implementer.

And just when I thought I understood it all, I find out that it's bad practice (The Self-Aware View). So I plead with people who understand this better than I: How do I construct a UserControl that keeps its presentation logic invisible to the end-user, such that I don't have to construct the wrapping presenter in my Main Form, without violating the principles that Matt Wynne discusses in the linked post above?

Or am I completely misunderstanding the concept of MVP here?

答:
I read through Matt Wynne's blog entry that you linked, and I can see where some of the confusion is coming from.  So let's point out a few differences between his article and your situation.

Your question was asked on Aug 21st of 2013.  Matt's article was published on June 13 of 2007.

You tagged your question with c# and winforms, although I think you meant wpf instead of winForms. Matt states his focus and experience has been with ASP.NET.

I want to point out that we're already at a) dated advice and b) differing UI technologies.

ASP.NET and the MV* pattern(s) it supports have changed significantly since then.  Likewise, users of Silverlight and WPF have since generated a lot of guidance with using the MVVM pattern and data binding.

And as a point of reference, I would recommend reading over Martin Fowler's articles on Passive View and Supervising Controller which are the patterns he broke out from his original MVP pattern.

I think your question is more interesting when looking at the broader point of view and asking "what does MV* help me with for a framework?"  And the primary driver of this family of patterns is to encapsulate the areas that are likely to change.  Related to that encapsulation is the single responsibility principle and making sure each component owns what it should.

We encapsulate all of the view logic in the View layer so we can more easily change out our UI technology at an appropriate point later on in time.  Likewise with the Model and whatever you choose to use with the middle layer.

So the answer to your question is to put the appropriate view logic within that layer to make your technology work.  If you're using winForms, you'll end up with a lot of code-behind in order to make the form work.  WPF supports data binding and significantly reduces the amount of code-behind.  The logic you put in the View should potentially go away when you change UI technologies.

Likewise, if you have presentation rules that are not imposed by the UI technology then you'll put those rules in your middle layer as they need to persist into your next UI.

I don't mean to diminish the fact that there are differences between the MV* patterns, and those differences exist for good reason.  But their development was driven by the needs of particular technologies.  You're using potentially different tech, so use the MV* pattern appropriate for your environment.  The frameworks are there to facilitate future change, not handcuff your current development.


问:
Shared hosting for a PHP application
I was reading Essential PHP Security and chapter 8 talks about problems with hosting your PHP app in a shared hosting environment.

Some of the problems he mentions are:

- Exposed source code and File system browsing.

a web server must be able to read the source code in order to execute it. Since the web server is shared a PHP script written by another developer on the server can read arbitrary files. An attacker can also create a script that browses the file system.

- Exposed session data and Session injection.

By default, PHP stores session data in /tmp which is writable by all users, so Apache has permission to write session data there. A simple script can allow other users to read, add, modify, or delete sessions.

It's like everything is exposed and vulnerable if I used shared hosting this way.

My questions:

Considering the book was published 8 years ago, are they problems still occurring or were they mitigated somehow in the last few years?

Why would one opt for shared hosting if it going to cause these huge security concerns?

I understand that shared hosting is cheap, but there must be a safer alternative to it and cheaper than dedicated hosting?

In case a customer ask me to develop an application that will be hosted on a shared hosting, is there a full proof way to develop a secure application or is it just a recipe for disaster?

答:
Partial answer:

By default, PHP stores session data in /tmp which is writable by all users, so Apache has permission to write session data there. A simple script can allow other users to read, add, modify, or delete sessions.

This is true, but there are workarounds - you can change session.save_path to something in your home directory, or store session data in a database instead.

Title: Shared hosting for a PHP application


答:
I haven't seen this listed explicitly (though Doc Brown's answer touched on it, regarding version numbers), but IMHO the single most important part to get right in a release process is the Configuration Management. You should to be able to identify exactly what artifacts were deployed, and be able to reproduce those artifacts on demand from source.

If a customer comes to you with a bug, you'll really want to know precisely the source under which the bug was created.

Title: Things to do before going to production


答:
If you have a private development branch assigned just to you, then this isn't so bad.  You'll need some way other than the checkin itself to indicate which checkins work properly and which don't, but you'll aboid losing work. I prefer to checkin when i get the next small something working, so that no checkin represents broken code.

On the other hand, if you share a branch with anyone else, then every partial checkin risks breaking other people's builds. That results in lots of other people trying to debug why something suddenly went wrong. This is a major time waste, duplicating effort of everyone who is debugging your broken stuff instead of building or fixing the stuff they are responsible for.


问:
What do I call people who extend my class in base class documentation?
Been calling them "implementers", but it seems weird to me.

```<code>/// <summary>
/// Implementers should implement this.  Derp
/// </summary>
protected abstract void InternalExecute();
</code>```

A point of clarification, I'm interested in what to call the people who create child classes, not the child classes themselves.

"Hey, you there" not "that thing there."

答:
If I had to write documentation speaking directly to a person writing code that extends my base class, I would call them a Developer, End User, or Consumer.

That being said, I think it's generally a bad idea to reference the people using your code in the comments.  Comments should state what the code does, not what the developer using it should be doing.


问:
Combine Data from Two Tables-Help Needed
I have developed a web site with a mysql backend, but am not satisfied with how I am getting one set of data and do not know how to get another dataset.

The page in question is at:

http://whistclub.org/test/ajax.php?vichill/results/1

The results are shown through October so there is some data to use.

I am pulling the results from two mysql tables (see below), but the code I have used is too ugly for me to tolerate.  Yeah, it works, but I have some standards!  Think calls to the database for each team.  I think joins should be used, but I can't get it to work.

Ideally (I think) the result array would convert the teamIDs to team names and use names for the winner and loser VP columns.

The standings table on the page is not working at all--what you see is hand coded just to show what is needed.

The tables are:

```<code>teams:

id--autoincremented
teamID--Asssigned to each team as part of the game
teamName

games:

id--autoincremented
gameID--I suspect this is not needed since it duplicates id.
teamA
teamB
date
winner
IMPmargin
winnersVPs
losersVPS
</code>```

The game is bridge and IMP and VP are scores.  VPs are derived from IMPs and the loser often gets a few VPs.  See the webpage for the details, but I do not think that is relevant to my issue.

Here is some data from the games table:

```
id  gameID  teamA  teamB  date        winner  IMPmargin  winnersVPs  losersVPs
1   1       11     18     2013-09-25  18      12         20          10
2   2       12     17     2013-09-25  12      22         22          8
3   3       13     16     2013-09-25  13      20         21          9
4   4       14     15     2013-09-25  14      0          15          15
5   5       19     99     2013-09-25  NULL    NULL       NULL        NULL
```

Team 99 is a dummy for a bye week for a team.

If the tables are designed too badly, let me know how to make them work better.

Hopefully, that is enough for someone to point me in the right direction.

答:
A join is indeed what you are after.

Consider the following sqlfiddle - http://sqlfiddle.com/#!2/f5412/1/0 (all parts are found below, that just makes it easier if you want to... well, fiddle with it)

The DDL is:

```<code>create table team (
    id int,
    teamId int,
    teamName varchar(16)
  );

create table game (
    id int,
    gameId int,
    teamA int,
    teamB int,
    gameDate date,
    winner int,
    IMPmargin int
  );

create table vp (
    margin int,
    winVp int,
    loseVp int
  );
</code>```

The associated data:

```<code>insert into team values
  (1,1,"Team A"),
  (2,2,"Team B"),
  (3,3,"Team C");

insert into game values
  (1,1,1,2,'2013-09-25',1,19),
  (2,2,1,3,'2013-09-25',1,10),
  (2,2,2,3,'2013-09-25',2,14);

insert into vp values
  (10,0,0),
  (11,2,1),
  (12,4,3),
  (13,7,5),
  (14,10,8),
  (15,13,11),
  (16,17,14),
  (18,26,22),
  (19,32,27);
</code>```

And the query:

```<code>select
  G.id,
  A.teamName as "team A",
  B.teamName as "team B",
  G.gameDate,
  W.teamName as "winner",
  G.IMPmargin,
  V.winVp,
  V.loseVp
from
  game G
  join team A on (G.teamA = A.id)
  join team B on (G.teamB = B.id)
  join team W on (G.winner = W.id)
  join vp V on (G.IMPmargin = V.margin)
</code>```

Note how the relationship between the game (G) is made to the team table three times - as A, B, and W.

You can see the relationships between these in the diagram:

```<code> +---------------+       +----------------+     +--------------+
 | team          |       | game           |     | vp           |
 |---------------|       |----------------|     |--------------|
 | id            +---+   | id             |  +--+ margin       |
 | teamId        |   |   | gameId         |  |  | winVp        |
 | teamName      |   +---+ teamA          |  |  | loseVp       |
 +---------------+   +---+ teamB          |  |  +--------------+
                     |   | gameDate       |  |
                     +---+ winner         |  |
                         | IMPmargin      +--+
                         +----------------+
</code>```

If you have a discrete victory point table, you can insert that into the database too and join against the margin to the victory points.

Back to the joins themselves...

When you do a Join team A on (G.teamA = A.id) you are saying that a this thing in this table is a that thing in another table.  That the teamA value in game is the same as the id in the team table.

Once you have that relationship established (and again for B, and W), you can select things from the tables A, B, and W as part of the query.

You may also find the following to be helpful:

Coding Horror - A Visual Explanation of SQL Joins

And some books (O'Reilly is a publisher I trust and while I don't have these books myself, I'm fairly confident you will find them useful references)

Amazon - Learning MySQL

Amazon - MySQL Cookbook

Amazon - Learning SQL

Body:
A join is indeed what you are after.

Consider the following sqlfiddle - http://sqlfiddle.com/#!2/f5412/1/0 (all parts are found below, that just makes it easier if you want to... well, fiddle with it)

The DDL is:

create table team (
    id int,
    teamId int,
    teamName varchar(16)
  );

create table game (
    id int,
    gameId int,
    teamA int,
    teamB int,
    gameDate date,
    winner int,
    IMPmargin int
  );

create table vp (
    margin int,
    winVp int,
    loseVp int
  );

The associated data:

insert into team values
  (1,1,"Team A"),
  (2,2,"Team B"),
  (3,3,"Team C");

insert into game values
  (1,1,1,2,'2013-09-25',1,19),
  (2,2,1,3,'2013-09-25',1,10),
  (2,2,2,3,'2013-09-25',2,14);

insert into vp values
  (10,0,0),
  (11,2,1),
  (12,4,3),
  (13,7,5),
  (14,10,8),
  (15,13,11),
  (16,17,14),
  (18,26,22),
  (19,32,27);

And the query:

select
  G.id,
  A.teamName as "team A",
  B.teamName as "team B",
  G.gameDate,
  W.teamName as "winner",
  G.IMPmargin,
  V.winVp,
  V.loseVp
from
  game G
  join team A on (G.teamA = A.id)
  join team B on (G.teamB = B.id)
  join team W on (G.winner = W.id)
  join vp V on (G.IMPmargin = V.margin)

Note how the relationship between the game (G) is made to the team table three times - as A, B, and W.

You can see the relationships between these in the diagram:

 +---------------+       +----------------+     +--------------+
 | team          |       | game           |     | vp           |
 |---------------|       |----------------|     |--------------|
 | id            +---+   | id             |  +--+ margin       |
 | teamId        |   |   | gameId         |  |  | winVp        |
 | teamName      |   +---+ teamA          |  |  | loseVp       |
 +---------------+   +---+ teamB          |  |  +--------------+
                     |   | gameDate       |  |
                     +---+ winner         |  |
                         | IMPmargin      +--+
                         +----------------+

If you have a discrete victory point table, you can insert that into the database too and join against the margin to the victory points.

Back to the joins themselves...

When you do a Join team A on (G.teamA = A.id) you are saying that a this thing in this table is a that thing in another table.  That the teamA value in game is the same as the id in the team table.

Once you have that relationship established (and again for B, and W), you can select things from the tables A, B, and W as part of the query.

You may also find the following to be helpful:

Coding Horror - A Visual Explanation of SQL Joins

And some books (O'Reilly is a publisher I trust and while I don't have these books myself, I'm fairly confident you will find them useful references)

Amazon - Learning MySQL

Amazon - MySQL Cookbook

Amazon - Learning SQL


问:
Having a generic data type for a database table column, is it "good" practice?
I'm working on a PHP project where some object (class member) may contain different data type. For example :

```<code>class Property {
    private $_id;     // (PK)
    private $_ref_id; // the object reference id (FK)
    private $_name;   // the name of the property
    private $_type;   // 'string', 'int', 'float(n,m)', 'datetime', etc.
    private $_data;   // ...

    // ..snip.. public getters/setters
}
</code>```

Now, I need to perform some persistence on these objects. Some properties may be a text data type, but nothing bigger than what a varchar may hold. Also, later on, I need to be able to perform searches and sorting.

Is it a good practice to use a single database table for this (ie. is there a non negligible performance impact)? If it's "acceptable", then what could be the data type for the data column?

答:
No, it's actually the worst possible practice. I am exaggerating.

You should use separate columns for each element in $data in order to maximize the power of the database. Writing search queries, sort queries, etc, against a data column would be a nightmare of complexity, whereas those kinds of queries are easy on a 'normalized' database table.

If your $data property could potentially contain all sorts of key=>value pairs that you cannot predict, then you should look into an EAV table structure for your database table. If the keys (the properties) in your $data variable are fairly constant, then you can use a regular flat database table.

Either way, I strongly advise you not to put $data into a single data column in a database. That would almost completely destroy every advantage of using a database in the first place. You might as well store your data in a text file.

As far as performance... again, you have negated all that is useful about a database, so your performance will be horrendous. And you'll spend hours writing convoluted queries that would take a minute to write if you had a normalized database. I hope you did not proceed with your data column. The whole point of a data base is to make finding and manipulating data easier!


答:
Try a rapid pace of:

Code some new functionality

Build locally

Test new code

Commit the change when it passes the tests.

I generally try to only commit working code.  For new code I can be quite lax o the definition of working.  For purpose of a commit, a method that returns a constant but has a TODO comment (preferably in a format my IDE recognizes) is considered working.  A new method that generates a compile time error is definitely not ready for a commit.

Try for code you can complete in an hour or so.  Cleanup as many of the TODO tags as you can before you move on to new code.  Legitimate reasons to leave a TODO tag might include:

Necessary information is not available.

Other code is required to complete the item.  This may be the next development priority.


问:
What is the size of a reference variable in java. Can it be calculated?
As pointers in C require 2 bytes of memory size irrespective of the size of the data type they are pointing. So does the same thing applies to java references also ?</p>

答:
The Java Language Specification doesn't say anything about how big a reference is in memory. The JLS doesn't even say that a reference needs to exist at runtime at all. The compiler is free to use 42 gigabytes for a reference or to eliminate it completely, making the size 0 bytes. (In fact, the Java Language Specification never says anything about a particular implementation strategy or representation, it only specifies the syntax and semantics of Java's language constructs, not their pragmatics.)

Most typical Java Implementations will simply implement references as pointers, thus making them the same size as in C. Sometimes, these references are referred to as OOPs (ordinary object pointers). But the Oracle Hotspot JVM, for example, has a feature called CompressedOOPs, which can make some references smaller than C pointers on 64 bit systems.


问:
Generally speaking can a Javascript-based application (iUI) be deployed without a webserver?
Suppose I have a Javascript based application written in iUI or Kendo UI.  Can it be packaged in such a way they can run locally without a webserver?

I have a few web applications, that with some rework and HTML5 LocalStorage, can possibly work offline (in an airplane or subway).

My mobile development experience is limited to Blackberry Playbook, which I only did so I can get a free one a few years ago.  That platform supports "mobile applications" based on HTML, and an additional out-of-band packaging set of tasks.

Question

Are other platforms (iPhone, Android, etc) similar in that I can simply package an iUI based application so that it can run offline or on a webserver?

答: On iOS, the UIWebView framework can be used inside a native app to display web content (HTML and JavaScript) that can be packaged with and inside an app's distribution bundle.  So a user can install it from the App Store just like other apps, and run it complete offline thereafter.</p>


问:
What is the proper way to store an object with many attributes in Objective-C?
I have an object that I am downloading over HTTP, that has approximately 50 attributes. What is the proper way to store this information in Objective-C? Should I have an NSObject with a property for each attribute (if so, what would be a good way to initialize this object?)? Should I use an NSDictionary with 50 key-value pairs?</p>

答: Both.  Properties in a model object for efficient access and compiler checking help.  And a Dictionary for rarely used, overflow and/or unrecognized new (or errored) attributes, making it easier to decouple changes to your download data and to the client apps in the field, without crashing or tossing data that might be needed further down the road, or for debugging.</p>

OwnerDisplayName: Lenny K


问:
NHibernate and complex domain model against a legacy database
I'm trying to refactor (actually, rewrite) an application which currently uses only stored procedures to access the database (hundreds of SPs). My goal is to use Nhibernate and follow a good design as much as possible.
But since the database (and the SPs) are used by dozens of other apps, I can't really change the db design. And off course, it's awful.

I'm facing a design problem and I can't really find a good solution.
I have a table called movies which contains movies, but these movies can be different "things". For example, this table contains movies as well as episodes of tv shows and the only way to know the difference is a field named "episode" which is set to 0 for movies and 1 for episodes.

My objective is to expose the following class hierarchy :

```<code>public abstract class Program {}
public class Episode : Program {}
public class Movie : Program {}
</code>```

Currently, I have mapped the whole movies table to a model class MoviesModel and then I build my Episode/Movie class through AutoMapper and a factory method in the Program class :

```<code>public static Program Load(MoviesModel movieModel)
    {
        if (movieModel.Episode > 0)
            return Mapper.Map<Episode>(movieModel);
        return Mapper.Map<Movie>(movieModel);
    }
</code>```

This seems really wrong on many levels : I have an anemic data model since my MoviesModel is totally empty of any business logic, the automapper stuff becomes really hard to maintain when I add many other entities with relations to Movies, and I break the lazy loading with AutoMapper.

I heard about the any mapping of nhibernate but it doesn't really solve my issue, it just creates sub components of a class.

So my questions are :

Ideally, where should be my business logic ? I guess in the MoviesModel class but I don't really like the idea to expose my database fields.

Is there a way with nhibernate to map the same table in different classes based on a field value ?

Is there a point to wrap the nhibernate objects if I want to provide a "clean" public API ?

My goal is to build a base library which will be used (hopefully) on other legacy apps so I want to provide a clean API with logical methods and without exposing the database mess even if I still have to deal with it.

Thanks for any help to put me in the right direction.

答:
@Dawmz, I am not big fan of ORM frameworks. Note that I am developer of Valentina Database, so know how things work internally in dbs.

In your case you already have hundreds SPs used by dozens(!) of other apps.

This is the best scenario for SPs, because you have central place where logic present ONCE. If you remove some SP, then where will go logic of that SP? Into dozens places? On different languages probably? Road to the hell.

As I understand these SPs was developed by somebody before you come? He/They did very good job. Do not break things.


答:
You shouldn't  mention the people who code in the doc, but how the base class should be extended,  hence, you could call them "implementations"

ie

This base class defines the basic structure of the blah blah blah. Implementations should do XYZ to make it work....

Or

Implementations of this class should also consider...

Title: What do I call people who extend my class in base class documentation?

Body:
Been calling them "implementers", but it seems weird to me.

```<code>/// <summary>
/// Implementers should implement this.  Derp
/// </summary>
protected abstract void InternalExecute();
</code>```

A point of clarification, I'm interested in what to call the people who create child classes, not the child classes themselves.

"Hey, you there" not "that thing there."


问:
How would I design an interface such that it's clear which properties may change their value, and which will remain constant?
I am having a design issue regarding .NET properties.

```<code>interface IX
{
    Guid Id { get; }
    bool IsInvalidated { get; }
    void Invalidate();
}
</code>```

Problem:

This interface has two read-only properties, Id and IsInvalidated. The fact that they are read-only, however, is by itself no guarantee that their values will remain constant.

Let's say that it were my intention to make it very clear that…

Id represents a constant value (which may therefore be safely cached), while

IsInvalidated might change its value during the lifetime of an IX object (and so shouldn't be cached).

How could I modify interface IX to make that contract sufficiently explicit?

My own three attempts at a solution:

The interface is already well-designed. The presence of a method called Invalidate() allows a programmer to infer that the value of the similarly-named property IsInvalidated might be affected by it.

This argument holds only in cases where the method and property are similarly named.

Augment this interface with an event IsInvalidatedChanged:

```<code>bool IsInvalidated { get; }
event EventHandler IsInvalidatedChanged;
</code>```

The presence of a …Changed event for IsInvalidated states that this property may change its value, and the absence of a similar event for Id is a promise that that property will not change its value.

I like this solution, but it's a lot of additional stuff that may not get used at all.

Replace the property IsInvalidated with a method IsInvalidated():

```<code>bool IsInvalidated();
</code>```

This might be too subtle a change. It's supposed to be a hint that a value is computed freshly each time — which wouldn't be necessary if it was a constant. The MSDN topic "Choosing Between Properties and Methods" has this to say about it:

Do use a method, rather than a property, in the following situations. […] The operation returns a different result each time it is called, even if the parameters do not change.

What kind of answers do I expect?

I am most interested in entirely different solutions to the problem, along with an explanation how they beat my above attempts.

If my attempts are logically flawed or have significant disadvantages not yet mentioned, such that only one solution (or none) remains, I would like to hear about where I went wrong.

If the flaws are minor, and more than one solution remains after taking it into consideration, please comment.

At the very least, I would like some feedback on which is your preferred solution, and for what reason(s).

答:
My 2 cents:

Option 3: As a non-C#-er, it wouldn't be much of a clue; However, judging by the quote you bring, it should be clear to proficient C# programmers that this means something. You should still add docs about this though.

Option 2: Unless you plan on adding events to every thing that may change, don't go there.

Other options:

Renaming the interface IXMutable, so it's clear that it can change its state. The only immutable value in your example is the id, which usually is assumed to be immutable even in mutable objects.

Not mentioning it. Interfaces are not as good at describing behaviour as we'd like them to be; Partly, that's because the language doesn't really let you describe things like "This method will always return the same value for a specific object," or "Calling this method with an argument x < 0 will throw an exception."

Except that there's a mechanism to expand the language and provide more precise information about constructs - Annotations/Attributes. They sometimes need some work, but the allow you to specify arbitrarily complex things about your methods. Find or invent an annotation that says "The value of this method/property can change throughout the lifetime of an object", and add it to the method. You might need to play some tricks to get the implementing methods to "inherit" it, and users may need to read the doc for that annotation, but it will be a tool that lets you say exactly what you want to say, instead of hinting at it.


问:
From a high level programming perspective, where does the 'different-paradigm' barrier between C# and F# really kick in?
I'm aware that they both use different programming paradigms, but from a high level perspective apart from differing syntax it seems most basic tasks can be achieved in similar fashion.

I only say this because when I've previously touched functional programming languages such as Haskell, writing code for basics tasks was (at first) difficult, frustrating, and required a completely different mindset.

For example the following took some time to get to grips with using recursive syntax:

```<code>loop :: Int -> IO ()
loop n = if 0 == n then return () else loop (n-1)
</code>```

Where as an F# loop is recognisable and understandable almost immediately:

```<code>let list1 = [ 1; 5; 100; 450; 788 ]
for i in list1 do
   printfn "%d" i
</code>```

When C# programmers start learning F# they are advised to completely re-think their thought pattern (which was definitely required for Haskell), but I've now written several F# programs dealing with conditions, loops, data sets etc to perform practical tasks, and I'm wondering where the 'different-paradigm' barrier really kicks in?

答:
I'm wondering where the 'different-paradigm' barrier really kicks in?

There largely is no "barrier". You're free to write non-idiomatic F# all you want - just like you could program C# for ages and not really practice object oriented programming.

The only case I can really see forcing your hand is working with other developers. You'll see their style with the language and will have to adapt to using it. More importantly, they'll not stand for you writing loops in a functional codebase.


答:
There is a fourth solution: rely on documentation.

How do you know that string class is immutable? You simply know that, because you've read the MSDN documentation. StringBuilder, on the other hand, is mutable, because, again, documentation tell you that.

```<code>/// <summary>
/// Represents an index of an element stored in the database.
/// </summary>
private interface IX
{
    /// <summary>
    /// Gets the immutable globally unique identifier of the index, the identifier being
    /// assigned by the database when the index is created.
    /// </summary>
    Guid Id { get; }

    /// <summary>
    /// Gets a value indicating whether the index is invalidated, which means that the
    /// indexed element is no longer valid and should be reloaded from the database. The
    /// index can be invalidated by calling the <see cref="Invalidate()" /> method.
    /// </summary>
    bool IsInvalidated { get; }

    /// <summary>
    /// Invalidates the index, without forcing the indexed element to be reloaded from the
    /// database.
    /// </summary>
    void Invalidate();
}
</code>```

Your third solution is not bad, but .NET Framework doesn't follow it. For example:

```<code>StringBuilder.Length
DateTime.Now
</code>```

are properties, but don't expect them to remain constant every time.

What is consistently used across .NET Framework itself is this:

```<code>IEnumerable<T>.Count()
</code>```

is a method, while:

```<code>IList<T>.Length
</code>```

is a property. In the first case, doing stuff may require additional work, including, for example, querying the database. This additional work may take some time. In a case of a property, it is expected to take a short time: indeed, the length can change during the lifetime of the list, but it takes practically nothing to return it.

With classes, just looking at the code clearly shows that a value of a property won't change during the lifetime of the object. For instance,

```<code>public class Product
{
    private readonly int price;

    public Product(int price)
    {
        this.price = price;
    }

    public int Price
    {
        get
        {
            return this.price;
        }
    }
}
</code>```

is clear: the price will remain the same.

Sadly, you can't apply the same pattern to an interface, and given that C# is not expressive enough in such case, documentation (including XML Documentation and UML diagrams) should be used to close the gap.

Title: How would I design an interface such that it's clear which properties may change their value, and which will remain constant?

Body:
I am having a design issue regarding .NET properties.

```<code>interface IX
{
    Guid Id { get; }
    bool IsInvalidated { get; }
    void Invalidate();
}
</code>```

Problem:

This interface has two read-only properties, Id and IsInvalidated. The fact that they are read-only, however, is by itself no guarantee that their values will remain constant.

Let's say that it were my intention to make it very clear that…

Id represents a constant value (which may therefore be safely cached), while

IsInvalidated might change its value during the lifetime of an IX object (and so shouldn't be cached).

How could I modify interface IX to make that contract sufficiently explicit?

My own three attempts at a solution:

The interface is already well-designed. The presence of a method called Invalidate() allows a programmer to infer that the value of the similarly-named property IsInvalidated might be affected by it.

This argument holds only in cases where the method and property are similarly named.

Augment this interface with an event IsInvalidatedChanged:

```<code>bool IsInvalidated { get; }
event EventHandler IsInvalidatedChanged;
</code>```

The presence of a …Changed event for IsInvalidated states that this property may change its value, and the absence of a similar event for Id is a promise that that property will not change its value.

I like this solution, but it's a lot of additional stuff that may not get used at all.

Replace the property IsInvalidated with a method IsInvalidated():

```<code>bool IsInvalidated();
</code>```

This might be too subtle a change. It's supposed to be a hint that a value is computed freshly each time — which wouldn't be necessary if it was a constant. The MSDN topic "Choosing Between Properties and Methods" has this to say about it:

Do use a method, rather than a property, in the following situations. […] The operation returns a different result each time it is called, even if the parameters do not change.

What kind of answers do I expect?

I am most interested in entirely different solutions to the problem, along with an explanation how they beat my above attempts.

If my attempts are logically flawed or have significant disadvantages not yet mentioned, such that only one solution (or none) remains, I would like to hear about where I went wrong.

If the flaws are minor, and more than one solution remains after taking it into consideration, please comment.

At the very least, I would like some feedback on which is your preferred solution, and for what reason(s).

Body:
There is a fourth solution: rely on documentation.

How do you know that string class is immutable? You simply know that, because you've read the MSDN documentation. StringBuilder, on the other hand, is mutable, because, again, documentation tell you that.

/// <summary>
/// Represents an index of an element stored in the database.
/// </summary>
private interface IX
{
    /// <summary>
    /// Gets the immutable globally unique identifier of the index, the identifier being
    /// assigned by the database when the index is created.
    /// </summary>
    Guid Id { get; }

    /// <summary>
    /// Gets a value indicating whether the index is invalidated, which means that the
    /// indexed element is no longer valid and should be reloaded from the database. The
    /// index can be invalidated by calling the <see cref="Invalidate()" /> method.
    /// </summary>
    bool IsInvalidated { get; }

    /// <summary>
    /// Invalidates the index, without forcing the indexed element to be reloaded from the
    /// database.
    /// </summary>
    void Invalidate();
}

Your third solution is not bad, but .NET Framework doesn't follow it. For example:

StringBuilder.Length
DateTime.Now

are properties, but don't expect them to remain constant every time.

What is consistently used across .NET Framework itself is this:

IEnumerable<T>.Count()

is a method, while:

IList<T>.Length

is a property. In the first case, doing stuff may require additional work, including, for example, querying the database. This additional work may take some time. In a case of a property, it is expected to take a short time: indeed, the length can change during the lifetime of the list, but it takes practically nothing to return it.

With classes, just looking at the code clearly shows that a value of a property won't change during the lifetime of the object. For instance,

public class Product
{
    private readonly int price;

    public Product(int price)
    {
        this.price = price;
    }

    public int Price
    {
        get
        {
            return this.price;
        }
    }
}

is clear: the price will remain the same.

Sadly, you can't apply the same pattern to an interface, and given that C# is not expressive enough in such case, documentation (including XML Documentation and UML diagrams) should be used to close the gap.


答:
In my idea, it all depends. Lot's of other factors come into the play:

Does your team have a dedicated tester?

Are you in a hurry of delivering a buggy demo to the client?

Do you mind the first release not to have bugs?

etc. etc.

I mean, while general guidelines exist, no prescription can be made for all teams around the globe.

Yes, of course testing and all concepts related to it would increase the quality of your product in a considerable way. Concepts like regression testing, unit testing, coded UI testing, integrity tests, security tests, performance tests, and all of'em make your software to become a first-class citizen to compete in the market. But that's only the academic view.

The practical view is however sometimes a little different. If you really need a demo, then write more code, and test less.

If you have a dedicated tester, then let him take the responsibility of testing. Collaborate, work together, but you spend more time developing and less time testing.

Also try to reuse tests through writing automated tests and getting far from manual testing.

As the last suggestion, I recommend that you reduce the features, because as a general rule:

Less robust features outweigh more buggy features.


答:
How useful? Not much. Based on my experience, I would describe them as a necessary evil. They are often manipulative salesmen and will lie to you constantly. They are typically very unprofessional too. For example: you are not given the job? don't bother waiting for a reply from them, you aren't worth any money now for the time to pick up the phone and give you the news. You mull it over and decide to reject a position? They might call you in spite to lash out and threaten you (not making that up.)

So they are an all-around dead-weight in the hiring process. Why "necessary" then? The economical forces move in mysterious ways and the fact is that a lot of companies decide to use them. Some jobs for which they are recruiting are not even advertised. They have managed to entrench themselves and found ways to make themselves necessary, although they are really not.

I believe nowadays that the industry is coming of age and more and more professional they are becoming an endangered species. They cannot get away with selling insurance one day and talk their way into discussing a technical job the next anymore. We already have websites like github, SO careers or hackernews which streamline and makes the hiring process much more transparent. I, for one, am happy these websites allow me not having to put up with their evil ways.

If you still want or need to deal with them, this is some advice that has worked better for me than being the nice, agreeable guy I once was. This may be highly subjective:

Don't hesitate to be not only assertive, but unreasonable and selfish, because they probably will be too. It's important you teach them they can't walk over you. The moment you pick up the phone tell them that the conversation will last no more than 15  minutes (should be long enough) and keep your word. Assume anything you cannot easily prove or disprove is untrue. Get them to answer your questions. Never be afraid to walk away from the process at any time. Don't ever yield to one of their requests if it doesn't directly benefit you. Report their friend requests in linked-in. They only see you as someone they need to place in a company at any cost so that they can earn a bunch of money as quickly and easily as possible; so don't try and be a nice guy. It won't be to your advantage. I can't stress this enough.

Just to be clear, I'm not advocating to be rude or disrespectful at all, quite the contrary. Just keep clear, unreasonable and self-serving boundaries that benefit you and don't step out of them.

Title: How useful are IT headhunters/recruiters when looking for a new job?

Body:
Since they exist for several fields with varying degrees of usefulness, I'm curious as to the reputation of headhunters/recruiters that focus solely on IT professionals (e.g. programmers, software engineers, CIOs, etc) when it comes to finding a new job.

Are they actually useful or is it fairly hit or miss? Does the old adage of only working with a limited number apply or can you safely give you resume/CV to several of them?


问:
How to manage ratings system of my web app?
I am making a website where in users would rate posts by other users, according to how useful they are.
The posts will be about products - mobiles, tablets, and other personal consumer electronics only.

I want to make sure no trolling or slandering goes on, so I'll need a system that will make sure the good ratings of posts are genuine, and not just from people hired by those products' companies, or the bad ratings aren't from that product's company's competitors.

I like the StackOverflow system of upvotes and downvotes. But that requires a lot of moderation, and frankly, I don't have the resources for that. I mean, the SO community has a lot of trusted mods, and admins, but in my site, in the beginning only me and my friend who are making this site would be the ones to trust, in order to keep only legit posts and legit ratings in our database, for the public to value from.

EDIT 1:
One solution I have in mind is, to include Facebook Like button as the only way to "upvote" a post. That way, leveraging the authenticity of users offered by Facebook (atleast to some extent), would benefit me. I'd count the number of likes and store them as upvotes for a particular post. There would be though, no downvotes. I'm thinking storing a ratio of "X users found it useful" as Viewers that liked this post/Total number of viewers of that post

答:
There is a saying in Persian that says:

You will be fed, only as much as you pay.

Can you bring forward examples of great successe with little work? I don't see examples. Yeah, Facebook might start by one guy, but soon it had to hire like hundreds of employees. Google too. Instagram, Pinterest, event StackExchange hires almost two or three times a year as much as I see their job ads.

So, what I'm trying to say is that while even at the beginning you might try to find a rapid, cheap solution, you soon should replace it with something decent in case of any scale and sale. So, first suggestions is:

Have a plan for great success. Be proactive instead of reactive

But for now, I think your solution should be enough for you to start. And for the case that it doesn't have negative votes (negative likes), you can think of a zero-based reputation system.


答:
F# is a hybrid language: it's primarily a functional language, but it can also do pretty much everything C# can do. So, you can use mutable variables, mutable collections, methods with side-effects and inheritance hierarchies everywhere. But if you do that, you will find that F# is not a very good imperative language and it would have been better if you stayed with C#.

On the other hand, if you want to write idiomatic F#, you will need to learn how to use immutable variables, immutable collections, pure functions, discriminated unions and pattern matching.

To sum up, if you really want to take advantage of what F# can offer, you will indeed need to re-think how you code, though probably not as radically as is required for Haskell.

Title: From a high level programming perspective, where does the 'different-paradigm' barrier between C# and F# really kick in?

Body:
I'm aware that they both use different programming paradigms, but from a high level perspective apart from differing syntax it seems most basic tasks can be achieved in similar fashion.

I only say this because when I've previously touched functional programming languages such as Haskell, writing code for basics tasks was (at first) difficult, frustrating, and required a completely different mindset.

For example the following took some time to get to grips with using recursive syntax:

```<code>loop :: Int -> IO ()
loop n = if 0 == n then return () else loop (n-1)
</code>```

Where as an F# loop is recognisable and understandable almost immediately:

```<code>let list1 = [ 1; 5; 100; 450; 788 ]
for i in list1 do
   printfn "%d" i
</code>```

When C# programmers start learning F# they are advised to completely re-think their thought pattern (which was definitely required for Haskell), but I've now written several F# programs dealing with conditions, loops, data sets etc to perform practical tasks, and I'm wondering where the 'different-paradigm' barrier really kicks in?


问:
web spider for facebook
I just subscribed to a facebook page which post links to different open source projects or code archives. I'll like to save those links and descriptions to a local db.

How can I do that? I heard something about the concept of web spiders and I know some php and java but I don't know how can I solve the problem from above.

Thank you!

答:
You are looking for a web scraper which is an application designed for reading the data on a web page and processing it.  The scraper is part of a crawler (the crawler also traverses the links on a page to find other pages out on the net).

Web scrapers and crawlers should honor the robot exclusion standard specified in robots.txt.  For facebook, this is at http://www.facebook.com/robots.txt

Note the specific list of allowed user agents (googlebot for example).  And the last one:

```<code>User-agent: *
Disallow: /
</code>```

Which says "you shouldn't be doing anything if you are not allowed".

There is a page mentioned in the human readable part of robots.txt:

```<code># Notice: if you would like to crawl Facebook you can
# contact us here: http://www.facebook.com/apps/site_scraping_tos.php
# to apply for white listing. Our general terms are available
# at http://www.facebook.com/apps/site_scraping_tos_terms.php
</code>```

http://www.facebook.com/apps/site_scraping_tos_terms.php starts out with:

These terms govern your collection of data from Facebook through automated means, such as through harvesting bots, robots, spiders, or scrapers ("Automated Data Collection"), as well as your use of that data.

You will not engage in Automated Data Collection without Facebook's express written permission.

I would suggest reading How I got sued by Facebook - their lawyers do have teeth.

Title: web spider for facebook

Body:
You are looking for a web scraper which is an application designed for reading the data on a web page and processing it.  The scraper is part of a crawler (the crawler also traverses the links on a page to find other pages out on the net).

Web scrapers and crawlers should honor the robot exclusion standard specified in robots.txt.  For facebook, this is at http://www.facebook.com/robots.txt

Note the specific list of allowed user agents (googlebot for example).  And the last one:

User-agent: *
Disallow: /

Which says "you shouldn't be doing anything if you are not allowed".

There is a page mentioned in the human readable part of robots.txt:

# Notice: if you would like to crawl Facebook you can
# contact us here: http://www.facebook.com/apps/site_scraping_tos.php
# to apply for white listing. Our general terms are available
# at http://www.facebook.com/apps/site_scraping_tos_terms.php

http://www.facebook.com/apps/site_scraping_tos_terms.php starts out with:

These terms govern your collection of data from Facebook through automated means, such as through harvesting bots, robots, spiders, or scrapers ("Automated Data Collection"), as well as your use of that data.

You will not engage in Automated Data Collection without Facebook's express written permission.

I would suggest reading How I got sued by Facebook - their lawyers do have teeth.


问:
ASP.NET deployment code?
I have a question regarding uploading an asp.net website to a real web sever. What type of files will be uploaded is it ASP.NET files or is it assemblies?

To be more clear if someone got an access to my ftp and downloaded all the files will he be able to edit those files?

答:
Generally, an ASP.NET website published on a third-party server (host) is (pre)compiled in a non-updatable way to avoid code modification.

About source code access

First point, precompilation as Steven said. Depending on your project type, if you don't precompile, the source code (*.cs in C# or *.vb in VB.NET) will be in the deployment package and present in your web site root. By default, it cannot be downloaded via the webserver because of the file extensions but these files are accessible on the file system.

Note that if you precompile in an updatable mode, the content of your .aspx, .ascx and .master will be readable. Check the link above.

Second point, reverse-engineering : even if you compile and make the effort to put the maximum of your code logic in your compiled code -ie. assemblies-, the source code is fully readable in your assemblies through 'spy' tools. Furthermore, these assemblies can be decompiled -and the source code is back-.

Finally, if you want to prevent source code theft, you have to obfuscate your code (assemblies). The role of obfuscation is to make the code unreadable by scattering the sources (classes and methods) and renaming the variables. The code in your final assemblies will be incomprehensible for a human.
It can be somehow decompiled but your code logic will be more difficult to analyze. There is a bunch of obfuscation tools. I like Eazfuscator .NET (last free version is 3.3).

Take a look : 7 Ways to Protect your .NET Code from Reverse-Engineering

Title: ASP.NET deployment code?


问:
Is Perl outdated for CGI and FCGI?
When we did web development in 1996 it was CGI, FCGI and Perl on the backend. Now why is Perl not that popular anymore and instead we use Java, Python, Go, PHP, C# and everything but Perl? To me it seems that Perl should be good since it has had long time to mature. What happened that causes Perl to lose its applicability as server language?</p>

答:
For the same reasons that everybody is writing everything in Java, Python, PHP, and C#... you use the right tool for the job at hand.

Perl really can do anything that you need it to. I mean, Movable Type and Markdown are both widely used pieces of software that are written in Perl, and they are completely different.

The reasons some people don't use Perl are mainly subjective (ugly code, difficult to learn, etc.) but you can say that about any language.

Title: Is Perl outdated for CGI and FCGI?


答:
The model for web programming in the 90's was to launch an application that used the common gateway interface to launch another process that was forked by the web server.

Forking a process is a rather heavy weight operation.  For perl, this means spinning up the interpreter, running it, and then letting the process terminate.  When working with heavy loads, this became prohibitively expensive (memory and cpu).

FastCGI reduced the overhead of CGIs by reusing the process, cutting back on the heavy forking of a process.  This is more inline with application servers, which leads us to...

The development approach today is to have an application server in a language that has a light weight process threading model, which can handle very large loads (compared to the days of CGI).  Of these you have Java, Go, and C# which follow this approach.

This doesn't mean perl is out.  There are application servers for Perl.  One rarely hears of Catalyst compared to things such as Zope, NodeJS, or the plethora of Java App servers.

Part of this is timing.  While the development of Java application servers was going on, Perl has been a bit bogged down with work on perl 6 (any <s>day</s> year now) and so the community as a whole let that development path slip by.

I personally discount the discipline of languages as a reason that perl has missed out pointing to javascript, php and ruby as three examples of similarly undisciplined languages that remain popular in the web area.

Languages such as Java and C# (and to an extent, python) with major company backing (Sun/Oracle, Microsoft, Google) and, yes, more discipline in the language are more appealing to enterprise development.

Title: Is Perl outdated for CGI and FCGI?

Body: When we did web development in 1996 it was CGI, FCGI and Perl on the backend. Now why is Perl not that popular anymore and instead we use Java, Python, Go, PHP, C# and everything but Perl? To me it seems that Perl should be good since it has had long time to mature. What happened that causes Perl to lose its applicability as server language?</p>