答:
If the database access is not part of the question, I hope 2 hours should be enough to get a minimum login feature working.

But do not pass or fail the candidate based on the completeness but do review the approach that they are taking.

Be sure to ask many follow up questions on the code after the interview is over.

what would you do if I have the lock the user after 3 attempts?

how would you implement the data access?

how would you implement the unit tests?

how would you improve this code?

Title: Interview assignment: how long is reasonable?

Body:
So I'm hiring for a senior developer/team lead role for an ASP.NET MVC3 project.  This is a big deal position for our team as this person will lead one of our two main products--a product that hasn't seen much developer love in a while.

So I need to ensure that my candidates do smart things with controllers, views, view models, DALs, unit tests, etc.  I use some trivial programming challenges during interviews but I want to give the folks who have trouble in whiteboard coding a chance to shine.

The best assignment I can think of: implementing a trivial log in page, is probably more than an hour of work and even if I cap it at 2 hours, it is unlikely to be 100% finished.

Is this fair?  I'm trying to strike a balance between keeping the assignment reasonable and giving the applicant a chance to show off the wide range of skills being a tech lead requires.


问:
Interview assignment: how long is reasonable?
So I'm hiring for a senior developer/team lead role for an ASP.NET MVC3 project.  This is a big deal position for our team as this person will lead one of our two main products--a product that hasn't seen much developer love in a while.

So I need to ensure that my candidates do smart things with controllers, views, view models, DALs, unit tests, etc.  I use some trivial programming challenges during interviews but I want to give the folks who have trouble in whiteboard coding a chance to shine.

The best assignment I can think of: implementing a trivial log in page, is probably more than an hour of work and even if I cap it at 2 hours, it is unlikely to be 100% finished.

Is this fair?  I'm trying to strike a balance between keeping the assignment reasonable and giving the applicant a chance to show off the wide range of skills being a tech lead requires.

答:
Having been on both sides of this issue, as a manager and a job applicant, I think you're right on with 1 - 2 hours. Anything longer gets frustrating for some of the job applicants (if not most). Anything shorter, on the other hand, will probably not get you enough information and insights into the candidate's skillset.

The only thing I would add is to make sure that the interview assignment wouldn't come as a complete surprise; perhaps it would be reasonable to give the candidate a general idea of what they should prepare for (even if it's just a general idea). Here's why: I sometimes spend a couple of months, doing nothing but database related programming. I get into a certain groove, and for a while, I'm pretty much on top of database related programming.

Then I'm being asked to implement proprietary video presentations, training, etc. in such a manner that nobody can rip them off...and I get into that groove, pretty much doing nothing else.

So even though you're interviewing a developer/team lead, if the candidate seems like a good guy, give him a chance to find out what you're after, again, if needs be just mention some general issues, or if you feel generous, give him a handful of specific topics to think about.

You and/or others may disagree wit this approach, but job interviews are tough. You want to make sure that the candidate is up to snuff, but you also want to give them opportunities to impress you and feel confident. Most likely, you will find that such candidates will give you much more genuine information than those who are a nervous wreck, because they know there will be some kind of assignment...but they don't know what it will be.

In a nutshell, yes, I think you're being fair!

ContentLicense: CC BY-SA 3.0


问:
Completion time on a company where the supervisors don't know programming
We are in a small company with around 10 developers. I am the team leader and responsible for the development process.

Supervisors and salesmen are close to us since we are a small team, but have no clue on how software is developed.

When they ask me how much time I want for a change (bugfixes/features) in a product, my response is 'let me calculate it'. After giving them the schedule, they start by saying OK you can do it in XX time which differs a lot from my plan. We are using a model close to Agile basic principles and have circles per week or per three days.

Of course I argue and say that this cannot be done. They seem to have no idea on the effort we are doing. They do not want to see WHY my schedule is for that amount of time.

I know this behavior is stupid, but how can I make them see the problem?

答:
There are two issues, which need disentanbled.

Stop quoting in time, start quoting in dollars.  This quickly allows them to do a cost / benefit analysis, and allows you to add a standard "time to analyze" quote.  Time is too sticky, because it doesn't reflect the real amount of work done (forty hours could be done in a day, five days, or three weeks), and it is far too easy to not push the budgeted release cycle back for such a request.

Provide the sales staff a request input into the dev cycle (preferably a non-human interface, to save time (measured in money)).

Sales people tend to think in terms of (if I have X, I can close this sale).  Their requests are often not coherent with the current architecture of the product, but they are coherent with the current need of a customer.

Indicate to the sales force that such requests are vital for your product, and as such, you need to not lose them in the "quick request, will take longer than the period of interest, drop the request, repeat" cycle.  Such requests need to be captured, analyzed, prioritized, integrated into the product, tested, and released with the next release cycle.

Then back up your words with actions.  Shorten the release cycle to under two months, indicate which items are going to be in the release, and hit your deadlines.  Don't educate the sales staff about the internal reasons this is necessary, just do an analysis of what an out-of-cycle request minimally costs (in dollars), and what the risk (extra dollars and percentage of occurrence) it could cost if a problem exceeds minimal complexity.   Then ask the sales person if the sale is large enough to support the out-of-cycle request.

Once they have a process for an in-cycle request, and they have an idea of how much it costs to handle an out-of-cycle request, odds are good that you can convert their out-of-cycle request into an in-cycle request, or determine that the out-of-cycle request is profitable enough to justify the expense.


答:
It should be assumed that their resume shows that they can code, otherwise why would you be interviewing them? If you can't see that they code don't bring them in, you are wasting your time.

That said, I would worry more about how they approach the solution than the mechanical part of the solution ( the code ), and how they communicate their solution. This is why whiteboards exist.

If you provide them with a base set of requirements and the first thing they don't do is start asking for specifics, then that is a strike. You should have a specific set of things you want to hear them say or ask before hand, this is more work for you but basing your decision off something like this is more accurate than having someone hack at something that isn't expected to work anyway.

Senior team members should be able to design a solution, present the design and explain it and defend any decisions if needed, or adapt any decisions based on feed back and communicate the plan to junior members of the team and explain it in a mentoring way.

This human interaction is more important than having them partially complete an entry level busy work assignment. Which most will not want to do; if they do it at all and if presented with an offer afterwards, will probably refuse as it is a demeaning task.

There are lots of senior cowboy coders that have no personal skills and don't work in a team at all, a contrived test that you propose will not weed these people out, and trust me you don't want a single one of these type of people on a team of any size!


答:
If they want to cut the schedule - ask them which features they want to be left out and the priority of those.

Then work on features in order of priority and tell them they can have they product whenever they like but it won't contain all the features they requested until the end date you specified initially.

Title: Completion time on a company where the supervisors don't know programming

Body:
We are in a small company with around 10 developers. I am the team leader and responsible for the development process.

Supervisors and salesmen are close to us since we are a small team, but have no clue on how software is developed.

When they ask me how much time I want for a change (bugfixes/features) in a product, my response is 'let me calculate it'. After giving them the schedule, they start by saying OK you can do it in XX time which differs a lot from my plan. We are using a model close to Agile basic principles and have circles per week or per three days.

Of course I argue and say that this cannot be done. They seem to have no idea on the effort we are doing. They do not want to see WHY my schedule is for that amount of time.

I know this behavior is stupid, but how can I make them see the problem?


问:
Queries about commercial products about using freewares libraries
I'm looking at developing some commercial product (sell for money, only binaries, no sourcecodes). I have read up on open source licensing, but I just could not understand if what I want to achieve is possible. Will need some bros to walk me through.

Like I mentioned, I looking forward to create a simple commercial product, I might be looking at using json for communication. I saw quite a number of favorable comments for Jackson JSON.

Is it legally advisable for me to use it's library, but do not distribute my own source code? Or is there any other condition that I have to adhere to before I can sell my product without distributing my own source code? I won't be modifying the Jackson library at all, only calling its method. I definitely have no intention of paying to obtain a separate license to allow me not to distribute my source code.

If this is not feasible, any other json library that I can look at?

ps:I hope that there will not be answers directing me to read up on the license, as I have read, but do not understand the advise legally.

答: LGPL allows linking and distribution for what you want to do.</p>


问:
Biggest mistake you've ever made
Similar to the question I read on Server Fault, what is the biggest mistake you've ever made in an IT related position. Some examples from friends:

I needed to do some work on a production site so I decided to copy over the live database to the beta site. Pretty standard, but when I went to the beta site it was still pulling out-of-date info. OOPS! I had copied the beta database over to the live site! Thank god for backups.

And for me, I created a form for an event that was to be held during a specific time range. Participants would fill out the form for a chance to win, and we would send the event organizers a CSV from the database. I went into the database, and found ONLY 1 ENTRY, MINE. Upon investigating, it appears as though I forgot an auto increment key, and because of the server setup there was no way to recover the lost data.

I am aware this question is similar to ones on Stack Overflow but the ones I found seemed to receive generic answers instead of actual stories :)

What is the biggest coding error/mistake ever…

答: At an internship, I was just learning SQL, performed an update without a where, affecting 17k+ rows instead of 10. Good news was that it was only the dev database. Bad news was that it couldn't be rolled back without the testers losing a lot of work, and a coworker was stuck fixing it for the rest of the day. I felt pretty bad.</p>

ContentLicense: CC BY-SA 2.5

Title: Biggest mistake you've ever made


问:
How to fulfill EASTL license
I'm integrating EASTL into my game programming framework. I did some changes to it since I have my own memory management sub-system and now I'm wondering what I need to do to not break the license under which EASTL was released.

The source code files include the following notice:

```<code>Copyright (C) 2005,2009-2010 Electronic Arts, Inc.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1.  Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
2.  Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.
3.  Neither the name of Electronic Arts, Inc. ("EA") nor the names of
    its contributors may be used to endorse or promote products derived
    from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY ELECTRONIC ARTS AND ITS CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL ELECTRONIC ARTS OR ITS CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
</code>```

Since I will probably be releasing the source code on GitHub at some point, but do not plan on releasing any binaries without source code, can I just add something similar to my own source files and be okay with this? Will something like the following do?

```<code>/*
 * Copyright (c) 2012 Bartlomiej Siwek All rights reserved.
 * Based on EASTL (https://github.com/paulhodge/EASTL) - copyright information follows.
 */

/*
 * Copyright (C) 2005,2009-2010 Electronic Arts, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of Electronic Arts, Inc. ("EA") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY ELECTRONIC ARTS AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL ELECTRONIC ARTS OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
</code>```

P.S. This is a repost of a legal-like question from StackOverflow where it was found off-topic. If this is off-topic here as well, please tell me where I can ask such question?

答:
Your own source files don't require that copyright notice.  Your source files were written by you, not EA.  What that provision is saying is that you are not to redistribute their source files without keeping their copyright/license block on them.  (It's a basic attribution requirement.)

Similarly, when you distribute a binary, you have to distribute something with it that has the license block.  I'd do it like "This product uses EASTL (https://github.com/paulhodge/EASTL), which is licensed under the following terms: <insert blurb here>".

Title: How to fulfill EASTL license


答:
Make clear you are estimating the amount of time it will take, not promising you will get done in that time, and that getting you to lower the number is nothing more than talking you into lying to them.  It won't actually magically make the software get done faster.

Ask them how much good it would do to talk a woman into lowering her estimate for her pregnancy from 9 months to 7 months.

Better yet, get a product manager.  Salesmen will tie your product into knots chasing commissions, because they have little incentive to care about the overall product and every incentive to chase the current sale.


问:
How to Model a simple file-system by UML class diagram
I want to model a file system which contains both files and directories, and directories can contain either files or other directories.

This is what I have reached so far:

In OOSE book, however, a similar model is presented:

Now I have two questions:

I wonder why the author did not use an Interface to represent the abstract type FileSystemElement? Isn't using an interface for this type correct?

As we know, files and directories must have names with similar constraint (e.g. maximum length of 256 characters). Therefore, it would be nice if I model this in the FileSystemElement. But an interface cannot have a abstract attribute, so I have to repeat name attribute in both Directory and File classes. Is there any better workaround for this problem?

答:
The base class approach makes sense because of the problem you raised in your second question. A base class allows you to have such an attribute and don't repeat yourself on validity checks etc.

On the other hand your interface approach makes sense because it offers you more flexibility. Suppose you want to add a third type of FileSystemElement that does not have a name attribute. And maybe this third type lends itself to use a very different base class. But you still want to address all three types from the Directory class. You can't do that with a base class.

So, let's see if we can combine the features. The motto here is separation of concerns.

concern: address all elements of a filesystem in the same way.

concern: Share the name implementation between the Directory and the File class.

We can't do both with one technique but nothing stops us from using both at the same time! Let's make FileSystemElement an interface and let Directory and File implement it. Additionally create a base class (possibly an abstract one) called e.g. NamedFileSystemElement with the desired attribute. Now let Directory  and File inherit from NamedFileSystemElement. See, best of both worlds.


问:
Handling database schema changes when pushing new versions
During times of heavy development, the database schema changes both rapidly and continuously, and by the time our weekly push to the beta build comes around, the schema has changed so much that the only sensible option is to nuke all of the tables I can and copy the new versions from my dev database. Obviously, this isn't going to work once we launch, since nuking production data is a recipe for disaster, so I was wondering what strategies were out there for managing database schema changes from one version/revision to another?

Some I've found or experienced:

Straight nuke-and-dump from one database to another (what I am doing now)

Maintaining an UPDATE.sql file with SQL statements that get run either via script or by hand.

Maintaining an update.php file with a corresponding "db-schema-version" value in the active database

The third option seems to be the most sensible, but there still exists the possibility of a badly constructed SQL query failing mid-script, leaving the database in a half-updated state, necessitating a restoration of a backup.

It seems like a non-issue, but it does happen, since we as a team, we use phpMyAdmin, and I can't seem to even rely on myself remember copying the executed SQL statement to paste into the update.php file. Once you navigate to another page, I have to re-write the SQL statement out by hand, or reverse my change and do it again.

I guess what I am hoping for is a solution that doesn't impact our established development workflow?

答:
Automate. Automate. Automate.

You're on the right track with an explicit DB version number, but I would go a step further and make the code explicitly aware of exactly what schema it expects to work against (e.g. by committing the actual DDL script and having the updater parse it); then at update time you only have to discover the existing scheme via database metadata and INSERT/DROP/ALTER as necessary, no matter from what version to what version you are updating. (You could also keep an explicit version number in the database itself and deliver the entire schema history with the installer so that you don't even need schema discovery.)

Potential syntax errors in the update SQL script are a problem, but you can solve that by verifying that the updater can only produce correct DDL statements. (Formal proofs are almost never worthwhile in enterprise software development - too much effort for too little assurance - but I feel that database integrity is one of the few exceptions: basic SQL isn't a particularly hard language to capture formally, and the benefit of protecting production data is so great that almost any amount of one-time up-front effort is justified, particularly if it has to work for unattended installs,)


答:
The database schema versioning is the way to go - each version has only one change to the database, or at least changes that can be reverted as whole. DBDeploy is a great tool to automate that.

Some things I have learned useful are:

Always test your change locally, and test your code with it, just the ALTER passing is not enough

You need to synchronize which get to do their change first - a simple wiki page where you can "take a number" worked great for my team.

Don't try to fix broken change, add a new counter-change to negate it, it's much painless

Your code depends on that changes - be sure to link the issues in your bug-tracking system with the DB changes. That is very helpful at deploy time.

Include DB changes to your CI - do apply your changes to a CI database on commit. Also, if you have any tests that use a database, run them on commit.

Title: Handling database schema changes when pushing new versions

Body:
During times of heavy development, the database schema changes both rapidly and continuously, and by the time our weekly push to the beta build comes around, the schema has changed so much that the only sensible option is to nuke all of the tables I can and copy the new versions from my dev database. Obviously, this isn't going to work once we launch, since nuking production data is a recipe for disaster, so I was wondering what strategies were out there for managing database schema changes from one version/revision to another?

Some I've found or experienced:

Straight nuke-and-dump from one database to another (what I am doing now)

Maintaining an UPDATE.sql file with SQL statements that get run either via script or by hand.

Maintaining an update.php file with a corresponding "db-schema-version" value in the active database

The third option seems to be the most sensible, but there still exists the possibility of a badly constructed SQL query failing mid-script, leaving the database in a half-updated state, necessitating a restoration of a backup.

It seems like a non-issue, but it does happen, since we as a team, we use phpMyAdmin, and I can't seem to even rely on myself remember copying the executed SQL statement to paste into the update.php file. Once you navigate to another page, I have to re-write the SQL statement out by hand, or reverse my change and do it again.

I guess what I am hoping for is a solution that doesn't impact our established development workflow?


答:
Since you're using phpMyAdmin, then I assume you are also using MySQL.

Take a look at EER Model diagrams in MySQL Workbench. They have been a great help to me in maintaining and updating schemas.

First, you can synchronize the model with a database source. So that changes in the diagram are pushed as ALTER TABLE commands. This allows you to perform your schema changes on the diagram, keep it always up to date while also pushing updates to your development database when needed.

Secondly, you can reverse engineer an EER diagram from a database source. Which can be handy by taking changes on a development database, and updating a production database since it will calculate the differences.

Thirdly, it can be used to assist in created the SQL that should go into your "update.sql" file.

CONS:

Database triggers and constraints are a problem with the synchronize updater. It doesn't seem to know the right order of things. Foreign key constraints often generate errors, but this can be resolved by editing the SQL it generates.

This is not a data migration tool. Any changes that are beyond purely schema will still need custom SQL.


答: Drop a production database by accident instead of a development version. I didn't see what server I was working. Fortunately, the last backup was produced 4 hour ago and the user didn't made a lot of changes on the system, so no big data loss.</p>

Title: Biggest mistake you've ever made

Body:
Similar to the question I read on Server Fault, what is the biggest mistake you've ever made in an IT related position. Some examples from friends:

I needed to do some work on a production site so I decided to copy over the live database to the beta site. Pretty standard, but when I went to the beta site it was still pulling out-of-date info. OOPS! I had copied the beta database over to the live site! Thank god for backups.

And for me, I created a form for an event that was to be held during a specific time range. Participants would fill out the form for a chance to win, and we would send the event organizers a CSV from the database. I went into the database, and found ONLY 1 ENTRY, MINE. Upon investigating, it appears as though I forgot an auto increment key, and because of the server setup there was no way to recover the lost data.

I am aware this question is similar to ones on Stack Overflow but the ones I found seemed to receive generic answers instead of actual stories :)

What is the biggest coding error/mistake ever…

OwnerDisplayName: Ernesto Otiz


问:
Recommendations for teaching junior programmers good coding style
I am a big fan of good coding style, producing clean, clear code that runs well and is easy to use and integrate into larger systems. I believe that we programmers are essentially craftspeople who should take pride in our work, every line. I am not fond of code that is inconsistently formatted, cluttered with commented out experimental code, and rife with unhelpful or misleading function and variable names. But I sometimes find it hard to argue with code like this that basically works.

If you think that coding style matters, I am looking for recommendations for ways of teaching good, professional coding style to the junior programmers under me. I want them to take pride in their work, but my concern is that they appear to become satisfied when their code just barely works, and seem to have no interest in producing what professionals like me would consider professional code. On the other hand, if you think coding style is not particularly valuable, I welcome your comments and am open to reconsidering my standards and tolerances.

I know the usual arguments in favor of good code: comprehensibility, ease of maintenance, etc., but I would also like to hear some rebuttals to arguments like "it works, what more do you want?"

In our industry we can use the compiler to hide a multitude of sins. Clean code and messy code can both lead to identically functioning programs, so does cleanliness matter, and if so, why?

[While there are several existing questions on coding style, I didn't find any that related to teaching methods and ways to instill good coding style in junior programmers.]

答:
Clean code and messy code can both lead to identically functioning programs, so does cleanliness matter, and if so, why?

A difference between clean and messy code is so huge :

changing a messy code is always a daunting task, because usually it has no a safe net called unit tests

messy code tend to have huge and very complex functions and classes. Trying to understand them is pointless and very difficult

messy code usually has copy/pasted code parts, increasing the complexity further

On the other hand, having a clean code, everyone in the team can easily understand the logic behind, and add new features without much efforts.


问:
Should software developers be skilled at software design?
There is an analysis and design phase of the software development life cycle. Should software developers be skilled enough for carrying out the work performed during this phase, such as drawing workflow diagrams, data flow diagrams, ERDs, UML, and other models?

I have seen some cases where developers can code very well given a clear understanding of what is required. However, when they are asked to design a system, they stagger at times.

答:
developers can code very well given a clear understanding of what is
  required.

Even if a user or business analyst can provide specifics on the application requirements, this doesn't tell a programmer how to build it. The ability to design is going to be needed at some level. I agree with the others that the formal use of diagrams isn't a requirement.

A good chef may not be able to write a cook book or perform on a cooking show, but that doesn't mean they ask someone else for the recipes either.


答:
Totally fair provided you tell them up front how much time is required for the interview. If someone doesn't want to write your test then you don't want to hire them. I've had longer tests before and I personally appreciated it. One in particular was difficult and longer than the time allotted but was an excellent measure of the resourcefulness, priority setting, and problem solving skills of the candidates. That employer had very highly skilled developers working there.

I think you are on the right track with what you are looking for in a candidate. All too often a resume lists a million things that the candidate has read about but doesn't actually know. Sometimes you can weed these things out in a regular interview, but if you want to know if someone can actually get something done, make them do it.

Just make sure the expectations are clear and you are testing the skills that are most important for the job.

In your scenario I might also be concerned with how well the candidate understands HTML, javascript and layout.


问:
Does this implementation of the state pattern make sense?
I have the task to implement the state pattern in one of my classes. The assignment referenced a suggested implementation, and upon reviewing that implementation I was confused since I believed it to be nonsensical for most applications and frankly simply bad from a design point of view, since it completely dismisses some very basic design principles of software code.

This is the class diagram of the suggested implementation:

I wonder: What is the use of this implementation? It (imo) clearly violates the two main design principles of software engineering: Make things easily maintainable, and easily extensible.

In my eyes, this implementation has zero easy extensibility(you have to change the source of at least two classes, for example, to implement a new state that you forgot about when first implementing it). The coupling between this code and client code seems to be huge. If you remove anything in this pattern, all client code will break. If you want to add anything, you have to change all client code in order to adapt, for example, a new state, because new states can only be entered via the enter() method of the concrete state, or by directing injecting them into the Controller using the changeState() method.

As a bonus, you can only have one garage door in the entire world, since the states are practically singletons. The enter() method in the concrete states was given as this:

```<code>public static State enter(Controller c) {
if(m_instance == null) m_instance = new <<concreteStateName>>(c);
return m_instance;
}
</code>```

Or you can have multiple garage doors, which all open simultaneously if you open one.

Why would you put all methods in the abstract State class? Where's the polymorpy? Why do concrete states have either empty or exception throwing versions of methods that have nothing to do with their state (for example, the resulting interface of Opened will have a "lock()" method, even though you can't directly lock the garage door when it's open. You have to close it first). Why not choose a single method and implement it differently in the concrete States, making the thing easily extensible again?

It is also (again, as far as I can see) not really maintainable without a lot of troubles. What if you, after a couple of months of using the garage, decide that one state is in fact not only obsolete but wrong? You're going to have to take it out, and the according method in State() with it, breaking the entire code base that uses this implementation. This is a garage door with four states. I wouldn't want to work on that thing if it had any more states.

The situation gets more confusing when I look around the internet: The pattern actually seems to be implemented exactly this way a lot of times (for example it is implemented like this way in our national Wikipedia (German)).

The actual question: Am I missing anything or is this simply bad? Since this is so widespread, I'm thinking that I might be missing something obvious here.

答:
an easier way would be to have the state methods return the state after the operation, and combine all methods in the abstract State into a generic procesInput(data,controller): state

this way states don't need to know what controller they are linked to (allowing them to be true singletons)

and now each state then only needs to know what next states are possible according to what input


问:
C# open-source framework for multithreaded task management
I have an API library for C# that provides flexible multithreaded task management of objects on task bases. The library was developed extensively for a project that was later cancelled by the client. I received the legal rights to the library, and the client doesn't care what I do with it now.

I don't know what to do with this source code.

Can you please explain to me, what the steps are in taking source code and making it a successful open source project? How do you attract developers? How will people know the library exists?

EDIT:

The reason I ask this question, is to bring the source code to an open source state. I'll be adding a full set of unit tests, documentation, examples, etc.. etc..

That represents more investment of my time, and if there is no pay off "i.e. no one uses it". Then what's the point?

答:
To get started is actually pretty easy, after that, not so much...

Step 1 - Choose a License

OSS licenses are like... noses, everybody's got one and it's important to choose one that will foster progress. If you have questions about the nuances of a particular license you'll probably want to take a look at The Open Source Initiative website. You can find the legalese for the majority of the most common OSS licenses there and the comments are a good place to figure out the nuances.

The most common licenses in use are GPL, MIT, BSD, Apache, etc... All of them ensure freedom to work on the source code but many have terms about how they can be extended and/or used in commercial software. IMHO, the two extremes of the 'freedom' scale are the GPL and MIT licenses.

GPL:

The upside is that it states that any open source included in a project needs to be made freely available to the public. That means, when Open Suse releases a new version with their proprietary extensions, they can sell you one version in a box but they have to have a link to the open source code buried somewhere on their site.

This is the one people are referring to when they accuse OSS of being 'viral' in nature. That's because if you include GPL code into your own personal project, your project has to either use the GPL or a more 'copy-left' (ie liberal) license or your violating the terms.

Richard Stallman basically created it as a response to all of his super-smart friends walking away with 'open source' code they had been working on to make massive amounts of money in the commercial world. I like to call it the 'Stickin it to the man, man...' license or 'Revenge of the Neckbearders'.

GPL is largely popular because it has become the ideological platform for OSS evangelists. Many people initially adopt it because they're not sure where to look for an alternative or they don't read the terms closely enough. Some choose it reluctantly but hold it at arms length.

If you're looking for some cheap entertainment, grab some popcorn and Google 'Linus Torvalds GPLv3'. Linus is known to be vocal and have strong opinions about things that piss him off. This topic just happens to be one of them.

MIT:

On the other end of the scale is the MIT license. It's the Ayn Rand of OSS licenses. It basically states that you can do whatever you want with the code as long as you maintain that the code is licensed under MIT. No requirements to provide source code, prevent extending the code, making money, nothing.

It basically says, 'I made some useful code, you can make use of it without worrying about me suing you.' This is my personal favorite because I don't like to have to fret about legalese.

LGPL:

If you're designing an API, this is the best of both worlds. It's GPL for libraries. Basically, they have to share the source code but they can include the code as a module/dll without affecting the license of their project. It also maintains that you can't change/extend the code without offering those changes back to the project. It may seem like a dickish clause but it prevents people from providing wholesale forks of your codebase and diluting your userbase.

Step 2 - Setup Source Control

Due to the geographic problems with OSS development, it's ridiculous develop without some sort of source control. The key thing to consider initially is how you'll accept code from others. Some are tempted to give write access to other developers but don't consider why that may be a bad idea.

Think of it like this. Have you ever built a sand castle as a kit only to have some little prick stomp on it as soon as you walked away. That's what you want to protect your project from.

With a CVCS the workflow is simple. Accept change patches and incorporate them as a commit. DVCS, is more complex but a lot more useful for OSS because anybody can commit to their personal repository. Patches are messy and inconvenient. Project members that want to do more extensive work will usually setup their own repository and request the manager to pull the changes in as a branch for review directly. What you choose depends on your preferences.

Step 3 - Choosing a Host

There are plenty of hosts. It usually depends on what you're trying to do with your project.

GitHub:

If you want something more developer-centric with a massive community where everybody will be forking the hell out of your code and making changes. GitHub really accelerates the development/improvement of a codebase but it provides little/nothing for non-developer users. If you want your code to be hacked on a lot and you're comfortable with using Git, this is the way to go.

SourceForge:

If you want something with a more stable project-based development model. They have everything you'd expect to foster good developer/user interaction. Such as, website, forums, mailing lists, etc...

This by no means an exhaustive list. But there are plenty places on StackOverflow, Programmers and Wikipedia where you can find more detailed info.

In fact steps 1-3 all go together because they hosting will dictate what types of source control and licenses you can use.

Step 4 - Profit

Seriously though, building a community around an open source project is extremely difficult. Unless your code magically cures Cancer/AIDS/Malaria and can increase the size of a certain member, people will most likely ignore it. Like everywhere else, it doesn't matter how brilliant and ground-breaking your code is, if you can't 'sell' it to people, they're not going to waste their effort to try it out.

What you need is a strong demonstration of your code's use. Not just a fancy write-up but an actual working demonstration that people can play with on their own.

Even with earth shattering demos, nobody will use it if they're not aware of it. That means you need to actively promote your project, or find others interested enough to do it for you.

Lastly, you need to zero in on the domain your project is addressing. Multi-threaded task management sounds kind of generic. Are you addressing OS tasks or a queue of program tasks that need to be executed? What does your interface/API consist of? Can you load tasks over a network?

And the million dollar question, 'Are there other projects that accomplish what yours does, but have a large community and/or are better implemented.' Just because you had a 'really great idea' doesn't mean there weren't 100 other people who had the exact same 'really great idea'.

You can get away with having no community to start if your code is better but don't expect everybody to jump ship right away. OSS is like trying to create a business with absolutely no marketing. Creating good documentation and 'spreading the word' is as important or more important than writing the actual code.

Aside:

I like to think of open source projects as any other good idea. Initially, you have a moment of enlightenment/clarity where you could see your idea applied to everything. It's so good that you'd be doing a disservice by not sharing it.

I'm pretty jaded but every time I hear people talk about a good idea like a fairy farted magical dust on them I can't help but to snicker. The idea that you can have a good idea that magically transforms into billions of dollars and supermodel girls throwing themselves at you is so ingrained into our consciousness that many people accept it as canon.

It's really common to hear that most Open Source projects were created to 'scratch and itch' because the authors who originally created them did so to provide a functionality or quality that they couldn't find anywhere else. They kept working on it because they needed it. They stayed after they didn't need it anymore because they liked the positive feedback they received from the community. And it survived after they left because the community valued it enough not to let it die.

The greatest danger to new Open Source projects now is the sheer number of dead projects that still exits on the web. I'm talking about one-offs where the developer spent a few weeks hacking, didn't finish building a working implementation, and haven't touched the code in 5+ years. I get the concept that 'the internet never forgets' but finding good (ie active) open source projects that aren't abandoned tomorrow gets herder every day. Don't be disappointed if people don't immediately adopt your code. If they know what they're doing, they'll check when the project was created and how active development has been before they decide to start actively contributing code. Nobody likes to ride a sinking ship.

If you have a project that you like working on, put it out there, it doesn't hurt to try. Like all good thing it requires hard work and determination, supermodel groupies notwithstanding.


答:
Here's the nitty-gritty on LGPL

You can link to (ie dll, module import) a LGPL module without requiring you to distribute the source code for that module.

You are not allowed to change or extend that code without submitting those changes back to the project. That means you can derive functionality from (ie inherit) but not extend the actual code internally (ie anything that would require a re-compile).

You also have to make the license visible and present to indicate that the library falls under that license when you distribute your software.

If it was GPL

The project that uses GPL code needs to make that code publicly available with the license present. The code can also only be used on a project that uses a similar or more copy-left (ie liberal) licensing scheme.

Both can be sold for money and/or paired with software that is sold for money as long as that software meets the terms.

Title: Queries about commercial products about using freewares libraries

Body:
I'm looking at developing some commercial product (sell for money, only binaries, no sourcecodes). I have read up on open source licensing, but I just could not understand if what I want to achieve is possible. Will need some bros to walk me through.

Like I mentioned, I looking forward to create a simple commercial product, I might be looking at using json for communication. I saw quite a number of favorable comments for Jackson JSON.

Is it legally advisable for me to use it's library, but do not distribute my own source code? Or is there any other condition that I have to adhere to before I can sell my product without distributing my own source code? I won't be modifying the Jackson library at all, only calling its method. I definitely have no intention of paying to obtain a separate license to allow me not to distribute my source code.

If this is not feasible, any other json library that I can look at?

ps:I hope that there will not be answers directing me to read up on the license, as I have read, but do not understand the advise legally.


答:
Do you want to give the same assignment to all candidates. You should be able to get to a shortlist of one. You assignment / test, is  there to show the candidate can not only talk the talk but can also walk the walk.

What I would do is bring the candidate back, inform him that the is on a short list (Don't say of 1), put him with one, or two of his potential (day to day) co workers, and get the "team" to solve the problem. 1-2 hours will be more than enough for the team to report back to you that they think he/she is good enough, a leader or follower, a doer or a slacker, competent or .... etc.

You are a small company, and nothing will destroy you organization faster than  dysfunctional personal relationships, ladder climbers, backstabbers and workplace psychopaths (about 1 in 20 are).  Focus on if the candidate has the right attitude, if he technically average and does, he will out perform 90% of candidates who a experts. Programming may be a solo task, but software development requires a strong team - and you are looking for a team lead as well as a technical lead.


答:
If you feel your estimates are accurate and history reflects that use this.

When they say you have XX time, revise your estimate taking out features until it gets down to this time.  Don't take out testing.

Then it is a negotiation about features and time, not just time, which history says you cannot change. If they insist on negating over time, start negoting bonuses for hitting said time (if you team is willing to work the overtime to get there).  Say we can make the time you want, but it is going cost you a $1000 bonus to get there

Remind them that software development is like a factory and the factory is capable of producing X in Y amount of time.  Goes to the bonus again, you can work overtime, but it is going to cost.  Don't call it overtime either or they will just work you to death.  It needs to be written down as well.  X product by Y date for Z bonus.  You might also insist on a day off afterwards since the team will be burned out after that.  Also have in the contract that adding features or bug fixes over X% of normal time will add time to schedule.

You can't change the time, only take out features.


答:
Well, I'd hope that in order to commit to a piece of work, it's understood you and Sales need to agree meeting the requirements is worth the value.

Emphasise that unless you and Sales can agree, they can't make the sale and the job does not happen, so either you need to agree a counter-offer for the customer (smaller spec, longer timeframe, etc.), or else they need to find another customer.

There's no point signing a contract with a customer that you know you cannot fulfil, it will just end up taking up everyone's time and you risk losing the customer and others, and may not even get the money for the job.


问:
MVC, Java Design Pratices, and Flaws of java.util.Observable and java.util.Observer
I am planning learning Model-View-Controller (MVC) development using Java. While reading I came across a post which mentions java.util.Observer and java.util.Observable for MVC development.

As I never heard of it before, upon more googling I came across this SO post, which discusses some design flaw with the above-mentioned classes.

My question now has three parts

Are these classes still used in Industry for MVC development (except Eclipse as mentioned in the SO post)?

What are the flaws with these classes and why/why not should one use them?

Are there some ways MVC projects are developed in industry? (would be
nice if you can answer this in general terms, NOT looking for
answers like SPRING :P ) [edit: both for desktop and web applications]

答:
I will answer only about web development.

Apart from the rare cases when you use JavaFX, you usually don't have Java code running on the client machine. This implies that you can't implement the Observer interface. Usually your view is HTML and javascript.

A recent trend in web development is using MVC implementations written in Javascript, like JavascriptMVC, Backbone.js, Knockout.js, and many others. This goes even more far away from those interfaces.

Also recently, Google proposed the usage of the Model-View-Presenter pattern, that is a modification of the MVC.


答:
I like the fact that you added an association between the file and the directory (although you did not specify multiplicity). Now as per your questions:

I wonder why the author did not use an Interface to represent the abstract type FileSystemElement? Isn't using an interface for this type correct?

You are correct, an interface could have been used. However, it is not the best choice. As you know, an Interface does not allow you to add implementation code to its methods. You better use a class instead of an interface because you can include implementation details of the methods you see common between the sub-classes. In this case, you may want to share the validation of the name property for example.

As we know, files and directories must have names with similar constraint (e.g. maximum length of 256 characters). Therefore, it would be nice if I model this in the FileSystemElement. But an interface cannot have a abstract attribute, so I have to repeat name attribute in both Directory and File classes. Is there any better workaround for this problem?

In c# you could define zero, one or more properties as part of an interface, for example:

```<code>public interface IFileSysElement
{
    // Property declaration:
    string ElementName
    {
        get;
        set;
    }
...
}
</code>```

So it is not a problem really.

The issue I see with the book's model is that having an association between a class and a sub class is cumbersome (to me). Another point to consider is the fact that the FileSystemElement name is the relative name (e.g. myFile.txt). You need another property or method to construct or retrieve the full file name for  (e.g. C:\Temp\myFile.txt). This is the 'business identifier' for either classes.

Title: How to Model a simple file-system by UML class diagram

Body:
I want to model a file system which contains both files and directories, and directories can contain either files or other directories.

This is what I have reached so far:

In OOSE book, however, a similar model is presented:

Now I have two questions:

I wonder why the author did not use an Interface to represent the abstract type FileSystemElement? Isn't using an interface for this type correct?

As we know, files and directories must have names with similar constraint (e.g. maximum length of 256 characters). Therefore, it would be nice if I model this in the FileSystemElement. But an interface cannot have a abstract attribute, so I have to repeat name attribute in both Directory and File classes. Is there any better workaround for this problem?

Body:
I like the fact that you added an association between the file and the directory (although you did not specify multiplicity). Now as per your questions:

I wonder why the author did not use an Interface to represent the abstract type FileSystemElement? Isn't using an interface for this type correct?

You are correct, an interface could have been used. However, it is not the best choice. As you know, an Interface does not allow you to add implementation code to its methods. You better use a class instead of an interface because you can include implementation details of the methods you see common between the sub-classes. In this case, you may want to share the validation of the name property for example.

As we know, files and directories must have names with similar constraint (e.g. maximum length of 256 characters). Therefore, it would be nice if I model this in the FileSystemElement. But an interface cannot have a abstract attribute, so I have to repeat name attribute in both Directory and File classes. Is there any better workaround for this problem?

In c# you could define zero, one or more properties as part of an interface, for example:

public interface IFileSysElement
{
    // Property declaration:
    string ElementName
    {
        get;
        set;
    }
...
}

So it is not a problem really.

The issue I see with the book's model is that having an association between a class and a sub class is cumbersome (to me). Another point to consider is the fact that the FileSystemElement name is the relative name (e.g. myFile.txt). You need another property or method to construct or retrieve the full file name for  (e.g. C:\Temp\myFile.txt). This is the 'business identifier' for either classes.


问:
ASP.NET MVC vs WCF for REST API + Webpage usage
I think the discussion for programmatic service oriented usage vs human interaction is clear.

But if I were to create an application that makes use of both a programmatic API and a website that makes use of the data connected by the same API, does it lean the favour towards using only ASP.NET?

How easy is it to integrate ASP.NET and WCF to work on the same application?

答:
I think the current guidence is to use MVC Web API instead of WCF for REST.  http://stephenwalther.com/blog/archive/2012/03/05/introduction-to-the-asp-net-web-api.aspx

The development model is pretty close and you bypass the sometimes nasty configuration of WCF.


问:
MonoTouch vs Objective-C for iPhone/iPod/iPad development
For someone with .Net experience and wanting to develop for iPhone/iPod/iPad, is it worth learning Objective-C? Is MonoTouch a good alternative? What are some of the trade-offs when using MonoTouch vs coding in Objective-C?</p>

答:
There's an article about one .NET devs experience in moving his skill set to iOS.

This blog post describes my experience of learning how to write iOS
  software, after having spent many years exclusively in the world of
  .NET development. It provides warnings, suggestions, and tips for
  others who are interested in learning iOS development. The post ends
  with a qualitative comparison of programming in WPF and iOS.


问:
How to improve the training of students regarding maintainability?
Maintainability is a major stake of professional software development. Indeed, maintenance is nearly always the longest part of a software life cycle, as it lasts from the project release until basically the end of times.

Moreover, projects being in maintenance represent a large majority of the overall number of projects. According to http://www.vlegaci.com/298/interesting-statistics-%E2%80%93-numbers-of-programmers-in-maintenance-vs-development/, the proportion of projects being in maintenance is about 2/3.

I recently came across this question, where the guy looks pretty surprised discovering that his job is mainly about maintenance. I then decided to open a discussion (french) on the main site of the French community of software development professionals (http://www.developpez.com/). The discussion is entitled "Are students well-enough trained to the reality of professional software development?" and is mainly about maintainability. It was pointed out that, at least in France, people are not well-enough prepared to face maintenance in both aspects of it:

maintain existing code

make maintainable code

My question here echoes to this discussion and aims at finding a good way to teach maintainability.

How can we teach maintainability?

What kind of exercise would you suggest?

If you have been well-trained regarding maintainability, what particular kind of courses did you take?

[edit]
After some misunderstanding, I think I must clarify my question.
As a project leader and software developer, I often work with trainees or freshly graduated students. I once was freshly graduated myself. The thing is that students are usually unfamiliar with principles such as SOLID that increase the maintainability of a project. We often end up having important difficulties making projects evolve (low maintainability).
What I am looking for here is a concrete academical example of successful teaching about the importance of maintainability and how to make better code regarding this particular point; or possible suggestions to improve the way students are trained.

答:
I think the best way to learn these sort of skills is by doing code reviews and pair programmings. During code reviews, experienced staff can point out how to make code more maintainable (typically by making it more readable) and justify why certain choices can create more maintainable code.

Pair programming is an even better way to teach this sort of thing, because it gives less experienced staff direct experience in maintaining code with someone who already knows how to do it well.

There are also some great books that you can read about writting clean, maintainable code. Clean Code comes to mind.

It's hard to get this experience through academia since students rarely modify large code bases. Most of these skill will come from learning on the job, and code reviews and pair programming can really facilitate this learning.


答:
Good code = Less maintenance and Easy to enhance / add features.

Bad code = maintenance nightmare

Basically we have to get the points across to the students that "whenever there is a crappy code in a project, a new developer who is going to join the company because the original author of the code is going to suffer and how the software is impacted."

So one of the best way to teach the student about software maintenance is to show the example of both  good code and bad code and ask them to add a feature and then teach them that writing a good code is not only for self satisfaction but for making it easy for the folks who are going to maintain the code.

Exercise:

1) Have a pre-written bad code (e.g)  duplicate code , a method say "to calculate the mortgage payment" is written in 9 places in a project.

Ask the student to enhance the feature to "add 1.2% surcharge to all mortgage payments".

Now the student will see the pain of locating and fixing the code in all 9 places. There are many chances he could not locate all 9 places the "mortgage payment" is calculated.

2) Now show the Good code which has this method which calculates the mortgage payment in one and only place. demonstrate to the student that how easy to enhance a well written code and explain him how does it enhance the maintainability of the code/project.

BTW, I loved your approach of exposing the students to maintainability of the software.

Title: How to improve the training of students regarding maintainability?

Body:
Maintainability is a major stake of professional software development. Indeed, maintenance is nearly always the longest part of a software life cycle, as it lasts from the project release until basically the end of times.

Moreover, projects being in maintenance represent a large majority of the overall number of projects. According to http://www.vlegaci.com/298/interesting-statistics-%E2%80%93-numbers-of-programmers-in-maintenance-vs-development/, the proportion of projects being in maintenance is about 2/3.

I recently came across this question, where the guy looks pretty surprised discovering that his job is mainly about maintenance. I then decided to open a discussion (french) on the main site of the French community of software development professionals (http://www.developpez.com/). The discussion is entitled "Are students well-enough trained to the reality of professional software development?" and is mainly about maintainability. It was pointed out that, at least in France, people are not well-enough prepared to face maintenance in both aspects of it:

maintain existing code

make maintainable code

My question here echoes to this discussion and aims at finding a good way to teach maintainability.

How can we teach maintainability?

What kind of exercise would you suggest?

If you have been well-trained regarding maintainability, what particular kind of courses did you take?

[edit]
After some misunderstanding, I think I must clarify my question.
As a project leader and software developer, I often work with trainees or freshly graduated students. I once was freshly graduated myself. The thing is that students are usually unfamiliar with principles such as SOLID that increase the maintainability of a project. We often end up having important difficulties making projects evolve (low maintainability).
What I am looking for here is a concrete academical example of successful teaching about the importance of maintainability and how to make better code regarding this particular point; or possible suggestions to improve the way students are trained.


答:
Disclaimer: I just got my CS degree. I'm not a teacher.

This may sound obvious, but I think the best way to teach code maintenance is to have students perform code maintenance. Here's what I would do:

Take a moderately complex problem, and two implementations that are semantically identical, but one is much more maintainable than the other.

Request a number of changes/feature additions that are much easier to implement on the better code base. One half of the students have to implement these on the more maintainable code base, the other half on the less maintainable one.

For the sake of fairness, you may want to repeat this exercise with the roles reversed.

Compare the average number of successfully implemented changes between the good and bad code bases, and the time spent on implementing them. Have students share their experiences, air their grievances, and just generally talk about the work they've done.

The idea is to not only have students work with someone else's code, but to also have them develop an appreciation for maintainable code that will hopefully improve their design skills.


问:
Is use of finally clause for doing work after return bad style/dangerous?
As part of writing an Iterator, I found myself writing the following piece of code (stripping error handling)

```<code>public T next() {
  try {
    return next;
  } finally {
    next = fetcher.fetchNext(next);
  }
}
</code>```

finding it slightly easier to read than

```<code>public T next() {
  T tmp = next;
  next = fetcher.fetchNext(next);
  return tmp;
}
</code>```

I know it's a simple example, where the difference in readability may not be that overwhelming, but I'm interested in the general opinion as to whether it is bad to use try-finally in cases like this where there are no exceptions involved, or if it is actually preferred when it simplifies the code.

If it's bad: why? Style, performance, pitfalls, ...?

Conclusion
Thanks you all your answers! I guess the conclusion (at least for me) is that the first example might have been more readable if it was a common pattern, but that it isn't. Therefore the confusion introduced by using a construct outside of it's purpose, along with possibly obfuscated exception flow, will outweigh any simplifications.

答:
That would depend on the purpose of the code inside the finally block. The canonical example is closing a stream after reading/writing from it, some sort of "cleanup" that must be always done. Restoring an object (in this case an iterator) to a valid state IMHO also counts as cleanup, so I see no problem here. If OTOH you were using return as soon as your return value was found, and adding a lot of unrelated code in the finally block, then it would obscure the purpose and make it all less understandable.

I don't see any problem in using it when "there are no exceptions involved". It's very common to use try...finally without a catch when the code can only throw RuntimeException and you don't plan on handling them. Sometimes, the finally is just a safeguard, and you know for the logic of your program that no exception will ever be thrown (the classic "this should never happen" condition).

Pitfalls: any exception raised inside the try block will make the finally bock run. That can put you in an inconsistent state. So, if your return statement were something like:

```<code>return preProcess(next);
</code>```

and this code raised an exception, fetchNext would still run. OTOH if you coded it like:

```<code>T ret = preProcess(next);
next = fetcher.fetchNext(next);
return ret;
</code>```

then it would not run. I know you're assuming the try code can never raise any exception, but for cases more complex than this how can you be sure? If your iterator were a long-lived object, that would continue existing even if an unrecoverable error happened in the current thread, than it would be important to keep it in a valid state at all times. Otherwise, it doesn't really matter much...

Performance: it would be interesting to decompile such code to see how it works under the hood, but I don't know enough of the JVM to even take a good guess... Exceptions are usually "exceptional", so the code that handles them don't need to be optimized for speed (hence the advice to never use exceptions in the normal control flow of your programs), but I dunno about finally.

Body:
That would depend on the purpose of the code inside the finally block. The canonical example is closing a stream after reading/writing from it, some sort of "cleanup" that must be always done. Restoring an object (in this case an iterator) to a valid state IMHO also counts as cleanup, so I see no problem here. If OTOH you were using return as soon as your return value was found, and adding a lot of unrelated code in the finally block, then it would obscure the purpose and make it all less understandable.

I don't see any problem in using it when "there are no exceptions involved". It's very common to use try...finally without a catch when the code can only throw RuntimeException and you don't plan on handling them. Sometimes, the finally is just a safeguard, and you know for the logic of your program that no exception will ever be thrown (the classic "this should never happen" condition).

Pitfalls: any exception raised inside the try block will make the finally bock run. That can put you in an inconsistent state. So, if your return statement were something like:

return preProcess(next);

and this code raised an exception, fetchNext would still run. OTOH if you coded it like:

T ret = preProcess(next);
next = fetcher.fetchNext(next);
return ret;

then it would not run. I know you're assuming the try code can never raise any exception, but for cases more complex than this how can you be sure? If your iterator were a long-lived object, that would continue existing even if an unrecoverable error happened in the current thread, than it would be important to keep it in a valid state at all times. Otherwise, it doesn't really matter much...

Performance: it would be interesting to decompile such code to see how it works under the hood, but I don't know enough of the JVM to even take a good guess... Exceptions are usually "exceptional", so the code that handles them don't need to be optimized for speed (hence the advice to never use exceptions in the normal control flow of your programs), but I dunno about finally.


答:
Personally, I'd give a thought to the idea of command query separation.  When you get right down to it, next() has two purposes: the advertised purpose of retrieving the element next, and the hidden side effect of mutating the internal state of next.  So, what you're doing is performing the advertised purpose in the body of the method and then tacking on a hidden side effect in a finally clause, which seems... awkward, though not 'wrong', exactly.

What it really boils down to is how understandable the code is, I'd say, and in this case the answer is "meh".  You're "trying" a simple return statement and then executing a hidden side effect in a code block that's supposed to be for fail-safe error recovery.  What you're doing is 'clever', and 'clever' code often induces maintainers to mumble, "what the... oh, I think I get it."  Better for people reading your code to mumble "yep, uh-huh, makes sense, yes..."

So, what if you separated state mutation from accessor calls?  I'd imagine the readability issue you're concerned with becomes moot, but I don't know how that affects your broader abstraction.  Something to consider, anyway.

Title: Is use of finally clause for doing work after return bad style/dangerous?

Body:
As part of writing an Iterator, I found myself writing the following piece of code (stripping error handling)

```<code>public T next() {
  try {
    return next;
  } finally {
    next = fetcher.fetchNext(next);
  }
}
</code>```

finding it slightly easier to read than

```<code>public T next() {
  T tmp = next;
  next = fetcher.fetchNext(next);
  return tmp;
}
</code>```

I know it's a simple example, where the difference in readability may not be that overwhelming, but I'm interested in the general opinion as to whether it is bad to use try-finally in cases like this where there are no exceptions involved, or if it is actually preferred when it simplifies the code.

If it's bad: why? Style, performance, pitfalls, ...?

Conclusion
Thanks you all your answers! I guess the conclusion (at least for me) is that the first example might have been more readable if it was a common pattern, but that it isn't. Therefore the confusion introduced by using a construct outside of it's purpose, along with possibly obfuscated exception flow, will outweigh any simplifications.


答:
Purely from a style standpoint, I think these three lines:

```<code>T current = next;
next = fetcher.getNext();
return current;
</code>```

... are both more obvious and shorter than a try/finally block. Since you're not expecting any exceptions to be thrown, using a try block is just going to confuse people.

Body:
Purely from a style standpoint, I think these three lines:

T current = next;
next = fetcher.getNext();
return current;

... are both more obvious and shorter than a try/finally block. Since you're not expecting any exceptions to be thrown, using a try block is just going to confuse people.


问:
Is it inefficient to concatenate strings one at a time?
I recall back from my days of programming in C that when two strings are joined, the OS must allocate memory for the joined string, then the program can copy all the string text over to the new area in memory, then the old memory must manually be released. So if this is done multiple times as in the case of joining a list, the OS has to constantly allocate more and more memory, just to have it released after the next concatenation. A much better way to do this in C would be to determine the total size of the combined strings and allocate the necessary memory for the entire joined list of strings.

Now in modern programming languages (C# for instance), I commonly see the contents of collections being joined together by iterating through the collection and adding all the strings, one at a time, to a single string reference. Is this not inefficient, even with modern computing power?

答: Joel wrote a great article on this subject a while back.  As some others have pointed, it is heavily dependent on the language.  Because of the way strings are implemented in C (zero terminated, with no length field), the standard strcat library routine is very inefficient.  Joel presents an alternative with just a minor change that is much more efficient.</p>


问:
how to structure MVC models and ORM models
I have some trouble getting a good folder structure in my project and i would like to know what other ways i could use to structure my files.

I'm currently working in an MVC sturctured folder.

```<code>www/
  Controllers/
  Models/
  Views/
</code>```

Nothing special so far. But i'm also using an ORM system. With it i can easily get an 'object' from my database like:

```<code>ORM::load('table');
</code>```

Now this sort of code should reside in a Model right? So i'd get something like this:

```<code><?php
class userModel
{
    public function getAllUsers ( )
    {
        return ORM::load('table');
    }

    public function getUserById ( $id )
    {
        return ORM::load('table', 'userid=?', array($id));
    }
}
?>
</code>```

Looks good so far in my opinion... But there's one more thing. I can also specify a 'model' when using the ORM system. With this model i can basically set up validation rules. Like so:

```<code>ORM::withModel('authModel');
</code>```

This lets the ORM know that before it adds a new row (or updates an existing one) to the DB, that it should check the following model first for validation rules.

```<code><?php
class authModel //Or maybe authValidation??
{
    // Method gets automatically triggered when an update is done with the ORM
    public function onUpdate ( $obj )
    {
        if ( $obj->username == '' )
            throw new \Exception('No username');
    }

    public function onInsert ( $obj )
    {
        // Validations here too.
    }
}
?>
</code>```

Now the problem is, is that i have 2 sorts of models. One where i basically use getters/setters to get and store data to the database (from my controller to my model).

And i have another model in which validation rules are set... I don't want to mix both in the same folder. So i must come up with another structure for this. Something like:

```<code>www/
  Controllers/
  Models/
    Repositories/
    Entities/
  Views/
</code>```

It's just that my model isn't a real 'repository', since it doesn't store any objects in the repo class and doesn't have a commit() method or anything like that.

I also can't store the 2nd model (for validations) in the Entities folder, because they're not Entities at all...

Any idea how i should structure this..??

答:
I'm slightly confused at the first question. They're actually working with data retrieval and storage, but they don't commit data anywhere? Or are you saying they don't actually store an object inside of the class so you shouldn't call them a Repository? If it's because they don't actually store an object you could rename the directory to DataAccess or something similar.

If the files inside of the Entities directory are only doing validation you could rename that to Validation or ValidationRules.

I hope that helped you a bit, but really as long as the name of the directory accurately describes what the files inside of it do you'll be fine.


答:
There are different approaches regarding to the structure, and decision is made based on how much abstraction you want.

If you want to separate the validation and data model classes, you can put the data classes in Entity directory and validation classes under Validation directory, both under Model directory.

You can put the search methods under Repository directory if you are using a separate repository class. Or you can combine it with the data class.

Different frameworks and different ORM systems have different conventions. You may want to check the framework and ORM documentation regarding best practices.

Title: how to structure MVC models and ORM models

Body:
I have some trouble getting a good folder structure in my project and i would like to know what other ways i could use to structure my files.

I'm currently working in an MVC sturctured folder.

```<code>www/
  Controllers/
  Models/
  Views/
</code>```

Nothing special so far. But i'm also using an ORM system. With it i can easily get an 'object' from my database like:

```<code>ORM::load('table');
</code>```

Now this sort of code should reside in a Model right? So i'd get something like this:

```<code><?php
class userModel
{
    public function getAllUsers ( )
    {
        return ORM::load('table');
    }

    public function getUserById ( $id )
    {
        return ORM::load('table', 'userid=?', array($id));
    }
}
?>
</code>```

Looks good so far in my opinion... But there's one more thing. I can also specify a 'model' when using the ORM system. With this model i can basically set up validation rules. Like so:

```<code>ORM::withModel('authModel');
</code>```

This lets the ORM know that before it adds a new row (or updates an existing one) to the DB, that it should check the following model first for validation rules.

```<code><?php
class authModel //Or maybe authValidation??
{
    // Method gets automatically triggered when an update is done with the ORM
    public function onUpdate ( $obj )
    {
        if ( $obj->username == '' )
            throw new \Exception('No username');
    }

    public function onInsert ( $obj )
    {
        // Validations here too.
    }
}
?>
</code>```

Now the problem is, is that i have 2 sorts of models. One where i basically use getters/setters to get and store data to the database (from my controller to my model).

And i have another model in which validation rules are set... I don't want to mix both in the same folder. So i must come up with another structure for this. Something like:

```<code>www/
  Controllers/
  Models/
    Repositories/
    Entities/
  Views/
</code>```

It's just that my model isn't a real 'repository', since it doesn't store any objects in the repo class and doesn't have a commit() method or anything like that.

I also can't store the 2nd model (for validations) in the Entities folder, because they're not Entities at all...

Any idea how i should structure this..??


问:
Project estimates for unreal tasks
I'm a developer in large IT company that is centered around providing services to clients (by that I mean development department is <20 people and not a major part of organisation). I'm solving different tasks relevant to current problems, and everything is fine so far, but management somehow came up with idea to implement some application that replicates most of features in industry award-winning products like MS's Visio or Autodesk's AutoCad.

They want to do that using available resources I've described above. My first answer was "that's impossible even in your most bold fantasies" because project of such measure is made by dozens of teams of developers/architects/testers, costs millions of dollars and develop-from-scratch period is at least 1,5-2 years.

They consider that, but have few counterarguments such as we don't have any deadlines on this project (legislation behind subject area is not yet done and may not be adopted in next few years) nor detailed specification so each implemented functionality can be considered as minor release that will be delivered to client and tested "on the field". And of course, we don't need 1:1 copy of Autocad, just "few major features like 10% of whole product functionality".

That arguments doesn't help in estimation at all, on the contrary it means we'll have a lot of uncertain requirement changes like "look at this feature of AutoCad and implement it" and test by customers and not professional QA department is (politically correct synonym for idiocy).

Any ideas how to reason and estimate such task? Though some numbers would be helpful, but all development costs/details of large projects are unavailable, I can operate only with such ambiguous facts as average known salary say of Microsoft SDE and timeline of MS Office releases i.e. talking about Visio.

答:
This sounds like the ideal project for a by-the-book scrum methodology (http://www.scrum.org/storage/scrumguides/Scrum_Guide.pdf).

Think of the project as delivering a number of tiny modules, each able to be released as they're finished, and each with a definite business value.  Get a "product owner" from the business to prioritise the modules, and estimate them within your team.  Continue in this vein for several iterations; and then, when the company finally realises that this project is a bad idea, they'll actually have something usable, rather than having a whole lot of unfinished work.

From iteration to iteration, your estimates will gradually improve, and before long, you'll have a really good feel for how much your team can complete within each iteration.

Title: Project estimates for unreal tasks


问:
What are approaches for analyzing the cost-benefits of a development methodology?
There are many development practices (TDD, continuous integration, cowboy-coding), principles (SOLID, layers of abstraction, KISS), and processes (RUP, Scrum, XP, Waterfall).  I have learned you can't follow any of these blindly, but have to consider context and ROI (return on investment).

My question is: How do you know whether you are getting a good ROI by following a particular methodology?  Metrics, guesstimation, experience?  Do analytical methods exist?  Or is this just the million-dollar question in software engineering that has no answer?

For clarification when I say ROI I mean overall business value.  This does not necessary exclude developer happiness--if all the developers quit (or worse: become apathetic) after a 6-month death march you lose all the technical experience in the organization.  If customers are unhappy you will need more customer support staff or lose business.

答:
There are a lot of case studies on the DACS (Data & Analysis Center for Software) site, e.g.

WHAT IS THE ROI OF AGILE VS. TRADITIONAL METHODS?

An analysis of XP, TDD, Pair Programming, and Scrum (Using Real
Options) by Dr. David F. Rico, PMP, CSM. Little is known about the
costs and benefits of Agile Methods since their popularization in
1999, though 67% of projects use them and 75 books and 100s of papers
have been written about them. The purpose of this article is to
analyze the costs and benefits reported in studies of new product
development approaches such as Agile Methods as compared to those of
Traditional Methods. Over 300 articles on Agile Methods were examined;
cost, schedule, productivity, quality, and customer satisfaction data
were found in 69 studies; and ROI data were identified in 29 studies.
Agile Methods ROI was four times more than expensive Traditional
Methods, two times less than inexpensive ones, and the best Agile and
Traditional Methods had equal ROI. However, it may not be proper to
compare Traditional Methods optimized for productivity and quality to
Agile Methods optimized for customer satisfaction, project success,
and risk reduction.

(source: http://www.thedacs.com/databases/url/key/3990/4944/7956)


问:
When to use Advanced Message Queuing Protocol like RabbitMQ?
Can somebody explain me in what use-cases I should consider using AMQP like e.g. RabbitMQ? What are the pros and cons? </p>

答:
Imagine that you have a web service that can accept many requests per second. You also have a accounting system that does a lot of things, one of which is processing the requests coming from the web service.

If you put a queue between the web service and the accounting system, you will be able to:

have less coupling between the two applications, because now both applications have to know the configuration parameters of the queue management system and the name of the queue. Here the catch is that usually you are more likely to move to another server some application than move the queue management system

if you have a lot of requests coming in a short amount of time, the accounting system will be able to process them all anyway

persist some requests if their number becomes really huge

Of course, you could have more complex situations where the number of your applications is much bigger than two and you need to manage the communication between them.


问:
Biggest mistake you've ever made
Similar to the question I read on Server Fault, what is the biggest mistake you've ever made in an IT related position. Some examples from friends:

I needed to do some work on a production site so I decided to copy over the live database to the beta site. Pretty standard, but when I went to the beta site it was still pulling out-of-date info. OOPS! I had copied the beta database over to the live site! Thank god for backups.

And for me, I created a form for an event that was to be held during a specific time range. Participants would fill out the form for a chance to win, and we would send the event organizers a CSV from the database. I went into the database, and found ONLY 1 ENTRY, MINE. Upon investigating, it appears as though I forgot an auto increment key, and because of the server setup there was no way to recover the lost data.

I am aware this question is similar to ones on Stack Overflow but the ones I found seemed to receive generic answers instead of actual stories :)

What is the biggest coding error/mistake ever…

答: The biggest mistake I ever made was not having my work in source control off of my development machine. My hard drive crashed and I lost weeks of work. It's a lesson hard-learned and something I'll never let happen again.</p>

Title: Biggest mistake you've ever made


答:
How can we teach maintainability?

That's a matter of practice.

The most straightforward way of practicing it in a controlled way I can think of is to simulate typical maintenance project about as follows.

Get some project (Project A) that is well done and introduce few issues over it: inject some bugs, a good doze of duplicated and dead code, drop some features, unit tests and documentation here and there etc. You may even have a dedicated name for that, like Project A - damaged version.

Establish an issue tracker and fill it with requests corresponding to particular damages you made. Establish basic rules and practices for development process - VCS commits, code reviews, QA etc - consider taking what you can from check list provided in The Joel Test.

coursework 1.

Fix bugs, add missing unit tests, documentation and features.

coursework 2.

Refactor.

coursework 3.

Maintenance / improvement of original projects to use by next year students

- Project A version 2.0 and Project A - damaged version 2.0, respectively.

By improving damaged version I mean making better educative damage to it. :)

Of the practices mentioned above, pay special attention to that of code reviews. This is likely the most effective way to ensure that code is easy to maintain, as indicated eg by the top answer in related question.


答:
How to define a "good" return on investment in relation to software development is probably the more relevant question.

ROI can have many meanings.  In the simplest terms, you are assuming there will be a direct correlation between the cost to implement and use a system, and the resulting gains or losses once the system is in place. Much of this can be relative however.  You might mean ROI for the life of a project, or for the life of a company, or you may wish to make a distinction between weeks, months, or even years that a system is in use.

Is your ROI going to be purely financially based, or will you consider other more ephemeral values as a part of your ROI definition.  Things such as Customer satisfaction, or team and management satisfaction. How about the difference between hitting your deadlines, or missing them, or in being able to complete more or less project work?  You may even consider a combination, where you assume that implementing a system will cost you financially up front, but that the cost may be worth the non fiscal outcomes.

Case studies and white papers rarely take all of this stuff into account when trying to determine if the effort will be worth the cost to adopt a new system of working, which leaves us at the mercy of people's perceptions, and which as a result often results in disaster for teams where a methodology champion manages to convince management that system-x is the panacea the company has been looking for, as often these champions are either novices, or non-programming managers. So where does that leave us?

There are no solid figures or hard and fast formula's that you can apply to determine if a specific methodology is the solution to all of your problems, and whether the risks will be worth the rewards. So how do we know that something can or will work without actually trying it? For that you need the situation to be analysed from the perspective of Experience, Logic, and an intimate understanding of the needs of all of the stakeholders of a project - by which I mean the programmers, company management, and the customers.

Anyone who has written software for 10-15 years will likely have experienced a number of methodologies, and will have experienced projects that have worked, and failed. This experience can give you a great basis for forming opinions about the value of a particular methodology, however without a good working knowledge of the needs of the stakeholders that will be affected by a methodology, even the experienced developer is likely to implement a system based on a predefined methodology that most closely the developer's own perceived needs.

The thing about Agility, is that in order to be truly Agile you need to understand that there is no one specific methodology that will satisfy absolutely everyone. Therefore, what is needed is to define a system that utilizes the practices that will most closely match the needs of all of the stake-holders. This means that a methodology needs to be tuned to satisfy the team, the company, the customer, and the project, all as a group, but also individually. In terms of determining ROI, this is a combination that makes measuring a "good return" very difficult to measure, as each stakeholder will view value and success differently.

In terms of relative success however, the success will only be known once the project is completed. While this may seem a little scary up front, being Agile means that you don't lock yourself in to a specific system.  You tune your methodology up front, then you review often and tune the methodology as you go, until either the project ends, or the methodology requires no further tuning. By doing this, you maximize your chances that your methodology will evolve to a point where it will be of value to all of the stakeholders. As to how to measure the success of your methodology, that comes down to a number of factors. Are the developers happy working with the methodology? Does the management have enough control over the process? Does the customer get what they have paid for? Is the customer satisfied with the result? Are targets and outcomes definable, and can those targets/outcomes be realized? The most important measure however is whether all of the stakeholders can agree that the way things are done now is better than the way things were before.

I realize that I've described much of this as being after the implementation of a methodology.  In real terms, the proof of a methodology can only be guaranteed by doing it. With experience however, you can apply your knowledge of the things you have done before that didn't work very well, and if you have learned valuable lessons from them, you can use this information to determine up front whether a particular approach will be worth your time and effort. Therefore, you can call it an educated guess, based on prior learning, in order to minimize risk. The result is that you can be reasonably certain of the value of any given methodology, and you would act on a decision to implement a methodology if you can accept the risk that your chosen method may fail, or may require further tuning.  If you feel you can live with the risks, then you might believe it's likely to achieve a reasonable return on your investment, and implementing your chosen methodology will - with tuning - most likely work for you as you'll have a vested interest in making it so.  This too is another intangible item that is almost impossible to objectively measure.

Title: What are approaches for analyzing the cost-benefits of a development methodology?

Body:
There are many development practices (TDD, continuous integration, cowboy-coding), principles (SOLID, layers of abstraction, KISS), and processes (RUP, Scrum, XP, Waterfall).  I have learned you can't follow any of these blindly, but have to consider context and ROI (return on investment).

My question is: How do you know whether you are getting a good ROI by following a particular methodology?  Metrics, guesstimation, experience?  Do analytical methods exist?  Or is this just the million-dollar question in software engineering that has no answer?

For clarification when I say ROI I mean overall business value.  This does not necessary exclude developer happiness--if all the developers quit (or worse: become apathetic) after a 6-month death march you lose all the technical experience in the organization.  If customers are unhappy you will need more customer support staff or lose business.


问:
Is it the job of programmers to design the database?
I've been a programmer for the past six years. Throughout my career, I have worked on many web applications.

Most of the time, when a database was needed, it was given to us (the programmers) or we had some legacy database to work on. If not that, we had to create and design the database on our own which was not that tough.

But are we, as programmers, supposed to create the entire database from scratch when we have to build new application where data is so important and have messy requirements with a complex data model?

Isn't it in the best interest of the app and the company to get it done by an expert?

I am not trying to run away from designing the database, but it's a thing that is so important to get right.

答:
First of all, it's your job if the project manager tells you so. Smaller companies often don't have full-time DB experts. There isn't (and shouldn't be) a clear distinction between developers and DB experts anyway - any good developer will have considerable knowledge about DBs, and any good DBA will know how to code, at least in the DB's language for stored procedures.

While the DB design is a pretty central part of an application, it's no more important to "get right" than other central parts that a lot of other code will depend on.

And just like code, the idea that you get some super-expert to sit down and think hard for a week and then write down the perfect design that will never need to change is an illusion. The DB design can and will change as the application is being developed.

It is therefore actually beneficial to have the DB designed by a programmer (who understands DBs well), because then you have someone who knows both sides. That's certainly better than having it done by someone who only understand DBs and has nothing to do with the rest of the development work.


答:
It's common for programmers to make the database. Very common. Unfortunately many programmers do not have experience with the DB. They don't understand how to report against big data, the concepts of data marts, star schemas, etc. Some don't even understand the basics of normalization.

If one man has the skills to do everything at an expert level it makes for a very good product. A one man army can do what a 10 man team can do in a fraction of the time with 1000 times the quality. Not an exaggeration.

It's in the best interest for the programmer to do it (less people), assuming the programmer knows what he is doing. Of course there are thousands of failures to point at too.

Title: Is it the job of programmers to design the database?

Body:
I've been a programmer for the past six years. Throughout my career, I have worked on many web applications.

Most of the time, when a database was needed, it was given to us (the programmers) or we had some legacy database to work on. If not that, we had to create and design the database on our own which was not that tough.

But are we, as programmers, supposed to create the entire database from scratch when we have to build new application where data is so important and have messy requirements with a complex data model?

Isn't it in the best interest of the app and the company to get it done by an expert?

I am not trying to run away from designing the database, but it's a thing that is so important to get right.