问:
Architecture of interaction modes ("paint tools") for a 3D paint program
We are developing a Qt-based application to navigate through and paint on a volume treated as a 3D pixel graphic. The layout of the app consists of three orthogonal slice views on which the user may paint stuff like dots, circles etc. and also erase already painted pixels. Think of a 3D Gimp or MS Paint.

How would you design the the architecture for the different interaction modes (i.e. paint tools)?

My idea is:

use the MVC pattern

have a separate controler for every interaction mode

install an event filter on all three slice views to collect all incoming user interaction events (mouse, keyboard)

redirect the events to the currently active interaction controler

I would appreciate critical comments on that idea.

答:
Your idea is basically correct. It also gets mentioned in the Design Pattern book at the State pattern. Your editor has a current Tool object (which implements a generic Tool interface), and delegates all the relevant user interactions to it (mouseclick, key events etc.). The paint tool, selection tool etc. classes will implement the Tool interface and will be responsible for handling sequences of user events.

public interface Tool {

```<code>void HandleKeyboardEvent(...);
void HandleMouseEvent(...);
</code>```

}

class RectangleTool : Tool {
    //accumulates drawing state
}

When you change a Tool it will be just the current tool object which changes, the rest of the logic in your UI stays the same.

If you have 3 orthogonal views then you can have 3 tool objects or just one, depending on your design.

Body:
Your idea is basically correct. It also gets mentioned in the Design Pattern book at the State pattern. Your editor has a current Tool object (which implements a generic Tool interface), and delegates all the relevant user interactions to it (mouseclick, key events etc.). The paint tool, selection tool etc. classes will implement the Tool interface and will be responsible for handling sequences of user events.

public interface Tool {

void HandleKeyboardEvent(...);
void HandleMouseEvent(...);

}

class RectangleTool : Tool {
    //accumulates drawing state
}

When you change a Tool it will be just the current tool object which changes, the rest of the logic in your UI stays the same.

If you have 3 orthogonal views then you can have 3 tool objects or just one, depending on your design.


问:
How would you react if someone told you your code is a mess?
I am a good programmer, or so I thought before. I always love to program. And I want to learn many things about programming to make me a better programmer. I studied programming for 1 year and now I am working as a programmer for almost 2 years. So in short, I have almost 3 years programming experience.

Our team is composed of 5 programmers, and 4 of us are new, 1 has more than 3 year experience. We've been working for a program for almost a year now and nobody ever review my code and I was given a page to work with. We never had a code review and we are all new so we don't know what is a clean code looks like. I think programmers learn by themselves?

We deployed our program to the program without thorough testing. Now it is tight and we need an approval and code review first before we make changes with the code. For the first time, someone reviews my code and he says it is a mess.

I feel so sad and hurt. I really love programming and making them say something like that really hurts me. I really want to improve myself. But it seems like I'm not a genius programmer like in the movies. Can you give me advise on how to be better? Have you ever experience something criticizing your code and you feel really hurt? What do you do on those events.

答:
The fact that you're concerned is a good sign. Let's start with that. You mention you love to program, but do you love being a professional programmer? There's a big difference between an enthusiast and a professional. As a professional you will be under constant scrutiny for your work product.

```<code>Our team is composed of 5 programmers, and 4 of us are new
</code>```

The fact that you've worked two years without any confrontation tells me that you're working in a very laid-back job  which, is not so good if you're actually wanting to move forward as a professional. Mind you, some of the best programmers in the world work for the Linux foundation and be rest assured they do not get treated kindly when they make  marginal mistakes ... much less 'messy code'.

For a quick review of some fairly standard coding guidelines, the Linux Community Contributors Standards should give you an idea of the level of responsibility to aspire towards for your product. Refer to GETTING THE CODE RIGHT.

To further that assertion you should learn to embrace review as most good software is thoroughly reviewed. This supports Linus' Law stating ...

"If there are enough reviewers, all problems are easy to solve."

Personally, I've seen highly skilled, responsible and dependable developers get the axe for something as simple as forgetting to leave comments ... so if someone tells you your codes a
mess then it probably is ... Get over it ... Refactoring. It's part of the gig.

```<code>I feel so sad and hurt.
</code>```

Go make a sadness application to gauge how upset you get when you don't apply yourself.

You answered your problem ... You Don't Test!

After seeing a comment you made stating that your a java developer, I almost got upset. So if I understand you correctly your saying that you and your development team are working in a java shop and don't have a test framework for your applications ...

Therein Lies The Rub

"We deployed our program to the program without thorough testing."

Cribbing UML Creator Grady Booch ...

The amateur software engineer is always in search of magic,
some sensational method or tool whose application promises to
render software development trivial. It is the mark of the
professional software engineer to know that no such panacea
exists.

Alistair Cockburn provides a wealth of information on his site on using agile methodologies to increase performance and quality for you and your team.

One of the most important aspects of programming {and life} is knowing your strengths and weaknesses. If you don't work on your weaknesses you will not have a well-rounded skill-set.

Outro ... Your doing fine - Just don't whine. Move forward in developing your craft and let your passion for programming keep you going. Good Luck :-)

ContentLicense: CC BY-SA 3.0

Body:
The fact that you're concerned is a good sign. Let's start with that. You mention you love to program, but do you love being a professional programmer? There's a big difference between an enthusiast and a professional. As a professional you will be under constant scrutiny for your work product.

Our team is composed of 5 programmers, and 4 of us are new

The fact that you've worked two years without any confrontation tells me that you're working in a very laid-back job  which, is not so good if you're actually wanting to move forward as a professional. Mind you, some of the best programmers in the world work for the Linux foundation and be rest assured they do not get treated kindly when they make  marginal mistakes ... much less 'messy code'.

For a quick review of some fairly standard coding guidelines, the Linux Community Contributors Standards should give you an idea of the level of responsibility to aspire towards for your product. Refer to GETTING THE CODE RIGHT.

To further that assertion you should learn to embrace review as most good software is thoroughly reviewed. This supports Linus' Law stating ...

"If there are enough reviewers, all problems are easy to solve."

Personally, I've seen highly skilled, responsible and dependable developers get the axe for something as simple as forgetting to leave comments ... so if someone tells you your codes a
mess then it probably is ... Get over it ... Refactoring. It's part of the gig.

I feel so sad and hurt.

Go make a sadness application to gauge how upset you get when you don't apply yourself.

You answered your problem ... You Don't Test!

After seeing a comment you made stating that your a java developer, I almost got upset. So if I understand you correctly your saying that you and your development team are working in a java shop and don't have a test framework for your applications ...

Therein Lies The Rub

"We deployed our program to the program without thorough testing."

Cribbing UML Creator Grady Booch ...

The amateur software engineer is always in search of magic,
some sensational method or tool whose application promises to
render software development trivial. It is the mark of the
professional software engineer to know that no such panacea
exists.

Alistair Cockburn provides a wealth of information on his site on using agile methodologies to increase performance and quality for you and your team.

One of the most important aspects of programming {and life} is knowing your strengths and weaknesses. If you don't work on your weaknesses you will not have a well-rounded skill-set.

Outro ... Your doing fine - Just don't whine. Move forward in developing your craft and let your passion for programming keep you going. Good Luck :-)


答:
I don't think building the interaction modes as different "controllers" will serve you well. What is your logic for this? A controller is to tie display and your user input to your model, but im imagining that this is only one canvas and one mouse pointer, so why multi controllers?

You could have the switching logic that changes between interaction modes in a model class. You probably shouldn't need to use it in more than one controller unless you're giving your user drastically different "canvas" type elements and layouts to draw on also. Either way, I think some good choices of Design Pattern would be a factory and/or a decorator or something similar.

Collect the event from the button click on the palette of interaction modes (you mean this to be a sort of Photoshop/MS Paint kind of toolbar on the side, right?). Use that event as the input to a factory. This factory will generate an instance of something adhering to the "Tool" interface (or whatever you want to call it). The newly generated Tool instance is stored in the controller somewhere to be ready to receive mouse input as the user draws, for example.

If you want to get complex - like what if some tools can be simultaneously chosen, like both a "magnetic lock" and a "draw" - your controller's reference to an instance implementing a Tool interface would need to be extended at runtime somehow, like w/ a Chain Of Responsibility pattern (or a decorator as previously mentioned). Now the factory mentioned before will make more than one Tool. The controller will "line these up" in the case of the Chain of Command before passing the user's mouse input. For example, the magnetic lock "Tool" implementation may change the users input slightly to exist on a guideline before passing it "along the chain" to the drawing tool.

Title: Architecture of interaction modes ("paint tools") for a 3D paint program

Body:
We are developing a Qt-based application to navigate through and paint on a volume treated as a 3D pixel graphic. The layout of the app consists of three orthogonal slice views on which the user may paint stuff like dots, circles etc. and also erase already painted pixels. Think of a 3D Gimp or MS Paint.

How would you design the the architecture for the different interaction modes (i.e. paint tools)?

My idea is:

use the MVC pattern

have a separate controler for every interaction mode

install an event filter on all three slice views to collect all incoming user interaction events (mouse, keyboard)

redirect the events to the currently active interaction controler

I would appreciate critical comments on that idea.


问:
A little code to allow word substitution depending on user
I'm creating a demo web app in html in order for people to physically see and comment on the app prior to committing to a proper build.

Whilst the proper app will be database driven, my demo is just standard html with some JavaScript effects.

What I do want to demonstrate is that different user group will see different words. For example, imagine I have an html sentence that says:

This will cost £100 to begin.

What I need to some way of identifying that if the user has deemed themselves to be from the US, the sentence says:

This will cost $100 to begin.

This requirement is peppered throughout the pages but I'm happy to add each one manually. So I envisage some code along the lines of 'first, remove the [boot US] trunk' where the UK version is 'first remove the boot' but the code is saying that the visitor needs the US version. It then looks up boot (in an Access database perhaps) and sees that the table says for boot for US, display 'trunk'.

I'm not a programmer but I can normally cobble together scripts so I'm hoping someone may have a relatively easy solution in JavaScript, CSS or ASP.

To recap: I have a number of words or short sentences that need to appear differently and I'm happy to manually insert each one if necessary (but would be even better if the words were automatically changed).
And I need a device which allows me to tell the pages to choose the US version, or for example, the New Zealand version.

答:
The simplest approach to to this is to use localised "dictionaries". This could be a table in the database or a "resource" file of strings, but the same principle applies.

You have a main dictionary that holds all of your text. This will be in the "neutral" language - the one where most of your users come from (for example).

You then have sub dictionaries for each language variant that holds the localised text. So your main dictionary (UK) will contain:

```<code>Id    Text
 1    First remove the boot
</code>```

Your sub dictionary (US) will contain:

```<code>Id    Text
 1    First remove the trunk
</code>```

Note that the ids are the same and that the whole phrase is present.

Then your application will check the users language (either by asking the user or by checking the locale of the browser/operating system they are using) and use the appropriate dictionary to find the text.

If the required id doesn't exist in the sub dictionary it will then look in the main dictionary for the default text to use.

The whole test is present as translations aren't usually as simple as replacing the odd word here and there. Often the same word (boot - footwear or part of car) has two or more meanings and a blind substitution doesn't take context into account. Also, while you might start off with a UK/US system it might require other languages later. This scheme is also easier to implement than a word substitution one.

As for currency symbols - store the numeric value only and format it with the users culture to output it as a string. Most frameworks have this ability.

Body:
The simplest approach to to this is to use localised "dictionaries". This could be a table in the database or a "resource" file of strings, but the same principle applies.

You have a main dictionary that holds all of your text. This will be in the "neutral" language - the one where most of your users come from (for example).

You then have sub dictionaries for each language variant that holds the localised text. So your main dictionary (UK) will contain:

Id    Text
 1    First remove the boot

Your sub dictionary (US) will contain:

Id    Text
 1    First remove the trunk

Note that the ids are the same and that the whole phrase is present.

Then your application will check the users language (either by asking the user or by checking the locale of the browser/operating system they are using) and use the appropriate dictionary to find the text.

If the required id doesn't exist in the sub dictionary it will then look in the main dictionary for the default text to use.

The whole test is present as translations aren't usually as simple as replacing the odd word here and there. Often the same word (boot - footwear or part of car) has two or more meanings and a blind substitution doesn't take context into account. Also, while you might start off with a UK/US system it might require other languages later. This scheme is also easier to implement than a word substitution one.

As for currency symbols - store the numeric value only and format it with the users culture to output it as a string. Most frameworks have this ability.


问:
Static analysis, dynamic analysis and testing
Based on answers I have received here and then confirmed in some authoritative sources (not ISTQB which seems to be too vague), there are 3 activities:

Static analysis

Dynamic analysis

Testing

But is there any reason why we cannot combine all of that as "testing"? I mean, even a dynamic analysis review of a program to look for memory leaks is a kind of testing, right?

答:
Because I am just working on a book covering these topics I can provide you my insight.

The main problem is the choice of a standard/approach to follow.

For example I believe - and so do many authors - that testing is an implicitly dynamic process and hence static testing is an improper name (I.S.T.Q.B. is using it to cover all static techniques but personally I'm not a fan of it).

To answer your question:

Testing - an actual execution of the program to exercise it by many methods (boundary analysis etc.)

Dynamic analysis - analyzing the memory, performance, etc. during run-time

Static analysis - reviews, static analysis tools, inspection

Also the other activities are useful when evaluating the quality of the product and are complementary to testing, related to it. But they are not testing in the true sense.

However, all can be regarded as part of quality assurance and quality control.


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
Well, not my favorite but...

If it is not broken, don't fix it

LastEditorDisplayName: Roger Pate

ContentLicense: CC BY-SA 2.5


答:
Can you give me advise on how to be better?

Jay's answer which recommends books is a good one, however it sounds like you're at a turning point at work already.

Past:

Our team is composed of 5 programmers, and 4 of us are new, 1 has more
  than 3 year experience. We've been working for a program for almost a
  year now and nobody ever review my code and I was given a page to work
  with.

Present:

Now it is tight and we need an approval and code review first before we make changes with the code.

It sounds like your company/team/department is learning as whole, in terms of project and team management as well as programming. Starting to review code is an excellent opportunity to improve in pretty much all areas if it's given proper attention.

Use this as an opportunity; assuming you're doing peer reviews (with the other developers on your team) suggest to them that this process is important and that everyone can learn from it.

At the base line it will be a quick review with the outcome being "yeah looks ok". With a little more focused effort you can bounce ideas off of each other, "yeah that works, but you could have approached it in this way, which would have made your goal clearer...". Take notes for future even if the code is deemed ok to deploy.

If this is going to be successful, you need to get your team and manager on side, which often means explaining the benefits to them. To the other developers this is an opportunity to learn. To your manager this is the opportunity to up-skill the team at little cost, therefore creating outputs a) with more value or b) faster c) with less maintenance cost (usually a big issue!).

This is a culture change, which you can't force through by yourself, but you can help to nudge things in the right direction!

Don't forget, this is kind of culture change can be hugely beneficial to organisations; good managers will recognise that you're working to make the whole team better, something worth rewarding.

Title: How would you react if someone told you your code is a mess?

Body:
I am a good programmer, or so I thought before. I always love to program. And I want to learn many things about programming to make me a better programmer. I studied programming for 1 year and now I am working as a programmer for almost 2 years. So in short, I have almost 3 years programming experience.

Our team is composed of 5 programmers, and 4 of us are new, 1 has more than 3 year experience. We've been working for a program for almost a year now and nobody ever review my code and I was given a page to work with. We never had a code review and we are all new so we don't know what is a clean code looks like. I think programmers learn by themselves?

We deployed our program to the program without thorough testing. Now it is tight and we need an approval and code review first before we make changes with the code. For the first time, someone reviews my code and he says it is a mess.

I feel so sad and hurt. I really love programming and making them say something like that really hurts me. I really want to improve myself. But it seems like I'm not a genius programmer like in the movies. Can you give me advise on how to be better? Have you ever experience something criticizing your code and you feel really hurt? What do you do on those events.


答:
But is there any reason why we cannot all that testing?

Well you could call it testing ... or cheese-making, or anything else that takes your fancy ... but that wouldn't help you to communicate with other computer professionals.

I mean even reviewing of dynamic analysis of program looking for memory leaks is a kind of testing..or not?

In my opinion memory leak detection is qualitatively different from what we normally mean by testing.

However, that's not really relevant.  What is relevant is that most software engineers wouldn't normally refer to that as "testing".  And if you want to communicate effectively, you need to use the same terminology (and meanings) that other people expect to hear.

Now if you want to convince everyone to change what they way that they classify these things, feel free to try.  But you are going to have to provide some persuasive arguments.

Title: Static analysis, dynamic analysis and testing

Body:
Based on answers I have received here and then confirmed in some authoritative sources (not ISTQB which seems to be too vague), there are 3 activities:

Static analysis

Dynamic analysis

Testing

But is there any reason why we cannot combine all of that as "testing"? I mean, even a dynamic analysis review of a program to look for memory leaks is a kind of testing, right?


问:
Can Clojure's thread-based agents handle c10k performance?
I'm writing a c10k-style service and am trying to evaluate Clojure's performance.  Can Clojure agents handle this scale of concurrency with its thread-based agents?  Other high performance systems seem to be moving towards async-IO/events/greenlets, albeit at a seemingly higher complexity cost.

Suppose there are 10,000 clients connected, sending messages that should be appended to 1,000 local files--the Clojure service is trying to write to as many files in parallel as it can, while not letting any two separate requests mangle the same single file by writing at the same time.

Clojure agents are extremely elegant conceptually--they would allow separate files to be written independently and asynchronously, while serializing (in the database sense)  multiple requests to write to the same file.

My understanding is that agents work by starting a thread for each operation (assume we are IO-bound and using send-off)--so in this case is it correct that it would start 1,000+ threads?  Can current-day systems handle this number of threads efficiently?  Most of them should be IO-bound and sleeping most of the time, but I presume there would still be a context-switching penalty that is theoretically higher than async-IO/event-based systems (e.g. Erlang, Go, node.js).

If the Clojure solution can handle the performance, it seems like the most elegant thing to code.  However if it can't handle the performance then something like Erlang or Go's lightweight processes might be preferable, since they are designed to have tens of thousands of them spawned at once, and are only moderately more complex to implement.

Has anyone approached this problem in Clojure or compared to these other platforms?  (Thanks for your thoughts!)

答: agents use an expandable thread pool rather than simply starting a thread per task. so the number of active threads will be cc close to the number of active agents. 1000 threads i seems reasonable for a modern computer. you will likely need to increase the max open file descriptors (assuming Linux) </p>


问:
What makes Java so suitable for writing NoSQL Databases
Looking at this page that aggregates the current NoSQL landscape, one can see that the majority of these projects are written in Java.

Databases are complex systems software dealing with the file system, and so C/C++ would be a better choice than Java for this. (that's my thinking which might be flawed)

Secondly, databases deal with transferring large amounts of data from disk to RAM -- which they call a working set. The JVM takes non-trivial amount of RAM for it's own purpose -- so it would be more efficient to use a platform that leaves lots of memory for data instead of hogging it for its own operations.

The major relational databases are ALL written in C/C++

```
MySQL              C, C++
Oracle             Assembler, C, C++
SQL Server         C++
PostgreSQL         C
SQLite             C
```

So what makes Java so popular in NoSQL world.

答: Most of the SQL DBs you list were written long before Java existed. So, the thing that makes Java more popular for NoSQL than for SQL is: it exists.</p>


答:
Can you give me advise on how to be better? Have you ever experience something criticizing your code and you feel really hurt? What do you do on those events.

The answer to this can be found in the new generation companies. I have been to companies like Google and FaceBook and I see that if you follow Agile/Scrum process religiously, then you can write better code and improve it every sprint.

```<code>How to be better?
</code>```

The answer is continuous refactoring. The modern development tools like visual studio has lot of tools that helps you in this process. If you follow Scrum software development process, then say for ex, you wrote bad code in sprint cycle 1 and someone pointed out during review it's bad, then in sprint 2, you have the opportunity to refactor the code.

These issues are occurring in the first place because of lack of good process. So the solution is to come up with a good software development process for your team and practice continuous refactoring.

Body:
Can you give me advise on how to be better? Have you ever experience something criticizing your code and you feel really hurt? What do you do on those events.

The answer to this can be found in the new generation companies. I have been to companies like Google and FaceBook and I see that if you follow Agile/Scrum process religiously, then you can write better code and improve it every sprint.

How to be better?

The answer is continuous refactoring. The modern development tools like visual studio has lot of tools that helps you in this process. If you follow Scrum software development process, then say for ex, you wrote bad code in sprint cycle 1 and someone pointed out during review it's bad, then in sprint 2, you have the opportunity to refactor the code.

These issues are occurring in the first place because of lack of good process. So the solution is to come up with a good software development process for your team and practice continuous refactoring.


答: The cost of developing in Java with or without one of its many frameworks in cheaper than cheaper than developing in .NET. Because of this, using Java makes it easier to get support in the open source community.</p>

Title: What makes Java so suitable for writing NoSQL Databases

Body:
Looking at this page that aggregates the current NoSQL landscape, one can see that the majority of these projects are written in Java.

Databases are complex systems software dealing with the file system, and so C/C++ would be a better choice than Java for this. (that's my thinking which might be flawed)

Secondly, databases deal with transferring large amounts of data from disk to RAM -- which they call a working set. The JVM takes non-trivial amount of RAM for it's own purpose -- so it would be more efficient to use a platform that leaves lots of memory for data instead of hogging it for its own operations.

The major relational databases are ALL written in C/C++

```
MySQL              C, C++
Oracle             Assembler, C, C++
SQL Server         C++
PostgreSQL         C
SQLite             C
```

So what makes Java so popular in NoSQL world.


答:
are you sure you counted right?

The majority of the DBs in "document store" section (which is what most people think of by NoSQL DBs) are written in C++ :

MongoDB (arguably the best of the lot BTW, good support from 10gen, and possibly the most widespread) Marklogic, Clusterpoint, EJDB are all in C/C++; with 1 in Erlang, 2 in .NET, and 2 in Java.

Even in the "Key Value / Tuple Store" section, only 2 are written in Java, the majority there are C/C++ too.

"Graph Databases" does have more Java (though one of those is listed as having a C/C++ core), but even so, there's only 3 with another 4 written in something else.

I've only considered the ones that have a language specified in that list, but its still obvious that the "majority java" claim is completely wrong.


问:
Can you explain why multiple threads need locks on a single-core CPU?
Assume these threads run in single core cpu. As a cpu only run one instruction in one cycle. That is said, even thought they share the cpu resource. but the computer ensure that one time one instruction. So is the lock un-necessary for multiplethreading?</p>

答:
Consider this quote:

Some people, when confronted with a problem, think, "I know, I'll use
  threads," and then two they haver poblesms

you see, even if 1 instruction runs on a CPU at any given time, computer programs comprise a lot more than just atomic assembly instructions. So for example, writing to the console (or a file) means you have to have to lock to ensure it works like you want.


问:
Why don't we have web IDEs?
Why don't we have a lot of good web-based IDEs? Which aspects of the system make it difficult for IDE to be implemented as a web application?</p>

答:
There are plenty of web based IDEs. Some of them place an emphasis on collaborative coding. I think that whatever makes you think there aren't a lot of "good" web-based IDE's is probably the subjective definition of what "good" actually means. What features are missing etc...

http://codiad.com/

http://www.eclipse.org/orion/

http://shiftedit.net/

https://c9.io ( http://ace.ajax.org/#nav=about )

http://ecco.sourceforge.net/

http://code.google.com/p/collide/

Personally, I'm always going to stick with my native desktop IDE.

Title: Why don't we have web IDEs?


答:
First off someone saying your code is a mess is very vague and subjective. It can mean different things to different people. Here's why; there are two different things that have to be considered.

Structure

The structure of your code is governed by the language, industry standards, and company standards to name a few. Obviously there are other factors as well.

These are the types of mistakes that lint, test tools, and similar products are designed to identify. They are well defined and you or your tools can make objective decisions as to their validity/correctness.

Style

Despite standardized structure/rules for code, every developer has a certain style in the way they write and approach a problem or task. Do code maintenance in any team environment and over time you'll be able to take an educated guess as to who wrote the code based on the style. You'll also develop your own style and it will change as you gain experience and learn your craft.

So any time that someone says your code is a mess you need to understand if they are talking about the structure or the style. They are two very different things; structure is objective while style is absolutely subjective.

That being said, any constructive feedback from other programmers can be very valuable to you. It's all up to you and how you take the criticism. Over time you'll learn who's opinion to take to heart versus who's to take with a grain of salt.

As you progress in your career you'll look back at your own code and see things that you could do differently, better, cleaner, and faster. It's all part of the learning process and seeing your own past mistakes is a true indication that you are honing and improving your craft.

Don't let a bit of criticism dampen your spirits. Take what you can from it and if it's meaningful and valuable add it to your store of knowledge.


问:
Why creating a new MDX language instead of extending SQL?
I have a long experience with SQL, but recently began working with datawarehouse and OLAP technologies: building fact and dimension tables, that then are queried using MDX (MultiDimensional eXpressions).

The problem is that MDX works with a completely different logic compared to SQL, and it's a whole new learning curve even for someone with a strong SQL background.

Yes, MDX allows you to do things that would be hard or almost impossible with plain SQL.
But sometimes it's frustrating to be hours around an MDX to do something you know you could achieve in minutes using SQL (ok, you can tell me to RTFM ...).

But why go on to the trouble of creating a new completely different language when you could build on SQL, extend it to add the features needed by OLAP applications?

答:
why go on to the trouble of creating a new completely different language when you could build on SQL, extend it to add the features needed by OLAP applications?

I share your pain in the MDX learning curve; having used SQL for some time, my company decided to adopt Analysis Services and create OLAP cubes to provide the ability to do rapid data analysis. I've been heavily involved in this and have had some trouble picking up certain bits of MDX.

That said, I think it's unfair to brand MDX as unnecessary. It does provide benefits, but only if you don't try to use it like you would SQL. Indeed, the reason it's tricky to pick up is because often there isn't a direct equivalent in SQL, so you're trying to learn the idea as well as the syntax.

There's an unhelpful vein of thought among some team members when it comes to retrieving data: OLAP cubes are an "upgrade" over traditional SQL tables. This isn't true, OLAP/MDX are good at certain things but traditional tables/SQL are better for others. Seeing the two as equivalent or different versions of the same thing isn't helpful, at least conceptually in my experience.


问:
Is adding in the header the license type enough to say: "my code is licensed"?
I read on various sites about licenses.

I did just put the license type in the header file (in my case a javascript file, open-source):

```<code>/*
 * "codeName" "version"
 * http://officialsite.com/
 *
 * Copyright 2012 "codeName"
 * Released under the "LICENSE NAME" license
 * http://officialsite.com/LICENSE NAME
 */

 javascript code
 ...
</code>```

In the same folder I leave a copy of the license. The listing of the folder looks like this:

```<code>* codeName.js
* LICENSE
</code>```

In the file LICENSE is the full text of the license my code uses.

What I cannot find anywhere that says is this is enough to say my code is licensed (the case of open-source). Is something more required?

答:
Major open source licenses like the Apache or GPL have instructions on exactly how to put a comment at the top of each one of your source files.  If you follow those instructions, you should be good.  And yes, generally that means choosing a license, and adding a header as you showed at the top of every one of your source files.  Please try to pick a license you will want to keep (understand the difference between Apache and GPL) and license all the files for your project under the same license.

The other thing you might want is a contributor's agreement.  Contributors sign it to state that they are not adding any copyrighted, patented, or trademarked contributions to your code, or that if anything is copyrightable, patentable, or trademarkable, it falls under the license for the project.  Consider a clause that states your intent in licensing and allows you to change the license to another one with the same intent at any time, or if the current license is proven difficult to enforce in court.

That said, I generally don't see licenses in HTML, CSS, or JavaScript files that get sent to the client.  I think it's reasonable if you want to consider an abbreviated version for those files to speed up download times.

I am not a lawyer.  These are just observations and suggestions, not legal advice.


答: Why? Because they are solving a problem that doesn't exist. The only advantages over a downloaded IDE that I can think of is they occupy less disk space. However, as the price of disk space has dropped to $1/10 Gb, I don't see that as an issue. For those who regularly write code, the disadvantages of Web-based IDEs are that they are slower and less capable compared to free IDEs like Eclipse.</p>

Title: Why don't we have web IDEs?

Body: Why don't we have a lot of good web-based IDEs? Which aspects of the system make it difficult for IDE to be implemented as a web application?</p>


问:
How can I test database access methods in Java?
I want to write a test for a method that accesses a database such as following. </p>

```<code>public class MyClass{
    public String getAddress(Int id){
        String query = "Select * from Address where id="+id;
        //some additional statements
        resultSet = statement.executeQuery();
        return result.getString(ADDRESS);
    }
}
</code>```

<p>How can I test this method? I am using Java. </p>

答:
Remember that you aren't testing whether your database works.

If you are using a database from one of the top vendors (or even the second and third tiers) you can guarantee that they have tested that a SQL statement will read or write.

You probably want to test a number of things:

Did I get my connection properties right?

Do the columns returned by my SQL statement match my data structure?

etc

Some of these can be addressed by mocking frameworks (as described by another poster). Some of these might be setup as integration tests that run independently of unit tests. Some of these can be tested using an in-memory database.

I've used HSQLDB in the past to create an inmemory database, pre-populate with data and then run my unit tests. In memory databases are orders of magnitude quicker than a traditional database, you don't have to worry about setting up transactions to clean them up etc.


问:
Parsing stdout with custom format or standard format?
To integrate with other executables, a executable may launch another executable and capture its output from stdout.

But most programs writes the output message to stdout in custom format and usually in human readable format.

So it requires the system integrator to write a function to parse the output, which is considered trouble and the parser code may be buggy.

Do you think this is old fashioned? Most Unix-style programs do that.

Very few programs write to stdout in standard format such as XML or JSON, which is more modern.
Example: Veracity (DVCS) writes JSON to stdout.

Should we switch to use modern formats?
For a console program, human readable or easy parsable: which is more important ?

答: Parsing any form of output can be buggy. Just because the output format follows a specific format does not guarantee correct semantics. If you have the source for the executables, you can change the output into whatever format you desire. If you do not, but the executable otherwise meets your needs, you suck it up and parse the output.</p>


答:
Most of the time you should say "Thank You" to the person that told you this.

Chances are that they care about their profession, they care about their work, they care about their team and they care about you.

It can be hard to take criticism. Don't get mad about it. Think about what they are trying to tell you and don't let your emotions get the better of you.

I've been programming for a long time (30 years) and my style and code is improving all the time (I hope). The only way that I know its improving is when other people tell me or if I go back and review my code.

Try looking at code you wrote at the start of your career. What does it look like to you now? Does it look as good as you thought it did when you wrote it ;)


答:
I would thank them for the feedback, and then ask them to explain what makes it bad and how it should be improved.

If you agree the person giving the feedback is making sense, consider making changes in the future.  But remember, just because someone says it doesn't mean it is true.

Can you give specific examples of what has been called "a mess" ?


问:
Solutions for "Maintenance Mode"
Given a web application running across 10+ servers, what techniques have you put in place for doing things like altering the state of your website so that you can implement certain features.

For instance, you might want to:

Restrict Logins/Disable Certain Features

Turn Site to "Read Only"

Turn Site to Single "Maintenance Mode" page.

Doing any of the above is pretty trivial. You can throw a particular "flag" in an .ini file, or add a row/value to a site_options table in your database and just read that value and do the appropriate thing.

But these solutions have their problems.

Disadvantages/Problems

For instance, if you use a file for your application, and you want to switch off a certain feature temporarily, then you need to update this file on all servers.  So then you might want to look at running something like ZooKeeper, but you are probably overcomplicating things.

So then, you might decide that you want to store these "feature" flags in a database. But then you are obviously adding unncessary queries to each page request. So you think to yourself, that you will throw memcached in to the mix and just cache the query. Then you just retrieve all of your "Features" from memcached and add a 2ms~ latency to your application on every page. So to get around this, you decide to use a two tier-cache system, whereby you use an inmemory cache on each machine, (like Apc/Redis etc). This would work, but then it gets complicated, because you would have to set the key/hash life to perhaps 60 seconds, so that when you purge/invalidate the memcached object storing your "Features" result, your on machine cache is prompt enough to get the the new states.

What suggestions might you have? Keeping in mind that optimization/efficiency is the priority here.

答:
If you deal with more than a handful of servers, you need some sort of configuration management/automation, even if it is a glorified multiplexed ssh client.

Once you have that in place, most systems have a "apply this on this set of servers now" operation, which you can use for instance to tweak your web server configuration and restart it (to enable a single-page maintenance site and disable your regular site) or change your website configuration.

Title: Solutions for "Maintenance Mode"


答:
Not trying to sound crotchety here, but one line per record, with fields in columns or delimited so they can be easily parsed by cut without writing custom code, is a standard format, and was a deliberate design decision.  Read Eric S. Raymond's The Art of Unix Programming sometime.  It will increase your appreciation for innovations that we now take for granted, and has whole chapters on the importance of output that is easily human readable.  A format still being around and widely used after 40 years is a sign of its strength, not its weakness.

A common approach is to use command line flags to make an output format that is easy for both humans and computers to parse.  Look at the git porcelain output formats for a good example.

One situation where xml or json is recommended, however, is when your data is arbitrarily nested instead of something easily put into rows.  That determination should be made on a case by case basis.  Xml is better than binary formats, but still not as readable as a plain text table.

Title: Parsing stdout with custom format or standard format?

Body:
To integrate with other executables, a executable may launch another executable and capture its output from stdout.

But most programs writes the output message to stdout in custom format and usually in human readable format.

So it requires the system integrator to write a function to parse the output, which is considered trouble and the parser code may be buggy.

Do you think this is old fashioned? Most Unix-style programs do that.

Very few programs write to stdout in standard format such as XML or JSON, which is more modern.
Example: Veracity (DVCS) writes JSON to stdout.

Should we switch to use modern formats?
For a console program, human readable or easy parsable: which is more important ?


问:
How to test Java web applications
So far I haven't been testing or learning how to test my java web applications.

If you do, what are the tools you need, and is it really necessary to test a web application if doesn't need scaling or it won't be handling big traffics and multi transactions?

What things should I test and what approaches should I take to ensure my application works correctly?

答:
I suggest you check out HTMLUnit. As per the description ...

HtmlUnit is not a generic unit testing framework. It is specifically a way to simulate a browser for testing purposes and is intended to be used within another testing framework such as JUnit or TestNG ...

HTML unit gives you a simulated browser environment to interface and integrate with your desired testing framework.

For HTMLUnit examples with JUnit or TestNG checkout Getting Started with HTMLUnit ...

I highly recommend it.

Title: How to test Java web applications


答:
TL;DR

How would you react if someone told you your code is a mess?

My straightforward, "too long didn't read (all the answers - apologies, I will hopefully find time to later and edit/amend this if necessary)" answer/tip:

Good old Peer Review. Ask different crews with different collective mentalities, expertise levels and/or levels of aggressiveness to review your code.

Just to elaborate a bit on what I mean by "different" peer groups: the StackExchange diaspora is probably the most clued up, professional and esteemed group because of the relative difficulty in becoming part of it compared to, say, Reddit. Reddit tends to be very aggressive in the more popular sub-reddits - but strangely enough the programming subreddits are quite friendly (from what I have experienced).

A good, perhaps the best, example of the aggressive, gangsta type of clique mentality are the XDK Forums crowd, and the worst of the worst trophy I hand to the CyanogenMod for Android forums/IRC channel populace.

That was a bit longer than I intended; my point was supposed to be - get varied reviews, but focus on getting honest critique from the people that know their trade, and know what constructive criticism is.
Oh, and be able to take any form of criticism without letting it get you down. Rule of thumb: if you start to hear similar commentary pertaining to a thing that can be mutual to the comments, then do some more thorough introspection.


答:
The problem, I think, is that there is so much complexity involved in developing any non-trivial application that a web-based IDE is just not the right environment for it. If you're looking for specific aspects of an IDE that are difficult, I would say debugging and deployment/hosting are the hardest to do over the web.

For example, say you are developing a web application. A company with enough time and resources can create a web-based HTML/JavaScript IDE to aid in creating the web application. But what does that IDE do when you have to go and deploy the application for testing/debugging locally? In theory, they could provide a few application hosting options themselves and auto-host the web application for you, but realistically, they would probably limit you to a small, finite set of hosting technologies (maybe IIS or Apache?).

Then what happens when you need to access features of the web-server that they haven't thought of exposing via their web-based IDE? There are so many configuration nuances for a web-server that in the act of exposing them all via a web IDE, you might as well just give the user remote-desktop access to the machine. And don't even get me started when you need a multi-server environment (i.e. web-server, SQL server, services server, etc.).

This is all assuming that you are working in the web domain. Now imagine creating an IDE that can ALSO support desktop development (i.e. service components, GUI apps). This adds an even greater level of complexity when trying to debug a desktop app via a browser.

Doing these complex tasks over-the-wire is probably possible, but just not practical. Also, the user experiences of web-based IDEs does not seem like it would be responsive enough for the type of productivity that today's developer expects from their IDE. Productivity tools such as Resharper (Visual Studio) require such high processing power that this behavior would be pretty hard to duplicate on the web.

Title: Why don't we have web IDEs?


答:
Modern IDEs are wrappers around more primitive tools (ie local compilers and debuggers) so you can't really answer the question without considering the limitations of pure web-based development in general.

One huge reason web based dev would be limited would have to be the inability to access local resources:

Can't communicate with local device hardware

Can't develop desktop apps without a web-based emulator

Can't access my local file system.

Can't setup a socket interface bound to my local network

Some other questions would have to be answered about a web-based IDE's ecosystem

How do I install dependencies (ie python libraries via a web interface?)

Could the IDE work with all the tools I need?

How do I configure required tools via a web interface? How would I configure say reddis? How would I install boost as a C++ dev? What if at the same time I need to do QT dev?

Will I be able to use arbitrary legacy code/libraries. I was told there would be FORTRAN :).

How do I deploy my code?

How do I perform remote debugging on a customer's deployed process (whatever that is equivalent to in this ecosystem)

In short I'd need a different model for development that didn't require config files, use things like stdin/stdout, etc. It'd have to be a web interface to a full VM. How would we do that? All the legacy work to do software installation etc is built around the desktop/command line interfaces.

So you'd be limited to a specific subset of programming. Probably limited to a pre-efined scope in pre-installed tools and libraries. Which likely is fine in a very narrow sense. I could see a web IDE for quickly standing up web apps. But Desktop Apps? Specialized apps (desktop or otherwise) that communicate with a specialized hardware? Apps that live in a very specific network enviroment? Apps that rely on very specific libraries?

I'm excited about the possibilities, especially coupled around VMs like EC2 instances. Some web tools built around your EC2 instance to aid in general development might be a cool area to work on. Don't want to limit the possibilities, but there's plenty of challenges that make this very hard compared to using a desktop dev environment.

Title: Why don't we have web IDEs?


答:
If you aren't compiling and running code on your local machine, then a web IDE does make a lot of sense. For instance, your IDE could set up an Amazon EC2 instance for your development, compile code there, and deploy it. This is nothing that a traditional IDE can't do, of course; in this situation, both web based and traditional GUI IDEs are usable.

However, developing any IDE to the Eclipse standard is difficult. Adding on this debug-to-cloud capability is added effort. There simply hasn't been enough time with a cloud emphasis on development for people to develop high-quality web IDEs.

Title: Why don't we have web IDEs?


答:
A CPU runs one instruction at a time, but what if you have two or more CPUs?

You are right in that locks are not needed, if you can write the program such that it takes advantage of atomic instructions: instructions whose execution is not interruptible on the given processor, and free from interference by other processors.

Locks are required when several instructions need to be protected from interference, and there is no equivalent atomic instruction.

For instance, inserting a node into a doubly-linked list requires the update of several memory locations. Prior to the insertion, and after the insertion, certain invariants hold about the structure of the list. However, during the insertion, those invariants are temporarily broken: the list is in an "under construction" state.

If another thread marches through the list while the invariants, or also tries to modify it when it is such a state, the data structure will probably become corrupted and the behavior will be unpredictable: maybe the software will crash, or continue with incorrect results.  It is therefore necessary for threads to somehow agree to stay out of each other's way when the list is being updated.

Suitably designed lists can be manipulated with atomic instructions, so that locks are not needed. Algorithms for this are called "lock free". However, note that atomic instructions are a actually a form of locking. They are specially implemented in hardware, and work via communication among processors. They are more expensive than similar instructions which are not atomic.

On multiprocessors that lack the luxury of atomic instructions, primitives for mutual exclusion have to be built up of simple memory accesses and polling loops. Such problems have been worked on  by the likes of Edsger Dijkstra and Leslie Lamport.

Title: Can you explain why multiple threads need locks on a single-core CPU?

Body: Assume these threads run in single core cpu. As a cpu only run one instruction in one cycle. That is said, even thought they share the cpu resource. but the computer ensure that one time one instruction. So is the lock un-necessary for multiplethreading?</p>


问:
How to TDD test that objects are being added to a collection if the collection is private?
Assume that I planned to write a class that worked something like this:

```<code>public class GameCharacter {
    private Collection<CharacterEffect> _collection;

    public void Add(CharacterEffect e) { ... }
    public void Remove(CharacterEffect e) { ... }
    public void Contains(CharacterEffect e) { ... }
}
</code>```

When added an effect does something to the character and is then added to the _collection.  When it is removed the effect reverts the change to the character and is removed from the _collection.

It's easy to test if the effect was applied to the character, but how do I test that the effect was added to _collection?

What test could I write to start constructing this class.  I could write a test where Contains would return true for a certain effect being in _collection, but I can't arrange a case where that function would return true because I haven't implemented the Add method that is needed to place things in _collection.

Ok, so since Contains is dependent on having Add working, then why don't I try to create Add first.  Well for my first test I need to try and figure out if the effect was added to the _collection.  How would I do that?  The only way to see if an effect is in _collection is with the Contains function.

The only way that I could think to test this would be to use a FakeCollection that Mocks the Add, Remove, and Contains of a real collection, but I don't want _collection being affected by outside sources.  I don't want to add a setEffects(Collection effects) function, because I do not want the class to have that functionality.  The one thing that I am thinking could work is this:

```<code>public class GameCharacter<C extends Collection> {
    private Collection<CharacterEffect> _collection;

    public GameCharacter() {
        _collection = new C<CharacterEffect>();
    }
}
</code>```

But, that is just silly making me declare what some private data structures type is on every declaration of the character.

Is there a way for me to test this without breaking TDD principles while still allowing me to keep my collection private?

答:
It's easy to test if the effect was applied to the character, but how do I test that the effect was added to _collection?

You shouldn't.

You need to ask why it matters that an item is added to the collection.  "Well, it should then have a certain effect on the character."  Then test for that effect.  There isn't any value in testing that a rudimentary collection works as a collection.

And suppose someday you modify the program to create character effects in a very different way.  If you test that your collection works, your test becomes useless when you get rid of the collection.  But if you test for character effects, your test will still work with a different code mechanism.  That's as it should be; you need to test that your program works correctly, not that your programming language works correctly.

Have a look at this answer, by Kent Beck, about what one should test:

How deep are your unit tests?

I get paid for code that works, not for tests, so my philosophy is to test as little as possible to reach a given level of confidence...If I don't typically make a kind of mistake (like setting the wrong variables in a constructor), I don't test for it.

Unless you're completely unfamiliar with the programming language you're using or with a library you're using, it just doesn't make sense to test that a collection works as a collection, or that you can create a new object, or that a variable is incremented when you tell it to increment.

All you're doing in such cases is making sure your programming language works as it's designed to, which is generally not a thing you'd have to test unless you're the one designing the language.


问:
Is it necessary to understand what's happening at the hardware level to be a good programmer?
I'm a self-taught programmer, just in case this question is answered in CS 101. I've learned and used lots of languages, mostly for my own personal use, but occasionally for professional stuff.

It seems that I'm always running into the same wall when I run into trouble programming. For example, I just asked a question on another forum about how to handle a pointer-to-array that was returned by a function. Initially I'm thinking that I simply don't know the proper technique that the designers of C++ set up to handle the situation. But from the answers and discussions that follow I see that I don't really get what happens when something is 'returned'.

How deep a level of understanding of the programming process must a good programmer achieve?

答:
I'd like to add a point about the overal design of higher level languages like C.

In general I think it's safe to say that such languages can be viewed as implementing an abstract machine, and indeed that's how Dennis Ritchie himself has described how C works and how the particular design of C's abstract machine has made it a more portable language.  As such having some understanding of computer architecture and machine-level functioning, can be extremely helpful in also understanding a language's abstract machine.

DMR's paper Portability of C Programs
and the UNIX System is the first I remember to discuss the (abstract) machine model for C.

I think DMR's paper about the history and development of C is also extremely useful in showing how real hardware affects language design, and is perhaps also an exemplar of early programming language design:  The Development of the C Language

ContentLicense: CC BY-SA 4.0


问:
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?

答: I don't do a time sheet. There are specific projects where I track estimates against actual time (I don't use any kind of timer.). This isn't required, but I feel a need to work on my estimation ability. </p>


问:
What is the convention for the star location in reference variables?
I have been learning Objective-C, noting that different books and examples use differing conventions for the location of the star (*) when naming reference variables:

```<code>MyType* x;
MyType *y;
MyType*z; // this also works
</code>```

I see the first two used interchangeably, and sometimes in the same code I've seen differing uses of both. Is one format easier to read, easier to maintain, or less error prone than the other formats, or is it simply a matter of personal preference?

答:
In my opinion this is more semantically clear:

```<code>MyType *x;
</code>```

Since you can also have this without changing the convention:

```<code>MyType *x, *y, *z;
</code>```

Also, I generally look at the variable declaration, not the type, when it comes to pointers.

Body:
In my opinion this is more semantically clear:

MyType *x;

Since you can also have this without changing the convention:

MyType *x, *y, *z;

Also, I generally look at the variable declaration, not the type, when it comes to pointers.


问:
Does FFMpeg support gpu acceleration of media encoding/decoding?
I was wondering if ffmpeg supported gpu acceleration. I was reading on their websites and came across contradicting information.

http://www.ffmpeg.org/general.html#Video-Codecs
-H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (VDPAU acceleration)

http://ffmpeg.org/trac/ffmpeg/wiki/x264EncodingGuide
-Will a graphics card make x264 encode faster?
No. libx264 doesn't use them (at least not yet). There are some proprietary encoders that utilize the GPU, but that does not mean they are well optimized, though encoding time may be faster; and they might be  worse than x264 anyway, and possibly slower. Regardless, FFmpeg today doesn't support any means of gpu encoding, outside of libx264.

If not, is there any way to add gpu acceleration to h.264 encoding/decoding?

答:
VDPAU only accelerates the decoding/playing of video. I don't know if the time taken to copy the raw video to the GPU encode, and then read back the compressed data would really mean there was much benefit from a GPU.

With playback you are forced to copy the data to the GPU anyway and it's obvisuly better to copy the smaller compressed source stream.

There is an example of doing the H264 compression step in the NVidia CUDA SDK but you need to provide other code to make an actual video


问:
how to verify ConcurrentHashMap is threadsafe?
As the jdk doc said, ConcurrentHashMap is thread safe and it doesn't block multiple thread read. It is not necessary to doubt that since it was under many and restricted test. But I just curious how to tell and write code to verify that.

Edited: to be more precisely

how to keep read consitent without read block

does it return the latest view of data

答:
To all practical purposes, you can't.  You can run a number of successful tests numerous times, then without making a change, a test will fail. This is what makes testing multi-threading hard - it is not deterministic.

You may be able to test to an acceptable degree of certainty using statistical methods i.e. we ran 10^y randomized tests with no faults found- it is statistically probable that there are no defects.

You cannot run a test that guarantees thread safety, it has to be done by design and white box testing that the design has been implemented correctly.

As far as  ConcurrentHashMap - if your vendor says something is thread safe, you can only decide, do I trust my vendor - or perhaps paraphrasing a great movie line "You've got to ask yourself one question: Do I feel lucky? Well, do ya, punk?" - and if you don't trust your vendor, I think maybe you have bigger problems.

EDIT: My background involves Life critical and Hard Real time (sub nanosecond) embedded systems. My questions is answered in the context of "Whats the worst that happens" being somewhat more important than "an unexplained software crash"......


答:
First off, you really never need to go around unit testing frameworks, especially not the main framework of a language.

Unit testing verification's for thread safety can be a little tricky, especially if you aren't super clear on handling threading/concurrency. Also you generally don't get 100% faultless guarantees (though for some scenarios you can), but you can get damn-good using appropriate techniques.

That said, it's a matter of defining the behaviors you don't want and attempting to cause them, then having tests that ensure the desired behavior was at play instead.

For this particular scenario with the steps I laid out you need to:

Define the beheaviors you don't want: You don't want reads to be blocked.

Attempt to cause them: Create two threads that try to read from the dictionary at the exact same time (use a signal or timestamp based event for both of them).

Test the desired behaviour is in play instead: timestamp before and after the read operation, ensure the timestamps started and ended with overlaps between the two threads.

This is a subpar approach though because you're testing for thread safety something where you don't have access to the guts of the system, when you write your own threading systems the trick is to force operations to take longer in the test cases. Normally I put mock objects in the middle of the lock or non-locking operations and force sleeps then ensure the timestamps do or don't overlap as expected depending on if I do want to see locking or don't want to see locking.

Title: how to verify ConcurrentHashMap is threadsafe?

Body:
As the jdk doc said, ConcurrentHashMap is thread safe and it doesn't block multiple thread read. It is not necessary to doubt that since it was under many and restricted test. But I just curious how to tell and write code to verify that.

Edited: to be more precisely

how to keep read consitent without read block

does it return the latest view of data


答:
But I just curious how to tell and write code to verify that.

It depends what you mean by "verify".  The normal Computer Science meaning of "verify" is to show that something is true / correct ... all of the time, not just some or most of the time.

In some cases, it is possible to show thing is true (e.g. certain invariants are always satisfied) purely by testing.  But the only way to do that by testing is to test for all possible inputs / starting conditions; i.e. by exhaustive testing  In cases which involve multi-threaded behaviour, it is usually not possible to do this.

This is not to say that testing is useless for multi-threaded applications.  But as someone said (Tony Hoare?) testing can prove the presence of bugs, but not the absence of bugs.  Testing alone is simply NOT SUFFICIENT to verify correctness of multi-threaded code.

The only way to verify (in the accepted sense) that ConcurrentHashMap is thread-safe is to analyse the source code, and construct a formal or informal proof of correctness for the thread-safety criteria.  That is hard work.  And on top of that "thread-safety" is actually a rather difficult concept to tie down in a formal sense.  (Basically, it means "works correctly when there are multiple threads" ... which begs the question - what does "works correctly" mean?


问:
OpenGL programming vs Blender Software, which is better for custom video creation?
I am learning OpenGL API bit by bit and also develop my own C++ framework library for effectively using them. Recently came across Blender software which is used for graphics creation and is in turn written in OpenGL itself.

For my part time hobby of graphics learning, I want to just create small-small movie or video segments; e.g. related to construction engineering, epic stories and so on.
There may be very minimal to nil mouse-keyboard interaction for those videos, unlike video games which are highly interactive.

I was wondering if learning OpenGL from scratch is worth for it or should I invest my time in learning Blender software?  There are quite a few good movie examples are created using Blender and are shown in its website.

Other such opensource cross platform alternatives are also welcome, which can serve my aforementioned purpose.

答:
If you're making animations and movies, then you'll want to use Blender and other software for rendering them.  Thats what they are specifically designed for.

Software like Blender would use OpenGL in its own code to render its graphics.  So you wouldnt need to deal with OpenGL yourself.


问:
Why the static data members have to be defined outside the class separately in C++ (unlike Java)?
```<code>class A {
  static int foo () {} // ok
  static int x; // <--- needed to be defined separately in .cpp file
};
</code>```

I don't see a need of having A::x defined separately in a .cpp file (or same file for templates). Why can't be A::x declared and defined at the same time?

Has it been forbidden for historical reasons?

My main question is, will it affect any functionality if static data members were declared/defined at the same time (same as Java) ?

答:
I think I found the reason. Defining static variable in separate space allows to initialize it to any value. If not initialized then it will defaulted to 0.

Before C++11 the in class initialization was not allowed in C++. So one cannot write like:

```<code>struct X
{
  static int i = 4;
};
</code>```

Thus now to initialize the variable one must write it outside the class as:

```<code>struct X
{
  static int i;
};
int X::i = 4;
</code>```

As discussed in other answers too, int X::i is now a global and declaring global in many files causes multiple symbol link error.

Thus one has to declare a class static variable inside a separate translation unit. However, still it can be argued that following way should instruct compiler not to create multiple symbols

```<code>static int X::i = 4;
^^^^^^
</code>```

Body:
I think I found the reason. Defining static variable in separate space allows to initialize it to any value. If not initialized then it will defaulted to 0.

Before C++11 the in class initialization was not allowed in C++. So one cannot write like:

struct X
{
  static int i = 4;
};

Thus now to initialize the variable one must write it outside the class as:

struct X
{
  static int i;
};
int X::i = 4;

As discussed in other answers too, int X::i is now a global and declaring global in many files causes multiple symbol link error.

Thus one has to declare a class static variable inside a separate translation unit. However, still it can be argued that following way should instruct compiler not to create multiple symbols

static int X::i = 4;
^^^^^^


问:
Microkernel architectural pattern and applicability for business applications
We are in the business of building customizable web applications. We have the core team that provides what we call as the core platform (provides services like security, billing etc.) on top of which core products are built. These core products are industry specific solutions like telecom, utility etc. These core products are later used by other teams to build customer specific solutions in a particular industry.

Until now we have a loose separation between platform and core product. The customer specific solutions are built by customizing 20-40% of the core offering and re-packaging. The core-platform and core products are released together as monolithic apps (ear).

I am looking to improve the current situation so that there is a cleaner separation on these 3. This allows us to have evolve each of these 3 separately etc.

I've read through the Microkernel architecture and kind of felt that I can take and apply the principles in my context. But most of my reading about this pattern is always in the context of operating systems or application servers etc. I am wondering if there are any examples on how that pattern was used for architecting business applications. Or you could provide some insight on how to apply that pattern to my problem.

答:
This is a "Module" pattern, as well as a "People" pattern - your code may look different as well but that's not where the meat of the difference lies. I think you understand what the pattern is given the situation you're trying to apply it to.

Actually applying it would look like the following:

Assume the Core Platform's the lowest layer in your "stack".

In code, these three layers would be in different packages - which you probably already have. Make certain that no layer below makes any specific reference to or has a dependence on something in the layers above. That will protect your Platform from complexities of your Products and Customer specific stuff. Create some series of Facades and other simple abstractions between any layer and the ones below it. For example, my Facade to a database Module in the Core Platform may consist of a Factory that will generate an instance that adheres to a "DataSource" interface, as opposed to someone on your Core Product team directly reaching into the Core Platform (not through the Facade) and concretely instantiating a SQLDatabaseSource instead. This will protect your Product and Customer layers from changes in the implementation of your Platform.

Secondly, the teams must be structured to communicate effectively in a manner conceptually matching this "downstream" approach. The Platform team must show interest in what features the Product teams need the most, cleanly document how to use them, and cleanly design them so that the Customer team doesn't have to tightly couple their implementation to it. They also have to make it clear the ways in which they are unwilling or unable to accomodate the teams downstream. Perhaps they will have the slowest cycles, as opposed to your Customer team, whose lower number of stakeholders (1 customer company as opposed to the 100 your platform team may ultimately serve) allows for faster iterations.

In light of all this, I think you may want to re-think the name "Core Products", because it's just confusing that you're building "Core" products on top of "Core" platform. Core means inside, so only one can be that.

Cant believe they took this off stackoverflow

OwnerDisplayName: Pangea


问:
How to set up a personal Apple developer account now with an eye on transferring app ownership to a company later?
I have two Mac applications that I wrote for my own personal use, but I'm considering polishing them up and giving selling them on the Mac App Store a try. It seemed very premature to consider what would happen if either app would become successful enough to make it possible to set up a business around it, or to sell it to another developer. That is, until I read that Apple doesn't make it easy to transfer app ownership.

I'm not sure how to best register with the Apple Developer program now to avoid any possible hassle in this respect later. From what I understand, one can really only transfer ownership of a developer account. I'm not sure about the relationship between an Apple ID and an Apple developer account.

Does this mean I should at least not use the Apple ID I'm already using for iTunes, but create a second one to use for registering as an Apple Developer? Is there any disadvantage to using separate Apple IDs like this on the same Mac (one ID for Xcode development, the other ID for iTunes/iCloud/App Store/...)? Should one go as far as having a separate Apple ID & Apple developer account per app one develops? Or is there some other solution to take into account the possibility of transferring app ownership?

答:
You have to either delete the app so the buyer can relist, or transfer the entire iOS account to the buyer. You should therefore create a separate iTunes Connect account for each app, if you think there's a reasonable possibility that you'll sell any of them.

Is there any disadvantage to using separate Apple IDs like this on the same Mac (one ID for Xcode development, the other ID for iTunes/iCloud/App Store/...)?

No - I do it. I have a personal account that's used for the app store, iCloud and iTunes, and a developer account for the company that's used in Xcode.

Update: As of WWDC 2013 it is now possible to transfer app ownership between Apple IDs without transferring the whole account. There are some caveats to this related to iCloud and recurring subscriptions.


问:
python server to manage wervices
i'm looking for a framework to build a webserver. This server will be used to manage webservices. huge amount of client may be able to connect to principally set data which will populate a noSQL DB. we work with python and naturally we would like a python framework. i looked at bottle, gevent, twisted and tornado but it's hard to choose.

Some feedbacks or propositions ?

答:
Flask And Gunicorn are a good fit for this kind of situation, they don't assume anything about your data, so you can use whatever database you want.

Here's how you can use them together.

Title: python server to manage wervices


问:
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 ?

答:
If you can derive the scenarios from the description, you're done.

An anti-pattern that I often see in BDD is people feeling the need to talk through, and write down, every scenario in detail.

Some scenarios are so well understood that it's enough to derive them from a brief description. For instance, if I say, "I'd like the login feature this week," you know what that should look like. You know that there are scenarios for the right password, the wrong password, the wrong username. We don't really need to talk through those or capture them in detail.

Similarly, I might say, "Here's the form for user registration. We need to be able to create new users, let them edit their details, and delete themselves, except that deletion shouldn't actually delete, it should just mark them as deleted so they can recover their accounts if they want to."

And you can ask, "Is account recovery part of this feature?"

"They can be two features if you want."

"Okay, so we have scenarios for create, read, update, delete; that should be easy enough. Let's talk about account recovery; that sounds more interesting."

In general, if the description of behavior is enough for the dev team to derive the scenarios, you don't need to talk through them. You can do so if there's any doubt, but you may just want to capture which scenarios you need to remember, if you capture any at all.

If you've never done it before or you're uncertain, talk through the scenarios.

Focus on the areas which are unusual, particularly if there are features you've never done before. These are fantastic places to have conversations and write down any surprising examples which come up. I usually have two questions I ask, based on the BDD template:

Given a context

  When an event happens

  Then an outcome should occur.

Is there any other context which, for the same event, produces a different outcome?

Is there any other outcome which is also important?

If everyone at the table is looking bored, the feature you're talking through is probably well understood. It's often enough to say, "It should work like X, but with Y instead." This is what Dan North calls the Ginger Cake pattern; it's like the recipe for chocolate cake, but with ginger instead of chocolate.

Even if the business stakeholder is able to derive the scenarios himself, it's really important for the dev team to be able to talk to him, pick up and internalise his language. That language then gets carried into the code, enabling them to have better conversations in the future, and helping newcomers to the project understand what's going on. If the devs don't get to speak the language, they won't use it.

If the business stakeholder or analyst really doesn't want to spend the time capturing things in the session, I'd rather the developers wrote the scenarios down in collaboration with the testers, then asked him to review it. This is more likely to uncover misunderstandings than the other way round.

Sometimes BDD doesn't work.

Another possibility is that you find a scenario the business stakeholder is uncertain about. "Oh, I hadn't thought of that! I'm not sure." Rather than trying to nail the business down and punish the business with certainty, it may be worth abandoning BDD at this point and trying something simple out to get some feedback and give the business something over which they can iterate. Keep it easy to change, and write the scenarios once there's a better understanding of what's going on.

BDD done well can really help to uncover places of uncertainty. Since every project worth doing has some aspect of it that's new and has never been done before, there is some uncertainty in there, somewhere. If you focus on using the scenarios to help deliberately discover ignorance, you'll learn faster, and learning is usually a large part of the time spent on a project.

Additionally I've found that the more dev teams collaborate in this way, the more the business are prepared to trust them with uncertainty, and the more innovation starts to occur. Innovative companies, by their very nature, have plenty of uncertainty in their projects.

I wrote a blog post a while back on Cynefin, which I find really helps me understand where the conversations will be most effective. If you read it and understand the four domains, here are the rules I use:

Simple and complicated stuff (known) is often well-understood and you don't need to talk through the scenarios in detail.

Highly complex stuff (unknown) is not understood at all. You may discover this by talking through the scenarios. The lack of certainty means that BDD won't work here, so iterate over something easy to change and get fast feedback instead. Any practice which retains your options, like A-B testing, is also great in this space.

BDD works brilliantly in the space in between (knowable) as a mechanism for passing on knowledge, and to uncover the other two spaces. It's not a hammer, and not everything is a nail. In fact, if you can focus the time spent having conversations on anything, it's not about the examples you can find; it's about finding the examples you can't.


问:
What is the most reliable session storage in PHP: Memcache, database or files?
What is the best and most safest way to handle PHP sessions. Is the best way to store sessions in:

Database (more reliable, but high bottleneck, slow speed, not good for high database usage websites)?

Memcache (super fast, but distributed more security problems, chances of loosing data when the server restarted and chances of loosing data when the cache is full)?

Files (default option, I guess slow since it reads and writes from file I/O, less security, etc).

Which method is the best? What are the problems and good things of each of those approaches?

答:
You can try to save your session on Redis. Redis is fast like Memcached but also has several data-persistence options. In addition, various PHP clients are supported.

In addition, you can try 3rd party services like the Memcached Cloud that has built-in replication and storage engine capabilities

Disclosure, I'm Co-Founder and CTO of Garantia Data.


问:
What is MVC, really?
As a serious programmer, how do you answer the question What is MVC?

In my mind, MVC is sort of a nebulous topic — and because of that, if your audience is a learner, then you're free to describe it in general terms that are unlikely to be controversial.

However, if you are speaking to a knowledgeable audience, especially an interviewer, I have a hard time thinking of a direction to take that doesn't risk a reaction of "well that's not right!...".  We all have different real-world experience, and I haven't truly met the same MVC implementation pattern twice.

Specifically, there seem to be disagreements regarding strictness, component definition, separation of parts (what piece fits where), etc.

So, how should I explain MVC in a way that is correct, concise, and uncontroversial?

答:
Analogy

I explained MVC to my Dad like this:

MVC (Model, View, Controller) is a pattern for organising code in an application to improve maintainability.

Imagine a photographer with his camera in a studio. A customer asks him to take a photo of a box.

The box is the model, the photographer is the controller and the camera is the view.

Because the box does not know about the camera or the photographer, it is completely independent. This separation allows the photographer to walk around the box and point the camera at any angle to get the shot/view that he wants.

Non-MVC architectures tend to be tightly integrated together. If the box, the controller  and the camera were one-and-the-same-object then, we would have to pull apart and then re-build both the box and the camera each time we wanted to get a new view. Also, taking the photo would always be like trying to take a selfie - and that's not always very easy.

Detailed Explanation

It was only after reading the following maillist question/answer that I felt like I  understood MVC. Quote: https://mail.python.org/pipermail/python-list/2006-January/394968.html

bwaha wrote:

The author refers to mvctree.py in wxPython as an example of MVC design.
    However I'm still too green so I find that particular example too complex
    and I'm not understanding the separation the author is recommending.

MVC is all about separation of concerns.

The Model is responsible for managing the program's data (both private
  and client data). The View/Controller is responsible for providing the
  outside world with the means to interact with the program's client
  data.

The Model provides an internal interface (API) to enable other parts
  of the program to interact with it. The View/Controller provides an
  external interface (GUI/CLI/web form/high-level IPC/etc.) to enable
  everything outwith the program to communicate with it.

The Model is responsible for maintaining the integrity of the
  program's data, because if that gets corrupted then it's game over for
  everyone. The View/Controller is responsible for maintaining the
  integrity of the UI, making sure all text views are displaying
  up-to-date values, disabling menu items that don't apply to the
  current focus, etc.

The Model contains no View/Controller code; no GUI widget classes, no
  code for laying out dialog boxes or receiving user input. The
  View/Controller contains no Model code; no code for validating URLs or
  performing SQL queries, and no original state either: any data held by
  widgets is for display purposes only, and merely a reflection of the
  true data stored in the Model.

Now, here's the test of a true MVC design: the program should in
  essence be fully functional even without a View/Controller attached.
  OK, the outside world will have trouble interacting with it in that
  form, but as long as one knows the appropriate Model API incantations,
  the program will hold and manipulate data as normal.

Why is this possible? Well, the simple answer is that it's all thanks
  to the low coupling between the Model and View/Controller layers.
  However, this isn't the full story. What's key to the whole MVC
  pattern is the direction in which those connection goes: ALL
  instructions flow from the View/Controller to the Model. The Model
  NEVER tells the View/Controller what to do.

Why? Because in MVC, while the View/Controller is permitted to know a
  little about the Model (specifically, the Model's API), but the Model
  is not allowed to know anything whatsoever about the View/Controller.

Why? Because MVC is about creating a clear separation of concerns.

Why? To help prevent program complexity spiralling out of control and
  burying you, the developer, under it. The bigger the program, the
  greater the number of components in that program. And the more
  connections exist between those components, the harder it is for
  developers to maintain/extend/replace individual components, or even
  just follow how the whole system works. Ask yourself this: when
  looking at a diagram of the program's structure, would you rather see
  a tree or a cat's cradle? The MVC pattern avoids the latter by
  disallowing circular connections: B can connect to A, but A cannot
  connect to B. In this case, A is the Model and B is the
  View/Controller.

BTW, if you're sharp, you'll notice a problem with the 'one-way'
  restriction just described: how can the Model inform the
  View/Controller of changes in the Model's user data when the Model
  isn't even allowed to know that the View/Controller, never mind send
  messages to it? But don't worry: there is a solution to this, and it's
  rather neat even if it does seem a bit roundabout at first. We'll get
  back to that in a moment.

In practical terms, then, a View/Controller object may, via the
  Model's API, 1. tell the Model to do things (execute commands), and 2.
  tell the Model to give it things (return data). The View/Controller
  layer
  pushes instructions to the Model layer and pulls information from the Model layer.

And that's where your first MyCoolListControl example goes wrong,
  because the API for that class requires that information be pushed
  into it, so you're back to having a two-way coupling between layers,
  violating the MVC rules and dumping you right back into the cat's
  cradle architecture that you were [presumably] trying to avoid in the
  first place.

Instead, the MyCoolListControl class should go with the flow, pulling
  the data it needs from the layer below, when it needs it. In the case
  of a list widget, that generally means asking how many values there
  are and then asking for each of those items in turn, because that's
  about the simplest and loosest way to do it and therefore keeps what
  coupling there is to a minimum. And if the widget wants, say, to
  present those values to the user in nice alphabetical order then
  that's its perogative; and its responsibility, of course.

Now, one last conundrum, as I hinted at earlier: how do you keep the
  UI's display synchronised with the Model's state in an MVC-based
  system?

Here's the problem: many View objects are stateful, e.g. a checkbox
  may be ticked or unticked, a text field may contain some editable
  text. However, MVC dictates that all user data be stored in the Model
  layer, so any data held by other layers for display purposes (the
  checkbox's state, the text field's current text) must therefore be a
  subsidiary copy of that primary Model data. But if the Model's state
  changes, the View's copy of that state will no longer be accurate and
  needs to be refreshed.

But how? The MVC pattern prevents the Model pushing a fresh copy of
  that information into the View layer. Heck, it doesn't even allow the
  Model to send the View a message to say its state has changed.

Well, almost. Okay, the Model layer isn't allowed to talk directly to
  other layers, since to do so would require it knows something about
  those layers, and MVC rules prevent that. However, if a tree falls in
  a forest and nobody's around to hear it, does it make a sound?

The answer, you see, is to set up a notifications system, providing
  the Model layer with a place it can announce to no-one in particular
  that it has just done something interesting. Other layers can then
  post listeners with that notification system to listen for those
  announcements that they're actually interested in. The Model layer
  doesn't need to know anything about who's listening (or even if anyone
  is listening at all!); it just posts an announcement and then forgets
  about it. And if anyone hears that announcement and feels like doing
  something afterwards - like asking the Model for some new data so it
  can update its on-screen display - then great. The Model just lists
  what notifications it sends as part of its API definition; and what
  anyone else does with that knowledge is up to them.

MVC is preserved, and everyone is happy. Your application framework
  may well provide a built-in notifications system, or you can write
  your own if not (see the 'observer pattern').

...

Anyway, hope that helps. Once you understand the motivations behind
  MVC, the reasons why things are done the way they are starts to make
  sense, even when - at first glance - they seem more complex than
  necessary.

Cheers,

has

Title: What is MVC, really?