问:
Javascript behavior depends only on browser or browser + OS?
Generally for a javascript application, compatibility is mentioned in terms of browser types and browser versions it supports.

Frameworks/Libraries like ExtJs also mention about the browser versions they are compatible with.

Does this mean that if my javascript application can run on Google Chrome 10+ version, then any operating system where Google Chrome 10+ can be installed will be able to run my javascript application without any glitches?

Or does type of operating system also have an effect on Javascript execution?

The reason behind asking this is to evaluate the scope of testing of javascript applications before making any commitment to the end user.

Thanks in advance for any guidance provided.

答: Since the browsers come with their own JavaScript engine, on first sight it should be sufficient to test browsers only. But some functions have to communicate with the underlying operating system (File API comes to mind), so there is a dependency, which requires OS specific testing.


问:
Should Cross browser testing be explicitly mentioned in the scope of a project?
I do freelance web development and front end dev is not my strongest point. This question came to me in my recent fixed bid project.

Nowadays we use Jquery and Bootstrap and these take care of lots of cross browser stuff. Still, there are lots of errors in different browsers. It requires testing tools and a whole lot of other things to worry about.

Should it be explicitly mentioned that the resulting site should be tested for cross browser compatibility in a contract? Or

Does it come by default in the scope of the project?

How can we estimate hours spent in cross browser compatibility?

Edit: Some great answers here. But how should a scenario be handled when no browser discussions happened at all at the time of signing contract?

答:
In your contract, you should specify an explicit list of supported browsers. This will save you a lot of trouble, if later the customer complains that the page looks broken on his stone-age Windows XP notebook with IE6. (Read what happened to this guy.)

Since you use libraries, the intersection of their browser compatibility lists (jQuery, Bootstrap) is probably a good starting point for your own list. Be sure to mention specific browser versions rather than minimum versions: If, in two years from now, a new IE/Firefox/Chrome version is released that renders your webpage incorrectly, why should you have to fix it for free?

As soon as you include a list of supported browsers, testing for these browsers (and fixing any problems due to use of those browsers) is part of the project. Compatibility with other browsers is not in the scope of the project and must be ordered and payed extra.

The time (and cost) for this varies widely, depending whether it is, for example, a small fix for a tablet-variant of some recent webkit-based browser (low price) or adding IE6 compatibility to a complex HTML5 webpage (very high price).

ContentLicense: CC BY-SA 3.0


答: Yes, you should specify what browsers will be supported by the resultant web site, ESPECIALLY on a fixed-price bid job. Your client may well have a good handle on their users, in which case they may be able to tell you what browsers they care about.</p>

Title: Should Cross browser testing be explicitly mentioned in the scope of a project?

Body:
I do freelance web development and front end dev is not my strongest point. This question came to me in my recent fixed bid project.

Nowadays we use Jquery and Bootstrap and these take care of lots of cross browser stuff. Still, there are lots of errors in different browsers. It requires testing tools and a whole lot of other things to worry about.

Should it be explicitly mentioned that the resulting site should be tested for cross browser compatibility in a contract? Or

Does it come by default in the scope of the project?

How can we estimate hours spent in cross browser compatibility?

Edit: Some great answers here. But how should a scenario be handled when no browser discussions happened at all at the time of signing contract?


答:
As a client, I would expect the website to be compatible with the "Top 5", i.e. Chrome, Firefox, Opera, Safari and IE8+.

As a freelancer, my opinion vary depending on the budget (unless the initial requirements specify explicitly the compatibility, in which case the question doesn't exist in the first place).

If the customer is one of those who don't have money and don't want to pay for quality and the project is on the lowest possible budget, I will ensure that the website works well in the browser I use myself. "It works on my machine", that's all I need. If you need compatibility with another browser, that will cost you additional N dollars.

For ordinary projects, I would at least ensure that the project works with the latest versions of Chrome, Firefox and IE; maybe I'll also try a previous version of IE, but won't spend too much time tweaking the layout for it.

For high-quality projects, I would require the list of browsers to be specified in the requirements. This makes things very clear, and the customer may ask even the compatibility with IE6, if he wants to pay twice the price of the project.

If browser compatibility is important, a study may also be done to gather/predict browser usage statistics. This would make it possible to determine precisely what browsers should be taken in account. Spending days on a bug within IE7 doesn't make sense if IE7 is used by 1% of the customers.

Note: what's also very important is how compatibility will be tested. If rounded corners are not rounded in IE7, while the requirements require the website to be compatible with IE7, does it violate the requirements? If a zone is 2 pixels larger on a browser compared to another, given that this discrepancy is barely visible, does it matter and should it be fixed? If only an ugly hack can fix a specific discrepancy, should it be used, or should the clarity of the code be the priority?


问:
RESTful API design. What should I return if there are no rows?
I'm currently coding an API for a social network with the Slim Framework. My question is: What are the best practices when there are no rows to return in the json structure?

Lets say that this call /v1/get/movies returns 2 rows from the table movie names:

```<code>[
    {"name": "Ghostbusters"},
    {"name": "Indiana Jones"}
]
</code>```

But, then I call /v1/get/books and there are no rows in that table. Should I just return an empty structure?

```<code>[
]
</code>```

...or would it be better a message and an error code?

```<code>[
    "errors": {
        "message": "no matches found",
        "code": 134
    }
]
</code>```

Which is a better practice? (the API will be used in iOS and Android apps) Thanks!

答:
If you execute operation successfully, but it doesn't have anything to return, such as empty map {} or empty array [] I would prefer to respond with 204 response code, here is excerpt from HTTP Status Code Definitions spec:

The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.

If the client is a user agent, it SHOULD NOT change its document view from that which caused the request to be sent. This response is primarily intended to allow input for actions to take place without causing a change to the user agent's active document view, although any new or updated metainformation SHOULD be applied to the document currently in the user agent's active view.

The 204 response MUST NOT include a message-body, and thus is always terminated by the first empty line after the header fields.

Essentially, I recommend using 204 in RESTful applications over HTTP when there is nothing to return.


问:
Is MVVM in WPF outdated?
I'm currently trying to get my head round MVVM for WPF - I don't mean get my head round the concept, but around the actual nuts and bolts of doing anything that is further off the beaten track than dumb CRUD.

What I've noticed is that lots of the frameworks, and most/all blog posts are from 'ages' ago.

Is this because it is now old hat and the bloggers have moved onto the Next Big Thing, or just because they've said everything there is to say?

In other words, is there something I'm missing here?

答:
All said and done, there is a limit to what you can do with an MVVM framework.

They are "done" since WPF has not moved on since Microsoft released it. If there were updates to the technology, the libraries would need updating too. This has not happened.

Title: Is MVVM in WPF outdated?


问:
IDE Generated Code
Many IDEs have the ability to spit out automatically written pieces of code. For example, it might generate a getter/setter pair for you. I wonder whether it isn't an attempt to work around some flaws in the language. If your IDE can figure out what the code should be without your help, why can't the compiler?

Are there cases where this is a really good idea? What kind of code generation does your IDE provide? Would the same thing be better provided as a feature of the language?

答: Think of the ambiguity you would introduce into pretty much any language if you let the compiler/interpreter try to guess what meant. </p>

ContentLicense: CC BY-SA 2.5

Title: IDE Generated Code


问:
modify source of copyrighted software
There is a a program that I want to use that is released in two (fully copyrighted) ways:

Stable binary form

Beta release, mostly-stable binary form that is easy to derive the source (uses jars) (this version is free)

Question:

Can I legally download the beta version, make the necessary changes to work properly on my machine, recompile and then use the software?

If yes to question 1, can I then explain to people I work with how to do the same thing so that they too can use the product?

In no way would I be giving them the modified software, but rather distributing instructions how to modify it.  The original download would still come from the copyright owner.

I believe I have done my due diligence searching these and google's forums, but as always, if you find a duplicate question, please let me know (and point to where it is found).  It seems odd to me that this hasn't been covered yet.

答:
You need to know how the application and associated source code are licensed.

Keep in mind that copyright != license.  They're related but different.

Some licenses such as BSD, MIT, GPL will allow you to do as you suggest.  Other licenses will not.

So the answer to your first question depends upon the license of the project.

The answer to your second question depends upon your jurisdiction and to a degree the license. Explaining how to reverse engineer proprietary code is usually prohibited by commercial licenses so you could run into problems there.  The same explanation on open source software isn't an issue.

Title: modify source of copyrighted software


问:
How do I know if I'm violating MVVM with WPF?
I was recently grabbing an auto generated TreeViewItem from a nested TreeView node in WPF, and I was using ItemContainerGenerator to get it in code behind.  Then I thought to myself I'm certainly violating MVVM right now. </p>

<p>What are some other signs that someone is violating MVVM ? </p>

答:
Not MVVM:

ViewModel isn't acting as an interface between model and View.

ViewModel doesn't provide data binding between View and model data.

ViewModel doesn't handle all UI actions by using command.

State and logic aren't stored in the Presenter.

View isn't isolated from the Model.

View isn't aware of the Presenter.

If your projet has at least one of the above, then you are violating MVVM.

Also, MVVM is a particular case of the PM (Presenter Model) where developers don't need to implement the link between the View and the ViewModel. Since the PM is a more general scenario you cannot comply with MVVM without complying with PM basics.


问:
Task-based authorization for user stories
My understanding is that the first step of defining user stories is to define roles. The problem with role-based systems is that this form of authorization is often too coarse-grained. Hence, people created task-based authorization where roles are still used to lump tasks into groups (see for example rhino security . At least that's my understanding.

How do I write user stories for task based authorization? Any feedback would be very much appreciated. Many thanks!

答:
I'm not sure, but I think you may be confusing story roles with authorization roles.  The user story should not tell you how to implement something.  The following user story is an example of user voice form using a role:

As a manager, I need to be able to add a new Foo Report to my Bar so
  that I can analyze all Foos and look for issues.

In my experience, the intention here is not to prescribe how to implement authorization, but instead to provide the developer with an idea of the type of person that is using this feature.  You may also use a persona, such as "Bob", instead of the role to capture demographics and information about the type of user using the Foo Report.  This gives you the context in how the feature will be used.

This should not mean that an authorization role of "Manager" should be created.  You can implement your security however you like, so long as a user that is like "Bob the manager" can be given access to report on the Foos in their Bar.

Since my teams work with a lot of security roles on their projects, we use personas instead to avoid the possibility of confusion within the team.

(BTW: My apologies if this is not what you meant, perhaps you are using user roles in a way that I am not familiar with)


问:
How far do you trust automerge?
Suppose you're getting the latest version of a file from source control and a conflict occurs. There are four possible types of changes in the conflict:

Yours

Theirs

Both

Conflicting

Naturally, in cases 3 and 4 you'd want to review the changes manually (in the latter case you even have to resolve it). Regarding cases 1 and 2 I'm not sure, but I'm thinking only changes of type 2 (Theirs) should prompt manual inspection. The reason being, you know what you changed, as opposed to "their" changes which may break your changes. So I'm thinking one could skip reviewing his own changes (case 1), and manually review / resolve the other changes (cases 2-4).

Other developers suggested more extreme approaches - such as only reviewing conflicting (or "both") changes and trusting automerge for the rest. The other extreme is reviewing all the changes every time.

Of course, other parameters may factor in. For example, if you only made a single correction to a file, and there are 200 changes made by others, then provided you can be reasonably sure that your change is unrelated (say it's an SQL file and you wrote a new separate stored procedure), perhaps you can skip reviewing the other changes.

I am torn between the dangers of not inspecting changes and the time and energy that could be saved by trusting the automatic merge. Supposedly, you have compilation and unit/component/e2e tests that will expose bad merges.

答:
Supposedly, you have compilation and unit/component/e2e tests that will expose bad merges.

This is the important part to me. In general, I will trust the auto-merge for code files (but not markup, project files, etc) where it can actually run (not conflicts). It tends to mangle projects and markup, but code files are (usually) fine.

But I also work in a place with frequent commits, good unit test coverage and gated check-ins (if the build/tests don't succeed, the commit does not work). Oh, and my release date is months into the future, not hours... 95+% of the time, it works just fine and I save the time and effort of looking through the merges. Different environments call for different carefulness.

Title: How far do you trust automerge?


答:
Even manual merging can be quite dangerous. Reason is that even if you do manage to merge it so that the code is compilable, the behavior of the code might be different from both original and your version. Martin Fowler has bliki explaining more into details.

And this is also reason you should integrate often with main repository. So you don't have to resolve crazy conflicts that encompass dozens of files.

Title: How far do you trust automerge?

Body:
Suppose you're getting the latest version of a file from source control and a conflict occurs. There are four possible types of changes in the conflict:

Yours

Theirs

Both

Conflicting

Naturally, in cases 3 and 4 you'd want to review the changes manually (in the latter case you even have to resolve it). Regarding cases 1 and 2 I'm not sure, but I'm thinking only changes of type 2 (Theirs) should prompt manual inspection. The reason being, you know what you changed, as opposed to "their" changes which may break your changes. So I'm thinking one could skip reviewing his own changes (case 1), and manually review / resolve the other changes (cases 2-4).

Other developers suggested more extreme approaches - such as only reviewing conflicting (or "both") changes and trusting automerge for the rest. The other extreme is reviewing all the changes every time.

Of course, other parameters may factor in. For example, if you only made a single correction to a file, and there are 200 changes made by others, then provided you can be reasonably sure that your change is unrelated (say it's an SQL file and you wrote a new separate stored procedure), perhaps you can skip reviewing the other changes.

I am torn between the dangers of not inspecting changes and the time and energy that could be saved by trusting the automatic merge. Supposedly, you have compilation and unit/component/e2e tests that will expose bad merges.


问:
How should I behave as a developer in a project that's headed for failure?
I am a developer in a 5-member team and I believe our project is headed for disaster. I'll describe why in a moment, but my question is: how should I behave?

The deadline is in 1.5 months, and I feel no matter what we do, this project will fail. I'm of the opinion that we should just terminate the project and stop wasting our time, but politically I think it's impossible for our manager to do that.

What should I do in this case? Should I put in extra effort, or should I just take it easy? And what should I say to the manager?

Reasons this project is headed for failure:

With deadline approaching many of the must-have features are not finished

Application is unstable and very difficult to use

System is very convoluted, code very hard to understand, very difficult to change - Data model is too driven by a complex relational database (100+ tables)

Unclear leadership; the manager responds to new information with major changes

Almost no automated tests or unit test

Heavily depends on other systems, but no integration tests yet

In fact, we actually just inherited this project (along with the mess) around 1-2 months ago from another dev team under the same manager, who has worked on it for a few months.

答:
This is an incredible opportunity for you! Let's take an entrepreneurial viewpoint on this.

Assuming that management wants this project to succeed you are in a great position to help them do so. The reason this realization is so important is because you have to develop the conviction and confidence that the warning signs you're seeing are in fact going to lead to this project's failure[1].

This is your chance to practice important skills in systematic thinking and interpersonal communication. Understand and visualize the issues and potential opportunities that are being missed so you can develop a strategy to communicate these as clearly and simply as possible.

Recognize your opportunity here to improve you skills.

[1] Canceling the project would actually be success. Failure would be spending good money after bad.


答:
With getters and setters, you don't always want both, but how is the compiler/interpreter to know that?

Also, when using the class, you'd have to remember on your own that a certain property is read-only, instead of having it clearly in the code that you can't use a setter because it doesn't exist.

Title: IDE Generated Code

Body:
Many IDEs have the ability to spit out automatically written pieces of code. For example, it might generate a getter/setter pair for you. I wonder whether it isn't an attempt to work around some flaws in the language. If your IDE can figure out what the code should be without your help, why can't the compiler?

Are there cases where this is a really good idea? What kind of code generation does your IDE provide? Would the same thing be better provided as a feature of the language?


问:
Java: How to make local fields & parameters final without having a 'final' keyword on each declaration
By default, I want all my local variables and method parameters to be final. Unfortunately, the Java language designers chose a different default: variables&parameters are by default non-final, and final variables&parameters need to be declared with the final keyword. So I need to add lots of finals. (And obviously I don't do this manually, but have my IDE add them for me.)

So I end up with source code where every default case is marked, whereas exceptions to my preferred default are barely visible. For readability, I would like it to be the other way round, i.e. only non-final local variables and parameters should be marked/highlighted/annotated/...

Is this possible?

I'm open to solutions that integrate at different levels, e.g. folding within the editor, style checkers, build steps, etc...

答:
I think your intention in making all local variables final is very good practice, but doing so implicitly (i.e. not explicitly with the final keyword) is a bad idea.

Rather than worry about readability for yourself, think about future maintainers of your code: will anyone reasonably expect that reassigning a field without the final keyword will fail to compile?

It looks like you can automate the inclusion of final keywords in Eclipse during code generation, but using a style checker to enforce it may highlight more false positives than it's worth.

If you're open to exploring other languages and paradigms, many functional languages default to immutability.


问:
Clever way to license/obfuscate web applications until the client has paid for it
I am doing contract work for various clients and I was wondering how best to go about safeguarding myself against non-payment. The projects will be ASP.NET web applications, most likely intranet-based.

I don't have any more details than that. I imagine that the client will want to run and test the applications from their side before making any payment. Is there any way I can "package" the application so that they can't access the source code? Is there an easy way I can make the application break after a certain number of days unless it is "unlocked" by me?

答:
Unless you install your ASP.NET application on hardware that you alone have admin on, no.  An unscrupulous client can take it without paying, and pay some unscrupulous programmer to work around any trap you leave.

Include clauses in your contract allowing you to collect both interest and collection expenses if they fail to pay on time, and requiring that they destroy any software you provide if they reject the final product.  The whole point of having a contract is for when things do not go as planned, and no amount of shenanigans in the program will let software do a contract's job.

Of course, that said, the way to avoid the issue altogether is to host the development code yourself on something like Windows Azure, and only install it on their hardware after you've been paid for development.  (Deployment and admin are separate functions that you can either not provide or bill separately for.)

ContentLicense: CC BY-SA 4.0


答: Is the intranet closed to the outside world? Otherwise you could you extract some components from the architecture and provide them as a service on an external server that you control, given that the architecture itself allows it.</p>

Title: Clever way to license/obfuscate web applications until the client has paid for it

Body:
I am doing contract work for various clients and I was wondering how best to go about safeguarding myself against non-payment. The projects will be ASP.NET web applications, most likely intranet-based.

I don't have any more details than that. I imagine that the client will want to run and test the applications from their side before making any payment. Is there any way I can "package" the application so that they can't access the source code? Is there an easy way I can make the application break after a certain number of days unless it is "unlocked" by me?


答:
Since your source needs to be on the web server and the server needs to read it, it's pretty difficult to protect your code unless you alone control the server.

The client will want to see the product working but that doesn't necessarily have to be on their server/network. If you can mock up the client's environment (required databases, etc.) you can stand up a demo machine which demonstrates that the work has been completed and that there's code to hand over in return for payment. (If you can't do this, how are you effectively developing and test the application?)

That said, unless you have good reason to question the intentions of your client, it may be counter productive to be over protective. There are people out there who will try and screw you over, but if you're dealing with a legitimate company and have agreements in writing you'll usually be ok. If you're co-operative and trusting the client will often reciprocate and it may result in more work in future.


答:
There's another answer to this, they're called ratified standards...  Agree up front which standards you're working to (xhtml1.0 transitional/css2.0 for example) and develop to that.  The standard itself is the final arbiter and changes in later browsers should take those changes into account.

Doing this takes you out of the situation where if a browser maker changes functionality as a patch (especially in a draft standard like html5 which is likely to change) then you're not caught out.  Equally if two render engines don't tally up then you have a fixed point of reference as to which behaviour is correct.

If you then want to add nonstandard code or use additional features targeting some non-standard browser behaviour like chrome or ie6 then you can do so in an additive way (through feature detection for example.)

If the client comes back with a problem then you can point them to the standard and say it's doing what it should but if you'd like me to update it for your chosen non-compliant platform then I'll be happy to, but it's going to cost you.

(* IE6 and Chrome are equally problematic as bad developers target browser specific features and don't code to fall back to a standard appropriately.)


答:
If you have many instances where there are 200 changes to a single file on a merge, I don't think you are merging often enough, and it's very likely that there is a complexity problem with that file.

We have bad merges probably once every few months, that we know of. Without some sort of release engineering team to investigate every change before a new release is created, or very good peer review, you aren't going to be able to catch every bad merge - if you have a bad merge in your unit tests and a bad merge in your code, which is more likely than one would think, then you wont catch the problem until something goes very wrong (or someone, probably not in IT, notices catastrophic data loss).

If you don't put any effort in, you can be 99% sure that everything merged fine. If you're willing to put in an extra 30-40% of release and change management time, you can probably be much closer to 99.99% sure. For a company like Microsoft, it's probably worth the investment, but for many others it isn't.

Title: How far do you trust automerge?


答:
You can trust automatic merges if -- and this is a big if -- you have everything else in order.  This means that you and anyone else working on the same file are aware of what's going on and have sanity-checked all of it before diving in.

Per Cederqvist said it best in section 1.2 of Version Management with CVS, which I make version control noobs read whether we're using CVS or something else:

CVS is not a substitute for developer communication.

When faced with conflicts within a single file, most developers manage
  to resolve them without too much effort.  But a more general definition
  of "conflict" includes problems too difficult to solve without
  communication between developers.

CVS cannot determine when simultaneous changes within a single file, or
  across a whole collection of files, will logically conflict with one
  another.  Its concept of a conflict is purely textual, arising when two
  changes to the same base ﬁle are near enough to spook the merge (i.e.
  diff3) command.

CVS does not claim to help at all in figuring out non-textual or
  distributed conflicts in program logic.

Title: How far do you trust automerge?


问:
Worst coding standard you've ever had to follow?
Have you ever had to work to coding standards that:

Greatly decreased your productivity?

Were originally included for good reasons but were kept long after the original concern became irrelevant?

Were in a list so long that it was impossible to remember them all?

Made you think the author was just trying to leave their mark rather than encouraging good coding practice?

You had no idea why they were included?

If so, what is your least favorite rule and why?

Some examples here

答:
My favorite would have to be the database naming guidelines we currently are trying to abide by. All tables used for many-many relationships should be named using the names of the linked tables and must be suffixed with "Link". And of course, no pluralization of table names.

OrderLines? Nope. It should be called OrderProductLink

Friends? Nope. It should be PersonPersonLink


答:
What can you do

Treat this in your own self excellence terms, it's "their" project, but also yours, take ownership even though you know it will fail. Why? because a) you might help it fail a little less, b) in time of challange, this is where you learn the most c) you should measure yourself via your own metrics of excellence, doing your best might not save the project, but you might end up still proud of yourself

Talk to other fellow developers and see what they think, you will probably find out that many share the same frustration, if done carefully (don't make people think you want to start a mutiny or something) then this can help not just you but others as well

Ignoring the problem is not going to make it go away, talking about ways how to, against all odds still pull it through, e.g. at least get some decent must haves, or the main "wow factor" use case done right, might make this project fail less miserably. How to do it? well, few ideas of "when going gets tough tough gets going" or "desperate times justify desperate measures" and other cliches, for example: massive use of OSS, extreme programming / agile methodologies, weekend hackathons (volunteers only, not forcing people to work weekends). This is time where you can show leadership (carefully if you are not in a team lead / senior position) but you can take this advantage and become their mockingjay, just get people to feel that they might get this project just a little less fail than everyone knows it will. You can show some leadership skills here that might help you later along the way, treat the problem as a challenge.

Make sure your management knows, but very, very carefully, if they know, they'll appreciate you telling them this in a non confrontational, calm way, if they don't they will appreciate it even more, and wonder why no one told them about it before. You should tell them this as a service, without any emotional side, just plain facts, and without an agenda. If they'll ask you what you think they should do (which is a great sign, but rare) then see the next section

What you can't do, but your management probably should

They should not add more people to the project "to help" see this

Call the customer immediately and tell them the bad news. Why is this a good idea? well, I'll leave quoting the manifesto for agile software development, but even without it, even water fall lovers hate bad surprises. If the customer knows in advance this project is doomed to fail, they will be unhappy, but will be much happier that you tell them there are issues before it blows in their face, and that you are on it, and doing your best to accommodate it. The customer can do many things but most of them are not worse than finding out in the last minute they don't have a deliverable (or they do but it's of non usable quality). The customer will appreciate it as they will be able to delay hiring testing staff, offshore IT people, change their internal training plans, and all just because you were honest with them.

with the customer, think of ways to still make something out of the project, the most common one is descoping things. for example there might be some features that are just too hard to develop the way they were designed, and if the customer will agree for some small modifications and simplifications, then some features will become simpler.

Update their own higher management, it will help them keep their job as well...

What you should NOT do

Ask to add more people to the project (see this)

Quit / look for another job (at least not yet), this is something you can learn from, and what will make you one day a better developer or better manager. You'll learn to appreciate many things better, better time manage, design better, write code better, and work with peers and management better. Look for a job after these 2 months are over if you don't like working there, not because of any other reason.

Whine, complain, or be negative about the project, management, the bad design you inherited, the newbie developers you got to mentor that it takes you 3 hours to explain them to do something that takes you 1 hour, be positive as much as you can.

Criticize management and become a target as a trouble maker, they are in the same boat, and they might know things that you don't, all you can do is update them (always update your own direct manager, never bypass her / him)

Blame people, (or yourself), it doesn't help, never

Take it too seriously, unless it's medical equipment, no one is likely to die if you miss the deadlines, it's software, we miss deadlines for a living, relax.

That's just my two cents, YMMV

Title: How should I behave as a developer in a project that's headed for failure?

Body:
I am a developer in a 5-member team and I believe our project is headed for disaster. I'll describe why in a moment, but my question is: how should I behave?

The deadline is in 1.5 months, and I feel no matter what we do, this project will fail. I'm of the opinion that we should just terminate the project and stop wasting our time, but politically I think it's impossible for our manager to do that.

What should I do in this case? Should I put in extra effort, or should I just take it easy? And what should I say to the manager?

Reasons this project is headed for failure:

With deadline approaching many of the must-have features are not finished

Application is unstable and very difficult to use

System is very convoluted, code very hard to understand, very difficult to change - Data model is too driven by a complex relational database (100+ tables)

Unclear leadership; the manager responds to new information with major changes

Almost no automated tests or unit test

Heavily depends on other systems, but no integration tests yet

In fact, we actually just inherited this project (along with the mess) around 1-2 months ago from another dev team under the same manager, who has worked on it for a few months.


问:
Github Organization Repositories, Issues, Multiple Developers, and Forking - Best Workflow Practices
A weird title, yes, but I've got a bit of ground to cover I think.

We have an organization account on github with private repositories.  We want to use github's native issues/pull-requests features (pull requests are basically exactly what we want as far as code reviews and feature discussions).  We found the tool hub by defunkt which has a cool little feature of being able to convert an existing issue to a pull request, and automatically associate your current branch with it.

I'm wondering if it is best practice to have each developer in the organization fork the organization's repository to do their feature work/bug fixes/etc.  This seems like a pretty solid work flow (as, it's basically what every open source project on github does) but we want to be sure that we can track issues and pull requests from ONE source, the organization's repository.

So I have a few questions:

Is a fork-per-developer approach appropriate in this case?  It seems like it could be a little overkill.  I'm not sure that we need a fork for every developer, unless we introduce developers who don't have direct push access and need all their code reviewed.  In which case, we would want to institute a policy like that, for those developers only.  So, which is better?  All developers in a single repository, or a fork for everyone?

Does anyone have experience with the hub tool, specifically the pull-request feature?  If we do a fork-per-developer (or even for less-privileged devs) will the pull-request feature of hub operate on the pull requests from the upstream master repository (the organization's repository?) or does it have different behavior?

EDIT

I did some testing with issues, forks, and pull requests and found that.  If you create an issue on your organization's repository, then fork the repository from your organization to your own github account, do some changes, merge to your fork's master branch.  When you try to run hub -i <issue #> you get an error, User is not authorized to modify the issue.  So, apparently that work flow won't work.

答:
The fork-per-developer approach is a very good approach if you value code reviews and code quality. The nice thing about using pull requests is that it shifts the responsibility from the maintainer to the developer.

The developer wants to get his code into the main branch, and requests it's inclusion.

This is much different context than the old model where people commit, and later the reviewer had to tell them "oh, this thing you did a few weeks ago wasn't so good, fix it now."

We use this model in our company. Pull requests made code requests viable, encourage discussion of other peoples code and generally helped with code quality, even with developers who were first against the new tool. I feel that it also made people take code reviews more seriously, because the reviewer has to actively merge the code into the main branch, instead of just saying 'ok' or 'not ok' after code was already commited.


问:
Is the development of CLI apps considered "backward"?
I am a DBA fledgling with a lot of experience in programming.

I have developed several CLI, non interactive apps that solve some daily repetitive tasks or eliminate the human error from more complex albeit not so daily tasks. These tools are now part of our tool box.

I find CLI apps are great because you can include them in an automated workflow.

Also the Unix philosophy of doing a single thing but doing it well, and letting the output of a process be the input of another, is a great way of building a set of tools than would consolidate into an strategic advantage.

My boss recently commented that developing CLI tools is "backward", or constitutes a "regression".

I told him I disagreed, because most CLI tools that exist now are not legacy but live projects with improved versions being released all the time.

Is this kind of development considered "backwards" in the market?

Does it look bad on a rèsumè?

I also considered all solutions whether they are web or desktop, should have command line, non-interactive options. Some people consider this a waste of programming resources.

Is this goal a worthy one in a software project?

I also think that for a web or desktop app, having an alternate CLI interface is a great way of demonstrating that the business logic is completely decoupled from the GUI.

答:
It basically comes down to "use the right tool for the job."

If you have to interact with a user, you'll want some sort of GUI.  We've got decades of research and experience showing that they make computing far more intuitive and productive.  That's why GUIs have inexorably taken over the world ever since 1984: they just work better for interacting with people.

But if you're automating a program with scripts, your program isn't interacting with people; it's interacting with a script.  And the best interface for that is a text-based one, for reasons that should be intuitively obvious.

The development of CLI programs for users to work with directly is considered backward, and with good reason.  But if that's not what you're doing, if you're writing automation productivity tools, then you aren't doing anything wrong by giving them a CLI.


答:
It may be an easy way out to assume that it is an inevitable and utter failure and just give up on the project.
As a consultant I am often invited to help with the projects that are in various stages of degeneration, failed or failing and part of what I am being paid for is reviving and completing such projects.

What you view as a complete failure, may not be perceived as such by everyone, depending on the perspective.
In an ideal world, every feature would complete, coded elegantly and independently of other systems and every line of code tested.
I haven't seen a single, project that looked like that in rev 1.
In real world, shipping a project means taking some compromises, maybe even missing some key features but the product can ship and even though it will be beta quality at best, at least you'll get the feedback on which things to fix first.
The upside of this is that it may inform the management that software is never done and rather than trying to develop a certain v 1.0 in vacuum it is better to iterate and respond to changes in an agile way.
Finally for you as a developer in this position, I think the key thing is to develop as good code as possible in these conditions - document it, write tests yourself, if you have to (especially for external dependencies) and use your knowledge of the system to communicate which features are truly crucial and must-have and which ones can wait a week or a month.
Make yourself vocal about your concerns and justify them as you did to us.
Rather than prepping for plan B, prepare for the fact that you and other poor souls will probably be fixing all that buggy and not done code yet AFTER the product has shipped - as stated above this means writing your code in a modular decoupled fashion - if you think that the persistence layer code is bad, hopefully you should be able to replace it completely in the next revision.
Finally, don't despair - dealing with such situation is part of what you're being paid for and it's a learning process. Regardless of the outcome in this particular project, this will count as a valuable experience in the future.


问:
Should a repository be passed in to the User Interface
In Mark Seeman's Dependency Injection in .NET he injects a repository into his UI layer. I believe that he is doing this so that he can store everything in the UI configuration, however this just strikes me as bad design. Wouldn't it be better to pass the service reference into the UI? What is to stop a future developer from using the repository directly? Also, he says that he is building this as an n-tier architecture. But, he has now coupled the data layer to the UI layer (no matter if DI is used or not). What if he wants to host all three layers on different self-contained servers. While his approach COULD work, it just seems wrong to me. So, I wanted to see what the general community has to say. Am I right in my thoughts, or am I missing something?

Simplified version of the code:

```<code>public class UI
{
  IRepository _repo;
  public UI(IRepository repo)
  {
    _repo = repo;
  }

  public stuff UIMethod()
  {
    var svc = new Service(_repo);
    return svc.GetStuff();
  }
}

public class Service
{
  IRepository _repo;
  public Service(IRepository repo)
  {
    _repo = repo;
  }

  public stuff GetStuff()
  {
    var persistenceStuff = _repo.GetStuff();
    //Do some business logic here
    return persistenceStuff.ToServiceStuff();
  }
}
</code>```

答:
But, he has now coupled the data layer to the UI layer

The purpose of a repository is to decouple the user of the repository (here the UI layer) from the persistence or database layer - not from the data objects itself. It helps you, for example, to provide in-memory generated data objects for testing purposes, without the need of retrieving them from a real database.


问:
How does signing headers and/or body provide security
I'm securing a WCF webservice with TransportWithMessageCredential security that uses certificates.
So I'll have to choosee between signing headers & body or signing and encrypting.

Now my question is, after reading Understanding Protection Level what the advantage is of just signing? The fact that WCF will notice that someone has been messing around with the message and going to reject it or am I wrong?

Thanks in advance.

答:
Encryption makes sure nobody else can read your message.

Signing makes sure it really comes from where it claims, and that nobody has changed the signed part.

Anyone can send you an encrypted message and claim it comes from someone else, as long as they have your public encryption key. But when they sign it, they need a private key, so if the signature checks out, you know that whoever wrote it had the private key in their possession.


答:
The best solution I can imagine for this problem is to have the final keyword in the source files as normal, but have my editor hide them and instead highlight all declarations without final keyword. This would give me exactly what I want, and the files would still be plain Java.

Unfortunately, I don't know any IDE that has support for this. For Eclipse, there is a bug proposing this enhancement.

Title: Java: How to make local fields & parameters final without having a 'final' keyword on each declaration

Body:
By default, I want all my local variables and method parameters to be final. Unfortunately, the Java language designers chose a different default: variables&parameters are by default non-final, and final variables&parameters need to be declared with the final keyword. So I need to add lots of finals. (And obviously I don't do this manually, but have my IDE add them for me.)

So I end up with source code where every default case is marked, whereas exceptions to my preferred default are barely visible. For readability, I would like it to be the other way round, i.e. only non-final local variables and parameters should be marked/highlighted/annotated/...

Is this possible?

I'm open to solutions that integrate at different levels, e.g. folding within the editor, style checkers, build steps, etc...


答:
To me, I would like to think that IDEs should help the users generate codes to

increase your coding speed e.g. generation of mundane (subjective) codes

give (to  a certain extent) an idea of how certain 'requirements' can be coded e.g. template for a specific class types

The codes by no means should be taken for granted to fit exactly what you want.

However, codes generated from visual editors/wizards (e.g. WinForm designer generating the designer.cs files) should not be meddled with unless you have deep understanding of what you are doing and prepared to get screwed if it affects the visual editor's ability to render the design-time view.

Title: IDE Generated Code


问:
Do I infringe copyright if I turn a book into a program?
Suppose I own a copy of a physics book containing original research. Suppose that this book is licensed under a non-free license.

If I use the formulas and concepts explained in that book in my program, am I infringing the book's copyright?

In my opinion the answer is no because I'm copying ideas, not text, and ideas can't be copyrighted. Though, I must say that in order to use the formulas, I'm forced to copy parts of the text, hence the question.

Update: I have no problems crediting the author and citing the book; my aim is to have freedom to choice the license I want for my software, without being limited by the book's license.

答:
Mathematical formulas usually are not covered by copyright, since there is a limited number of ways to express them.  And unless you're copying mathematica source code, you have to "re-write" the formula anyway.

That said, it's possible that you may be encumbered by a separate license relating to How you acquired the book.  I.e., via a specific contract instead of just picking it up at a bookstore.

I do have to wonder what the point of a physics book whose formulas you aren't allowed to use, though.


问:
Is it sane to use Document based NoSQL for store big data tables
In Document based NoSQL to create tables (AFAIK) I need:

Create such many as many rows in table documents with same ID field (that will be table id) and each time need to set the columns (for each document).

Then you first search documents by id (table) and next search what you need in the selection.

Please correct if I understand it wrong... And is it sane? How could that be fast?

答:
What you describe (if I understand correctly what you describe) could be a performance nightmare in updating the said tables - if you store each "table" as a single document in a NoSQL system, and want to update a row in that "table", then you'd need to update the whole (potentially huge) document every time.

But if you need/want a strict structure, then why would you need to use NoSQL systems? For SQL type problems, SQL databases will be faster and better. For key-value type problems, key-value datasystems will be faster and better. For document storage type problems, document-based systems will be faster and better.


答:
Eric Raymond's The Art of Unix Programming is the canonical work for the argument you're making.  I won't try to condense his excellent book into a couple paragraphs.  However, keep in mind that argument applies mostly to programmers, administrators automating tasks using scripting, or power users of highly technical software like CAD.

Even with highly technical users, you have to consider which hats they are wearing at the time.  For example, I write embedded software for networking equipment for a living.  Our products all have both a CLI and a GUI, but developers almost universally prefer the CLI, due to its flexibility, scriptability, availability, speed, etc.

However, that exact same group of developers overwhelmingly prefers the GUI on our version control software, even though its CLI is more powerful and is supported and documented just as well as the GUI.  The difference is we are the end users of the version control software, not administrators or developers.

So carefully consider what roles your users are in when they're using your utilities, and plan the user interface accordingly.  If your boss is mentioning it, chances are you need to improve the documentation and/or training on the CLI at the very least.  If you're constantly telling people a feature is only available on the CLI when they expect it for the GUI, you probably need to rethink your development priorities, taking the needs of your users better into account.

Title: Is the development of CLI apps considered "backward"?

Body:
I am a DBA fledgling with a lot of experience in programming.

I have developed several CLI, non interactive apps that solve some daily repetitive tasks or eliminate the human error from more complex albeit not so daily tasks. These tools are now part of our tool box.

I find CLI apps are great because you can include them in an automated workflow.

Also the Unix philosophy of doing a single thing but doing it well, and letting the output of a process be the input of another, is a great way of building a set of tools than would consolidate into an strategic advantage.

My boss recently commented that developing CLI tools is "backward", or constitutes a "regression".

I told him I disagreed, because most CLI tools that exist now are not legacy but live projects with improved versions being released all the time.

Is this kind of development considered "backwards" in the market?

Does it look bad on a rèsumè?

I also considered all solutions whether they are web or desktop, should have command line, non-interactive options. Some people consider this a waste of programming resources.

Is this goal a worthy one in a software project?

I also think that for a web or desktop app, having an alternate CLI interface is a great way of demonstrating that the business logic is completely decoupled from the GUI.


问:
Storing n-gram data
I was hoping to brainstorm a little bit on the subject of storing n-gram data.
In my project, I am trying to solve linguistic problems where I know all (n-1) data items and want to statistically guess my n using linear interpolation over all applicable n-grams. (Yes, there is a tagger that assigns tags to known words according to its lexicon and a suffix tree that tries to guess the word kind for unknown words; the n-gram component discussed here will be tasked with resolving ambuguity.)

My initial approach would be to simply store all observed n-grams (for n = 1..3, i.e. monogram, bigram, trigram) data in respective SQL databases and call it a day. But the requirements of my project may change to include other vector lengths (n), and I would like my application to adapt to 4-gram without a lot of work (updating schema, updating application code, etc.); ideally, I would simply tell my application to work with 4-grams now without having to change code much (or at all) and train its data from a given data source.

To sum up all requirements:

Ability to store n-gram data (initially for n = {1, 2, 3}

Ability to change what kinds of n-grams should be used (between application runs)

Ability to (re-)train n-gram data (between application runs)

Ability to query the data store (e.g. if I have observed A, B, C, I'd like to know the most frequently observed item for what might follow using my trained 4-, 3-, 2-, 1-gram data sets)

The application will most likely be read-heavy, data sets most likely won't be retrained that often

The solution employs the .NET Framework (up to 4.0)

Now what design would be better fit for such a task?

A fixed table managed by a SQL server (MSSQL, MySQL, ...) for each n (eg. dedicated tables for bi-grams, tri-grams, etc.)

Or a NoSQL document database solution that stores the first n-1 as the key of the document, and the document itself contains the n-th value and observed frequencies?

Or something different?

答:
Contrary to what the others are suggesting, I'd suggest to avoid any data structures more complex than a hashmap or a key-value store.

Keep in mind your data access requirements:
a) 99% requests - query ngram "aaa-bbb-ccc" and retreive the value (or 0)
b) 1% requests - inserting/updating a count of specific ngram
c) there is no (c).

The most effective way is to retrieve it with a single lookup. You can use an out-of-bounds (or escaped) separator to combine the full n-gram in a single string (e.g. "alpha|beta|gamma" for 3gram, "alpha" for unigram, etc) and just fetch that (by the hash of that). That's how quite a lot of NLP software does it.

If your ngram data is small (say, < 1 gb) and fits in memory , then I'd suggest to use an efficient in-program memory structure (hashmaps, trees, tries, etc) to avoid overhead; and just serialize/deserialize to flat files. If your ngram data is terabytes or more, then you may choose NoSQL key-value stores split on multiple nodes.

For extra performance, you may want to replace all words everywhere with integer ids so that your core algorithm doesn't see any (slow) strings at all; then it's slightly different to implement the same idea.

Title: Storing n-gram data


答:
Find the problems your project is running into and try to clearly quantify as objectively possible. With every "metric" you quantify make sure you define why you believe this metric is important. You want to give your manager insight into what the consequences would be if a certain metric would not be within "acceptable range". You will need to give some guidelines for each metric to indicate which values are "Good", "Acceptable", "Problematic" or "Bad". Define every criterion up front. If possible you could describe what would be minimally needed for a project to success and contrast this with the current project.

Static Code Quality can be quantified by lots of static analysis tools. You can keep this as simple or detailed as you see fit. The metrics I suggest you start with:

Cyclomatic Complexity

Size of your code (eg, Nr of lines per function/class, number of files, number of tables...)

Identify which modules are too large

Duplication.

Adherance to code style

Defect rate

per KLOC by module and or subsystem (identify troublesome parts of your system)

you could calculate how much per team member but I think you should keep that for yourself

solved vs found

time needed to solve a bug (perhaps if this is inclining make a graph of this)

perhaps make an estimate of how much time is needed if this keeps going at the current rate

Planning

Extrapolate time used for the features built. Take into account complexity of the feature. This doesn't have to be very precise. What you want to convey with this would be along the lines of "Feature A, B and C are around the same complexity of D, E and F. With features ABC used 170% if the planned time. If nothing changes we expect the same time is needed for DEF" or along the line of "The average feature is taking X% time longer than calculated. We have no reason to assume that the rest of the functionality is easier to build so we should compensate for this in the future planning. It is of no use to have a planning if it is not realistic.

Try to have some monthly or preferably even shorter release schedule. If only internal. This could help you further with extrapolating the time you need for the project. This could also save you from making unrealistic commitments (if you don't commit to new work before a release is done). Make a planning for each cylce and sure new features only enter into the next cycle (ie. they can never be added to the current cycle).

Test coverage: explain the "normal" test coverage values and show how what your current coverage is

Documentation: How much % is actually documented? How good?

Modularity:

Class based (coupling and cohesion)

Package based

Subsystem based (how many communication paths are there?)


问:
Is there any hard data on the (dis-)advantages of working from home?
Is there any hard data (studies, comparisons, not-just-gut-feel analysis) on the advantages and disadvantages of working from home?

My devs asked about e.g. working from home one day per week, the boss doesn't like it for various reasons, some of which I agree with but I think they don't necessarily apply in this case.

We have real offices (2..3 people each), distractions are still common. IMO it would be beneficial for focus, and with 1 day / week, there wouldn't be much loss at interaction and communication. In addition it would be a great perk, and saving the commute.

Related: Pros and cons of working remotely / from home  (interesting points, but no hard facts)

To clarify: it's not my decision to make, I agree that there are pro's and con's depending on circumstances, and we are pushing for "just try it". I've asked this specific question because (a) facts are a good addition to thoughts in arguing with an engineer boss, and (b) we, as developers, should build upon facts like every respectable trade.

答:
Since moving to a new role that allows working from home nearly 100% of the time (still have a dedicated office space if I need it), I honestly feel there is no downside other than having to not appear to be gloating or flaunting the fact that I can work from home when talking to others who cannot.  Also - others, particularly my family seems to think that because I am at home - that it is not really working (but will generally leave me alone when I am working).

Sure the cats want attention every once and a while, but it wastes less time than the obligatory small talk about family, kids, sports, etc. with co-workers.  Office Communicator saves all my "chat" conversations with my team - better than the notes I would take myself.

We use Citrix to connect, MS Outlook for email and meeting scheduling, Office Communicator as a primary means of communication between the team, SharePoint for a common document workspace, Live Meeting or OC for sharing desktops, and of course a conference call bridge for meetings.  People working in the office use all of those things too - even when they are sitting next to each other.

I work for a large company that increasingly allows working from home as an option for several thousand workers.  It is cheaper for the company, the employee, better for the environment, and the experience at least with my company is that there is no difference in productivity.


答:
imo, passing the repo through the service is pointless. Why have the service at all, if you're just going to use the repository?

I think that every layer of abstraction needs to be thought out. If you don't need a service, don't have one. If you don't need a repository (most are DAO's anyway), don't have one.

I agree with you. As that code stands, it's bad design. He should either remove his Service layer and reference the Repository directly, or use the Service. Typically you shouldn't pass references of objects through other objects.

Title: Should a repository be passed in to the User Interface

Body:
In Mark Seeman's Dependency Injection in .NET he injects a repository into his UI layer. I believe that he is doing this so that he can store everything in the UI configuration, however this just strikes me as bad design. Wouldn't it be better to pass the service reference into the UI? What is to stop a future developer from using the repository directly? Also, he says that he is building this as an n-tier architecture. But, he has now coupled the data layer to the UI layer (no matter if DI is used or not). What if he wants to host all three layers on different self-contained servers. While his approach COULD work, it just seems wrong to me. So, I wanted to see what the general community has to say. Am I right in my thoughts, or am I missing something?

Simplified version of the code:

```<code>public class UI
{
  IRepository _repo;
  public UI(IRepository repo)
  {
    _repo = repo;
  }

  public stuff UIMethod()
  {
    var svc = new Service(_repo);
    return svc.GetStuff();
  }
}

public class Service
{
  IRepository _repo;
  public Service(IRepository repo)
  {
    _repo = repo;
  }

  public stuff GetStuff()
  {
    var persistenceStuff = _repo.GetStuff();
    //Do some business logic here
    return persistenceStuff.ToServiceStuff();
  }
}
</code>```


答:
Can you be more specific than just ASP?
Standard MVC ASP has all the models and controllers compiled, so the client just gets binaries and views. While it's much easier to reverse engineer than say C, it's still often more hassle than just paying the developer. And then you can program in whatever time limitation you want.

I've also always had luck by splitting work into smaller billable units. It's much easier for a client to pay $1000 in 10 chunks, than $10000 all at once. Especially if they don't get the next feature until they've paid. Worst case and they don't pay, you're only down 10% of the time, and because the client sees regular checkpointed progress they've happier (provided you do good work). Everyone wins.
So then you can give them the first bit of work to demo, then once that's settled they get the next bit, and so on.


答:
Copyright isn't your only concern.  You also need to potentially worry about associated patents.  However, most academics publish their work because they want others to use them, and in my experience, most would welcome a practical implementation, especially if that implementation is freely licensed.

My first step would be to contact the author and tell him what you plan to do.  Chances are he'll give you express permission.  If he doesn't, you'll probably have to ask a lawyer's advice anyway.

Title: Do I infringe copyright if I turn a book into a program?

Body:
Suppose I own a copy of a physics book containing original research. Suppose that this book is licensed under a non-free license.

If I use the formulas and concepts explained in that book in my program, am I infringing the book's copyright?

In my opinion the answer is no because I'm copying ideas, not text, and ideas can't be copyrighted. Though, I must say that in order to use the formulas, I'm forced to copy parts of the text, hence the question.

Update: I have no problems crediting the author and citing the book; my aim is to have freedom to choice the license I want for my software, without being limited by the book's license.


问:
I don't understand how TDD helps me get a good design if I need a design to start testing it
I'm trying to wrap my head around TDD, specifically the development part. I've looked at some books, but the ones I found mainly tackle the testing part - the History of NUnit, why testing is good, Red/Green/Refactor and how to create a String Calculator.

Good stuff, but that's "just" Unit Testing, not TDD. Specifically, I don't understand how TDD helps me get a good design if I need a Design to start testing it.

To illustrate, imagine these 3 requirements:

A catalog needs to have a list of products

The catalog should remember which products a user viewed

Users should be able to search for a product

At this points, many books pull a magic rabbit out of a hat and just dive into "Testing the ProductService", but they don't explain how they came to the conclusion that there is a ProductService in the first place. That is the "Development" part in TDD that I'm trying to understand.

There needs to be an existing design, but stuff outside of entity-services (that is: There is a Product, so there should be a ProductService) is nowhere to be found (e.g., the second requirement requires me to have some concept of a User, but where would I put the functionality to remind? And is Search a feature of the ProductService or a separate SearchService? How would I know which I should choose?)

According to SOLID, I would need a UserService, but if I design a system without TDD, I might end up with a whole bunch of Single-Method Services. Isn't TDD intended to make me discover my design in the first place?

I'm a .net developer, but Java resources would also work. I feel that there doesn't seem to be a real sample application or book that deals with a real line of business application.  Can someone provide a clear example that illustrates the process of creating a design using TDD?

答:
The idea of TDD is to start with testing and work from that.  Thus, to take your example of "A catalog needs to have a list of products" could be seen as having a test of "Check for products in catalog" and thus this is the first test.  Now, what holds a catalog?  What holds a product?  Those are the next pieces and the idea is to get some bits and pieces put together that would be something like a ProductService that will be born from getting that first test to pass.

The idea of TDD is to start with a test and then write the code that makes that test pass as the first point.  Unit tests are part of this yes, but you aren't looking at the overall picture that is formed by starting with tests and then writing the code so that there aren't blind spots at this point since there isn't any code yet.

Test Driven Development Tutorial where slides 20-22 are the key ones.  The idea is to know what the functionality should do as a result, write a test for it and then build a solution.  The design part will vary as depending on what is required it may or may not be that simple to do.  A key point is to use TDD from the start rather than try to introduce late into a project.  If you start with tests first this can help and is likely worth noting in a sense.  If you try to add the tests later, it becomes something that may be put off or delayed.  The later slides may also be useful as well.

A main benefit of TDD is that by starting with the tests, you aren't locked into a design initially.  Thus, the idea is to build the tests and create the code that will pass those tests as a development methodology.  A Big Design Up Front can cause problems as this gives the idea of locking things into place which makes the system being built to be less nimble in the end.

Robert Harvey added this in the comments which is worth stating in the answer:

Unfortunately I think that this is a common misconception about TDD:
  you can't grow a software architecture by just writing unit tests and making them pass. Writing unit tests does influence the design, but
  it doesn't create the design. You have to do that.


问:
RESTful API design. What should I return if there are no rows?
I'm currently coding an API for a social network with the Slim Framework. My question is: What are the best practices when there are no rows to return in the json structure?

Lets say that this call /v1/get/movies returns 2 rows from the table movie names:

```<code>[
    {"name": "Ghostbusters"},
    {"name": "Indiana Jones"}
]
</code>```

But, then I call /v1/get/books and there are no rows in that table. Should I just return an empty structure?

```<code>[
]
</code>```

...or would it be better a message and an error code?

```<code>[
    "errors": {
        "message": "no matches found",
        "code": 134
    }
]
</code>```

Which is a better practice? (the API will be used in iOS and Android apps) Thanks!

答:
There has been a reasonable amount of work done on creating a standardised JSON API format.

Following the principles in that specification mean that all resources returned should effectively be "collections" (even when just a single resource is included).  Following this would mean that your call to /v1/get/movies would return:

```<code>{
    "movies": [
        {"name": "Ghostbusters"},
        {"name": "Indiana Jones"}
    ]
}
</code>```

Your call to /v1/get/books (which returns zero resources) would return:

```<code>{
    "books": []
}
</code>```

Body:
There has been a reasonable amount of work done on creating a standardised JSON API format.

Following the principles in that specification mean that all resources returned should effectively be "collections" (even when just a single resource is included).  Following this would mean that your call to /v1/get/movies would return:

{
    "movies": [
        {"name": "Ghostbusters"},
        {"name": "Indiana Jones"}
    ]
}

Your call to /v1/get/books (which returns zero resources) would return:

{
    "books": []
}


答:
I would definitely not say it's a bad thing. The nice thing about CLI programs is that when implementing them you can have a very restricted scope. For instance, if I want to write a cat clone or "a program to print the contents of a file to the screen", that's very feasible with CLI.

However, what if you didn't use CLI, well then you'd have a basic program with a GUI that displayed some text. But then you'd also have to tie in opening a file dialog and hooking that up.. but then someone also wants to be able to modify the text and save it elsewhere..

Scope creep is ridiculous with GUI apps. It's so extremely easy to avoid though with CLI apps. "You want to edit the file and then resave it? cat foo > ed > bar" With CLI apps it's trivial for your users (not you, the developer) to combine it with other tools.

Now, that being said, CLI programs are starting to be viewed as "backwards". This is because a lot of application development these days happens in marketplaces where users combining your tool with other tools is next to impossible. I won't go into that here, but I did write a blog post about how "marketplaces enforce master-of-none mentality", which is the complete opposite of a well designed CLI app (to do one thing and to do it well)


问:
How do web apps create subdomains?
I want to understand the architecture of web apps that use subdomains. I don't think that I'm phrasing this well, so let me explain.

Many web apps, like tumblr or shopify create a user's site on a subdomain. Say for example my tumblr account was johndoe then you could find my tumblr blog at johndoe.tumblr.com. Can someone explain how this is implemented?

答:
Basically you could either set new CNAME record to your DNS server for each user (if you have such ability by your Hosting/DNS server provider) or use the Wildcard DNS record method and then use some rewrite rules to process the requests.

You can read more about it on this older post in stackoverflow.

Title: How do web apps create subdomains?


问:
External repository moved from Sourceforge (SVN) to GitHub, now what?
We've been getting the head revision of the JEDI Code library for a while, we only use it a tiny bit so never have bothered to manage which version we're getting.  The problem is they appear to be totally untethered from SVN now and we'd been including it in our repository as an external and now my build server it kaput.

The obvious thing to do would be to just download zip and make a new repository on my SVN server and use that instead, updating when I feel like it.  But is there a better solution? We use Tortoise SVN as an SVN client.

(BTW, it's pretty strange that the JCL changed to Git with the great integration in the Delphi IDE isn't it?)

答:
Awesome apparently you can connect straight to github using SVN.

Now all they need is a redirect from sourceforge and the other broken links on the wiki!


答: If you could't edit your DNS record, you can also insert a subdomain which will be pointing to *.yourdomain.com and it willl receive any subdomains, that way you will can check on your system if that subdomain inserted by the user is a valid domain, check on a whitelist array, os simply checking on the database if the user exists on the system.

Title: How do web apps create subdomains?

Body:
I want to understand the architecture of web apps that use subdomains. I don't think that I'm phrasing this well, so let me explain.

Many web apps, like tumblr or shopify create a user's site on a subdomain. Say for example my tumblr account was johndoe then you could find my tumblr blog at johndoe.tumblr.com. Can someone explain how this is implemented?


答:
Others may disagree, but to me many of the newer methodologies rely on the assumption that the developer is going to do most of what the older methodologies spelled out just out of habit or personal pride, that the developer is usually doing something that is fairly obvious to them, and the work is encapsulated in a clean language or the cleaner parts of a somewhat messy language so you can do all the test business.

Some examples where I have run into this in the past:

Take a bunch of spec-work contractors and tell them their team is
Agile and Test First.  They often have no habit other than to work to
spec and they have no concern over the quality of the work as long as
it lasts long enough to finish the project.

Try and do something new test first, spend much of your time ripping
tests as you find various approaches and interfaces are crap.

Code something low level and either get slapped for lack of coverage,
or write a lot of tests that do not amount to much value because you
cannot mock the underlying behaviors you are tied to.

Any situation where you don't have enough of the underlying mechanics in place ahead of time to add a testable feature without writing a bunch of underlying untestable bits first, like disk subsystem, or a tcpip level communication interface.

If you are doing TDD and it is working for your, good for you, but there are a lot of things (whole jobs, or stages of a project) out there where this just simply does not add value.

Your example sounds like you aren't even to a design yet, so either you need to have an architecture conversation, or you are prototyping.  You need to get through some of that first in my opinion.

Title: I don't understand how TDD helps me get a good design if I need a design to start testing it

Body:
I'm trying to wrap my head around TDD, specifically the development part. I've looked at some books, but the ones I found mainly tackle the testing part - the History of NUnit, why testing is good, Red/Green/Refactor and how to create a String Calculator.

Good stuff, but that's "just" Unit Testing, not TDD. Specifically, I don't understand how TDD helps me get a good design if I need a Design to start testing it.

To illustrate, imagine these 3 requirements:

A catalog needs to have a list of products

The catalog should remember which products a user viewed

Users should be able to search for a product

At this points, many books pull a magic rabbit out of a hat and just dive into "Testing the ProductService", but they don't explain how they came to the conclusion that there is a ProductService in the first place. That is the "Development" part in TDD that I'm trying to understand.

There needs to be an existing design, but stuff outside of entity-services (that is: There is a Product, so there should be a ProductService) is nowhere to be found (e.g., the second requirement requires me to have some concept of a User, but where would I put the functionality to remind? And is Search a feature of the ProductService or a separate SearchService? How would I know which I should choose?)

According to SOLID, I would need a UserService, but if I design a system without TDD, I might end up with a whole bunch of Single-Method Services. Isn't TDD intended to make me discover my design in the first place?

I'm a .net developer, but Java resources would also work. I feel that there doesn't seem to be a real sample application or book that deals with a real line of business application.  Can someone provide a clear example that illustrates the process of creating a design using TDD?


答:
It's not just Unix that's driven by command line programs.  Microsoft is heading that way too.

Microsoft has been pushing PowerShell for some time now.  All of their current server software (Exchange, SharePoint, Server 2012, System Center, etc) can be completely controlled through the PowerShell command line. And PowerShell relies on small functions that do one thing well and pipe data to the next one (though it pipes objects instead of just text).

Most of the GUIs to those programs are simply a frontend to the PowerShell commands, many even tell you what commands it's going to run to make scripting easier. Everything you can do from the GUI you can do from PowerShell. The reverse is not true - there are quite a few functions that are exposed only in PowerShell.

So if *nix has always done it, and Microsoft is heading that way... doesn't seem very backwards to me!


问:
How to calculate throughput if there is network traffic
I came across this question in a textbook, but there are no solutions and I'm not sure how to solve this.

The question is: Suppose Host A wants to send a large file to Host B. The path from Host A to Host B has three links of rates R1=500Kb/s, R2=2Mb/s and R3=1Mb/s. Assuming that there is another busy flow that travels through the same set of links (say from Host C to Host D), what will be the throughput for this file transfer?

I know that the throughput for no traffic would be the min(R1, R2, R3), so would the throughput with traffic be the max(R1, R2, R3)?

答:
```<code> Speed = min(R1,R2,R3) / number_of_connections
</code>```


答:
TTD drives design discovery by test failure, not success, therefore you can test unknowns and iteratively retest as unknowns are exposed ultimately leading to a complete harness of unit tests - a very nice thing to have for ongoing maintenance and a very difficult thing to try to retrofit after code is written/released.

For example, a requirement may be that input can be in several different formats, not all are known yet.  Using TDD you would first write a test that verifies the appropriate output is supplied given any input format.  Obviously this test will fail, so you write code to handle the known formats and retest.  As the unknown formats are exposed through requirements gathering, new tests are written before the code is written, these also should fail.  Then new code is written to support the new formats and all tests are rerun reducing the chance for regression.

It is also helpful to think of unit failure as "unfinished" code instead of "broken" code.  TDD allows for unfinished units (expected failures), but reduces the occurrence of broken units (unexpected failures).


问:
How can I avoid editing conflicts repeatedly when merging from one to branch to another?
I have an SVN repository set up like so:

trunk

branches

UAT

QA

DevelopmentTeam

programmer1

projectA

projectB

programmer2

projectC

projectD

programmer3

projectE

projectF

projectG

projectH

Each programmer can have multiple projects which are branches, and can be merged to their "programmer" branch.

All programmers branches are merged to the DevelopmentTeam branch by the Manager, where the changes are tested with other programmers' projects.

Once this testing is complete, the DevelopmentTeam branch is merged to the QA branch, where QA testing is performed.

Once QA testing is complete, the QA branch is merged to the UAT branch, where UAT is performed.

Once UAT is complete, the changes are merged to the trunk.

Now, let's say I have one programmer working on two project branches. They complete them on the same day, and each is merged to the DevelopmentTeam branch, then QA, then UAT. However, during UAT, it is discovered that some changes are needed. So the programmer goes back to his project branch, makes the changes, commits, then the merging up the line begins again. The problem is, that the new "conflicts" have to be managed at each merge.

I've used SVN for several years, so I understand branching, tags, merging, commits, etc.. But, I think I need a lesson in "organizing" (for lack of a better term).

Note developers are working in separate branches instead of shared (aka "unstable") trunk because I'm trying to setup a system where the trunk exists as the "production" code base. Anything in the trunk is considered "live". Then the Dev, QA, and UAT branches are for each level of testing (QA is the QA website, UAT is the UAT website).

答:
Conflicts occur because two people change the same part of the code in different, incompatible ways.  If you see a lot of them, this should raise some questions about your basic development methodology.

First, you appear to be abusing branching rather severely.  Giving every developer their own repository basically defeats the purpose of having a collaborative version control system in the first place.  (Yes, you still have the advantages of keeping a history and a "time machine" that you can roll back to, but that's only half the point of a VCS when you have a development team.)

Your project ought to be branched by version--a 3.0 branch, a 3.1 branch, a 3.2 branch, and so on--not by developer.  When you need a stable revision of a version for a release, turn it into a Tag.

Having your developers all check in to the same branch (and synchronize frequently) minimizes the number of merge conflicts you run into, because having a shorter interval between merges means that it's less likely that two developers will touch the same code without synchronizing.

Also, try to assign specific areas of the codebase to specific developers.  Again, this cuts down on the number of times their changes will overlap, which cuts down on merge conflicts.


问:
How to handle conflicts between developers in your team?
This is happening in every team.

For some reasons, conflicts arise in the team and they affect the overall motivation and productivity.

What is your recommended approach to solve that common problem?

Examples:

one part of the team wants to implement dependency injection, the other part think it's a waste of time.

some developers think the rest of the team is slowing down development (which explains why they are late on the schedule)

personal incompatibilities between one or more developers

one developer refuse to talk to another one (without apparent reason)

答:
I've found a "team Contract" usefull.

It has to be colaboratively developed by the team members them selves, if it comes down from on high it won't work.

Although, it's a little late if the team is already fighting.


答:
Your problem is you aren't working on the same codebase. Each dev has their own codebase, which is apparently being allowed to diverge significantly from the trunk (if it wasn't diverging, you wouldn't have this problem).

I think the existence of the 'programmer' branches is really the problem here. You should probably go for per-project branches, and when you promote the change to the trunk, then you should either terminate the branch, or at least sync the trunk changes back onto the branch.

Doing that will keep the difference between the project branches and the trunk to a minimum, and minimize the issues when merging.

Another way to deal with this would be to have the programmers grab trunk changes onto their branches on a regular basis (daily would probably be best). This again will keep their branches as similar to the trunk as possible, again minimizing hassle during merge.

Title: How can I avoid editing conflicts repeatedly when merging from one to branch to another?

Body:
I have an SVN repository set up like so:

trunk

branches

UAT

QA

DevelopmentTeam

programmer1

projectA

projectB

programmer2

projectC

projectD

programmer3

projectE

projectF

projectG

projectH

Each programmer can have multiple projects which are branches, and can be merged to their "programmer" branch.

All programmers branches are merged to the DevelopmentTeam branch by the Manager, where the changes are tested with other programmers' projects.

Once this testing is complete, the DevelopmentTeam branch is merged to the QA branch, where QA testing is performed.

Once QA testing is complete, the QA branch is merged to the UAT branch, where UAT is performed.

Once UAT is complete, the changes are merged to the trunk.

Now, let's say I have one programmer working on two project branches. They complete them on the same day, and each is merged to the DevelopmentTeam branch, then QA, then UAT. However, during UAT, it is discovered that some changes are needed. So the programmer goes back to his project branch, makes the changes, commits, then the merging up the line begins again. The problem is, that the new "conflicts" have to be managed at each merge.

I've used SVN for several years, so I understand branching, tags, merging, commits, etc.. But, I think I need a lesson in "organizing" (for lack of a better term).

Note developers are working in separate branches instead of shared (aka "unstable") trunk because I'm trying to setup a system where the trunk exists as the "production" code base. Anything in the trunk is considered "live". Then the Dev, QA, and UAT branches are for each level of testing (QA is the QA website, UAT is the UAT website).


答:
I'm trying to wrap my head around TDD...
  To illustrate, imagine these 3 requirements:

A catalog needs to have a list of products

The catalog should remember which products a user viewed

These requirements should be restated in human terms.  Who wants to know which products the user previously viewed?  The user?  A salesperson?

Users should be able to search for a product

How?  By name?  By brand?  The first step in test-driven development is to define a test, for example:

```<code>browse to http://ourcompany.com
enter "cookie" in the product search box
page should show "chocolate-chip cookies" and "oatmeal cookies"
</code>```

>

At this points, many books pull a magic rabbit out of a hat
  and just dive into "Testing the ProductService", but they don't
  explain how they came to the conclusion that there is a ProductService
  in the first place.

If these are the only requirements, I certainly wouldn't leap to create a ProductService.  I might create a very simple web page with a static product list.  That would work perfectly until you get to the requirements to add and delete products.  At that point I might decide it is simplest to use a relational database and an ORM, and create a Product class mapped to a single table.  Still no ProductService.  Classes like ProductService will be created when and if they are needed.  There may be multiple web requests that need to perform the same queries or updates.  Then the ProductService class will be created to prevent code duplication.

In summary, TDD drives the code to be written.  Design happens as you make implementation choices, and then refactor the code into classes to eliminate duplication and control dependencies.  As you add code, you will need to create new classes to keep the code SOLID.  But you don't need to decide ahead of time that you will need a Product class and a ProductService class.  You may find that life is perfectly fine with just a Product class.

Body:
I'm trying to wrap my head around TDD...
  To illustrate, imagine these 3 requirements:

A catalog needs to have a list of products

The catalog should remember which products a user viewed

These requirements should be restated in human terms.  Who wants to know which products the user previously viewed?  The user?  A salesperson?

Users should be able to search for a product

How?  By name?  By brand?  The first step in test-driven development is to define a test, for example:

browse to http://ourcompany.com
enter "cookie" in the product search box
page should show "chocolate-chip cookies" and "oatmeal cookies"

>

At this points, many books pull a magic rabbit out of a hat
  and just dive into "Testing the ProductService", but they don't
  explain how they came to the conclusion that there is a ProductService
  in the first place.

If these are the only requirements, I certainly wouldn't leap to create a ProductService.  I might create a very simple web page with a static product list.  That would work perfectly until you get to the requirements to add and delete products.  At that point I might decide it is simplest to use a relational database and an ORM, and create a Product class mapped to a single table.  Still no ProductService.  Classes like ProductService will be created when and if they are needed.  There may be multiple web requests that need to perform the same queries or updates.  Then the ProductService class will be created to prevent code duplication.

In summary, TDD drives the code to be written.  Design happens as you make implementation choices, and then refactor the code into classes to eliminate duplication and control dependencies.  As you add code, you will need to create new classes to keep the code SOLID.  But you don't need to decide ahead of time that you will need a Product class and a ProductService class.  You may find that life is perfectly fine with just a Product class.


答:
For what it's worth, TDD helps me come to the best design more quickly than not doing TDD. I would probably come to the best design with or without it. But that time that I would have spent thinking it through and taking a few stabs at the code is spent writing tests instead. And it's less time. For me. Not for everyone. And, even if it took the same amount of time, it would leave me with a suite of tests, so that refactoring would be safer, leading to even better code down the line.

How does it do it?

First, it encourages me to think about every class as a service to some client code. Better code comes from thinking about how the calling code wants to use the API rather than worrying about how the code itself should look.

Second, it stops me writing far too much cyclometic complexity into one method, while I'm thinking it out. Each extra path through a method will tend to double the number of tests I need to do. Sheer laziness dictates that after I've added too much logic, and I have to write 16 tests to add one condition, it's time to pull some of it out into another method / class and test it separately.

It's really that simple. It's not a magic design tool.


问:
Which Ext JS license should be acquired (when developing a Spring MVC/Hibernate/Ext JS web application)?
I am inquiring about a web app which uses Spring MVC and hibernate on the server and
ExtJS 4 (Sencha JavaScript framework) for the client framework (widgets).

The app is cloud-hosted - it is not "distributed" to users. It is required that users
of the app shall need to purchase a license from the vendor in order to use it.

I am completely new to software licensing and am not sure which ExtJS license is
required/preferable, i.e the commercial license or the GNU GPL license?

I have a few questions to hopefully help clarify:

Is it possible to use the GPL license or similar allowing only part of the app's source
to be distributable, e.g. the Extjs components, but not allow users to see other components of the system? i.e. the Spring MVC, hibernate server components?
Is it possible to restrict access to the ExtJS source if using a GPL license?
In general is it possible to restrict distribution of some aspects of the source when using GPL?

If the GPL license is acquired, is the source available only to users of the system
or is it open to the whole general public?

答:
Read Sencha's Open Source FAQ and if that doesn't clear it, up ask them.  They will tell you what their license allows and how they interpret the GPL.

Sencha appears to be pretty strict in their definition of derived work and "conveyance".  Since ExtJS is a javascript library you are conveying the work to all end users of the application.  And it appears that by their definition both the client code and server code of any application that uses the ExtJS library is a derived work.

Also, Sencha has the following clause in their commercial license:

The license prohibits combining code that you develop using a GPL licensed version of the software with code that you develop using a commercial licensed version. In other words, you may not begin development with our GPL version and then "convert" it to our commercial version.

So don't start with the GPL licensed version if you plan on ever releasing under a non-GPL license.

My interpretation of the Sencha Licenses:  If your code is not GPLv3 do not do any development with the GPL licensed ExtJS code.

And to specifically address your questions:

No, Sencha considers the whole application a derived work.

My interpretation of their license and FAQ is that you will be obligated to provide the source code of your web app to all end users of your web app. The GPL does not require you to give the source to the general public but it does allow your users to give it away to the general public.


答:
Having the ability to work with a CLI is hardly what I would consider backwards. It looks great on a resume, especially if you can spin it on your resume with a phrase like "Used (Powershell/Bash) to build a suite of automation tools to send SMS messages when the Database was down".

When I am responsible for hiring people, a working knowledge of the CLI is something I look for.


答:
In the question it is stated:

... many books pull a magic rabbit out of a hat and just dive into "Testing the ProductService", but they don't explain how they came to the conclusion that there is a ProductService in the first place.

They came to that conclusion by thinking about how they were going to test this product. "What sort of product does this?" "Well, we could create a service". "Ok, let's write a test for such a service"


问:
IDE Generated Code
Many IDEs have the ability to spit out automatically written pieces of code. For example, it might generate a getter/setter pair for you. I wonder whether it isn't an attempt to work around some flaws in the language. If your IDE can figure out what the code should be without your help, why can't the compiler?

Are there cases where this is a really good idea? What kind of code generation does your IDE provide? Would the same thing be better provided as a feature of the language?

答:
This feature can be taken away from the compiler proper and be given a name of its own.  This need not be a language feature.  There can be generic template generators or skeleton code generators.

They could sit somewhere in between compiled languages and interpreted languages.  By taking them away from the compiler proper, you do not unnecessarily fatten it up.  Not everyone will be using every template.

If it need not be provided by the compiler, the language need not provide it as a feature.

Title: IDE Generated Code


问:
Does domain specific languages use other programming languages?
Does a domain specific language use other languages like c++ or java, or is it standalone?</p>

答:
Yes, DSLs are often implemented using other languages. Tcl, ruby, groovy, and many others are very good for creating DSLs. A simple DSL can be developed in a matter of just a few hours or days in many cases.

A lot depends on he "D" -- the domain. If you're writing a DSL for financial traders, you might write it in C to get high performance. If you're writing a DSL for a testing framework or to describe a GUI, building atop an existing language may make more sense.

Other factors include whether this is a DSL that will be used daily by domain experts who have a specialzed vocabulary, or if it is for novices to configure a game once every few months. Will it be a commercial product or a freebie? And so on.

There are many, many use cases for small DSLs to be written on top of scripting languages.