答:
what way is correct ...

Being cynical just for a moment, none of them.

Try as we might; we never get it completely right.  But we can try.

... for performance ...

Database.

For raw data processing power, leverage your DBMS.  You don't say which one you're using but all the Big Players have some sort of procedural language (PL/SQL, T-SQL, etc.) that you can write code in, using the full power of the database and without those nasty network overheads.

... and future support?

And there's the problem.

You could write something that runs inside the database and is phenomenally fast, but if no-one else in the company knows that language, then you have a problem.
It might be better to sacrifice that raw power for a program written in something more "mainstream"; except in a very few cases, maintainability should be your #1 priority, even at the expense of straight-line speed.

Title: How should I compare two database tables - with SQL or using Java?

Body:
I have two tables with different structure. I should compare ID from 1st table with ID of the intermediate table and then comapre TXT field of the intermediate table with TXT field of the 2nd table.

If there are missing records, or different values for TXT field in 1st and 2nd table I should add flag to the record in the 2nd table and recreate this record with additions from the 1st table.

I have two ways to do it. Using Java with JDBC or using SQL (or PL/SQL). But what way is correct for performance and future support?


问:
How can I ask my boss (in a polite way) to comment his code?
I am being taught by my boss (I just finished school and he wanted someone with a little programming experience, so he chose me to train me on what that company specializes in) and started working with ASP.NET MVC applications, some HTML and CSS. I'm fine with the web design stuff he gives me (it is pretty simple to understand without clarification).

But for instance, he gives me a task to do with ASP.NET MVC, he explains it really well. But he doesn't explain anything in the code he has just given me. (We use source control in Visual Studio 2013), so it's literally hundreds of lines of code, without any background on what it is supposed to do. The kind of code that I'm seeing is code I've never seen before, so it is really difficult to try and figure out.

I would try and ask him more questions, but he is always working (it's his own business), and I feel as though he might get annoyed with all these questions I have on my hands.

So just something that will help my out until I get a grip on things, how can I ask my boss to put comments into his code that he gives me, but politely?

答:
As a software engineer of 20 years standing, mostly working on safety-related stuff (SF-PD), I'd have to say that your boss may not the person you want to be your example.  Lack of comments is a sign of either a self-taught amateur coder who's never learnt how to do the job properly, or an inexperienced engineer.  Or perhaps an engineer who simply doesn't have the time - deadlines and expediency can do horrible things to your code! ;)  It's definitely an anti-pattern for every competent software engineer though.

Your boss might be a very good coder, but it sounds like he's not a good software engineer.  An engineer uses collective group experience to avoid the pitfalls that other people have already been caught out by.  Effective commenting is part of that collective group experience for software, in the same way as stress analysis is part of the collective group experience for mechanical engineering.  What counts as effective commenting is more fluid though, and it's definitely something you get from experience.

The most basic thing is that comments should not say what a line of code does.  There are times when comments to say what a function does are superfluous too (especially in C#).  Over-commenting can be just as ineffective (and a pointer to lack of experience) because you can't find the important stuff in the dross.  As a novice, you may still be working on figuring out the "what" of the code, and for that you just need to read and understand what he's done.

The important thing for comments though is that they say WHY a line of code or a function does what it does, where this might not be obvious.  Do you need to set up module X before module Y?  Is it important to check a return code to see whether a file was already open, or are we consciously ignoring the return code because this has been checked somewhere else?  The "why" of the code will be relevant to everyone, regardless of experience - and it'll be relevant to him as well in 6 months time, when he's forgotten about the good reason for doing something a particular way.  Commenting isn't just for other people, it's for helping you in the future as well.

If you want to avoid annoying your boss, ask smart questions.  Focus on asking about the "why", and try to work out the "what" yourself (unless it genuinely is obscure).  No good boss will mind being asked questions if they aren't the kind of things that you could have found from R-ing TFM.  And no good engineer will mind being asked to do something that'll make another engineer's life significantly easier, at little cost to them.  (Just don't ask him to backfill comments on the entire codebase! ;)

ContentLicense: CC BY-SA 3.0


答:
Firstly let this be an example to you to comment your code properly, grasshopper!

Then, I have to do this all the time. I have my local copy checked out, and I go through it and comment it myself. (I can strip them all back out again if I am going to check it back in - or leave them in, if nobody minds.) Then when I really can't see further, I can ask someone, here, I think it does this (what I commented), am I right? So you may have done the actual commenting, but it's done and that's the point.

Title: How can I ask my boss (in a polite way) to comment his code?

Body:
I am being taught by my boss (I just finished school and he wanted someone with a little programming experience, so he chose me to train me on what that company specializes in) and started working with ASP.NET MVC applications, some HTML and CSS. I'm fine with the web design stuff he gives me (it is pretty simple to understand without clarification).

But for instance, he gives me a task to do with ASP.NET MVC, he explains it really well. But he doesn't explain anything in the code he has just given me. (We use source control in Visual Studio 2013), so it's literally hundreds of lines of code, without any background on what it is supposed to do. The kind of code that I'm seeing is code I've never seen before, so it is really difficult to try and figure out.

I would try and ask him more questions, but he is always working (it's his own business), and I feel as though he might get annoyed with all these questions I have on my hands.

So just something that will help my out until I get a grip on things, how can I ask my boss to put comments into his code that he gives me, but politely?


问:
How can user stories not contain requirements (when written on a card) and still be implementable
I've been told "User Stories are not requirements, it is just a reminder of what customer wants, you cannot put requirements within a story". But let's take for an example that a customer wants a different processing for different credit cards. There are strict requirements that must be implemented and known so that test cases can be written. Where should requirements go if not in the user story?

How can developers develop from a story if there are no lower requirements? How testers can write test cases (detailed ones) based on a user story? Where to requirements like DB constraints, fields validation etc. live outside of the user story?

答:
Yup, its BS. And Scrum is not Agile.

I hate the rigidity of so-called agile practitioners who tel you that there is one way of doing agile and that you must follow all the rules laid out in the holy scriptures of whichever 'agile' methodology they use. Its all BS.

Agile is about being agile.

Agile is about getting stuff done with a minimum of overhead. This doesn't mean "no documentation" as you usually end up documenting more in an agile role, you just get on with the documenting without having to plan a process for doing the documentation. Similarly with coding, testing and requirements capture. The only things that matter in an agile process are those that help you get your job done, quickly and efficiently without any BS.

So in this case, if putting user requirements in the cards helps you write, test, document and demonstrate the code that is needed... put the requirements on the card and tell the gurus that the team is always right.

What does the rest of your dev team think? In a true agile methodology, if they all think requirements should be written up front without any 'user conversations' then that should be it, you do what the team thinks works best for them to do their work. If the team thinks that the user conversations are a good thing, then listen to them and understand why they think this and bring yourself into their way of working.


答:
Just don't call this a User Story and everyone will be happy.

I think the answer is, you can write this down wherever you want.

In general, specific implementations are not included in a user story for a few reasons:

You know what the customer wants, but you don't know how it is going to be implemented.

The customer is aware there are more specific requirements involved, but really doesn't care and/or understand them anyway.

Everyone thinks they are fully aware of the specific implementations at this time, but nobody wants to write them down because in their experience, it is all going to change anyway and no one will want to rewrite it.

There are no rules that omit additional documents when necessary. Maybe the client needs access to it and maybe not. If you're hopes are to generate some sort of contract between you and the client on the specific implementation as if you can follow it and when it doesn't work blame the client for agreeing to it, you're mistaken. If the client understands the technical details of credit card processing, you should share these documents with them and possibly make it a part of the conversation.

Title: How can user stories not contain requirements (when written on a card) and still be implementable

Body:
I've been told "User Stories are not requirements, it is just a reminder of what customer wants, you cannot put requirements within a story". But let's take for an example that a customer wants a different processing for different credit cards. There are strict requirements that must be implemented and known so that test cases can be written. Where should requirements go if not in the user story?

How can developers develop from a story if there are no lower requirements? How testers can write test cases (detailed ones) based on a user story? Where to requirements like DB constraints, fields validation etc. live outside of the user story?


答:
This answer will focus on how to work with User Stories and lower level requirements.  I won't be discussing the virtues, or lack thereof, of Scrum or Agile.  I won't be talking about gurus either.

This answer assumes you're on board with Scrum but haven't yet found a way to make it work for you.

As others have mentioned, User Stories are meant to cover how the Users would like the software to be.  Because the Users don't care about low level implementation stuff like database tables, constraints, architectural patterns, etc, you won't find such details in a User Story.

However, that doesn't mean these details should not be recorded anywhere.

When developers implement User Stories they need to be aware of lower level details typical Users won't know.  This information can come from SMEs, BAs, the Product Owner, your architect, or any other expert or technically minded person.

Does this mean low level details should be recorded in User Stories?  No (and yes).

At some point between the time the story is created and implemented somebody will need to work out how to implement it.  This usually takes the form of conversations with the people involved in the Story (User, architect, developer, etc).  These conversations should result in unambiguous Acceptance Criteria which clearly delineate the scope of the User Story's implementation.  These details will need to be recorded somewhere and where that is is really up to you.  The key here is that these details are elicited after the User Story has been created.  I think this is what your guru is trying to emphasise.

As a developer it is clear that you'll need a way to associate more specific requirements with your User Story.  Just how you do that is entirely up to your team.

If people on your team want to keep these details out of the User Stories then you may need to respect that.  There are benefits to keeping your high level User Stories free of implementation details.  It keeps them lean and your backlog can be read as a history of what your Users and Product Owner wanted.  Just make your needs as a developer known as well.  You should be able to work out a compromise where simply linking to the User Story keeps everyone happy.


问:
Is XHTML5 dead or is it just an synonym of HTML5?
So what happened to XHTML5?

http://www.w3.org/TR/html5/

That page is a draft for both xhtml5 and html5?
So there's no difference between these doctypes?

答:
HTML5 is a de facto and de jure standard! XHTML is there, as standard also.

HTML5 - A vocabulary and associated APIs for HTML and XHTML

W3C Recommendation 28 October 2014

The title of the standard contains the string "and XHTML", so, we are talking about a final decision of W3C to merge HTML and XHTML into one single standard; and this standard shows how to serialize an HTML file into XHTML file and vice-versa.

XHTML parts and important notes:

the MIME type is application/xhtml+xml

2.2.4. Interactions with XPath and XSLT

9.  The XHTML syntax

Understanding and using

As summarized by LF Sikos

XHTML5 is the XML serialization of HTML5. The syntax is described by the HTML5 specification. However, one shouldn’t be confused since XHTML5 is as an application of XML. In other words, HTML5 and XHTML5 have identical vocabulary but different parsing rules.

HTML5 documents might also be valid XML documents. This markup is often referred as a “polyglot” language. It is the overlap language of documents which are HTML5 and XML documents at the same time. HTML5 and XHTML5 serializations are cross-compatible. However, XHTML5 has a stricter syntax. Furthermore, some parts of XHTML5 are not valid in HTML5, e.g., processing instructions.

So, strictly speaking (and emphasized by  @vaxquis) "XHTML is just a syntax for XML serialization", there are no DTD or other kind of XML schema.

Some people not like to say "XHTML5 is XHTML". The question must split into a mini-FAQ about "when I can use it as XHTML". This is a WIKI, please correct if there are some "misunderstanding"...

FAQ

Can I use XHTML5 as the "2014's version of XHTML standard"?

There are some problems in a "perfect and generic HTML5-to-XHTML5/XHTML5-to-HTML5 convertions", you must do "personal choices" and lost information. As the context will be different answers:

Loose speaking: YES. There are a lot of (simple) examples where the mapping is perfect and reversible.

Strictly speaking: NO.  See also @vaxquis comment below and old answers in this page.  Some typical problems:

https://stackoverflow.com/a/16591582/287948

... please enhance with more examples...

Can I use (fearless!) XHTML5 serialization with XSLT, XPath, etc.?

Yes, you can. Even serializing fragments.

Can I validate XHTML5?

Yes, but not so fast and easy than the old DTD's... See complex validators, as validator.nu

Can I use XHTML5 as non-terminal output in a XSLT chain?

Yes, you can. Let's explain what you can.

Some frameworks, like Cocoon, use "XSLT chains". HTML5 and XHTML5 outputs can be used as "last output in the chain"... Of course, in intermediary steps, HTML5  can not be used because is non-XML, but XHTML5 can be used.

The above problem of validation reappears here: there no strong convention, so, sometimes, less clarity of "XHTML standard structure" appears. In that situation you must pay attention in "yourself conventions", and be consistent.

When using DOMDocument of a HTML5 page, can I use a saveXML() method?

Yes.
This is a typical situation where the serializaion recommendations are used. The XML will be valid, the XHTML5 code is mapped from the original HTML5 and DOM state... But, in some structures, some information can be lost, as commented above.


问:
Big tasks vs short list of small ones at sprint planning meeting
Simply: Sprint planning, we do not have well described user stories and we need to create tasks (since we do PoC-like module, technology remain somewhat unknown). Should a team either:

Create big tasks that cover teams capacity completely. Then tasks in our view are not defined well.
or

Create short but incomplete list of small tasks that can be started at the beginning of the sprint. Later on we add consecutive tasks that will emerge naturally. Then our initial workload is only 1/3 of our capacity.

ADDED:
We are lacking domain knowledge and PO needs a couple of weeks to work it out. I just want to know that if it is okay to start the sprint with incomplete list of tasks for the whole sprint (we have user stories, but things change very rapidly during the sprint).

Which one is a pragmatic Scrum standard or just better in terms of your experience?

答:
Smaller tasks are more easily estimated and implemented.  Smaller tasks also make it easier to identify when you're "done" with the particular task.

The ideal Agile process is highly iterative, so having lots of short but incomplete lists of small tasks makes it easier to iterate through and develop the proof of concept that you're looking for.

Likewise, with big tasks, they are harder to estimate accurately; have a really bad tendency of bleeding over into the next sprint; and are horrifically subject to "scope creep" where the developer constantly realizes "Oh yeah! We need to have baz feature along with foo and bar"


答:
A User Story is one specific kind of artefact with the goal of describing the interface that the user expects from the system and that is why low-level details simply does not belong there. If you put them there, you are changing the intent of the artefact and it no longer fits the definition of a US.

Use other forms of specification to capture lower level requirements and design decisions. Exactly what these other forms should be is something that have to be resolved in your organization and customized to your specific environment.

Your question sounds very similar to something like

I have this CarFactory and I need to have it make Bicycles as well, but our OOD "Guru" says I'm not allowed to do that. What is this BS!?!

Respect the separation of concerns and cohesion of your artefacts, both the ones in your code and the ones in your processes.


问:
Does Un copyrighted software or code fall automatically under copyright?
A programming tutorial, code, software anything that doesn't have a copyright notice or a license ,is it automatically copyrighted to the author ? or its the same as something under public domain or something else ? and does this differ from country to another as some terms differ lets say from US to Australia, and what terms should i follow my country's or the authors ?

Yes i know this is not a website for law things , i asked this on Meta SE and someone suggested that here is the best place for anything that has to do with license about code or software ...

答:
Yes, at least in the US and in all EU member states, copyright exists by default and rights to use the work are automatically reserved either to its author or their employer (if the work is written as part of their obligations to the employer).

In the specific case of examples in a text book, tutorial, or other similar document, you could argue (unless the author states otherwise) that they were clearly intended to be copied, and that's probably acceptable, but in most other circumstances you have no right to use code someone else wrote without them granting you a license of some kind.


答:
Creative works, like books, software, images, etc., are always protected by copyright, even if there is no explicit claim to copyright on them.

The default copyright "license" is that only the original author has the right to distribute and/or modify the work.

If something can be released into the public domain depends on the jurisdiction. Some jurisdictions don't recognize the concept of public domain, or allow works only to fall to the public domain after the copyright expires (typically 70 years after the death of the author).

If you wish to dedicate something you created to the public domain, you can use the Creative Commons CC0 dedication. In jurisdictions that don't allow dedication to the public domain, this automatically becomes a very lax license.

Title: Does Un copyrighted software or code fall automatically under copyright?

Body:
A programming tutorial, code, software anything that doesn't have a copyright notice or a license ,is it automatically copyrighted to the author ? or its the same as something under public domain or something else ? and does this differ from country to another as some terms differ lets say from US to Australia, and what terms should i follow my country's or the authors ?

Yes i know this is not a website for law things , i asked this on Meta SE and someone suggested that here is the best place for anything that has to do with license about code or software ...


问:
Separating Django models for SOA
First of all, the goal of this exercise is to create a SOA with Django.

I am trying to understand what the implications would be if I decided to separate and insulate models into apps, provide a REST API for accessing those apps and then create other apps which basically use the REST API to obtain data and perform operations on the models (DB).

I have been reading documentation and playing with Django for a while (not too long), but, as far as I can tell, the only important Django features I would be forefeiting are the ability to use generic views and forms. Since I am not really very experienced with Django I'd like to get more insight before I jump into it.

What other really useful Django features would I lose?

Is there a way to overcome this without exposing the models to other Apps?

答:
What other really useful Django features would I lose?

"Lose" is probably the wrong way to think about it. Never use and just take up space is probably more accurate. It could be argued that Django is too big a framework for what you are describing. Is there any particular reason why you have to use Django? A micro-framework like Flask might fit the requirements better, it is light weight and would not include a lot of code you will never use.

Is there a way to overcome this without exposing the models to other Apps?

You don't expose models via HTTP, you expose resources. Some times resources will be the same as the model, but other times they won't. Some web frameworks map models to resources in a 1 to 1 fashion but this is considered these days to be a bad idea to hard code this mapping, as it makes your apps much less flexible (your model might change as the app grows but you would not necessarily want your resources to change)

So think of resources and your domain model as two related but separate things.

Title: Separating Django models for SOA


答:
I think if what your Scrum consultants are telling you is that Scrum doesn't require requirements then you have some very poor consultants.  They are even wrong to tell you that a user story is not in fact a requirement at all, they just happen to be one kind of requirement.

What are the different types of software requirements?

Business Requirements

These are generally a high level business need, something that generally would amount to some kind of executive style statement about a system.  It is purposely high level and broad and by itself cannot be implemented without vastly more detail.

User Requirements

These are the User Story requirements that you are familiar with.  They can generally fit on a sticky note.

Actor - Typically a user or stakeholder.

Need - Some item or general functionality that is needed by the user

Reason - The reason or context behind why this need exists

Acceptance Criteria - This is the framework for user acceptance testing and during Sprint Demo how the Product Owner will be able to decide if a user story is Accepted or not.

Functional or System Requirements

This seems to be the missing piece in your puzzle.  Driven from the user level requirements, a functional requirement defines system level actors and properties of a system, as well as behaviors and functions of a system.  This could also be done in a story format and included in your backlog.  These items should stand alone and can be implemented independently of any one user requirement.

Actor - A system or component of some kind.

Need - A need, or property, or statement of behavior of a system that should exist.

Reason - A context behind why this is needed in the system

Acceptance Criteria - Scenarios, behaviors, functions and flows that are necessary to communicate how System and Integration testing should be performed.  When these types of tests are passed for the requirement then we know this functional requirement has been completed.  These can exist in external documentation from your user stories but should be completed prior to these stories being assigned in a sprint.

The functional requirements define your solution which sounds like what you are describing as the gap in your process.

Notable requirement types that need mentioned but are inconsequential to your question: Non-Functional Requirements, Technical Requirements, etc...


答:
Which is Scrum standard/better in terms of your experience?

Getting user stories well defined. If necessary, that means getting the product owner in your sprint planning to answer questions. That will lead to two sort of scenarios:

You get your questions answered. Sweet, now you can make your small well-defined stories as you normally would.

Nobody knows what's going on, so you need to investigate.

I'll focus on the latter case, since that seems to be what you have. In that case, what I've seen work best is to not do a lot of sprint planning. "Okay Bob, we need to figure out how to do XYZ - what do you think you'll be able to show in 2 weeks?" Bob gives some tentative goal, everyone agrees and Bob can go dig into stuff.

Bob then keeps everyone up to date during standup, which also provides opportunity to manage expectations about that tentative goal. If he can define tasks for the different parts of investigation, great. That is really only necessary if there are others that need to work on the tasks.

Having formal tasks for this sort of work is only counterproductive in my experience. They are going to be tiny or vague. Tiny stories just increase overhead and cause clutter. Vague stories just cause project managers to interfere and provide no value.

The main thing to remember is that as soon as Bob starts saying "I made..." you stop him and make tasks. Research is a vague, exploratory affair. Implementation (even prototypes) is not. Once you found out what you need to find out, go back to the better process.

Title: Big tasks vs short list of small ones at sprint planning meeting

Body:
Simply: Sprint planning, we do not have well described user stories and we need to create tasks (since we do PoC-like module, technology remain somewhat unknown). Should a team either:

Create big tasks that cover teams capacity completely. Then tasks in our view are not defined well.
or

Create short but incomplete list of small tasks that can be started at the beginning of the sprint. Later on we add consecutive tasks that will emerge naturally. Then our initial workload is only 1/3 of our capacity.

ADDED:
We are lacking domain knowledge and PO needs a couple of weeks to work it out. I just want to know that if it is okay to start the sprint with incomplete list of tasks for the whole sprint (we have user stories, but things change very rapidly during the sprint).

Which one is a pragmatic Scrum standard or just better in terms of your experience?


问:
Cheap implementations in fundamental TDD
This is a question concerning the fundamental approach of TDD, so the example below is as simple as possible which might make it seem a little useless; but of course the question applies to more complicated situations as well.

Some colleagues and I are currently discussing and trying out some basic TDD ways of coding.  We came across the questions how to deal with cheap solutions for existing but not encompassing TCs.  In TDD one writes a TC which fails, then implements whatever it takes (and not more!) to let the TC pass.  So the task at hand would be to make the TC green with as little effort as possible.  If this means to implement a solution which uses inside knowledge of the TC, so be it.  The reasoning was that later TCs would check for more general correctness anyway, so that first solution would need to be improved then (and only then).

Example:

We want to write a comparison function for a data structure with three fields.  Our comparison shall return whether the given values are equal in all three fields (or differ in at least one).  Our first written TC only checks if a difference in the two first values is detected properly:  It passes (a,b,c) and (a,b,c) and checks for a correct detection of equality, then it passes (a,b,c) and (x,b,c) and checks for a correct detection of inequality.

Now the cheap approach would be to also implement only a comparison of the first field because this should be enough to pass this TC.  Keep in mind that this can be done because we know that later tests will also check for the equality of the two other fields.

But of course it does not seem very useful to only implement such a (more or less) nonsense solution; every programmer doing this would do it in the knowledge of writing a bug.  It obviously seems more natural to write a decent comparison right away in the first iteration.

On the other hand, writing a correct solution without having a TC which checks it might lead to the situation that such a TC which tests the behaviour more thoroughly will never get written.  So there is behaviour which was written without having a TC for it (i. e. which is not developed test-driven).

Maybe a proper approach is to not write such rudimentary TCs (like the one only checking the first field) in the first place, but that would mean to demand perfect TCs in first iteration (and of course in complexer situations one will probably not always write perfect TCs).

So how should one deal with rudimentary TCs?  Implement a cheap solution or not?

答:
You're correct that demanding perfect Test Cases is unrealistic for most code (with a possible exception for Mars Rover code).

I'd argue that it's necessary to honor the intent of the Test Case / specification in addition to the 'letter of the law'.  In your example the developer has the opportunity to write an obvious bug.  The correct action would be to fix the Test Case first, then write the code.

Tests are code too, and are also subject to bugs, incomplete implementations, etc.


答:
I think your problem arises only because the requirement is very simple and the solution comparing all 3 values at once maybe just a one-liner. Having slightly more complex requirements, and it will perfectly make sense not to implement anything beyond the scope of the already implemented test cases.

Nevertheless, your "cheap approach" has indeed one advantage which makes it less nonsensical than you might think: chances are much better you don't forget to add all of the important test cases. If you implement the three-value comparison at once, there is a certain probability that you might omit further test cases, since you are already in the mental state of "beeing done". If, however, you know your code is "not ready" yet, and you force yourself not to change it without further test cases, chances are much higher you actually will take the time and add those test cases.

Especially for TDD learning purposes, I recommend "TDD as if you Meant it", an exercise invented by Keith Braithwaite to train developers doing TDD in even smaller steps. Applied to your example: in this exercise, your first step would not even be to implement a function with one equality check, you would implement the equality check in the testing code first, and then refactor it out afterwards to the comparison function.

Title: Cheap implementations in fundamental TDD

Body:
This is a question concerning the fundamental approach of TDD, so the example below is as simple as possible which might make it seem a little useless; but of course the question applies to more complicated situations as well.

Some colleagues and I are currently discussing and trying out some basic TDD ways of coding.  We came across the questions how to deal with cheap solutions for existing but not encompassing TCs.  In TDD one writes a TC which fails, then implements whatever it takes (and not more!) to let the TC pass.  So the task at hand would be to make the TC green with as little effort as possible.  If this means to implement a solution which uses inside knowledge of the TC, so be it.  The reasoning was that later TCs would check for more general correctness anyway, so that first solution would need to be improved then (and only then).

Example:

We want to write a comparison function for a data structure with three fields.  Our comparison shall return whether the given values are equal in all three fields (or differ in at least one).  Our first written TC only checks if a difference in the two first values is detected properly:  It passes (a,b,c) and (a,b,c) and checks for a correct detection of equality, then it passes (a,b,c) and (x,b,c) and checks for a correct detection of inequality.

Now the cheap approach would be to also implement only a comparison of the first field because this should be enough to pass this TC.  Keep in mind that this can be done because we know that later tests will also check for the equality of the two other fields.

But of course it does not seem very useful to only implement such a (more or less) nonsense solution; every programmer doing this would do it in the knowledge of writing a bug.  It obviously seems more natural to write a decent comparison right away in the first iteration.

On the other hand, writing a correct solution without having a TC which checks it might lead to the situation that such a TC which tests the behaviour more thoroughly will never get written.  So there is behaviour which was written without having a TC for it (i. e. which is not developed test-driven).

Maybe a proper approach is to not write such rudimentary TCs (like the one only checking the first field) in the first place, but that would mean to demand perfect TCs in first iteration (and of course in complexer situations one will probably not always write perfect TCs).

So how should one deal with rudimentary TCs?  Implement a cheap solution or not?


答:
Implementing the "cheap" solution first is a good idea, not just because it forces you to write tests that cover all expected behaviour, but also because it sometimes ends up with you writing a simpler solution than you might have in your head.

A good example of this is given in the book Beautiful Code, describing the FIT testing framework. This system works by scanning HTML documents for tables containing data to plug in to test cases and then produces an output document with the table row coloured red or green. A naive approach would be to use an HTML parser, but by just taking the tests one at a time and writing the simplest possible solution at each step, the authors arrived at a much simpler solution that just uses simple string manipulation.

Another thing to consider is Robert C Martin's "Transformation Priority Premise". This is an extension of TDD that gives some extra rules for writing your code as a sequence of simple transformations (similar to refactoring, but with the goal of changing behaviour in controlled ways rather than preserving it), and can give some very interesting results. It's well worth investigating further, I think.


答:
I'd say that something like a tree structure works best. You have a few huge 'root' tasks, detailed into smaller but still large tasks, split into small, less-than-a-day, easy-to-track 'leaf' tasks.

What you discuss for sprint intake is leaf tasks. But you can always trace them back to a bigger picture, which helps understand which small tasks are more worth taking. Also, you can sort-of track the scope and progress of the big tasks.

An example:

Implement user authentication / authorization (a huge task)

...

Implement social login (a large task)

...

Get an OpenID example working (a leaf task)

Get a Google OAuth2 example working (a leaf task)


答:
I think the purpose of this approach is not to constrain user stories, but to prevent bad requirements.

In my experience, users are generally incapable of writing requirements.  Developers are generally incapable of writing requirements.  Heck, let's just admit it straight out: requirements are hard to write!

I think it would be valid for a user to write something in requirements lingo as part of a use story.  However, doing so should not automatically make it a requirement.  Having two conflicting use stories is a minor issue; having two conflicting requirements is a major contract-breaking issue.  There's no sense in promoting one to the other before its time.

I think the draconian viewpoint comes from a recognition of human nature.  If people start thinking of user stories as a place to put requirements, they will begin to do so.  The real advantage of use stories over other means of gathering requirement like information is that they are worded in user's natural wordings and notation.  This makes it more likely that the developers are thinking from the perspective of the customer.  In a perfect world, cold requirements lingo could go there as well.  In reality, such words tend to cause developers to latch onto the easy to understand requirements and miss the subtle wordings and nuances agile development wants to unearth using use stories.


答:
Make your own decisions

The answer to 'So how actually can developers ever develop a story if there are no lower requirements?' is very simple - the detailed requirements that are orthogonal to the needs of the end user (e.g. DB constraints, fields validation, etc) don't actually matter to the user. If the user needs can be met by very different fields validation, very different DB structures or perhaps even no traditional DB at all, then it would be counterproductive to have the users make up such information with a particular implementation in mind, which may be very different from how the system is implemented in the end.

You're professional developers, so make professional decisions to the best of your ability about implementation details. An user who wants a table can tell a carpenter what type of wood they'd like, but the carpenter is expected to decide how thick the table legs should be to handle reasonable loads. If you lack some information to make a meaningful decision, then that needs to be discussed with the user, but some 90% of content for a detailed requirements document actually does not need any information aside from the vague user stories common sense and industry best practices.

All those details aren't arbitrary - there are bad choices and better choices, and they should be documented since they affect other parts of the implementation, but in the end they are still implementation details that can and should be decided by the implementing team according to user needs and best practices.

A standard car analogy - if a customer wants the car painted red, then an appropriate clarification for the user story would be to ask which shade of red would be better, but not the chemical composition of the paint; nonetheless it would be expected that they wouldn't choose to paint the car with watercolors that would wash out in the rain, since it's best practice not to do so.


答:
I wouldn't ask for additional comments, but here are some ideas for you:

Schedule a sit down with your boss and have him go through the code at a high level. This should get you started.  I would expect a few hours to maybe a half a day so you can get up to speed.  This should include overall design, patterns used, etc.

Create a tests project and start writing unit tests against the code, this will help you understand it without impacting it.  You may also find some bugs as well!

Debug the code as needed to understand certain areas.

Take an enhancement or bug off the backlog and work on it.

Comments are OK, but if the code is written in a straight forward manner it should be understandable after a few days.

Also don't expect to understand it all, it is better to focus in on key areas first and then expand code base knowledge as needed.


问:
Naming conventions: camelCase versus underscore_case ? what are your thoughts about it?
I've been using underscore_case for about 2 years and I recently switched to camelCase because of the new job (been using the later one for about 2 months and I still think underscore_case is better suited for large projects where there are alot of programmers involved, mainly because the code is easier to read).

Now everybody at work uses camelCase because (so they say) the code looks more elegant .

What are you're thoughts about camelCase or underscore_case

p.s. please excuse my bad english

Edit

Some update first:

platform used is PHP (but I'm not expecting strict PHP platform related answers , anybody can share their thoughts on which would be the best to use , that's why I came here in the first place)

I use camelCase just as everibody else in the team (just as most of you recomend)

we use Zend Framework which also recommends camelCase

Some examples (related to PHP) :

Codeigniter framework recommends underscore_case , and honestly the code is easier to read .

ZF recomends camelCase and I'm not the only one who thinks ZF code is a tad harder to follow through.

So my question would be rephrased:

Let's take a case where you have the platform Foo which doesn't recommend any naming conventions and it's the team leader's choice to pick one. You are that team leader, why would you pick camelCase or why underscore_case?

p.s. thanks everybody for the prompt answers so far

答: Honestly, it doesn't really matter as long as everyone on the team uses the same scheme. Chances are one or the other is more natural to you, though the real importance is readability of code in the long run and then it is crucial that everyone adheres to the same naming rules.</p>

ContentLicense: CC BY-SA 2.5


问:
Replace repeated timestamp with variable in tests
I have couple hundred tests and I work with date/time a lot. In some tests, I aim for output format, elsewhere, I check date ranges. Therefore, my tests have lots of these:

```<code>FactoryGirl.create(:foo, ended_at: Time.zone.local(2014, 5, 5, 22, 15))
</code>```

I thought, maybe there's a shortcut to these, since in some test files, I only work with few timestamps.

```<code>FactoryGirl.create(:foo, ended_at: may_5_22_15)
</code>```

Where may_5_22_15 would be defined in method or using let.

Is this a good way to go?

Update: More context (thanks @Snowman for pointing out).

Motivation for this is to improve readability of testsuite. It makes it easier to me to read "Foo ended at May 5th by 22:15" rather than parsing a bunch of numbers in Time constructor.

The model has bunch of date/time attributes (ended_at, started_at, closed_at...) and the more specs I write, the more Time constructors I use and re-use. So I thought maybe I could do something like this:

```<code>let(:may_5_22_15) { Time.zone.local(2014, 5, 5, 22, 15) }
</code>```

What I'd like to know is whether this is a good practice or not, in terms of test suite maintenance, readability or if there are any reasons why not to do it.

答:
Just create a specific factory or use default with redefinable value ended_at, as follows:

```<code>factory :foo do
   ended_at { |foo| foo.ended_at || Time.zone.local(2014, 5, 5, 22, 15) }
end
</code>```

or with ignore block:

```<code>factory :foo do
   ignore do
      ended_at { Time.zone.local(2014, 5, 5, 22, 15) }
   end

   after :build do |foo, evaluator|
      foo.ended_at = evaluator.ended_at
   end
end
</code>```

or pass some usual symbol with encoded datetime in its name:

```<code>factory :foo do
   ignore do
      ended_at { '' }
   end

   after :build do |foo, evaluator|
      foo.ended_at = Time.strptime(evaluator.ended_at, '%b_%e_%k_%M')
   end
end
</code>```

Body:
Just create a specific factory or use default with redefinable value ended_at, as follows:

factory :foo do
   ended_at { |foo| foo.ended_at || Time.zone.local(2014, 5, 5, 22, 15) }
end

or with ignore block:

factory :foo do
   ignore do
      ended_at { Time.zone.local(2014, 5, 5, 22, 15) }
   end

   after :build do |foo, evaluator|
      foo.ended_at = evaluator.ended_at
   end
end

or pass some usual symbol with encoded datetime in its name:

factory :foo do
   ignore do
      ended_at { '' }
   end

   after :build do |foo, evaluator|
      foo.ended_at = Time.strptime(evaluator.ended_at, '%b_%e_%k_%M')
   end
end


答:
A lot of this boils down to what is "cheap, useless and ... little effort as possible."

Here's another simple example:  Write a function that returns the result of two numbers added together.
Test:

```<code>check func(2, 2) = 4
// Simple:
  func(a, b) { return a + b}
</code>```

I would like to think this is the first strategy I would take. Seems simple enough to me, but now that I think about it, what about an even simpler approach:

```<code>//Simpler
func(a,b) { return 4}
</code>```

It is simpler and probably useless, but did it really take the least amount of effort? Seems like the first reasonable solution that pops in your head would take the least amount of effort unless the amount of typing is a productivity problem. If something is so obvious that it is a waste of time, don't do it. This is the advantage of having experience and a possible explanation why some people feel good programmers can be 10x more productive because they don't waste time repeating mistakes or writing code they don't need.

Body:
A lot of this boils down to what is "cheap, useless and ... little effort as possible."

Here's another simple example:  Write a function that returns the result of two numbers added together.
Test:

check func(2, 2) = 4
// Simple:
  func(a, b) { return a + b}

I would like to think this is the first strategy I would take. Seems simple enough to me, but now that I think about it, what about an even simpler approach:

//Simpler
func(a,b) { return 4}

It is simpler and probably useless, but did it really take the least amount of effort? Seems like the first reasonable solution that pops in your head would take the least amount of effort unless the amount of typing is a productivity problem. If something is so obvious that it is a waste of time, don't do it. This is the advantage of having experience and a possible explanation why some people feel good programmers can be 10x more productive because they don't waste time repeating mistakes or writing code they don't need.


答:
The problem that you have is really in thinking about writing your test cases.  You are getting stuck in TDD Dogma of needing to have only one test fail at a time.

You define the behavior that you want to be that a function determines if two groupings of three elements have the same values.  Then you define the test case checking only the first one.  You know from the definition of the problem that you have at least four cases to test (equal, 1st not equal, 2nd not equal, 3rd not equal).  So you would create these test cases immediately so that you define the behavior of the code.

In your example, the behavior is that in the two groupings the first element is checked to be equal.  That is an incomplete definition of the behavior.  And you would end up creating the naive solution that you have and thus needing to do more work as you go on.

Use your tests to define one behavior and write tests that fail and only pass when that behavior has been properly created.


问:
What to do when time estimation goes wrong?
Let’s say you estimated time for a case to be 3 days.
In day two you notice that the case is growing and new scenarios are popping up which were not counted when the time estimation where done.  The new finding leads to 2 days extra (total 5 days). This is a typical problem that you will face sooner or later as developer.

Which strategy can be used when you are going to notify project leader the new time of delivery?

Often you get the question why? How do you motivate the new time of delivery?

The fact is that many projects don’t put much time on analysis & design during SDLC.

EDIT:
In very complex projects no matter how much reasonable time you put on Analysis & Design there are always surprises since the business rules are too complex. However in such cases I believe the project leader must be aware of the complexity and have right attitude when unexpected surprises comes up. The question is how to tackle project leaders who don’t understand the complexity.

答:
Let the all team know it and try to find a solution. I recommend 3 solutions, from high to low in priority:

a. Try to find a temporary hot-fix, or a quick-around

b. The work that you can do it, do it best. After showing your excellent part of work to the client, ask for their help: we can do this, but there's some problem, and it may slow the productivity of your work... Maybe you can ask them if there is any unnecessary request/feature which can be dropped, or cut down.

Propose an alternative approach for their problem maybe a good idea.

c. Overtime-working


答:
TL;DR

User stories are for documenting what value should be added to the product, and why. Implementation details (e.g. how the value should be added, tested, measured, or validated) are constrained by the story, but are not contained within them. They are deliberately left as separate artifacts to maintain flexibility and agility within the framework.

The specifications and implementation details are most often captured in other artifacts such as Acceptance-Test Driven Development (ATDD), Test-Driven Development (TDD), and Behavior-Driven Development (BDD) scripts and scenarios. These particular artifacts aren't mandated by the Scrum framework, but they will certainly give you a good starting point if you don't already have other effective process controls in place.

User Stories Are Not Specifications

The original poster (OP) asked the following question:

[A] customer wants a different processing for different credit cards, there are strict requirements that must be implemented and known so that test cases can be written... WHERE SHOULD I PUT IT IF NOT IN THE STORY?

A user story is a feature that delivers value, provides some context to guide conversations about implementation, and a point of view tied to a value consumer who will benefit from the value delivered by the feature.

The whole point of a user story is that the implementation details are not prescriptive. The team is free to implement the feature in any way that delivers the identified value to the value consumer within the appropriate context.

A Worked Example

A Sample User Story

This is easier to explain if you start with a less ambiguous set of user stories. Since the OP didn't provide an actionable user story that follows the INVEST mnemonic, I'll invent one for the sake of an example. Consider the following story:

As a user who prefers to pay by Discover card,

  I would like the option to make my purchases with the Discover card

  so that I am not limited to Visa, Mastercard, or American Express.

This provides a concrete feature, provides some context that can guide the implementation decisions the team must make, and identifies the value consumer as a Discover-card owning customer. That's not a set of specifications, but it's what you need to have the right conversations with the customer and with the team about how best to implement the story during an iteration of development.

Analysis and Implementation

The actual implementation is up to the team. The team will have to do some analysis to determine:

The easiest way to implement a new feature.

Which of the various implementation options will be easiest to support going forward, without accruing technical debt.

How to apply the open-closed and YAGNI principles to ensure that your new feature is robust without being over-engineered.

One of the core principles of the Agile Manifesto is customer collaboration. A cross-functional, self-organizing team is expected to be able to collaborate with the customer to work out the implementation details within the guidelines provided by the user story.

If your user stories are not written well, or if the team doesn't have the skills or process maturity to do the just-enough analysis required by their agile framework, then this will obviously be much harder than it needs to be. Whole books have been written on the subject of how to create good user stories at the properly level of granularity; there is unfortunately no silver bullet, but it is a learnable skill for agile teams.

Test-Driven and Behavior-Driven Design

The best way to ensure that the analysis is sound, and that the implementation is both sane and supportable is through the use of TDD and BDD practices. For example, given the story above, the team should capture the planned implementation through artifacts such as:

Cucumber features with testable scenarios.

This is most useful for driving the development of acceptance tests, and for documenting user expectations of application behavior. For example, the user story should have one or more related Cucumber features that describes how the user is able to check out with a Discover card, and what that process looks like to the user.

RSpec tests that validate the behavior (not the internal implementation details) of new code features.

This is most useful for documenting and validating the intended behavior of the feature within the application. For example, the user story will drive the creation of unit and integration tests that ensure that using a Discover card invokes whatever card-specific behavior the application requires to authorize a sale through the payment gateway.

The specific tools don't matter. If you don't like Cucumber or RSpec, use whatever tools or methodologies work best for your team. However, the point is that the implementation details are based on the user story, but aren't prescribed by it. Instead, the implementation (or specifications, if you prefer) are details to be worked out during the development of the feature in a collaborative fashion.


问:
How to write a new annotation that behaves precisely like an existing one?
Here is my use case. Suppose annotations did have inheritance and would automatically inherit the entire behaviour of the base class. Then I would do the following (note the two package statements):

```<code>package cdiswitcher.precdi;
public @interface SessionScoped extends javax.faces.bean.SessionScoped {}
public @interface ManagedBean extends javax.faces.ManagedBean {}

package cdiswitcher.cdi;
public @interface SessionScoped extends javax.enterprise.context.SessionScoped {}
public @interface ManagedBean extends javax.inject.Named {}
</code>```

The same for various other annotation pairs such as @ejb and @inject. This would simplify switching between the two bean injection systems: Just replace every instance of cdiswitcher.precdi by cdiswitcher.cdi, or vice versa.

Another use case might be extending the behaviour of an annotation, perhaps even creating a single new annotation that has the same effect as two existing ones.

答:
Inheritance is not allowed with annotations. However, there is a way to do what you are trying to do, but it may or may not be worth the effort.

You could write a build script that performs regex replacements on your source before compiling. This could change annotation names and import packages dynamically. I would suggest not importing packages if you do this, so you only need to replace text at one location in each file. The less magical text replacement you perform, the better

This is not a good solution, but it is a valid solution. In general, source code should either be manually created or dynamically generated, not some freakish combination of the two. Personally, I would try to change the requirements. It might be more sane.


问:
Deployments, another unsolved problem in software engineering
Why is it so hard to package and deploy software? I want to understand what exactly is the inherent complexity of creating self-contained binaries? Currently it seems that golang is the only game in town when it comes to almost completely solving the deployment problem but even go has some issues with versioning dependencies. Why aren't more languages solving this problem at the compiler/language level?

Note that I'm not talking about library code. I'm talking about an actual application or a service that needs to get to a production environment as quickly and as reliably as possible.

答:
The root of this problem is that your program doesn't live in isolation in your system hard drives are shared, libraries, etc.

In this realm Snappy Ubuntu makes an important contribution, from their website:

Ubuntu Core provides transactional updates with rigorous application isolation. This is the smallest, safest Ubuntu ever, on devices and on the cloud. We’re excited to unleash a new wave of developer innovation with snappy Ubuntu Core! (Mark Shuttlewort)

What that means:

Transactional: A new installation succeeds completely or fails completely. If it does fail then it rolls back and leaves the system exactly how it was. No more crap from files of a partial update.

Application Isolation: It doesn't matter what specific version of a library your program uses depends on, that library won't be overwritten by any other application. Nor can your application delete other apps files.

Small: This basic version of Ubuntu is around 70 MB.


问:
What is best practice on ordering parameters in a function?
Sometimes (rarely), it seems that creating a function that takes a decent amount of parameters is the best route.  However, when I do, I feel like I'm often choosing the ordering of the parameters at random.  I usually go by "order of importance", with the most important parameter first.

Is there a better way to do this?  Is there a "best practice" way of ordering parameters that enhances clarity?

答:
Sometimes (rarely), it seems that creating a function that takes a decent amount of parameters is the best route.

Using several parameters is often a clear indicator, that you violate the SRP in this method. A method, which needs many parameters is unlikely to do only one thing. Excpetion may be a mathematical function or a configuration method, where indeed several parameters as such are needed. I would avoid multiple parameters as the devil avoids the holy water. The more parameters you use within a method, the higher the chance, that the method is (too) complex; the more complexity means: harder to maintain and that is less desirable.

However, when I do, I feel like I'm often choosing the ordering of the parameters at random. I usually go by "order of importance", with the most important parameter first.

In priniple you are choosing at random. Of course you might think paramter A is more relevant than parameter B; but that might not be the case for users of your API, who think B is the most relevant parameter. So even if you were attentive in choosing the ordering - for others it could seem random.

Is there a better way to do this? Is there a "best practice" way of ordering parameters that enhances clarity?

There are several ways out:

a) The trivial case: Do not use more than one parameter.

b) As you did not specify, what language you've chosen, there is the chance, that you chose a language with named parameters.
This is nice syntactic sugar which allows you to loosen the significance of the ordering of paramters: fn(name:"John Doe", age:36)

Not every language allows such niceties. So what then?

c) You could use a Dictionary/Hashmap/Associative Array as parameter:
e.g. Javascript would allow the following: fn({"name":"John Doe", age:36}) which is not far away from (b).

d) Of course if you work with a statically typed language like Java. you could use a Hashmap, but you would loose typeinformation (e.g. when working with HashMap<String, Object>) when parameters have different types (and need to cast).

The next logical step would be to pass an Object (if you are using Java) with appropriate properties or something more lightweight like a struct (if you write e.g. C# or C/C++).

Rule of thumb:

1) Best case - your method needs no parameter at all

2) Good case - your method needs one parameter

3) Tolerable case - your method needs two parameters

4) All other cases should be refactored


问:
Where is the evidence for the performance of Node.js?
A lot of developers, especially ones who haven't used Node.js in production, seem to believe that Node.js is faster than other interpreted languages such as PHP, Python, and Ruby.

These claims include:

Node.js/V8 is x times faster than y language.

The JavaScript reactor pattern will always handle concurrency better than any multi-threaded application.

I can certainly believe the first claim, yet I am unable to find any satisfactory benchmarks showing this.  The second claim seems unfounded, or at least too absolute.

What are the characteristics of Node.JS and V8 that justify such claims?

答:
Let's have a look at the second claim.

The JavaScript reactor pattern will always handle concurrency better than any multi-threaded application.

To address this claim, I'm going to assume that concurrency in this context equates to scalability, since scalability is one of the primary motivations behind Node.JS.  The distinction is subtle, but significant: there are many ways to get an application to scale better; concurrency is one way, but there are others.  I'm also going to assume that NodeJS implements the reactor pattern, though I'm not going to describe it in great detail here.

By scalability, I mean "the ability to handle as many simultaneous requests as possible."  The way that node.js does this is by providing an event loop.  The event loop accepts a request from the client, and then immediately hands it off to "some other mechanism" for processing.  It then returns control to the caller.  This asynchronous approach allows node.js to accept many requests in a given time frame, and differs from other, more synchronous strategies, where the caller must wait for the result before continuing. The amount of processing that the event loop demands is quite small, so it is ready (or almost ready) most of the time to accept new requests.

What happens to the requests once they are handed off?  Well, for purposes of our discussion, that's an implementation detail.  A given request could be put into its own thread, or it could be queued on a thread containing others tasks.  It could be handed to a Windows Service, or even sent to some other system for fulfillment.

The important thing to consider is the scalability that the event loop provides by making the acceptance of a request take as little time as possible.  This doesn't require a separate thread for each request; all you really need are two threads (one to run the event loop, and the other to process the requests).

Naturally, if you want your request to be fulfilled in some reasonable time frame, you must throw some horsepower at the implementation detail I mentioned earlier.  There is no free lunch.  But that's a different practical concern than the scalability that arises by making sure that requests to a service are accepted rapidly, even though getting the results of those requests is deferred to some later time.

So when someone says something like "the reactor pattern handles concurrency better than multiple threads," they're being a bit imprecise.  In a general way, they're comparing asynchronous techniques to multi-threading (asynchronous programming does not necessarily require new threads).  The way I would say it is:

By using an event loop, you can abstract the acceptance of a request away from the fulfillment of a request, thereby improving scalability without incurring the unnecessary overhead of additional threads.

Further Reading

A Quick Introduction to How Node.js Works

Understanding the node.js event loop

Reactor:
An Object Behavioral Pattern for
Demultiplexing and Dispatching Handles for Synchronous Events


问:
Should a newcomer to Perl learn both Perl 5 and 6?
I have started playing around with Perl 5 lately, and it seems very interesting. I would like to spend some time learning it more in depth when I can.

My question, since Perl 6 is slowly taking place (I believe...) and is said to break backward compatibility, is this: am I better learning Perl 5 and then Perl 6, or is learning Perl 6 directly a better time investment according to you?

If the changes from Perl 5 to 6 are making it hard to understand Perl 5, I should certainly start with Perl 5 to be able to read "old" scripts, then check Perl 6. There is also the "Perl 6 is not yet completely released" problem. I know there's an early adopter implementation for Perl 6, but if Perl 6 isn't officially released before some more years, I'll stick to 5 for now.

I would certainly like some insight on this. Feel free to discuss related stuff. My interest in scripting languages is fairly new.

Thanks!

答:
Don't learn Perl 6.

CPAN doesn't even support it yet.  (I suspect it will ship with a module that allows Duke Nukem Forever to be played entirely through the use of regexes...)


问:
Are there any easy-to-follow/reliable methods for simplifying code?
There is a problem with the way I code. Regardless of how much of a plan I write beforehand, the code becomes overcomplicated quickly.

Reading books on good practice and attempting to adhere to their principles isn't working.

Is there some surefire/proven way of auditing code to simplify it, other than being more thorough and dedicated in the planning stage?

答:
....no. There is not.

I never really thought before of the idea of such a thing existing because it's relatively obvious there's no perfect solution, but now that you mention it....that would be awesome!

However no, there is not nor will there ever be a perfect solution to ensuring your code isn't terrible, quickly, slowly, or inbetween (sluickly?).


答:
Practice.

No, really.

You will never fully appreciate a technique in a book or blog post until you've written your first plate of spaghetti or big ball of mud, and realize that many of these techniques are just effective ways to tame that complexity.  Then you will understand them at a deeper level, much deeper than the cargo cultist who is just stringing patterns together to look cool, but doesn't fully understand the reasons behind them.

Check out the patterns.  Are any of them easy?  Well, they're definitely easier than writing a plate of spaghetti or a big ball of mud, and having to maintain it later.  But you still have to make a study of these patterns.  Even the best painter uses more than one brush.

Title: Are there any easy-to-follow/reliable methods for simplifying code?

Body:
There is a problem with the way I code. Regardless of how much of a plan I write beforehand, the code becomes overcomplicated quickly.

Reading books on good practice and attempting to adhere to their principles isn't working.

Is there some surefire/proven way of auditing code to simplify it, other than being more thorough and dedicated in the planning stage?


问:
Using uniqueness types to implement safe parallelism
I've been interested in uniqueness types as an alternative to monads in pure functional languages for some time; unfortunately, this is kind of an esoteric area of CS research and online resources about programming with uniqueness types are few and far between.

It's obvious how uniqueness types may be used to implement stateful data structures like references ("boxes") and arrays, though it escapes me how you might implement other common stateful data structures with them.

Is it possible to implement, for example, locking with unique types?  Can uniqueness types be used to share mutable data across threads?  Is it possible to use unique types to build synchronization primitives (like mutexes), or is message passing necessary?

答:
Is it possible to implement, for example, locking with unique types?

I followed the link that Robert Harvey provided and I did a quick read-up. I cannot say that I understood everything or that I have a high level of confidence that I really understood what I think I understood, but it appears to me that the whole point of external uniqueness and reference immutability is to have no need for locking.

Modern approaches to multithreading try to avoid locking because only highly experienced programmers can write code which uses locking, and even their code is highly prone to have bugs. If you add on top of that the fact that locking code is virtually untestable, it should be obvious that it is a highly undesirable way of doing things, and any solution aiming to free us from locking is promising to say the least.

The way we have been avoiding locking is with message passing, which requires that the messages must be immutable. Roughly, (at first glance,) reference immutability appears to be a technique that can help us guarantee immutability without having to actually construct immutable types, and external uniqueness appears to be a technique that can help us relax the strict immutability requirement locally.

Can uniqueness types be used to share mutable data across threads?

The paper did not clearly state it, but from what I understand, an externally unique cluster of objects is thread safe because somehow (really, how?) it is guaranteed that there exists only one outside reference into that cluster of objects, which means that a thread receiving such a reference can treat the referenced objects as mutable without having to worry that some other thread might also mutate them, because no other thread can possibly have another a reference. I would be curious to know how such a theoretical construct can be implemented and enforced.

Is it possible to use unique types to build synchronization primitives (like mutexes), or is message passing necessary?

Again, from what I understand, externally unique types and reference immutability are meant to render locks, mutexes, and the like unnecessary. Message passing appears to be the way to go, and that's good.


答:
My one surefire way is:

Not being afraid to refactor the plan at the first hint that the code
  is turning complex.

(Which, of course, does not negate at all what you have already mentioned about being more thorough and dedicated in the planning stage.)


答:
The easiest way is to get yourself a mentor who writes clean code, show him or her your messy code, and ask what's wrong with it.

The thing to realize is clean code doesn't happen at the planning stage, and you can't continually "adhere" to clean coding principles.  You can only periodically reset to them.  You will write messy code.  As soon as you recognize it, you fix it.  The more frequently you reset your code, the better it will be.

You said you've read books on the principles, so you know what they are.  You can be methodical about resetting to them.  It's often helpful to take a principle to extremes before backing off.  Like tuning an instrument, it's easier to hear the proper set point if you first go way past it.  If your function is way too long, split it into the smallest possible pieces, then recombine a little perhaps.


答:
If at all possible, use an IDE supplied with (at least) these two components:

some kind of static code checker with metrics and, if you can, a report tool.

a quick way to refactor code (hunt symbols and so on).

Books are great to understand the why and the how - you need a tool that will pitilessly ferret out the what and the how much.

You can then check periodically the code you wrote, and wherever e.g. the cyclomatic complexity of a function exceeds a predetermined threshold, you refactor the function. And so on. Put aside some time in each development cycle and devote it to refactoring; that's a possible "when". With time and practice you'll be able both to better estimate the refactoring overhead, and reduce said overhead by fixing most things almost automatically as you go by. Also, you'll be able to see what metrics (and values thereof) work best for you.

(Finally, "overhead" is a mistaken label - think of it as "small and comfortable down payments that allow your code not to go into huge technical debt, and bankrupt the project at some time in the future").


答: I think you should use naming convention adopted by your platform. underscore_case will look weird in C# code, as camelCase in Ruby =)</p>

Title: Naming conventions: camelCase versus underscore_case ? what are your thoughts about it?

Body:
I've been using underscore_case for about 2 years and I recently switched to camelCase because of the new job (been using the later one for about 2 months and I still think underscore_case is better suited for large projects where there are alot of programmers involved, mainly because the code is easier to read).

Now everybody at work uses camelCase because (so they say) the code looks more elegant .

What are you're thoughts about camelCase or underscore_case

p.s. please excuse my bad english

Edit

Some update first:

platform used is PHP (but I'm not expecting strict PHP platform related answers , anybody can share their thoughts on which would be the best to use , that's why I came here in the first place)

I use camelCase just as everibody else in the team (just as most of you recomend)

we use Zend Framework which also recommends camelCase

Some examples (related to PHP) :

Codeigniter framework recommends underscore_case , and honestly the code is easier to read .

ZF recomends camelCase and I'm not the only one who thinks ZF code is a tad harder to follow through.

So my question would be rephrased:

Let's take a case where you have the platform Foo which doesn't recommend any naming conventions and it's the team leader's choice to pick one. You are that team leader, why would you pick camelCase or why underscore_case?

p.s. thanks everybody for the prompt answers so far


问:
How can I ask my boss (in a polite way) to comment his code?
I am being taught by my boss (I just finished school and he wanted someone with a little programming experience, so he chose me to train me on what that company specializes in) and started working with ASP.NET MVC applications, some HTML and CSS. I'm fine with the web design stuff he gives me (it is pretty simple to understand without clarification).

But for instance, he gives me a task to do with ASP.NET MVC, he explains it really well. But he doesn't explain anything in the code he has just given me. (We use source control in Visual Studio 2013), so it's literally hundreds of lines of code, without any background on what it is supposed to do. The kind of code that I'm seeing is code I've never seen before, so it is really difficult to try and figure out.

I would try and ask him more questions, but he is always working (it's his own business), and I feel as though he might get annoyed with all these questions I have on my hands.

So just something that will help my out until I get a grip on things, how can I ask my boss to put comments into his code that he gives me, but politely?

答:
Been in the similar situation, I'd say

Your boss might want you to learn the dirty way (by walking through the code that you have no clue of) for a reason. This is the way we learn more in a month at work than an year at college as mentioned in other answers.

This is "the norm" as mentioned in other answers. You should be more worried about where to start and how to approach and what to focus on than trying to understand every line of code right away. Ask your boss about the right tools and ways to debug/step through the code. This kind of questions will buy you some points.

On regular basis, keep approaching your boss for feedback on how you are doing so you'll get an idea where you stand in percentile terms assuming your boss have seen good number of people in the same situation and have an idea how they did.

Take this as an opportunity and as you get better with understanding the code, keep adding comments that you originally expected to ask your boss.


答:
You are probably not going to get him to change his style.

What you can do is ask lots of questions, and write down the answers.

I inherited a huge code base at my last job, little documentation and few comments. So I would try for half an hour on the same problem, then if I still couldn't figure it out, I would go ask someone who either wrote it, or knew how to use it. Then I would document all the things that he told me. Most went in our documentation, some went in the code as comments. After a year there I had practically written a large portion of our documentation and I knew a lot about the code base.

Good luck!


答:
If you really want to try to ask him to put comments in his code (I don't recommend it) I would suggest finding code that you need to edit that could really use some comments (most is self explanatory) and asking the question about like this "I was looking at this code here and I'm trying to figure out [Issue you're having] and I couldn't find any comments to help explain it".  Basically try to show that you've put effort towards understanding it and explain why it is that you both could benefit from comments being there.

Probably 90% of well written code doesn't need comments.  You only really want to document the parts of code that have been optimized and have become rather tense.  I worked at a company once that required you to document every piece of code you modified basically the comments ended up being actively detrimental to code readability because they often referred to code that had been removed or modified beyond recognition.  Beware of poor comments I spent a week debugging a function and in the end I found that the comment I kept reading about setting such and such a flag to "false" was actually the whole issue I set the flag to "true" and everything worked as it was supposed to.


问:
C# if statements
I am currently working on a C# checkers game for a university project in programming. But i have came to the point where i need to check whether a piece can be moved, or jump, but i feel like i'm using lots of code that isn't necessary to get true or false answers.

```<code>if (arrayX == 0)
{
    if (board.GetBoard(arrayX + 1, arrayY - 1).Piece == null)
    {
        return true;
    }
}
else if (arrayX == 7)
{
    if (board.GetBoard(arrayX - 1, arrayY - 1).Piece == null)
    {
        return true;
    }
}
</code>```

For example, is there a more efficient way of doing these if statements? In the code i have more if statements branching off other if statements.
So in summary, is there a way you can check loads of parameters, efficiently, without using loads of if statements branching off of one another?

答:
I looked at your code and it does not seem to me that it can be simplified in the sense of reducing the total number of lines.  It could be made less verbose if you got rid of some of the unnecessary, annoying curly brackets, but I suppose if you liked that idea you would have already done it:

```<code>        if (arrayX == 0)
        {
            if (board.GetBoard(arrayX + 1, arrayY - 1).Piece == null)
                return true;
        }
        else if (arrayX == 7)
        {
            if (board.GetBoard(arrayX - 1, arrayY - 1).Piece == null)
                return true;
        }
</code>```

However, there is one thing that you could try and see if it would simplify your code: define an immutable struct to hold a point.

```<code>struct Point
{
    readonly int x; //these are 32-bit, so the entire struct will fit inside a
    readonly int y; //   machine word in a 64-bit architecture.
    Point( int x, int y )
    {
        Assert( x >= 0 && x < 7 );
        Assert( y >= 0 && y < 7 );
        this.x = x;
        this.y = y;
    }
    Point left { get { Assert( x >= 0 );  return new Point( x - 1, y ); } }
    Point right { get { Assert( x <= 7 );  return new Point( x + 1, y ); } }
    bool isLeftmost { get { return x == 0; } }
    bool isRightmost { get { return x == 7; } }
    ...
}
</code>```

then, you will be able to add cool things to your structure, like this:

```<code>    IEnumerable<Point> EnumerateSurrounding()
    {
        for( int dx = -1;  dx <= 1;  dx++ )
        {
            for( int dy = -1;  dy <= 1;  dy++ )
            {
                int xx = x + dx;
                int yy = y + dy;
                if( xx < 0 || xx > 7 )
                     continue;
                if( yy < 0 || yy > 7 )
                     continue;
                if( xx == 0 && yy == 0 )
                     continue;
                yield return new Point( xx, xy );
            }
        }
    }
</code>```

So, you will be able to visit all cells surrounding a given cell like this:

```<code>foreach( Point p in mypoint.EnumerateSurrounding() )
{
    //do something with p here
}
</code>```

Disclaimer: I just typed all of the above code, so it is bound to have syntax errors, and perhaps even logical errors.  Do not rely on it blindly, read it carefully and use your judgement.

Title: C# if statements

Body:
I looked at your code and it does not seem to me that it can be simplified in the sense of reducing the total number of lines.  It could be made less verbose if you got rid of some of the unnecessary, annoying curly brackets, but I suppose if you liked that idea you would have already done it:

        if (arrayX == 0)
        {
            if (board.GetBoard(arrayX + 1, arrayY - 1).Piece == null)
                return true;
        }
        else if (arrayX == 7)
        {
            if (board.GetBoard(arrayX - 1, arrayY - 1).Piece == null)
                return true;
        }

However, there is one thing that you could try and see if it would simplify your code: define an immutable struct to hold a point.

struct Point
{
    readonly int x; //these are 32-bit, so the entire struct will fit inside a
    readonly int y; //   machine word in a 64-bit architecture.
    Point( int x, int y )
    {
        Assert( x >= 0 && x < 7 );
        Assert( y >= 0 && y < 7 );
        this.x = x;
        this.y = y;
    }
    Point left { get { Assert( x >= 0 );  return new Point( x - 1, y ); } }
    Point right { get { Assert( x <= 7 );  return new Point( x + 1, y ); } }
    bool isLeftmost { get { return x == 0; } }
    bool isRightmost { get { return x == 7; } }
    ...
}

then, you will be able to add cool things to your structure, like this:

    IEnumerable<Point> EnumerateSurrounding()
    {
        for( int dx = -1;  dx <= 1;  dx++ )
        {
            for( int dy = -1;  dy <= 1;  dy++ )
            {
                int xx = x + dx;
                int yy = y + dy;
                if( xx < 0 || xx > 7 )
                     continue;
                if( yy < 0 || yy > 7 )
                     continue;
                if( xx == 0 && yy == 0 )
                     continue;
                yield return new Point( xx, xy );
            }
        }
    }

So, you will be able to visit all cells surrounding a given cell like this:

foreach( Point p in mypoint.EnumerateSurrounding() )
{
    //do something with p here
}

Disclaimer: I just typed all of the above code, so it is bound to have syntax errors, and perhaps even logical errors.  Do not rely on it blindly, read it carefully and use your judgement.


问:
Does HTML 5 undercut the need for a full-featured Javascript framework?
We're redesigning a website.  Right now it uses Dojo, a large (and complex) Javascript framework.   One person insists that we need Dojo because of things like (random examples)  client-side validation, cross-browser compatibility, and client-side data storage.

After doing some checking, it seems like most of the things that Dojo provides are already built into HTML5.   In fact it seems like there's a lot of overlap:  Both provide client-side storage, client-side validation, and are at least partly supported by all major browsers.

Would using HTML5 constructs eliminate the need for us to load this huge, complex and troublesome Javascript framework?   In general, does HTML5 take care of a lot of what Javascript frameworks were written for 10 or 15 years ago?

答:
It depends quite a bit on the complexity of your application. But the general advantage in using a framework is that they generally target all major browsers, and are quite backward-compatible. Whereas if you rely on HTML5 only some features might only work with the latest browsers or not at all.

I just tried <input type="datetime"/> for example. Doesn't work in Firefox 34. But I am sure Dojo has a nice dropdown picker.

Now, maybe Dojo is a bit too complex for your application. So you could check out jQuery and jQueryUI, which are a bit more lightweight.


答:
You may start by creating a method inside the Board class which makes your code slightly shorter:

```<code>public class Board()
{
    public bool IsPieceMissing(x, y)
    {
        return this.GetBoard(x, y).Piece == null;
    }
}

...

if (arrayX == 0)
{
    if (board.IsPieceMissing(arrayX + 1, arrayY - 1))
    {
        return true;
    }
}
else if (arrayX == 7)
{
    if (board.IsPieceMissing(arrayX - 1, arrayY - 1))
    {
        return true;
    }
}
</code>```

The next thing is to work on the business logic, but for that, you need to provide a more global picture. What is the complete body of the method? Is it returning false at the end? Assuming it contains only the part you already provided and the return false; at the end, like this:

```<code>private bool DoSomething(arrayX, arrayY)
{
    if (arrayX == 0)
    {
        if (board.IsPieceMissing(arrayX + 1, arrayY - 1))
        {
            return true;
        }
    }
    else if (arrayX == 7)
    {
        if (board.IsPieceMissing(arrayX - 1, arrayY - 1))
        {
            return true;
        }
    }

    return false;
}
</code>```

you can return immediately instead of waiting until the end. The method becomes:

```<code>private bool DoSomething(arrayX, arrayY)
{
    if (arrayX == 0)
    {
        return board.IsPieceMissing(arrayX + 1, arrayY - 1);
    }
    else if (arrayX == 7)
    {
        return board.IsPieceMissing(arrayX - 1, arrayY - 1);
    }

    return false;
}
</code>```

Since the first condition now returns something anyway, you don't need the else:

```<code>private bool DoSomething(arrayX, arrayY)
{
    if (arrayX == 0)
    {
        return board.IsPieceMissing(arrayX + 1, arrayY - 1);
    }

    if (arrayX == 7)
    {
        return board.IsPieceMissing(arrayX - 1, arrayY - 1);
    }

    return false;
}
</code>```

Title: C# if statements

Body:
I am currently working on a C# checkers game for a university project in programming. But i have came to the point where i need to check whether a piece can be moved, or jump, but i feel like i'm using lots of code that isn't necessary to get true or false answers.

```<code>if (arrayX == 0)
{
    if (board.GetBoard(arrayX + 1, arrayY - 1).Piece == null)
    {
        return true;
    }
}
else if (arrayX == 7)
{
    if (board.GetBoard(arrayX - 1, arrayY - 1).Piece == null)
    {
        return true;
    }
}
</code>```

For example, is there a more efficient way of doing these if statements? In the code i have more if statements branching off other if statements.
So in summary, is there a way you can check loads of parameters, efficiently, without using loads of if statements branching off of one another?

Body:
You may start by creating a method inside the Board class which makes your code slightly shorter:

public class Board()
{
    public bool IsPieceMissing(x, y)
    {
        return this.GetBoard(x, y).Piece == null;
    }
}

...

if (arrayX == 0)
{
    if (board.IsPieceMissing(arrayX + 1, arrayY - 1))
    {
        return true;
    }
}
else if (arrayX == 7)
{
    if (board.IsPieceMissing(arrayX - 1, arrayY - 1))
    {
        return true;
    }
}

The next thing is to work on the business logic, but for that, you need to provide a more global picture. What is the complete body of the method? Is it returning false at the end? Assuming it contains only the part you already provided and the return false; at the end, like this:

private bool DoSomething(arrayX, arrayY)
{
    if (arrayX == 0)
    {
        if (board.IsPieceMissing(arrayX + 1, arrayY - 1))
        {
            return true;
        }
    }
    else if (arrayX == 7)
    {
        if (board.IsPieceMissing(arrayX - 1, arrayY - 1))
        {
            return true;
        }
    }

    return false;
}

you can return immediately instead of waiting until the end. The method becomes:

private bool DoSomething(arrayX, arrayY)
{
    if (arrayX == 0)
    {
        return board.IsPieceMissing(arrayX + 1, arrayY - 1);
    }
    else if (arrayX == 7)
    {
        return board.IsPieceMissing(arrayX - 1, arrayY - 1);
    }

    return false;
}

Since the first condition now returns something anyway, you don't need the else:

private bool DoSomething(arrayX, arrayY)
{
    if (arrayX == 0)
    {
        return board.IsPieceMissing(arrayX + 1, arrayY - 1);
    }

    if (arrayX == 7)
    {
        return board.IsPieceMissing(arrayX - 1, arrayY - 1);
    }

    return false;
}


答: I was taught to use camelCase at university. I've used a few different conventions over the last few years but prefer camelCase over anything else. I think I remember reading somewhere that camelCase is actually the easiest to read and understand.</p>


问:
Resource representation can depend on identity?
If some resource on a RESTful api is to be protected, we can do it by using OAuth for example, and then if the there's no token on the headers of the request (i.e. no identity) we return a 401 status code, and if there is we return some representation.

My doubt is the following: considering the identity of who is requesting the resource (specifically I'm thinking about using claims based identity), is it ok to return a resource representation that changes with the identity?

So for example, for a request from someone with a certain set of claims we return one representation containing some set of data and some set of links. If the request is from someone with another set of clains, the set of data changes and so the links. If someone has no identity whatsoever, we return even another representation. So basically we are controlling who can see and can do what with each resource.

Is that something useful to do, or there's some problem with it that I'm not seeing?

答:
There is nothing wrong in doing that. Imagine a list of messages which are shown to some groups of users only: one person would see a specific response, another one will see more messages; an administrator will probably see every possible message; a guest won't see anything.

You should be careful though. If the form of the response changes radically and there are too many different representations of the same resource, it may be overly complicate to build a client for such API, since the client would have to handle all those different representations and be able, somehow, to detect which representation is used right now (hopefully it can rely on the HTTP response code).


问:
How can user stories not contain requirements (when written on a card) and still be implementable
I've been told "User Stories are not requirements, it is just a reminder of what customer wants, you cannot put requirements within a story". But let's take for an example that a customer wants a different processing for different credit cards. There are strict requirements that must be implemented and known so that test cases can be written. Where should requirements go if not in the user story?

How can developers develop from a story if there are no lower requirements? How testers can write test cases (detailed ones) based on a user story? Where to requirements like DB constraints, fields validation etc. live outside of the user story?

答:
Lots of good answers here. Hopefully I can add some value with another one...

I think one hang up your team might be having is migrating from a non-Agile methodology.

That's usually some form waterfall methodology and, in practice, that usually does involve trying to document all technical requirements before a line of code is written.

But that doesn't always work. Often it doesn't work. The reason? Because the requirements rarely align with reality. Things change. Hence the move towards Agile.

With Agile, the User Story is all that the user cares about. They want to get form point A to point B. How to get there in terms of implementation is in your hands. If you're waiting for someone to tell you the technical requirements, then that's not really Agile. If you have questions, ask. If you need documentation, document, but you don't want the customer making all of these decisions for you. They may have opinions, but in an Agile environment those opinions should be (as your guru suggests) discusses in a conversation.

It may feel that this is a burden to your team, but consider it a luxury. Your team now has a lot of say in the solution--which wasn't necessarily the case in the waterfall model.


问:
Why Java is a factor 2-3 slower than equivalent C++ program?
I know there is an opinion that programs written in Java and running under JVM as as fast as C++ programs, after introducing just-in-time (JIT). I see many cases when Java is terribly slow for simple programs compared to C++, i.e. about factor 2-3 slower than equivalent C++ programs.

Just give you a small example: This is simple benchmark code to merge particles in clusters:

https://github.com/chekanov/hepjet

Go to "scjet_cpp" and type "make; make run". This runs C++ code.
 Then go to "scjet_java" and type "make; make run". This runs the same
 code written in Java.

Th first C++ code finishes merging particles within 50 msec (i7 desktop). Exactly the same Java code finishes for 170 ms. There is nothing special about the code, i.e. identical implementation in C++ and Java.

Any comment?

答:
Your measurement is probably flawed.

If you're just running both applications and measure the time from start to end in the terminal, you are not measuring execution time, but also startup time. For Java application, this means that those 170 ms. also contain JIT compilation.

Moreover, 50 ms. vs. 170 ms. is not representative. Doing a task in a loop and obtaining 50 s. vs. 170 s. will be more relevant.

You can't just take a single project and say: "This language is better, because this particular project executes faster with this language." A single project is not representative enough. Maybe authors knew C++ more than Java. Maybe they missed opportunities to optimize code.

Compilers you use may make a huge difference. Some will create code with terrible performance. Others will use clever optimization techniques.

Also, what's your goal? To be able to say: "Java sucks, everyone should use C++?" This is not particularly constructive. A more constructive approach is to build an application using the technology your team knows best (say Java), then find the bottleneck and find that it can be removed only by moving this part of the project to low-level language (including Assembler).


问:
What parts of your coding standard contribute to quality code?
In response to This Question, I ask:   What are the best parts of your coding standard?

What are the best practices that help with code quality, reliability, maintainability, readability, etc.

Please include the language, the item from the standard, and the reason it improves your code.

答: Just one public class must be put in each file, no more.</p>