问:
Why is Python slower than Java but faster than PHP
I have many times seen various benchmarks that show how a bunch of languages perform on a given task.

These benchmarks always reveal that Python is slower than Java, and faster than PHP, and I wonder why that's the case.

Java, Python, and PHP run inside a virtual machine

All three languages convert their programs into their custom byte codes that run on top of the OS -- so none is running natively

Both Java and Python can be "compiled" (.pyc for Python) but the __main__ module for Python is not compiled

Python and PHP are dynamically typed, and Java statically -- is this the reason Java is faster, and if so, please explain how that affects speed.

And, even if the dynamic-vs-static argument is correct, this does not explain why PHP is slower than Python -- because both are dynamic languages.

You can see some benchmarks here and here, and here

答:
Why Java is the fastest:

Statically typed + JIT compile + --server flag to aggressively recompile running code.

Why Python is faster than PHP:

Python might be a dynamic language, but it is still strongly typed.
This means that the structures you code are capable of runtime optimization.

Why PHP sucks:

It's basically javascript on the server (no multithreading support, totally dynamic, loosely typed).

In essence, the more the compiler knows about your code, the more it can optimize.  Java is fully optimizable before it is run, and while it is running.  Python is optimizable while it is running, and PHP is, well, terrible.  Facebook actually transpiles their PHP to C before it gets on the server.

https://developers.facebook.com/blog/post/2010/02/02/hiphop-for-php--move-fast/


问:
.NET - refactoring code
I have inherited and now further develop a large application consisting of an ASP.NET application, VB6 and VB.NET application.

The software was poorly written.  I am trying to refactor the code as I go along.  The changes I am making are not live (they are contained in a folder on my development machine).  This is proving to be time consuming and I am doing this along side other work which is the prioritiy.

My question is: is this a practical approach or is there a better methodology for refactoring code? I don't have any experience with version control software or source control software and I am wandering if this is what I am missing.  I am a sole developer.

答:
I am in a slightly similar situation(code is probably much better quality, but we just now dropped support for .Net 1.0)

What we do that works well for us is refactor as we go and spend any free time refactoring. So... Say, you have a function which puts the title on the page or some such. Now, your boss needs you to alter that title function so that the website's name is included in it, not just the specific page. So, you go to fix it and find that there are 5 different Title functions which do similar things. You should refactor those to 1 function so you don't have to fix it in 5 places. You might also find that a PageTitle class might need to be made instead or something

I'm sure some people will disagree with me, but sometimes, working code is good enough. If you have a huge 1000 line method that you haven't had to change in 5 years, and it doesn't cause big integration problems, why change it? Most likely it won't be touched for the next 5 years after you refactor it as well. You really need to have priorities when refactoring on a schedule. This is the general order I follow

Code that I'm currently modifying (usually scoped to a class or two)

Code that I don't necessarily have to modify, but that causes integration pains in code I'm having to write.

Code that is difficult to read

Code that is not easy to read, but never breaks.

(ie, never usually) code that could be cleaner, but otherwise is decently readable and modifiable.

Real life example of these priorities. There is a parser in the product I maintain that is generated from a grammar file using some tool. It's the most horrific code I've ever seen, but it hasn't been touched in 5 years or more. I don't expect to ever have to touch it either because it's never broke. (and we have tests to make sure of that).

However, we have a very big pain point in our .Net 1.0 to modern conversion. Some genius decided to use IEnumerator instead of IEnumerable throughout the code base. This prevents foreach loops from working. Almost every chunk of code I write I end up coming across needing to use one of these IEnumerator's. Instead of continuing to use this anti-pattern, I fix it. Always. Sometimes, it requires modifying 50 or more lines of code, but it's something that lowers technical debt where it matters.

And I'll leave one last point. USE VERSION CONTROL. Trust me! If you're the only maintainer and management doesn't care about it, then use git or mercurial. You don't even need a central repository for these and still get most of the benefits. Version control is invaluable when you decide to embark on refactoring something and find out it significantly breaks things. With version control, you roll back the last commit. Without, you cross your fingers you made a copy of the directory recently.

ContentLicense: CC BY-SA 3.0

Title: .NET - refactoring code


问:
Are Scrum and XP comparable things or are they used for different things
Are Scrum and XP comparable things or are they used for different things? what is the main features of each of them? how do they overlap?

I've been reading about both XP and Scrum over the past weeks and something is vague about them for me. Scrum does have a definitive official rulebook but for XP I'm not sure where to look.

答:
Probably the biggest difference is that you can be completely trained in scrum without even mentioning software.  It is more about the process of choosing what software to write and when to write it rather than how.

Conversely, extreme programming is primarily about the how, and specifically recommends certain programming practices, taken to the extreme.  Peer reviews are a good thing, so take that to the extreme and do pair programming.  Tests are too often forgotten, so take that to the extreme and write them first with TDD.  Long release cycles are problematic, so take it to the extreme by being ready to release every iteration.  Integration is easier the more frequently you do it, so take it to the extreme and do continuous integration.

Since scrum doesn't say anything about the "how," a lot of scrum teams eventually adopt XP practices, so you will see a lot of overlap.  At my company, some scrum teams are essentially indistinguishable from XP teams, where others are pure scrum, and others pick and choose where appropriate.  For example, they might do TDD for new development, but not for maintaining legacy code.

I would recommend for any team to get trained in both, but to not try to worry about being "pure" one way or the other.  Your team is going to work best when it adapts to find its own style.


答:
The benchmarks are rather skewed in favour of heavy mathematical programming.

It not surprising that Python is pretty good at complex math if you consider where and why it was first written.

PHP on the other hand was written to serve web pages, it can do other things but web pages is what its best at and its on a par or better than Java at this task.

Title: Why is Python slower than Java but faster than PHP

Body:
I have many times seen various benchmarks that show how a bunch of languages perform on a given task.

These benchmarks always reveal that Python is slower than Java, and faster than PHP, and I wonder why that's the case.

Java, Python, and PHP run inside a virtual machine

All three languages convert their programs into their custom byte codes that run on top of the OS -- so none is running natively

Both Java and Python can be "compiled" (.pyc for Python) but the __main__ module for Python is not compiled

Python and PHP are dynamically typed, and Java statically -- is this the reason Java is faster, and if so, please explain how that affects speed.

And, even if the dynamic-vs-static argument is correct, this does not explain why PHP is slower than Python -- because both are dynamic languages.

You can see some benchmarks here and here, and here


问:
Automatic generate code: "derived work"?
For example, I've GPL software. I'm the author of this GPL software. This GPL software has, between its code, Doxygen comments. These Doxygen comments are written to generate a CC-BY-SA html page, in order to upload this generated documentation in my project website under CC-BY-SA license.

But, is the Doxygen documentation output a "derivate work"? After all, this documentation is based on my GPL source code. In this case, the documentation must be GPL. But, I want the documentation is CC-BY-SA, because it is documentation. GFDL doesn't help. GPL code can't become GFDL (the opposite yes).

If this output is really a derivate work, I think, creates a strange situation, because, if I distribute my work, recipient users can't legally distribute the generated documentation: while with my work I can do I want, the users don't, thus, they have to distribute any derivated work with the same license I offer them.

What is the solution?

答:
The question is moot.

If you are the author of the program, you have all the rights to distribute it under the terms you like. So if you generate the documentation under a different license, you will have it under a different license. Because you said so.

The program wasn't written by you? Then, the documentation you produce should be GPL, but that presents a different problem. The GPL doesn't talk about documentation. It talks about software.

So if you want to reprint commercially the output of a doxygen run of a GPL program you did not write, here's what you do: you write to the author and ask for explicit permission. Same thing if you want to distribute those docs under CC-BY-SA. You don't stick the label, you ask the author to stick it.

Law isn't a weird mind game. It's about people convincing juries or judges. Judges hate mind games and juries sometimes don't even get the law correctly. (§ Apple vs. Samsung)

So, worst case scenario.

The author is deceased, the heirs are stupid and they just like to sue people. You reprinted commercially the output of a doxygen run of a GPL program. My guess is (but IANAL) you still may win, but it might be harder than planned and you may face a judge very tedious on distinguishing software from written word meant for human consumption. I'd still bet on a 70% success rate.

Why did I say reprint commercially? Cause it's hard to sue people for damages if you can't tell the value of the "work of art" (the documentation) that's been illegally distributed. If the subject of the suit is unsellable or of unquantifiable value, you cannot claim enough damages to pay a lawyer.


问:
Using table-styled divs instead of tables
I was referred here from stackoverflow as my question was apparently too broad.

I'm working on a template, and I know using CSS is preferred over HTML tables for positioning... But, is it acceptable to get the best of both worlds and use table-like styles on my divs? For example:

```<code>display: table;
</code>```

This not only helps solve the sticky footer problem, but it also avoids the pains associated with using floats. Somehow it feels dirty, but I can't logically explain why because it works without any "tricks" or ugly hacks, which is how it should be, right?

Is this technically incorrect, or does it ultimately boil down to just a matter of opinion? ...Thoughts?

答:
Using tables for layout is discouraged because it is semantically wrong -- table markup is supposed to be for tables and specifically for tabular data. Your HTML says what something is (e.g. a table, a paragraph, or a generic text division) CSS is just instructions for displaying it.

If it's consistent across browsers that are important to you, whether it's displayed as a block or a table is no different than whether it's displayed in red or green. Table and table-cell display properties are often cited as good methods for dealing with problems like vertical centering.


问:
What software do you use to track time spent on a project?
What software do you use to track time spent on a project?</p>

答:
Redmine

From the Redmine website:

Some of the main features of Redmine are:

Multiple projects support

Flexible role based access control

Flexible issue tracking system

Gantt chart and calendar

News, documents & files management

Feeds & email notifications

Per project wiki

Per project forums

Time tracking

Custom fields for issues, time-entries, projects and users

SCM integration (SVN, CVS, Git, Mercurial, Bazaar and Darcs)

Issue creation via email

Multiple LDAP authentication support

User self-registration support

Multilanguage support

Multiple databases support

ContentLicense: CC BY-SA 2.5


问:
How are requirements determined in open source software projects?
In corporate in-house software development it is common for requirements to be determined through a formal process resulting in the creation of a number of requirements documents. In open source software development, this often seems to be absent. Hence, my question is: how are requirements determined in open source software projects?

By "determining requirements" I simply mean "figuring out what features etc. should be developed as part of a specific software".

答:
In corporate in-house software development it is common for requirements to be determined through a formal process resulting in the creation of a number of requirements documents.

To my experience this is much more common when doing contract-based development, especially when having an external company doing the development for your company, and there is the legal need for a contract. But lots of other companies control their inhouse development by their own people in a different way:

informal communication

prioritized requirements/bugs/issues/tickets lists (and that is definitely not an invention from the "agile" community)

This is the same way most open source projects work - since there is no need for a formal contract, no one bothers to work out big, detailed, formal requirement docs, just small, painless lists of missing features, or tickets collected in an issue tracker to be solved.


问:
What is the use of Association, Aggregation and Composition?
I have gone through lots of theories about what is encapsulation and the three techniques of implementing it, which are Association, Aggregation and Composition.

What I found is:

Encapsulation

Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.

Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Access to the data and code is tightly controlled by an interface.

The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.

Association

Association is a relationship where all object have their own lifecycle and there is no owner. Let’s take an example of Teacher and Student. Multiple students can associate with a single teacher and a single student can associate with multiple teachers, but there is no ownership between the objects and both have their own lifecycle. Both can create and delete independently.

Aggregation

Aggregation is a specialized form of Association where all objects have their own lifecycle, but there is ownership and a child object cannot belong to another parent object. Let’s take an example of a Department and teacher. A single teacher cannot belong to multiple departments, but if we delete the department the teacher object will not be destroyed. We can think of it as a “has-a” relationship.

Composition

Composition is again a specialized form of Aggregation and we can call this as a “death” relationship. It is a strong type of Aggregation. Child object does not have their lifecycle and if parent object deletes all child object will also be deleted. Let’s take again an example of relationship between House and rooms. House can contain multiple rooms but there is no independent life of a room and any room cannot belong to two different houses. If we delete the house, the room will automatically be deleted.

The question is:

Now these all are real world examples. I am looking for some description about how to use these techniques in actual class code. I mean what is the point for using three different techniques for encapsulation, How these techniques could be implemented and How to choose which technique is applicable at time.

答:
Using those techniques usually results in design practices like SOLID or various design patterns.

The point of using patterns, practices and such is to describe a solution to a specific problem that is also maintainable and extensible. You simply need to get enough experience to tell where to use which pattern or technique.

ContentLicense: CC BY-SA 4.0


答:
The distinction between association, aggregation and composition as you describe it is a legacy going back to the old times of manual memory management. For example in C++ the memory used by objects has to be manually released and it is thus paramount to carefully design the lifecycle of composed objects. While the distinction between aggregation and composition is still being taught by many text books, it is essentially irrelevant when programming in environments with automatic memory management. If you have garbage collection all of them are just composition, period.

Encapsulation on the other hand is a much more general principle than what you describe. It is foremost the idea of bundling data and the functions that operate on this data in one module. One way to implement this is by keeping the state of the module private and expose changes to that state through public services. So client cannot access the state on their own but have to tell the module their intend by sending messages. So encapsulation is not limited to objects  but applies to services as well. Actually, one way of looking at objects is to look at them as services.

Here's an example of encapsulation

```<code>public class Counter {
    private int n = 0;
    public int inc() { return n++; }
}
</code>```

or the same using lambda functions

```<code>var counter = (function() {
    var n = 0;
    var inc = function() { return n++; }
    return inc;
})();
</code>```

In both cases the data, that is the variable n, is bundled together with the function inc that operates on it. And there is no way any other function could ever access n, thus we have an encapsulated module that provides counting as a service.

NB: exposing all of an object's inner state through accessors is actually a violation of encapsulation. Alas, it is such a common violation that many will confuse it with good object-oriented design.

Title: What is the use of Association, Aggregation and Composition?

Body:
I have gone through lots of theories about what is encapsulation and the three techniques of implementing it, which are Association, Aggregation and Composition.

What I found is:

Encapsulation

Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.

Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Access to the data and code is tightly controlled by an interface.

The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.

Association

Association is a relationship where all object have their own lifecycle and there is no owner. Let’s take an example of Teacher and Student. Multiple students can associate with a single teacher and a single student can associate with multiple teachers, but there is no ownership between the objects and both have their own lifecycle. Both can create and delete independently.

Aggregation

Aggregation is a specialized form of Association where all objects have their own lifecycle, but there is ownership and a child object cannot belong to another parent object. Let’s take an example of a Department and teacher. A single teacher cannot belong to multiple departments, but if we delete the department the teacher object will not be destroyed. We can think of it as a “has-a” relationship.

Composition

Composition is again a specialized form of Aggregation and we can call this as a “death” relationship. It is a strong type of Aggregation. Child object does not have their lifecycle and if parent object deletes all child object will also be deleted. Let’s take again an example of relationship between House and rooms. House can contain multiple rooms but there is no independent life of a room and any room cannot belong to two different houses. If we delete the house, the room will automatically be deleted.

The question is:

Now these all are real world examples. I am looking for some description about how to use these techniques in actual class code. I mean what is the point for using three different techniques for encapsulation, How these techniques could be implemented and How to choose which technique is applicable at time.

Body:
The distinction between association, aggregation and composition as you describe it is a legacy going back to the old times of manual memory management. For example in C++ the memory used by objects has to be manually released and it is thus paramount to carefully design the lifecycle of composed objects. While the distinction between aggregation and composition is still being taught by many text books, it is essentially irrelevant when programming in environments with automatic memory management. If you have garbage collection all of them are just composition, period.

Encapsulation on the other hand is a much more general principle than what you describe. It is foremost the idea of bundling data and the functions that operate on this data in one module. One way to implement this is by keeping the state of the module private and expose changes to that state through public services. So client cannot access the state on their own but have to tell the module their intend by sending messages. So encapsulation is not limited to objects  but applies to services as well. Actually, one way of looking at objects is to look at them as services.

Here's an example of encapsulation

public class Counter {
    private int n = 0;
    public int inc() { return n++; }
}

or the same using lambda functions

var counter = (function() {
    var n = 0;
    var inc = function() { return n++; }
    return inc;
})();

In both cases the data, that is the variable n, is bundled together with the function inc that operates on it. And there is no way any other function could ever access n, thus we have an encapsulated module that provides counting as a service.

NB: exposing all of an object's inner state through accessors is actually a violation of encapsulation. Alas, it is such a common violation that many will confuse it with good object-oriented design.


答:
If the problem is a common one like, say, writing a compiler or a browser, the requirements are pretty much given in the form of language standards, target operating systems and target hardware, etc.

For things like GNU Emacs, which is many things to many besides excellently fulfilling its original goal of being a text editor, I think the requirements made sense because of the immense scope to extend it.  Chats, emails, newsgroups, code editing, version control come to the mind.  There is a research scientist working on Emacspeak.  I think similar things can be said of browsers and other things that allow extensions.

If the software is catching up a function that is available only in non open-source software, the requirement is pretty much given again.

EDIT:

When the open source software goes on to maintenance and fewer original requirements remain unmet, most of the requirements can come from bugs, need to adapt to new platforms such as multi core CPUs and other hardware that offer better performance when exploited, and such.

In a fully research based project like the GNU Hurd, I'd think the requirements come from research results and papers.

To sum up,

when starting out, the requirements for software that attempts to solve common problems can come from standards documents

for software that is catching up to other existing software, the requirements are likely to be to produce all or most of the existing software's feature set and some other features that the developers/users find interesting to have

for research projects, papers and other publications could set the requirements

when in maintenance, bugs, need to adapt to newer environments can be major source for requirements

Title: How are requirements determined in open source software projects?

Body:
In corporate in-house software development it is common for requirements to be determined through a formal process resulting in the creation of a number of requirements documents. In open source software development, this often seems to be absent. Hence, my question is: how are requirements determined in open source software projects?

By "determining requirements" I simply mean "figuring out what features etc. should be developed as part of a specific software".


问:
Where do you put scenarios on a scrum board?
So traditional scrum board looks something like this

```<code>Backlog       |       Story    notStarted   inprogress    Done
story 1               Story1   tasks
Story 2               Story2   tasks
Story ..
Story n
Epic  x
Epic  x+1
</code>```

However in general a story has many scenarios and when working with BDD you want to write each scenario for a story as Given, when and then. Also the scenarios don't belong in the notstarted column, inprogess or Done as a scenario is not a task.

So you realize that a scenario/s should have their own column between "story" and "notstarted", as a scenario can have many task to be considered done.

If you are going to build your task from scenarios then why would you need the story on the scrum board in the first place, maybe they should be left in the backlog.

Some people put scenarios on the back of each story.

This is a on going debate in my team and I wanted to see if anyone has solved this differently.

Cheers!

答:
I agree with Lunivore when she says the conversation is the single most important thing. But this isn't a conversation about BDD nor is about who should write the scenarios.

I think this question is more about if you don't store the Acceptance Criteria digitally how do you capture the Scenarios visually?

Having Acceptance Criteria then sticking on a whole bunch of scenarios on them means you'll need one very large scrum board and you'll run out of space quickly.

Having a conversation in theory sounds great but how do you remember said conversation when trying to prove they work afterwards? We are assuming that you will not forget these, and it could be alot of info to keep rattling around up there.

I think you need to concede that there is a need for them to appear digitally. Heck the developers will be typing them out in code anyway. I think the key to them being valuable is getting re-use from them and avoid duplicating effort.

At the very least if they are typed out in Given When Then, then the developers can copy and paste this as a starting point to generate some tests.

I am currently seeking a lightweight solution myself for the same thing.
Should I use wiki? speadsheet? Trello? Selenium IDE? Buy a heavyweight tracking tool like Version One, Jira? Cucumber? Twist? Should I not write them out freehand by pen and paper and just print them out? All possibilities.. I don't know the answer yet, but I do know I need somewhere for these scenarios to live, breathe, and evolve.

User stories and scenarios have iterations of there own and everyone should be empowered to edit them.


问:
Why Firefox caching work will reset in version 3 but version 16 don't?
I am developing a web application and have the app deployed into Tomcat server. Tested on IE and Firefox and are working fine. Meaning when I close the browser and reopen the app, the data will be reset. When deploy to Websphere, the data is reset only in IE but Firefox don't. Meaning Firefox will cache the old data. I did try to clear the cache in FF but still failed. I did a test in FF3 and FF16, FF3 will reset the value but FF16 doesn't, I am just so curious why this could happened?

Now I don't know whether this is my code problem or is actually the FF caching problem. Any clue on this?

答:
HTTP caching is quite complex and influenced by a number of HTTP headers, so there is ample room for misunderstanding and different interpretations of the standard. And the standard has been extended a few times. This explains why you're seeing different results with different browsers.

This document explains it in detail. Read it, understand it, then look at what HTTP headers your application sends. If you still can't solve the problem, ask another question here that includes those HTTP headers.


问:
How to be successful at BDD Specifications Workshops?
Today we tried to introduce BDD in our software development process by having a specification workshop.

For this workshop we had 2 developers, 1 tester and 1 business analyst. The workshop lasted 1h30 and by the end of it we managed to figure out some BDD scenarios for our new feature.
We tried to focus on finding the scenarios that we could miss, and the difficult ones.

At the end of the workshop some people were actually unhappy with the workshop.

One developer felt he wasted his time as he was used to be given out the scenarios directly by the business analyst and review them with her.
The business analyst didn't feel confident with our scenario coverage (Had a feeling that we could have missed out other important stuff) but more importantly felt that this workshop was also a waste of time as she could have figured out all these scenarios by herself and in a shorter period of time.

This experimental workshop lasted 1h30, and by the end of it, we didn't feel confident enought about what we did...sure we could have spent more time on it but honestly most people get exhausted after 1h30 of brainstorming to fetch out business rules from the BA brain.

So my question is how that kind of workshop can actually work.
In the theory, given you have a new feature to develop, you put the tree 'amigos' (dev/tester/ba) in the same room so that they can collaborate together on writing the differents requirements for the new feature using examples. I can see all the benefits from that. Specially in term of knowledge sharing and common product/end goal/done vision.

Our conclusion from this experiment was that it is actually more cost effective to first have a BA to work on his own on the examples and only then to have the scenarios to be reviewed/reworked by the 3 'amigos'. By having the BA to work on his own, we actually feel more confident that we are less going to miss out stuff + we still get to review the scenarios afterward to double check. We don't think than simple one time brainstorming/deliberate discovery session is actually enought to seriously cover all the requirement for a new feature. The business analyst is actually the best person for that kind of stuff. The best thing we can do is to review what she wrote and see if then we have a common understanding (which could then lead to rewrite some of her scenarios or add new ones she could have missed).

So how can you get that to work effectively in practice ?

答:
Always make sure everybody in a meeting is prepared for the subject of that meeting!

Do not ever use a meeting to "brainstorm" anything together. It wastes everybody's time.

General recipe for effective meetings:

have someone prepare the items to be discussed

require all participants to have studied (not just read) them those items

gather comments beforehand and require all participant to have studied (not just read) them

hold the meeting to take decisions


问:
What's the best way to use requestAnimationFrame and fixed frame rates
I recently got into using the HTML5-requestAnimationFrame-API a lot on animation-heavy websites, especially after seeing the Jank Busters talk. This seems to work pretty well and really improve performance in many cases.

Yet one question still persists for me: When wanting to use an animation that is NOT entirely calculated (think spritesheets for example) you will have to aim for a fixed frame rate. Of course one could go back to use setInterval again, but maybe there are other ways to tackle this.

The two ways I could think of using requestAnimationFrame with a fixed frame rate are:

```<code>var fps = 25; //frames per second

function animate(){

   //actual drawing goes here
   setTimeout(function(){
      requestAnimationFrame(animate);
   }, 1000 / fps)

}

animate();
</code>```

or

```<code>var fps = 25; //frames per second

var lastExecution = new Date().getTime();

function animate(){

    var now = new Date().getTime();

    if ((now - lastExecution) > (1000 / fps)){
        //do actual drawing
        lastExecution = new Date().getTime();
    }

    requestAnimationFrame(animate);

}

animate();
</code>```

Personally, I'd opt for the second option (the first one feels like cheating), yet it seems to be more buggy in certain situations.

Is this approach really worth it (especially at low frame rates like 12.5)? Are there things to be improved? Is there another way to tackle this?

答:
For seamless animations, even sprite based use the second option, with Date.now(). Dont forget about

Return value

requestID is a long integer value that uniquely identifies the entry
  in the callback list. This is a non-zero value, but you may not make
  any other assumptions about its value. You can pass this value to
  window.cancelAnimationFrame() to cancel the refresh callback request.

(from MDN )


问:
Why do game developers prefer Windows?
Is it that DirectX is easier or better than OpenGL, even if OpenGL is cross-platform? Why do  we not see real powerful games for Linux like there are for Windows?</p>

答:
The answer is obvious. The objective of writing a game is to make money. More end users run Windows, therefore there is a bigger market and you would expect to make more money from a Windows game than a Linux game. It's that simple.

If ever you ask yourself the question 'Why does someone do...', just remember that money makes the world go round.

Title: Why do game developers prefer Windows?


问:
As a programmer, are you required to do timesheets?
Timesheets are something that I've never been fond of, but none the less something that is a requirement within my company. They don't bother me so much, but they seem to really grind some other people's gears. I suppose I have a few questions, and feedback would be great.

Are you required to do timesheets, assuming you aren't a contractor? (That is understandable to me).

What is the granularity of timesheets that you would be comfortable with or that you use? (ex: all entries must be under two hours).

Would timesheets ever factor into your reasons for not accepting a job or leaving a current one?

How has management within your organization justified timesheets if you aren't billing to a client?

答: Yes. But at a fairly coarse level for management reports weekly. This gets reported by the PMO all the way up from senior management to director level at an appropriate granularity. For individual projects it is at project task level for tracking progress but that doesn't feed into the timesheet but more for project management.</p>


答:
The length of the meeting is not your problem. It's OK for those meetings to go on a long time. BUT everyone should come out of it feeling confident. That they didn't is your problem.

I would suggest a short meeting to discuss a requirement. Schedule a second meeting a few days later, so everyone knows they must be prepared by then.

Then the BA and tester should each come up with their scenarios, because they both look at software in very different ways. Get them to write them on cards and stick them all on a board somewhere, at least a day before the second meeting, let everyone look through in their own time and think it over. Throw away any duplicates, stick up any scenarios that weren't considered.

Don't throw away anything you disagree with, but mark it as contentious. If a very brief conversation with the person who wrote it will help, do that, but mostly save it.

THEN have your planning/design meeting. Have a solid agenda for that meeting (start with the pile of cards, put the contentious ones at the top) and don't allow it to wander off-track. Make sure you come out of that meeting with all points of contention resolved.

Title: How to be successful at BDD Specifications Workshops?

Body:
Today we tried to introduce BDD in our software development process by having a specification workshop.

For this workshop we had 2 developers, 1 tester and 1 business analyst. The workshop lasted 1h30 and by the end of it we managed to figure out some BDD scenarios for our new feature.
We tried to focus on finding the scenarios that we could miss, and the difficult ones.

At the end of the workshop some people were actually unhappy with the workshop.

One developer felt he wasted his time as he was used to be given out the scenarios directly by the business analyst and review them with her.
The business analyst didn't feel confident with our scenario coverage (Had a feeling that we could have missed out other important stuff) but more importantly felt that this workshop was also a waste of time as she could have figured out all these scenarios by herself and in a shorter period of time.

This experimental workshop lasted 1h30, and by the end of it, we didn't feel confident enought about what we did...sure we could have spent more time on it but honestly most people get exhausted after 1h30 of brainstorming to fetch out business rules from the BA brain.

So my question is how that kind of workshop can actually work.
In the theory, given you have a new feature to develop, you put the tree 'amigos' (dev/tester/ba) in the same room so that they can collaborate together on writing the differents requirements for the new feature using examples. I can see all the benefits from that. Specially in term of knowledge sharing and common product/end goal/done vision.

Our conclusion from this experiment was that it is actually more cost effective to first have a BA to work on his own on the examples and only then to have the scenarios to be reviewed/reworked by the 3 'amigos'. By having the BA to work on his own, we actually feel more confident that we are less going to miss out stuff + we still get to review the scenarios afterward to double check. We don't think than simple one time brainstorming/deliberate discovery session is actually enought to seriously cover all the requirement for a new feature. The business analyst is actually the best person for that kind of stuff. The best thing we can do is to review what she wrote and see if then we have a common understanding (which could then lead to rewrite some of her scenarios or add new ones she could have missed).

So how can you get that to work effectively in practice ?


问:
Which design better when use foreign key instead of a string to store a list of id
I'm building online examination system. I have designed to table, Question and GeneralExam. The table GeneralExam contains info about the exam like name, description, duration,...

Now I would like to design table GeneralQuestion, it will contain the ids of questions belongs to a general exam.

Currently, I have two ideas to design GeneralQuestion table:

It will have two columns: general_exam_id, question_id.

It will have two columns: general_exam_id,

list_question_ids (string/text).

I would like to know which designing is better, or pros and cons of each designing.

I'm using Postgresql database.

答:
The first design is the better one.

This is because you can then also create foreign keys to the questions. Also you have no further processing for parsing the list of ids. Also in this case you have the ability to get all questions together with the general exam query (only one round-trip to the database).

In the case of the second design you have to get the database entry for a general exam, parse the text and then query the database again for the questions...


答:
Nice and Tricky Question

It depends on usage. But most of the times INT key is preferred. Usually you will find something like ID to show the primary key.

Ultimately it depends on the usage. What kind of requirements you are going to have. Accordingly decide. But INT is most preferred.
Here I have explained both

For int IDs (First option) #

Identity field should be numeric and not string based, because

Space saving (An int is 4 bytes, a string can be as many bytes as you like. Because of that, an int will always perform better)

Performance reasons (matching keys on strings is slower than matching
on integers)

Data redundancy will be solved by int column. As Foreign keys need to
be updated (and/or deleted) whenever the data is updated.

Updates/deletes on a foreign key can be set to cascade.

For String/Text (Second option) #

Using a foreign key means that to get user-readable data (ie, the
text) a JOIN must be made. Using a descriptive foreign key, no JOIN
needs to be made to get user-readable data. This includes reading
with SELECTs and when INSERTing or modifying data. For example, to
insert into AddressNum the groupId is needed.

Human-readable data in the database. This will make it easier for the
DBA to debug data issues, as they can use a SHOW CREATE TABLE to find
the foreign key references, and then get a sample of data from one
table and understand the scenario, without having to JOIN.

I like the @user1598390's comment

OP is not asking whether to use int IDs or String IDs. He/she is
  asking whether to used int IDs (one to many) or having all questions
  IDs concatenated in a text column like "123311;121322;123455;123487".

First option I took as int IDs and Second option I took as Text/String.

It depends on usage. What kind of requirements you are going to have. Accordingly decide. Most of time, First option is preferred. In this case, for first option you have no further processing for parsing the list of ids.

Title: Which design better when use foreign key instead of a string to store a list of id

Body:
I'm building online examination system. I have designed to table, Question and GeneralExam. The table GeneralExam contains info about the exam like name, description, duration,...

Now I would like to design table GeneralQuestion, it will contain the ids of questions belongs to a general exam.

Currently, I have two ideas to design GeneralQuestion table:

It will have two columns: general_exam_id, question_id.

It will have two columns: general_exam_id,

list_question_ids (string/text).

I would like to know which designing is better, or pros and cons of each designing.

I'm using Postgresql database.


问:
What is the correct way to handle debug output in Java?
As my current Java projects grow bigger and bigger, I feel a likewise growing need to insert debug output in several points of my code.

To enable or disable this feature appropriately, depending on the opening or closure of the test sessions, I usually put a private static final boolean DEBUG = false at the beginning of the classes my tests are inspecting, and trivially use it this way (for example):

```<code>public MyClass {
  private static final boolean DEBUG = false;

  ... some code ...

  public void myMethod(String s) {
    if (DEBUG) {
      System.out.println(s);
    }
  }
}
</code>```

and the like.

But that doesn't bliss me out, because of course it works but there could be too many classes in which to set DEBUG to true, if you are not staring at just a couple of them.

Conversely, I (like - I think - many others) wouldn't love to put the whole application in debug mode, as the amount of text being output could be overwhelming.

So, is there a correct way to architecturally handle such situation or the most correct way is to use the DEBUG class member?

答: This is exactly what logging frameworks like log4j or the newer slf4j are meant for. They allow you to control logging in great detail, and configure it even while the application is running.</p>


答:
As a manager yes I get the team to do timesheets.  Here's why and a few notes on how they're implemented to, hopefully, minimise disruption:

As a business much of our work is done on a time and materials basis.  Without timesheets that obviously doesn't work.  We have 10 clients and a range of different projects and products but we're not a big enough to devote people to clients or projects full time which means that we have to have some way of working out how long things took.
Even if this weren't true to manage a team you still need to understand what takes time and how much. Think that old app the mailroom guys use is taking more time to support than it's worth? What about when someone asks how much work went into feature X on the new website which doubled sales? Or when your developers say you should recruit someone else and you get asked to breakdown what they do to help justify it?

Categories exist for all reasonable "non-work" including mentoring, general technical discussions, support, meetings and so on.

Bug fixing - we record time against a whole project rather than bug by bug.  This tends to make things a lot easier - spend the day fixing bugs, 7.5 hours bug fixing goes against the project and you're done.  No need to try and work out how it was divided between the 13 bugs you fixed.

When we implemented them I promised that no-one would be penalised / rewarded for what was on their timesheet so long as it was accurate.  So there is no input into reviews based on profitability or utilisation or anything else.  This means that there is no incentive to distort.

By accurate I mean roughly.  People really shouldn't have to spend too much time worrying about what happens when they make a coffee or go to the toilet.  Basically if you make a note on a pad of each thing you worked on during the day, then at the end of the day roughly break it down across the hours you worked and that's it.  If shouldn't take more than 5 minutes max.

If I don't like what I see - for instance someone has spent too long on task X - the investigation is into what we can do to make X faster, rather than anything to do with the timesheet.

Knowing how long you spent doing something is a great way of improving estimates.

The anti-timesheet feeling among many programmers seems to come from two things - (1) badly implemented timesheets which take too long to complete, demand more information than is really needed and encourage lying and distortion so the information is worthless anyway, and (2) a feeling that every single thing that slightly inconveniences a developer should be done away with.

The first one is fair but you should blame the implementation and the rules someone has attached, not the whole idea of timesheets which can be done in ways that don't have these issues.  The second one is just unrealistic - there are many parties involved in projects, both inside and outside the company, each of whom have many demands on them.  Yes we want to do everything we can to make programmers productive, but it has to be balanced with the needs of other parties.

Title: As a programmer, are you required to do timesheets?

Body:
Timesheets are something that I've never been fond of, but none the less something that is a requirement within my company. They don't bother me so much, but they seem to really grind some other people's gears. I suppose I have a few questions, and feedback would be great.

Are you required to do timesheets, assuming you aren't a contractor? (That is understandable to me).

What is the granularity of timesheets that you would be comfortable with or that you use? (ex: all entries must be under two hours).

Would timesheets ever factor into your reasons for not accepting a job or leaving a current one?

How has management within your organization justified timesheets if you aren't billing to a client?


答:
use a logging framework

most of the time there's a static factory method

```<code>private static final Logger logger = Logger.create("classname");
</code>```

then you can output your logging code with different levels:

```<code>logger.warning("error message");
logger.info("informational message");
logger.trace("detailed message");
</code>```

then there will be a single file where you can define which messages for each class should be written to the log output (file or stderr)

Title: What is the correct way to handle debug output in Java?

Body:
As my current Java projects grow bigger and bigger, I feel a likewise growing need to insert debug output in several points of my code.

To enable or disable this feature appropriately, depending on the opening or closure of the test sessions, I usually put a private static final boolean DEBUG = false at the beginning of the classes my tests are inspecting, and trivially use it this way (for example):

```<code>public MyClass {
  private static final boolean DEBUG = false;

  ... some code ...

  public void myMethod(String s) {
    if (DEBUG) {
      System.out.println(s);
    }
  }
}
</code>```

and the like.

But that doesn't bliss me out, because of course it works but there could be too many classes in which to set DEBUG to true, if you are not staring at just a couple of them.

Conversely, I (like - I think - many others) wouldn't love to put the whole application in debug mode, as the amount of text being output could be overwhelming.

So, is there a correct way to architecturally handle such situation or the most correct way is to use the DEBUG class member?

Body:
use a logging framework

most of the time there's a static factory method

private static final Logger logger = Logger.create("classname");

then you can output your logging code with different levels:

logger.warning("error message");
logger.info("informational message");
logger.trace("detailed message");

then there will be a single file where you can define which messages for each class should be written to the log output (file or stderr)


答:
You want to look at a logging framework, and maybe at a logging facade framework.

There are multiple logging frameworks out there, often with overlapping functionalities, so much so that over time many evolved to rely on a common API, or have come to be used through a facade framework to abstract their use and allow them to be swapped in place if needed.

Frameworks

Some Logging Frameworks

Java Logging Framework (part of the JDK),

Apache Log4J (bit old, but still going strong and actively maintained),

LogBack (created to provide a more modern approach than Log4J, by one of the creators of Log4J).

Some Logging Facades

SLF4J (by the creator of LogBack, but has adapters for other frameworks),

Apache Commons Logging (but a bit dated now).

Usage

Basic Example

Most of these frameworks would allow you to write something of the form (here using slf4j-api and logback-core):

```<code>package chapters.introduction;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

// copied from: http://www.slf4j.org/manual.html
public class HelloWorld {

  public static void main(String[] args) {
    final Logger logger = LoggerFactory.getLogger(HelloWorld.class);

    logger.debug("Hello world, I'm a DEBUG level message");
    logger.info("Hello world, I'm an INFO level message");
    logger.warn("Hello world, I'm a WARNING level message");
    logger.error("Hello world, I'm an ERROR level message");
  }
}
</code>```

Note the use of a the current class to create a dedicated logger, which would allow SLF4J/LogBack to format the output and indicate where the logging message came from.

As noted in the SLF4J manual, a typical usage pattern in a class is usually:

```<code>import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyClass {

    final Logger logger = LoggerFactory.getLogger(MyCLASS.class);

    public void doSomething() {
        // some code here
        logger.debug("this is useful");

        if (isSomeConditionTrue()) {
            logger.info("I entered by conditional block!");
        }
    }
}
</code>```

But in fact, it's even more common to declare the logger with the form:

```<code>private static final Logger LOGGER = LoggerFactory.getLogger(MyClass.class);
</code>```

This allows the logger to be used from within static methods as well, and it is shared between all instances of the class. This is quite likely to be your preferred form. However, as noted by Brendan Long in comments, you want to be sure to understand the implications and decide accordingly (this applies to all logging frameworks following these idioms).

There are other ways of instantiating loggers, for instance by using a string parameter to create a named logger:

```<code>Logger logger = LoggerFactory.getLogger("MyModuleName");
</code>```

Debug Levels

Debug levels vary from one framework to another, but the common ones are (in order of criticality, from benign to bat-shit bad, and from probably very common to hopefully very rare):

TRACE Very detailed information. Should be written to logs only. Used only to track the program's flow at checkpoints.

DEBUG Detailed information. Should be written to logs only.

INFO Notable runtime events. Should be immediately visible on a console, so use sparingly.

WARNING Runtime oddities and recoverable errors.

ERROR Other runtime errors or unexpected conditions.

FATAL Severe errors causing premature termination.

Blocks and Guards

Now, say you have a code section where you are about to write a number of debug statements.
This could quickly impact your performance, both because of the impact of the logging itself and of the generation of any parameters you might be passing to the logging method.

To avoid this sort of issue, your often want to write something of the form:

```<code>if (LOGGER.isDebugEnabled()) {
   // lots of debug logging here, or even code that
   // is only used in a debugging context.
   LOGGER.debug(" result: " + heavyComputation());
}
</code>```

If you hadn't used this guard before your block of debug statements, even though the messages may not be output (if, for instance, your logger is currently configured to print only things above the INFO level), the heavyComputation() method would still have been executed.

Configuration

Configuration is quite dependent on your logging framework, but they offer mostly the same techniques for this:

programmatic configuration (at runtime, via an API - allows for runtime changes),

static declarative configuration (at start-time, usually via an XML or properties file - likely to be what you need at first).

They also offer mostly the same capabilities:

configuration of the output message's format (timestamps, markers, etc...),

configuration of the output levels,

configuration of fine-grained filters (for instance to include/exclude packages or classes),

configuration of appenders to determine where to log (to console, to file, to a web-service...) and possibly what to do with older logs (for instance, with auto rolling files).

Here's a common example of a declarative configuration, using a logback.xml file.

```<code><configuration>

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <!-- encoders are assigned the type
         ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
  </appender>

  <root level="debug">
    <appender-ref ref="STDOUT" />
  </root>
</configuration>
</code>```

As mentioned, this depends on your framework and there may be other alternatives (for instance, LogBack also allows for a Groovy script to be used). The XML configuration format may also vary from one implementation to another.

For more configuration examples, please refer (amongst others) to:

the LogBack manual on configuration,

the Log4J 2 manual on configuration.

Some Historical Fun

Please note that Log4J is seeing a major update at the moment, transitioning from version 1.x to 2.x. You may want to have a look at both for more historical fun or confusion, and if you pick Log4J probably prefer to go with the 2.x version.

It's worth noting, as Mike Partridge mentioned in comments, that LogBack was created by a former Log4J team member. Which was created to address shortcomings of the Java Logging framework. And that the upcoming major Log4J 2.x version is itself now integrating a few features taken from LogBack.

Recommendation

Bottom line, stay decoupled as much as you can, play around with a few, and see what works best for you. In the end it's just a logging framework. Except if you have a very specific reason, apart from ease of use and personal preference, any of these would do rather OK so there's not point being to hung over it. Most of them can also be extended to your needs.

Still, if I had to pick a combination today, I'd go with LogBack + SLF4J. But if you had asked me a few years later I'd have recommended Log4J with Apache Commons Logging, so keep an eye over your dependencies and evolve with them.

Body:
You want to look at a logging framework, and maybe at a logging facade framework.

There are multiple logging frameworks out there, often with overlapping functionalities, so much so that over time many evolved to rely on a common API, or have come to be used through a facade framework to abstract their use and allow them to be swapped in place if needed.

Frameworks

Some Logging Frameworks

Java Logging Framework (part of the JDK),

Apache Log4J (bit old, but still going strong and actively maintained),

LogBack (created to provide a more modern approach than Log4J, by one of the creators of Log4J).

Some Logging Facades

SLF4J (by the creator of LogBack, but has adapters for other frameworks),

Apache Commons Logging (but a bit dated now).

Usage

Basic Example

Most of these frameworks would allow you to write something of the form (here using slf4j-api and logback-core):

package chapters.introduction;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

// copied from: http://www.slf4j.org/manual.html
public class HelloWorld {

  public static void main(String[] args) {
    final Logger logger = LoggerFactory.getLogger(HelloWorld.class);

    logger.debug("Hello world, I'm a DEBUG level message");
    logger.info("Hello world, I'm an INFO level message");
    logger.warn("Hello world, I'm a WARNING level message");
    logger.error("Hello world, I'm an ERROR level message");
  }
}

Note the use of a the current class to create a dedicated logger, which would allow SLF4J/LogBack to format the output and indicate where the logging message came from.

As noted in the SLF4J manual, a typical usage pattern in a class is usually:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MyClass {

    final Logger logger = LoggerFactory.getLogger(MyCLASS.class);

    public void doSomething() {
        // some code here
        logger.debug("this is useful");

        if (isSomeConditionTrue()) {
            logger.info("I entered by conditional block!");
        }
    }
}

But in fact, it's even more common to declare the logger with the form:

private static final Logger LOGGER = LoggerFactory.getLogger(MyClass.class);

This allows the logger to be used from within static methods as well, and it is shared between all instances of the class. This is quite likely to be your preferred form. However, as noted by Brendan Long in comments, you want to be sure to understand the implications and decide accordingly (this applies to all logging frameworks following these idioms).

There are other ways of instantiating loggers, for instance by using a string parameter to create a named logger:

Logger logger = LoggerFactory.getLogger("MyModuleName");

Debug Levels

Debug levels vary from one framework to another, but the common ones are (in order of criticality, from benign to bat-shit bad, and from probably very common to hopefully very rare):

TRACE Very detailed information. Should be written to logs only. Used only to track the program's flow at checkpoints.

DEBUG Detailed information. Should be written to logs only.

INFO Notable runtime events. Should be immediately visible on a console, so use sparingly.

WARNING Runtime oddities and recoverable errors.

ERROR Other runtime errors or unexpected conditions.

FATAL Severe errors causing premature termination.

Blocks and Guards

Now, say you have a code section where you are about to write a number of debug statements.
This could quickly impact your performance, both because of the impact of the logging itself and of the generation of any parameters you might be passing to the logging method.

To avoid this sort of issue, your often want to write something of the form:

if (LOGGER.isDebugEnabled()) {
   // lots of debug logging here, or even code that
   // is only used in a debugging context.
   LOGGER.debug(" result: " + heavyComputation());
}

If you hadn't used this guard before your block of debug statements, even though the messages may not be output (if, for instance, your logger is currently configured to print only things above the INFO level), the heavyComputation() method would still have been executed.

Configuration

Configuration is quite dependent on your logging framework, but they offer mostly the same techniques for this:

programmatic configuration (at runtime, via an API - allows for runtime changes),

static declarative configuration (at start-time, usually via an XML or properties file - likely to be what you need at first).

They also offer mostly the same capabilities:

configuration of the output message's format (timestamps, markers, etc...),

configuration of the output levels,

configuration of fine-grained filters (for instance to include/exclude packages or classes),

configuration of appenders to determine where to log (to console, to file, to a web-service...) and possibly what to do with older logs (for instance, with auto rolling files).

Here's a common example of a declarative configuration, using a logback.xml file.

<configuration>

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <!-- encoders are assigned the type
         ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
  </appender>

  <root level="debug">
    <appender-ref ref="STDOUT" />
  </root>
</configuration>

As mentioned, this depends on your framework and there may be other alternatives (for instance, LogBack also allows for a Groovy script to be used). The XML configuration format may also vary from one implementation to another.

For more configuration examples, please refer (amongst others) to:

the LogBack manual on configuration,

the Log4J 2 manual on configuration.

Some Historical Fun

Please note that Log4J is seeing a major update at the moment, transitioning from version 1.x to 2.x. You may want to have a look at both for more historical fun or confusion, and if you pick Log4J probably prefer to go with the 2.x version.

It's worth noting, as Mike Partridge mentioned in comments, that LogBack was created by a former Log4J team member. Which was created to address shortcomings of the Java Logging framework. And that the upcoming major Log4J 2.x version is itself now integrating a few features taken from LogBack.

Recommendation

Bottom line, stay decoupled as much as you can, play around with a few, and see what works best for you. In the end it's just a logging framework. Except if you have a very specific reason, apart from ease of use and personal preference, any of these would do rather OK so there's not point being to hung over it. Most of them can also be extended to your needs.

Still, if I had to pick a combination today, I'd go with LogBack + SLF4J. But if you had asked me a few years later I'd have recommended Log4J with Apache Commons Logging, so keep an eye over your dependencies and evolve with them.


答: IE7 doesn't support 'display: table', so you can only use it for IE8 and up. Other browsers handle it fine, mostly.</p>

Title: Using table-styled divs instead of tables

Body:
I was referred here from stackoverflow as my question was apparently too broad.

I'm working on a template, and I know using CSS is preferred over HTML tables for positioning... But, is it acceptable to get the best of both worlds and use table-like styles on my divs? For example:

```<code>display: table;
</code>```

This not only helps solve the sticky footer problem, but it also avoids the pains associated with using floats. Somehow it feels dirty, but I can't logically explain why because it works without any "tricks" or ugly hacks, which is how it should be, right?

Is this technically incorrect, or does it ultimately boil down to just a matter of opinion? ...Thoughts?


问:
What is an appropriate way for managing a MySQL connection through C#
My question, at the bottom line, is what is the appropriate(best) way to manage our connection towards MySQL db with C#.

Well, currently I'm working on some C# (WinForms type) <-> MySQL application and I've been looking at Server Connections in MySQL Administrator, been witness of execution of my MySQL queries, connection opens an closes, ... an so on! In my C# code I'm working like this and this is an example:

```<code>public void InsertInto(string qs_insert)
{

     try
     {
          conn = new MySqlConnection(cs);
          conn.Open();

          cmd = new MySqlCommand();
          cmd.Connection = conn;
          cmd.CommandText = qs_insert;
          cmd.ExecuteNonQuery();

     }
     catch (MySqlException ex)
     {
         MessageBox.Show(ex.ToString());
     }
     finally
     {
         if (conn != null)
         {
            conn.Close();
         }
     }
}
</code>```

Meaning, every time I want to insert something in db table I call this table and pass insert query string to this method. Connection is established, opened, query executed, connection closed. So, we could conclude that this is the way I manage MySQL connection.

For me and my point of view, currently, this works and its enough for my requirements.

Well, you have Java & Hibernate, C# & Entity Framework  and I'm doing this :-/ and it's confusing me. Should I use MySQL with Entity Framework?

What is the best way for collaboration between C# and MySQL? I don't want to worry about is connection that I've opened closed, can that same connection be faster, ...

答:
I would suggest using

```<code>using(MySqlConnection conn = new MySqlConnetion(cs)
{
    conn.open();
    //setup and execute query

} //conn gets closed here
</code>```

Here, once you exit the using block, the connection is closed.

Body:
I would suggest using

using(MySqlConnection conn = new MySqlConnetion(cs)
{
    conn.open();
    //setup and execute query

} //conn gets closed here

Here, once you exit the using block, the connection is closed.


问:
Brief material on C++ object-lifetime management and on passing and returning values/references
I was wondering if anybody can point to a post, pdf, or excerpt of a book containing the rules for C++ variable life-times and best practices for passing and returning function parameters. Things like when to pass by value and by reference, how to share ownership, avoid unnecessary copies, etc. This is not for a particular problem of mine, I've been programming in C++ for long enough to know the rules by instinct, but it is something that a lot of newcomers to the language stumble with, and I would be glad to point them to such a thing.</p>

答:
Here's the rules in a summary post:

pass-by-value + copying is related + slicing

pass-by-reference + polymorphism is related

ownership passing is (usually) done via pointers.

sizeof(T) is compile-time constant, making all c++ types have compile-time size

ownership sharing via shared_ptr

never pass ownership -style

escaping from function local scope to upper scope requires copying the data, because the local scope data storage disappears after function call ends.

call stack is one path in a tree; function call is moving to a subtree

User-defined types are special - order of classes in header file is important for inheritance and composition - class scope lifetime can be tied to either heap or stack

Polymorphic factory usually uses ownership passing; but can also be implemented using copying/clone and pass-by-reference.

Avoiding unnecessary copies is bad practise - copying should be supported for all data.

Interfaces only support passing compile-time amount of data through the interface. All data needs to be split to small pieces; and dynamic amount of it requires repeated function calls to the interface.

Constructor parameters allow adding parameters to object

All heap allocation in arrays is outside of the type system -- there does not exists type that can contain dynamic amount of memory inside it.


答:
About the Complaints...

Let's start with these:

One developer felt he wasted his time as he was used to be given out the scenarios directly by the business analyst and review them with her.

Which is what he was doing in the workshop. So that seems like a moody and bad excuse to me. I'd suspect this developer just doesn't like either (or both) the scrutiny of the workshop and its scheduling constraints.

The business analyst didn't feel confident with our scenario coverage (Had a feeling that we could have missed out other important stuff)

How is this different than when she does it on her side and has it reviewed by a developer, apart from the fact that more people looked at it? I'd suspect this is just the outcome of workshop being maybe a bit chaotic. You'll get confidence that you have enough tests by implementing them and integrating them. You can never be sure you found all bugs, and when it comes to coverage, the best way would be to diagram them in your user stories.

but more importantly felt that this workshop was also a waste of time as she could have figured out all these scenarios by herself and in a shorter period of time.

Yes, and entirely on her own, in her walled garden, and without sharing knowledge. Whereas by doing this future workshops might be more productive as all participants have gained a little knowledge of how to approach these things.

Maybe the meeting was slow this time, it doesn't mean it will always be. And as an external personal, I'd have, given some training to get this right, more confidence that the coverage was better in a workshop with 3 participants with different mindsets that with a single dictator.

Also, if there already was a need for a developer to review these scenarios with her, I'm pretty sure the back-and-forth is much faster and efficient in the workshop than using the "I do my stuff alone and give stuff to you, you review it alone and get back to me and let's do this again" approach.

Suggestions

Be positive and stress that if the process is right, you'll get better at it.

Try to streamline the workshop and keep it on track.

Maybe give some room for "lone-wolf" analysis, by starting the workshop with everybody designing a few scenarios on their own (even better, before the workshop), then triage and merge them.

And if you don't think doing that brainstorming thing is needed, fine: have the BA work alone, but then do the review as a workshop, at least. The more eyeballs the better, to quote Eric S. Raymond's Linus' Law:

```<code>Given enough eyeballs, all bugs are shallow.
</code>```

Body:
About the Complaints...

Let's start with these:

One developer felt he wasted his time as he was used to be given out the scenarios directly by the business analyst and review them with her.

Which is what he was doing in the workshop. So that seems like a moody and bad excuse to me. I'd suspect this developer just doesn't like either (or both) the scrutiny of the workshop and its scheduling constraints.

The business analyst didn't feel confident with our scenario coverage (Had a feeling that we could have missed out other important stuff)

How is this different than when she does it on her side and has it reviewed by a developer, apart from the fact that more people looked at it? I'd suspect this is just the outcome of workshop being maybe a bit chaotic. You'll get confidence that you have enough tests by implementing them and integrating them. You can never be sure you found all bugs, and when it comes to coverage, the best way would be to diagram them in your user stories.

but more importantly felt that this workshop was also a waste of time as she could have figured out all these scenarios by herself and in a shorter period of time.

Yes, and entirely on her own, in her walled garden, and without sharing knowledge. Whereas by doing this future workshops might be more productive as all participants have gained a little knowledge of how to approach these things.

Maybe the meeting was slow this time, it doesn't mean it will always be. And as an external personal, I'd have, given some training to get this right, more confidence that the coverage was better in a workshop with 3 participants with different mindsets that with a single dictator.

Also, if there already was a need for a developer to review these scenarios with her, I'm pretty sure the back-and-forth is much faster and efficient in the workshop than using the "I do my stuff alone and give stuff to you, you review it alone and get back to me and let's do this again" approach.

Suggestions

Be positive and stress that if the process is right, you'll get better at it.

Try to streamline the workshop and keep it on track.

Maybe give some room for "lone-wolf" analysis, by starting the workshop with everybody designing a few scenarios on their own (even better, before the workshop), then triage and merge them.

And if you don't think doing that brainstorming thing is needed, fine: have the BA work alone, but then do the review as a workshop, at least. The more eyeballs the better, to quote Eric S. Raymond's Linus' Law:

Given enough eyeballs, all bugs are shallow.


问:
Agile product backlogs
We are starting an Agile project, and the product owner has made a start adding user stories to the product backlog (mostly epics at this stage).

Who would be responsible for breaking down epics into smaller user stories - is it left to the product owner, or would you expect the rest of the team to be involved (bearing in mind they won't have any knowledge of the requirements or problem domain)?

答:
IMO, the team would be responsible for breaking down the epics into smaller user stories which while in the beginning will be a challenge is likely something that will improve over time.

The team should be taking on an understanding of the domain and accepting their part in ramping up in getting the product built.  While there may be various questions initially, the team can ask the product owner for elaboration on the epics but the organization of the work and break down into tasks should definitely fall under the team's purview.

Title: Agile product backlogs


答:
As a general rule, the whole team is responsible for breaking down the epics prior to implementing them. It's fine to put the epic in the backlog and prioritize it, and then break it down just before the iteration in which it is planned for implementation. When breaking it down, the product owner (or other customer and user representatives) would help to identify the subprocesses of the epic so that it can be broken down into its constituent parts.

However, without an understanding of the problem domain or the requirements of the system, I'm not sure how the development team can have a conversation with the product owner, customers, and users about what they are delivering. Depending on the complexity of the problem domain, they might not have an in-depth understanding, but I would expect some kind of education about the customer's business and domain-specific terminology, the problems the system is trying to solve, and the general direction and high-level requirements of the system under development for everyone involved in the project.

Title: Agile product backlogs

Body:
We are starting an Agile project, and the product owner has made a start adding user stories to the product backlog (mostly epics at this stage).

Who would be responsible for breaking down epics into smaller user stories - is it left to the product owner, or would you expect the rest of the team to be involved (bearing in mind they won't have any knowledge of the requirements or problem domain)?


问:
How to reduce tight coupling between two data sources
I'm having some trouble finding a proper solution to the following architecture problem.

In our setting (sketched below) we have 2 data sources, where data source A is the primary source for items of type Foo. A secondary data source exists which can be used to retrieve additional information on a Foo; however this information does not always exist.

Furthermore, data source A can be used to retrieve items of type Bar. However, each Bar refers to a Foo. The difficulty here is that each Bar should refer to a Foo which, if available, also contains the information as augmented by data source B.

My question is: how to remove the tight coupling between SubsystemA.1 and DataSourceB?

答:
One way to deal with this is to make an aggregated data source that contains the data from both data sources in one place. A job would run periodically to check for changes in sources A and B, and writing the "deltas" into your aggregated data source. This would convert two tightly coupled data source into a single coherent data source.

Several things could prevent you from taking this approach:

The amount of data may be prohibitive - A full copy of A and B needs to be made, doubling the space requirements.

The data mus be live - There will be periods between the time the data in the source has changed and the aggregating job has propagated it into the aggregated source.

You need to reconcile the data with the original sources - The task of moving the changes back into their original places becomes a lot more complex if you take this approach.


答:
You can't.

If I understand correctly, Foo and Bar come from dsA.  Bars belong to Foos.

Preferably, you don't want Bars assigned to Foos, unless the Foo has been supplemented by Foo.enhancedInfo that comes from dsB.

Your preference for assigning Bars to Foos is what's creating your tight coupling.  I would qualify that as a "requirements challenge" which is forcing you down a particular path.

So the technical challenges are that dsB may or may not have information on any given Foo and that dsB may not even be available.

You need to decide how hard and fast that preference for Foo.enhancedInfo really is.  Based upon that requirement, you can decide to either provide a Foo + Bar object, or not.  Allowing a non-enhanced Foo to be provided only complicates the logic and tells me that the preference isn't as strict as it may appear.  Determine what variants of Foo, Foo.enhanced, and Bar your application(s) can support and you'll have your ultimate answer.

There are other things you could do to move the Foo related information closer together, and that might solve some of these problems.  The way your question is phrased, it sounds like you're dealing with the problem at the data object level and you may not be able to consider infrastructure type changes.

Title: How to reduce tight coupling between two data sources

Body:
I'm having some trouble finding a proper solution to the following architecture problem.

In our setting (sketched below) we have 2 data sources, where data source A is the primary source for items of type Foo. A secondary data source exists which can be used to retrieve additional information on a Foo; however this information does not always exist.

Furthermore, data source A can be used to retrieve items of type Bar. However, each Bar refers to a Foo. The difficulty here is that each Bar should refer to a Foo which, if available, also contains the information as augmented by data source B.

My question is: how to remove the tight coupling between SubsystemA.1 and DataSourceB?


答:
If the data in data source B cannot stand on its own, you would probably want to migrate it over to data source A if possible.

If they are independent but related, you should look into data virtualization. This will allow applications to treat the data as one set (when appropriate) in an agnostic manner. Depending on your platform, there will probably be an existing framework/library that can help you implement this.


问:
Is the escaping provided by the Google-Gson library enough to ensure a safe JSON payload?
I am currently using the Google-Gson library to convert Java objects into JSON inside a web service.

Once the object has been converted to JSON, it is returned to the client to be converted into a JSON object using the JavaScript eval() function. Is the character escaping provided by the Gson library enough to ensure that nothing nasty will happen when I run the eval() function on the JSON payload?

Do I need to HTML Encode the Strings in the Java Objects before passing them to the Gson library? Are there any other security concerns that I should be aware of?

答: No, Gson is not meant to be used to securely encode JSON in all possible cases. Instead, use a library dedicated to securely parse JSON. JSON.parse is a good example.</p>


问:
Is it okay to use a language that isn't supported by your company for some tasks?
I work for a company that supports several languages: COBOL, VB6, C#, and Java. I use those languages for my primary work, but I often find myself coding some minor programs (e.g. scripts) in Python because I find it to be the best tool for that type of task.

For example: an analyst gives me a complex CSV file to populate some DB tables, so I use Python to parse it and create a DB script.

What's the problem?

The main problem I see is that a few parts of these quick and dirty scripts are slowly gaining importance and:

My company does not support Python

They're not version controlled (I back them up in another way)

My coworkers do not know Python

The analysts have even started to reference them in emails ("launch the script that exports..."), so they are needed more often than I initially thought.

I should add that these scripts are just utilities that are not part of the main project; they simply help to get trivial tasks done in less time. For my own small tasks they help a lot.

In short, if I were a lottery winner to be in a accident, my coworkers would need to keep the project alive without those scripts; they would spend more time fixing CSV errors by hand, for example.

Is this a common scenario? Am I doing something wrong? What should I do?

答:
The first thing you need to do is talk with the team and your boss. Right now, you have a huge truck factor (if you got hit by a truck, no one else would easily be able to maintain your scripts). It looks like having scripts to do these tasks are important, but it's also important that anyone who needs to can edit and maintain these scripts. You need to explain how using Python adds value - how it saves time, effort, resources, money, and so on.

Second, get it into the project's version control. Now. Nothing that you produce for a project should be outside of that project's version control, ever.

Be prepared for backlash - people typically don't like change. Running off on your own, using unsupported and unknown (to the team/organization) technologies was a bad idea, without consulting at least the other developers and determining the best (for the project, not just you) way of automating these tasks for everyone to use.

I think this is probably a good case of

It's easier to ask forgiveness than it is to get permission.

It sounds like you got the job done, but you are going to have to deal with the repercussions now.


问:
What's The Difference Between Imperative, Procedural and Structured Programming?
By researching around (books, Wikipedia, similar questions on SE, etc) I came to understand that Imperative programming is one of the major programming paradigms, where you describe a series of commands (or statements) for the computer to execute (so you pretty much order it to take specific actions, hence the name "imperative"). So far so good.

Procedural programming, on the other hand, is a specific type (or subset) of Imperative programming, where you use procedures (i.e., functions) to describe the commands the computer should perform.

First question: Is there an Imperative programming language which is not procedural? In other words, can you have Imperative programming without procedures?

Update: This first question seems to be answered. A language CAN be imperative without being procedural or structured. An example is pure Assembly language.

Then you also have Structured programming, which seems to be another type (or subset) of Imperative programming, which emerged to remove the reliance on the GOTO statement.

Second question: What is the difference between procedural and structured programming? Can you have one without the other, and vice-versa? Can we say procedural programming is a subset of structured programming, as in the image?

答:
most of the popular languages of the past 50 years have been designed around the prevalent computer architecture, called the Von Neumann architecture, after one of its originators, John von Neumann.

These languages are called imperative languages.

In a von Neumaan computer, both data and programs are stored in the same memory. The CPU which executes instructions is separate from the memory. Therefore instructions and data must be transmitted from memory to CPU. Results of operations in the CPU must be moved back to memory. Nearly all digital computers built since 1940s have based on von Neumaan architecture.


答:
The rule is: open as late as possible. Close as soon as possible. (actually you are getting and putting to the connection pool, but the method names are open/close).

Your code snippet is OK, but if you want to follow the rule literally, then Open() could be moved right before ExecuteNonQuery().

As DFord suggested, the using blocks are preferred in C#. This is for stylistic reasons. This is a scope-based style. You can treat your resources (connections) somewhat like you would ordinary local primitives like int, double, etc. When they are out of scope, then everything is automatically cleaned up. The "using" block is converted to a try/finally by the compiler.

The using block is a simulation of RAII. However it is a simulation, not the real thing. Using blocks are a syntactic sugar for writing try/catch.  In real RAII you don't have to write any special syntax to get the stack pop effect as it's controlled by the literal stack. Real RAII is slightly safer as you don't need to remember to write any special constructs like "using" or "try".

Title: What is an appropriate way for managing a MySQL connection through C#

Body:
My question, at the bottom line, is what is the appropriate(best) way to manage our connection towards MySQL db with C#.

Well, currently I'm working on some C# (WinForms type) <-> MySQL application and I've been looking at Server Connections in MySQL Administrator, been witness of execution of my MySQL queries, connection opens an closes, ... an so on! In my C# code I'm working like this and this is an example:

```<code>public void InsertInto(string qs_insert)
{

     try
     {
          conn = new MySqlConnection(cs);
          conn.Open();

          cmd = new MySqlCommand();
          cmd.Connection = conn;
          cmd.CommandText = qs_insert;
          cmd.ExecuteNonQuery();

     }
     catch (MySqlException ex)
     {
         MessageBox.Show(ex.ToString());
     }
     finally
     {
         if (conn != null)
         {
            conn.Close();
         }
     }
}
</code>```

Meaning, every time I want to insert something in db table I call this table and pass insert query string to this method. Connection is established, opened, query executed, connection closed. So, we could conclude that this is the way I manage MySQL connection.

For me and my point of view, currently, this works and its enough for my requirements.

Well, you have Java & Hibernate, C# & Entity Framework  and I'm doing this :-/ and it's confusing me. Should I use MySQL with Entity Framework?

What is the best way for collaboration between C# and MySQL? I don't want to worry about is connection that I've opened closed, can that same connection be faster, ...


答:
It seems that at the top level there are two types: Foo and Bar, and you have only two top-level actions: findFoo(...) and findBar(...).  That is the interface to the I/O layer.

Your description of the data sources implies that there are two methods on A: findFoo and findBar and one method on B: findFooAuxiliaryInformation.  In findFoo you will need to merge the information from A and B.

I'm not sure what "tight coupling" you are referring to.  There are three data types contained in the two datasets: Bar, Foo, and FooAuxData.  The coupling between Foo and FooAuxData is inherent in the input data, and cannot be reduced.  But that coupling should appear only in the findFoo method.  That is the best you can do.  The requirement is implemented in a single place.  If it changes, you have to change that code.


答:
The only time I didn't resent having to fill in timesheets was when I worked in a team using XP. I suppose that was because

those cards were filled in as part of the stand-up meeting every morning (which was the first time I could actually see meetings having a high result/time ration)

I could actually see the results of the effort being used (for calculating the time needed to implement future tasks)

OTOH, I have been using a home-made Excel sheet to track my overtime state (and what I've done each day) for more than ten years. So currently I usually fill in the timesheet on Friday before I leave the company, copying from my Excel sheet.


问:
Are there examples of non CRUD approaches?
I'm a programmer but also have worked as an archivist. As archivist it's a lot about keeping data.

I often get into arguments with colleagues when it comes to operations on data. I don't like the U and the D in CRUD too much. Rather then update a record I prefer to add a new one and have a reference to the old record. That way you build a history of changes.
I also don't like deleting records but rather mark them as inactive.

Is there a term for this? Basically only creating and reading data? Are there examples of this approach?

答:
Marking a record as deleted is known as soft-deleting. I've never heard an alternate phrase for updating, but I guess that's cause you soft-delete the old record and create a new one.

It should be noted, this is a controversial technique. See links: Con vs Pro.


问:
Does having a higher paid technical job mean you do not get to code any more?
I work at a large company where technical people fall roughly in one of these categories:

A developer on a scrum team who develops for a single product and maybe works with other teams that are closely related to the product.

An architect who is more of a consultant on multiple teams (5-6) and tries to recognize commonalities between team efforts that could be abstracted into libraries (architects do not write the library code, however). This architect also attends many meetings with management and attempts to set technical direction.

In my company the architect role is where most technical people move into as the next step in their career.

My questions are: Do most companies work such a way that their highest paid technical people are far removed from writing code? Is this a natural tendency for a developer's career? Can a developer have it all (code AND set direction?)

答:
Do most companies work such a way that their highest paid technical people are far removed from writing code?

Most bad companies. There is a natural trend for more responsibility to involve less code writing and more focus on other aspects of software development. That said, it's very common for technical folks to lose touch with what is common/best/possible if they don't spend time actually coding. This has a disasterous effect on the company.

Is this a natural tendency for a developer's career?

Yes. In the end, a person can help the product a lot more by mentoring, coordinating, designing, knowing the problem domain and doing other software development tasks than they can by writing code. And in all honesty, having good leadership or design skills are far more rare (read: valuable) than code-writing skill.

Can a developer have it all (code AND set direction?)

Absolutely. Though you need to realise that the amount of coding will go down. You just can't do those other valuable things well if you spend 80% of the day heads down in an IDE.

The other option that happens is that of the 'principal engineer' for lack of a better term. Some developers are very specialized. I worked with someone for example who wrote gigabit ethernet drivers for Linux. We needed him to do that sort of work for us, and since only a handful of people could do that job well, he made piles of cash in addition to writing code as the majority of his day.

Most companies don't need that sort of specialization though. They're just plumbing data together or making yet another website/mobileapp.


答: You can use "soft-deletes" as pdr suggested. As for updates, you could keep history of records, sort of like my answer here: https://dba.stackexchange.com/questions/28195/save-history-editable-data-rdbms/28201#28201 where the OP wanted to be able to keep track of all versions of certain kinds of data.</p>

Title: Are there examples of non CRUD approaches?

Body:
I'm a programmer but also have worked as an archivist. As archivist it's a lot about keeping data.

I often get into arguments with colleagues when it comes to operations on data. I don't like the U and the D in CRUD too much. Rather then update a record I prefer to add a new one and have a reference to the old record. That way you build a history of changes.
I also don't like deleting records but rather mark them as inactive.

Is there a term for this? Basically only creating and reading data? Are there examples of this approach?


答: A logging framework is definitely the way to go.  However, you also must have a good test suite. Good test coverage may often eliminate the need for debug output all together.</p>


答:
One of the problems with retaining a change history is that it clutters up the database and can dramatically increase its size (depending on usage patterns). So a good idea would be to store the audit trail in a separate place, and keep the actual application tables populated only with relevant data. So each time a CRUD operation is performed by the application, the change is recorded in the audit tables, and the CRUD operation is performed on the application tables (no soft deletes).

By keeping the audit trail separate gives you a pristine data store for your application to interact with, while still retaining the change history should you need it. You can also now archive the audit trail separately or even destroy it, depending on your business requirements.


问:
Will You Use an Online Technical Skills Test to Hire a Senior Developer?
There are online services such as IKM that offer skills tests in many areas, including programming.

Would you use these kind of tests when hiring for a senior developer position?

What about just for objectively benchmarking candidates before calling them for an interview? Would you use it as a step after short-listing candidates after interviews?

Is this approach more suitable in some situations compared to others? Have you personally used this kind of service or know someone who has?

答:
To be blunt:  No, No, No, No and No!

Get the candidate in to do some coding with you, it's the only way you'll know how they think their way through problems and how they might fit into your team.

As an aside I'd try to avoid recruiting via the CV lottery technique :-), instead find good people through word of mouth, conferences, technical community meetups etc.  Avoids the sharky recruitment agents as well.


问:
Question on refactoring and code design
Suppose, I have a class with a constant static final field. Then I want in certain situations that field to be different. It still can be final, because it should be initialized in constructor. My question is, what strategy I should use:

add this field value into the constructor

create 2 subclasses, replace original field usage with some protected method and override it in subclasses

Or create some composite class that will held instance of my class inside and somehow change that value?

Which approach should I use and why?

答:
I think you need to ask why the field was set to final in the first place.  The impression is that it wasn't ever intended to be changed.

The fact that you need to change the value (or have multiple options for the value) indicates that the original assumptions driving the design are no longer valid.

I would recommend thinking about what function that field is actually serving and how best to provide that functionality to other objects.  That might mean a small-ish factory pattern implementation, or it might be two separate properties that can be retrieved as the callers require.  Your original question doesn't provide enough context to suggest a more accurate alternative.

So I think your three options are solving the wrong problem.  You're trying to shoe-horn change into an element that was explicitly designed to not accept change.  Find a better way of serving up that functionality based upon your application.

Title: Question on refactoring and code design