问:
Encapsulate bitmap (*.bmp) as C++ class
How would you implement / design a class which has to represent a bitmap?
I'm stuck at handling the different possible color modes and I keep thinking that this should be somehow implementable using templates / design patterns in an elegant AND efficient way:

Suppose you have a file.bmp. You then want to open that file to use it in your application:

```<code>Bitmap myBitmap();
myBitmap.open("file.bmp");
</code>```

The bitmap you just opened could have RGB colors, or it could be a grayscale image, or even a 1 bit per pixel image (i.e. black and white).
In my application, I want to operate on the image (pixel) data. For example, I need some sort of brightness filter where I black out pixels whose (Red + Blue + Green) / 3 is below some filter value (i.e. 100).

So I need access to the pixels:

```<code>Pixel somePixel = myBitmap.pixelAt(10,30);
</code>```

But now I face the problem of NOT knowing what type of pixel this is. Of course, I could provide subclasses of Pixel (which then is an abstract base class) which ALL implement methods like getRGB(), getGrayScale(), ... where each subclass gives a way of converting between those colormodes (i.e. RGB to grayscale)

But this feels ... hm, "wrong".

Do you know some good way to implement this?

A nice feature I was thinking about is something like:

```<code>myBitmap.getMode(); // A RGBMode object, RGBMode being a subclass of Mode
myBitmap.setMode(new BlackWhiteMode()); // Converts the bitmap to a 1bpp image
</code>```

Any ideas, recommendations, improvements?

So the really hard part is to represent the different color modes, like RGB (8bit and 4bit), HSV, Grayscale, BlackWhite, ... without messing the applications code.

答:
Depending on your processing needs, I'd go with either:

a) A bitmap class that stores raw pixel data and format information; when loading, you resolve RLE compression, but otherwise leave the raw pixel values intact. Then add some methods to query the class for its pixel format, and possibly a getter/setter pair to transparently modify pixels in a format-independent way (i.e., convert to and from floating-point RGB representation on the fly). If you ever need to convert between pixel formats, you would do that in this model by loading the original bitmap, creating a new empty bitmap with the desired target format, and then copying pixels over through the floating-point RGB getters/setters.
b) Store pixel data as RGB floats (or 16-bit integers, depending on the kind of transformations you want to do). When loading convert everything to that format, and then when saving, specify the target pixel format explicitly.

Method a) has the advantage that some filters can be implemented in a completely lossless way, by using raw data and adapting the filter to the actual pixel format; it is more complicated to write such filters though, and if apply do more than one floating-point filter, you'll get more rounding errors on each pass (because you convert to and from integer every time).

Method b) is easier to implement, especially because your filters only ever need to accommodate one pixel format, and it produces less rounding errors, but it does not allow for completely lossless filters (not even an identity filter: loading and then saving the same bitmap still introduces one round-trip's worth of integer-to-floating-point conversion errors).

Title: Encapsulate bitmap (*.bmp) as C++ class


问:
Are all security threats triggered by software bugs?
Most security threats that I've heard of have arisen due to a bug in the software (e.g. all input is not properly sanity checked, stack overflows, etc.). So if we exclude all social hacking, are all security threats due to bugs? In other words, if there were no bugs, would there be no security threats (again, excluding the faults of humans such as disclosing passwords and such)? Or can systems be exploited in ways not caused by bugs?</p>

答:
There can be situations where hardware bugs cause security issues, too. Just consider a faulty RAM chip that spontanously flips the "isAdmin" bit.

Or consider a hypothetical hardware bug where the memory protection doesn't work as expected and one process can overwrite another process' memory without triggering an interrupt.

For your reading pleasure: Computer security compromised by hardware failure

ContentLicense: CC BY-SA 3.0


答:
Lots of security threats arise from software features, not bugs.  Lots of very useful software features turn out to have uses for good or evil, depending only on the user's
intent.</p>

Title: Are all security threats triggered by software bugs?

Body: Most security threats that I've heard of have arisen due to a bug in the software (e.g. all input is not properly sanity checked, stack overflows, etc.). So if we exclude all social hacking, are all security threats due to bugs? In other words, if there were no bugs, would there be no security threats (again, excluding the faults of humans such as disclosing passwords and such)? Or can systems be exploited in ways not caused by bugs?</p>


答:
How about something like Firesheep, the Firefox addon that steals cookies being transmitted on a shared wireless network?

You could argue that vulnerability to such attacks is a bug, but you could also argue against it as well. There's not much a website can do to avoid users being compromised other than just running all communications over HTTPS - can you say that it's a bug to accept HTTP communications on your website?


答:
Social engineering.

Hello, I'm XX from the IT department. Your computer is currently spreading viruses to other office computers. I need your username and
  password to be able to remove it.

When the hacker have got the username/password he can safely install trojans etc.

Social engineering can be applied in several ways and using it to circumvent security is one.


答:
Consider a distributed denial of service attack (DDOS). That can be a security risk, but it's not caused by a software bug but rather by an attacker going over the limits of what the system was designed for. And every system has a limit.

So the answer to your question is: no, not all security threats are triggered by software bugs.


答:
Yes, insofar as a failure in the software's security is—whatever the proximate cause—a failure by the software to fulfil its requirements.

I accept that this is just a tautology, but that's the measure of it.


问:
Static is bad, but what about the Factory pattern?
I'm on a TDD project, so I try to stick as much as possible to the good pratices involved with that kind of development. One of them is avoiding as much as possible static and global.

I'm facing this problem:
I've an object "article" that can have "options" (additionnal "micro-articles") linked to it.

I can't figure out how to have a good approach that will not be counter productive or generate too much queries because I would be in a situation where everything is so decoupled that I'll basically need to make 1 query per object.

From my actual perspective, I see 3 options:

1) Build inside article:

```<code>class Article
{
    //[...]
    public function getArrOption(){
        //Build an array of Options instance.
        //return an array of Options.
    }
}
</code>```

Pro: Straight forward

Const: Maintenability: The article object now contain the building logic for the Option object. This will probably lead to code duplication.

2) Using an optionFactory

```<code>class Article
{
    //[...]
    public function getArrOption(){
        return OptionFactory::buildFromArticleId($this->getId());
    }
}
</code>```

Pro: Building logic is not out of the Article class

Const: I'm breaking the "static is hard to mock" rule, making my Article class hard to test.

3) Separate all logics.

```<code>//Build the array of Option instance in a controller somewhere, using a Factory:
$arrOption = OptionFactory::buildFromArticleId($article->getId());
</code>```

Pro: Article only handle his own responsability, and doesn't care about his "father" link to the options. Things are really decoupled

Const: Will require more code inside the Controller everytime I'll need to access the Options. That mean that I should never use a Factory inside an object, and that sound kind of utopic to me...

What's the best way to go ? ( Did I've miss something ? )
thanks.

Edit:

Not to mention that if I can't call factory inside class, I can basicaly never use the lazy initialization pattern too...

答:
Here's a quote from paper that argues that you never need static methods, that abstract factories have been demonstrated to be confusing, and suggests a slight language change towards dependency injection as the solution.

Tight coupling between instances and their classes breaks encapsulation, and, together with the global visibility of static methods, complicates testing. By making dependency injection a feature of the programming language, we can get rid of static methods altogether. We employ the following semantic changes:

(1) Replace every occurrence of a global with an access to an instance variable;

(2) Let that instance variable be automatically injected into the object when it is instantiated.

"Seuss: Decoupling responsibilities from static methods for fine-grained configurability"

Wayback Machine Link

ContentLicense: CC BY-SA 2.5


答:
A bug is defined as software not operating up to specs. Now if specs are faulty, it's not a software bug. If a dumb customer demands all passwords must be three-digit codes with no grace period between faulty entries, it's not the software that is to be blamed.

Many systems have "service mode" that can override the security, and while access to it should be secure, the codes often leak to the public.

Advances in mathematics compromise old cryptography methods. Something that was viable security 30 years ago becomes weak nowadays.

There are various methods of data theft that are often overlooked. A wireless keyboard has about 2m range, due to tiny antennas, and the code sent is unencrypted. Reading it out from across the street with a good antenna is a well-known method.

Sometimes security trade-offs are made with full awareness of consequences - crypto systems take power and CPU time. Embedded monitoring applications often send their data in a way clearly readable to the public because first, the value of compromising the data is negligible, and then the extra cost of implementing the security is unnecessary.

All security is based on trust. It takes no social engineering for the appointed admin to go rogue and read your mail.

And in the end, can one consider applying baseball bat to a knee a social technique?


问:
Arithmetic Coding vs. Machine Numeric Precision
When subdividing intervals for arithmetic coding, the worst case scenario is that the final interval will have size 2^(1-n), where n is the number of unique symbols you are encoding. This will reach the limits of machine precision, when using regular datatypes, really quickly: For instance, I've made a JavaScript implementation and it breaks after encoding around just 15 characters!

As this is pretty limiting, how do codecs get around this?

Encode [very] short blocks, within the machine's limits, and concatenate them together? That will add overhead.

Use non-native types with arbitrary precision? This will be slow.

Something else?...

答:
According to Wikipedia:

Rather than try to simulate infinite precision, most arithmetic coders
  instead operate at a fixed limit of precision which they know the
  decoder will be able to match, and round the calculated fractions to
  their nearest equivalents at that precision. [...]

A process called renormalization keeps the finite precision from
  becoming a limit on the total number of symbols that can be encoded.
  Whenever the range is reduced to the point where all values in the
  range share certain beginning digits, those digits are sent to the
  output. For however many digits of precision the computer can handle,
  it is now handling fewer than that, so the existing digits are shifted
  left, and at the right, new digits are added to expand the range as
  widely as possible.


答:
While the "arithmetic" part of the name "arithmetic coding" is useful because it explains how the system works, we shouldn't assume that the encoded "number" is ever actually used or useful as a number.  In fact, in the general case, it's just a stream of bits.

So I don't think the size of numeric datatype that can be handled natively is really an issue.  You encode by pushing bits onto the end of a stream which can be arbitrarily large, and you decode by reading that stream.

Title: Arithmetic Coding vs. Machine Numeric Precision

Body:
When subdividing intervals for arithmetic coding, the worst case scenario is that the final interval will have size 2^(1-n), where n is the number of unique symbols you are encoding. This will reach the limits of machine precision, when using regular datatypes, really quickly: For instance, I've made a JavaScript implementation and it breaks after encoding around just 15 characters!

As this is pretty limiting, how do codecs get around this?

Encode [very] short blocks, within the machine's limits, and concatenate them together? That will add overhead.

Use non-native types with arbitrary precision? This will be slow.

Something else?...


问:
Is there some software to manage a XP Project?
I was wondering if there's some software to manage a XP project. I'm starting a school project and I want to follow this methodology, but, we don't have a place to work. Each one works at home (in pairs), therefore I can't follow XP ambient patterns.

So, anyone knows of any software to manage this?

答:
XP is agile and extreme. If management is bad, XP makes the worst enemy out of it, so that the management is undefined :)

Cards

CRC cards can be used regardless of the process for as long as you follow OOP, same for prototyping which I'd expect mentioned here.

Prototyping

In XP, the idea is typically first coded as a small prototype and then either thrown away for a better idea, or refactored into the final solution. (details)

Pair Programming

This is one important aspect of XP which you won't achieve by remote collaboration. A couple of programmers (not a love couple) sits at the same table with just one keyboard. While one person writes the code the other is meant to correct him or suggest useful improvements. (details)

Reporting

XP is iterative and incremental. There can be a release plan with features on the CRC cards and the schedule in which they are meant to be implemented. For every planned release, pile up some cards. Be careful not to exceed the available slot. You need to be measuring whether all those cards fit in, as explained in the next point.

Release & Iteration Planning

First take one CRC card which you consider a small task, implement it, measure it, and then try to size the card to other cards. How many times bigger are the tasks on other cards compared to the card you've taken for your sizing? Use this technique to roughly estimate the size, so that you can stuff the right amount of work into each iteration.

Risks

The biggest risk of XP, in my opinion, is unnecessary rework caused by unclear / unstable requirements or too much refactoring caused by the two programmers striving for perfection. Secondly, there is a risk the two programmers won't get along well. This may happen surprisingly often, providing they haven't been working together previously in this setup. XP is still a big experiment. I wouldn't consider it as reliable and dependable as conventional techniques such as the Unified Process.

Applicability

This is up to you to decide. Where may XP apply well and why?

Software Tools

Although I am unaware of any specific XP project management software, other software may fit the purpose, such as CASE tools supporting CRC modelling and any Agile release / iteration planning software.

For example:
QuickCRC, Visual Paradigm, others. (CRC)

Atlassian Greenhopper, VersionOne, Extreme Planner (Release / Iteration planning)

Since you are collaborating remotely, consider also using some team collaboration software, such as Atlassian JIRA.


问:
Does auto make C++ code harder to understand?
I saw a conference by Herb Sutter where he encourages every C++ programmer to use auto.

I had to read C# code some time ago where var was extensively used and the code was very hard to understand—every time var was used I had to check the return type of the right side. Sometimes more than once, because I forgot the type of the variable after a while!

I know the compiler knows the type and I don’t have to write it, but it is widely accepted that we should write code for programmers, not for compilers.

I also know that is more easy to write:

```<code>auto x = GetX();
</code>```

Than:

```<code>someWeirdTemplate<someOtherVeryLongNameType, ...>::someOtherLongType x = GetX();
</code>```

But this is written only once and the GetX() return type is checked many times to understand what type x has.

This made me wonder—does auto make C++ code harder to understand?

答:
Many good answers so far, but to focus on the original question, I do think Herb goes too far in his advice to use auto liberally. Your example is one case where using auto obviously hurts readability. Some people insist it is a non-issue with modern IDEs where you can hover over a variable and see the type, but I disagree: even people that always use an IDE sometimes need to look at snippets of code in isolation (think of code reviews, for instance) and an IDE won't help.

Bottom line: use auto when it helps: i.e. iterators in for loops. Don't use it when it makes the reader struggle to find out the type.

OwnerDisplayName: Felics


问:
design for interruptable operations
I couldn't find a better topic but here it is;

1) When user clicks a button, code starts t work,

2) When another button is clicked, it would stop doing whatever it does and start to run the second button's code,

3) Or with not user interaction, an electrical power down detected from a connected device, so our software would cancel the current event and start doing the power down procedure.

How is this design mostly applied to code? I mean "stop what you are doing" part?

If you would say events, event handlers etc. how do you bind a condition to the event? and how do you tell the program without using laddered if's to end it's process?

```<code>method1();
if (powerdown) return;
method2();
if (powerdown) return;
</code>```

etc.

答:
F# (another .NET language) has an asynchronous workflow which takes care of flow and cancellation for you behind the scenes, giving you a nice, easy way to code your tasks.

Assuming you have your tasks broken down into smaller operations (that return an async themselves -- you may have to wrap them) you could do something like:

```<code>let button1Task arg =
    async {
        let! r1 = someAsyncComputation(arg)
        do! Async.Sleep(500)
        let! r2 = someOtherAsyncComputation(r1)
        return r2
    }
</code>```

Then start the operation like this:

```<code>let asy = button1Task someValue
let cts = new CancellationTokenSource()
Async.Start(asy, cts.Token)
</code>```

Then, when you want to stop it, you do:

```<code>cts.Cancel()
</code>```

and it'll stop (I believe after finishing whatever operation it was performing -- i.e. when it hits the next do! or let!). I don't think the Cancel() call is blocking, but there may be a different version or a way to check and ensure that the computation has stopped.

In your button scenario, you could have each button or power event check for currently running tasks and cancel them before starting its own task.

The difference between this and threads is that you wouldn't have to do your ladder if's and could still safely abort the task (without having to resort to Thread.Abort()).

You might be able to find something similar for C#, but it probably won't code up as nice.

Here is some reading:

Articles

http://tomasp.net/blog/csharp-fsharp-async-intro.aspx

http://tomasp.net/articles/async-csharp-differences.aspx

http://tomasp.net/blog/async-compilation-internals.aspx

Reference

http://msdn.microsoft.com/en-us/library/ee370232.aspx

I'm still learning about these myself so this might not have been the best explanation.

Title: design for interruptable operations

Body:
F# (another .NET language) has an asynchronous workflow which takes care of flow and cancellation for you behind the scenes, giving you a nice, easy way to code your tasks.

Assuming you have your tasks broken down into smaller operations (that return an async themselves -- you may have to wrap them) you could do something like:

let button1Task arg =
    async {
        let! r1 = someAsyncComputation(arg)
        do! Async.Sleep(500)
        let! r2 = someOtherAsyncComputation(r1)
        return r2
    }

Then start the operation like this:

let asy = button1Task someValue
let cts = new CancellationTokenSource()
Async.Start(asy, cts.Token)

Then, when you want to stop it, you do:

cts.Cancel()

and it'll stop (I believe after finishing whatever operation it was performing -- i.e. when it hits the next do! or let!). I don't think the Cancel() call is blocking, but there may be a different version or a way to check and ensure that the computation has stopped.

In your button scenario, you could have each button or power event check for currently running tasks and cancel them before starting its own task.

The difference between this and threads is that you wouldn't have to do your ladder if's and could still safely abort the task (without having to resort to Thread.Abort()).

You might be able to find something similar for C#, but it probably won't code up as nice.

Here is some reading:

Articles

http://tomasp.net/blog/csharp-fsharp-async-intro.aspx

http://tomasp.net/articles/async-csharp-differences.aspx

http://tomasp.net/blog/async-compilation-internals.aspx

Reference

http://msdn.microsoft.com/en-us/library/ee370232.aspx

I'm still learning about these myself so this might not have been the best explanation.


问:
Storing Dynamic SQL in text files vs inline code
Our Architecture team is proposing a framework that would see our SQL queries moved from coded strings within our applications, into a file based system where we would invoke them with function calls. Our application makes heavy use of SQL queries ranging from the mundane, to very complex. This is a .NET solution.

The idea is that each query would be written to text files, and we would be able to tag fields, joins, and conditions with attributes. When calling our SQL functions, we could pass arguments to toggle these attributes on/off based on our business logic, allowing for only the portions of the SQL we need to be executed.

Although I like the idea of abstracting away our SQL, I am skeptical that this system will result in any tangible benefits. The major driver of this is our past experience where many coders created some massively bungled dynamic SQL functions which were impossible to understand. The idea is that this will make it easier to define your queries, will make all queries more easily testable, and clearly define the business logic involved. I am unsure if this will survive the test of reality.

I’d like to get some feedback on the pros/cons of this approach.

Also, before anyone suggests it, the Entity Framework was rejected due to questionable support from our database provider (Teradata).

答:
I ran into this same dilemma at my job a while back.  I got the same advice you did, and here's what I thought about it:

Pros:

SQL queries can be tested on their own, separate from the mainline code.

Your queries can be modified without having to recompile.

Cons:

SQL is code.  I find it easier to manage when all the code that does something is in the same place.

I've found it rare that you modify a SQL query without a corresponding mainline code change.

I decided that the cons outweighed the pros and left the SQL in the mainline source.  It's been about a year since I made that decision and I haven't regretted it once.


问:
Do people in non-English-speaking countries code in English?
I've heard it said (by coworkers) that everyone "codes in English" regardless of where they're from. I find that difficult to believe, however I wouldn't be surprised if, for most programming languages, the supported character set is relatively narrow.

Have you ever worked in a country where English is not the primary language?

If so, what did their code look like?

答:
I'm from Serbia.

When I code for school, I almost always use Serbian comments and variable names. That code will never be read by someone who doesn't know Serbian anyway and will never be used outside of the exam it is written on and I don't see the point of using English for English's sake.

When I'm doing some coding for myself, I tend to use Serbian too, because nobody else is going to read it and I need code to be readable easily for me and not some non-existent third party. The bad side of this is that I'd have to translate source code of a program if I'm going to share it internationally, but this never happened to me so far.

When I'm writing code which other people will read, I use English and English comments. I generally do my best to make English as readable as possible and to have as little spelling errors as possible. New IDEs with English dictionaries help here.

My reason for preferring Serbian is simple: I'm sick of code which is supposed to be written in English, but looks more like Engrish (or Senglish in my case). Furthermore this so called English continues to evolve separately from English used in countries which actually speak English. This way words which are seriously outdated in modern English, or never existed in English at all keep popping up in source code and in programmer's speech and slowly find their way into technical literature. This way instead of making new words for English technical terms in Serbian, we are making new words for English technical terms in English which English users will not recognize.


问:
How to efficiently store IP addresses?
Background

I have a requirement where I need to remove a few nodes in a network based upon a command given by the user. To keep the nodes from transmitting or receiving data I thought of changing its IP address to some other address.  Before I change the address  I want to save the node's IP so that I can re-assign the original IP back to the node after the simulated network outage is over.

My problem is how to efficiently save the nodes' IP addresses. Should I use a linked list or a hash table?

答:
To keep the nodes from transmitting or receiving data I thought of changing its IP address to some other address.

That is a very dicey solution to your stated problem. You don't need to worry too much about efficiently storing IP Addresses if your solution doesn't involve this sort of hack.

Title: How to efficiently store IP addresses?


问:
OOP terminology in Ruby and C++
I am taking a C++ class in my school. Since I've programmed in Ruby I know some OOP stuff.

But in C++ there are member functions, member variables, and static functions. In Ruby we have instance methods, instance variables, and class variables. And there are more...

Any reason they're different? Are they quite different levels of OOP? Or just some  differences in tradition these ecosystems have?

答: The concepts - or as you call them, levels - of OOP are similar or the same across OO languages and a lot of the differences in terminology come out of the history and tradition of the languages and their ecosystems. That's why you're seeing different terms used to describe very similar concepts when you're comparing the two languages.</p>

Title: OOP terminology in Ruby and C++


问:
How to do external API testing (blackbox)
Assume you are using APIs from a vendor, how to make sure their API is working as expected?

My main concern is sometimes the vendor pushed the changes to their code and break the API, we want to have some sort of automatic software to test them continually. How to deal with this?

答:
Based on the poster's phrasing, it's more than just testing, IMO. After you write your unit test for the API and make sure everything is working as expected, you need to monitor third-party APIs so you catch issues before the users do. That's the real risk with third-party APIs - it's not your code and you have no control over how much testing was done on the API or when/if it changes.

(Disclaimer: product names used here) If you use soapUI to write your API tests, those tests can be re-used in AlertSite as an operational monitor to make sure the API keeps working as expected. If it fails the test, you can get alerted before your users call you and complain that your app doesn't work.


答: They are just different names for the same thing.  You see the same thing with inheritance:  base vs. parent vs. super classes.  School teachers and people who only know one language will sometimes be very pedantic about the terms.  In industry you'll find people mixing and matching more often.</p>

Title: OOP terminology in Ruby and C++

Body:
I am taking a C++ class in my school. Since I've programmed in Ruby I know some OOP stuff.

But in C++ there are member functions, member variables, and static functions. In Ruby we have instance methods, instance variables, and class variables. And there are more...

Any reason they're different? Are they quite different levels of OOP? Or just some  differences in tradition these ecosystems have?


答:
Instance in Ruby and member in C++ are effectively the same thing, so instance variables and member variables are the same, as are instance methods and member functions.

However, static members are somewhat different from class variables in Ruby since the the Ruby object model is quite different to C++. In Ruby, classes are objects, so class variables are instance variables of a class object.

Title: OOP terminology in Ruby and C++


问:
Advantages and disadvantages of structuring all code via classes and compiling to classes (like Java)
Edit: my language allows for multiple inheritance, unlike Java.

I've started designing and developing my own programming language for educational, recreational, and potentially useful purposes.

At first, I've decided to base it off Java.

This implied that all the code would be written in form of classes, and that code compiles into classes, which are loaded by the VM.

However, I've excluded features such as interfaces and abstract classes, because I found no need for them. They seemed to be enforcing a paradigm, and I'd like my language not to do that. I wanted to keep the classes as the compilation unit though, because it seemed convenient to implement, familiar, and I just liked the idea.

Then I noticed that I'm basically left with a module system, where classes could be used either as "namespaces", providing constants and functions using the static directive, or as templates for objects that need to be instantiated ("actual" purpose of classes in other languages).

Now I'm left wondering: what are the upsides and the downsides of having classes as compilation units?

Also, any general commentary on my design would be much appreciated. An informative post on my language can be found here: http://www.yannbane.com/2012/12/kava.html.

答:
Instead of answering this question, I will go one level up and suggest studying the MIT OpenCourseWare, particularly 6.035 (Computer Language Engineering). This will explain the whole problematics, so that you will not get tempted to ask questions like this again.

Computer Language Engineering

The only pre-requisite is Java.

http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-035-computer-language-engineering-spring-2010/lecture-notes/

Course Description

This course analyzes issues associated with the implementation of higher-level programming languages. Topics covered include: fundamental concepts, functions, and structures of compilers, the interaction of theory and practice, and using tools in building software. The course includes a multi-person project on compiler design and implementation.


问:
Would using Quercus make my code fall under the GPL?
Quercus is an implementation of PHP written in Java, and released under the GPL.

If I use it, does my PHP code fall under the GPL?

What about my Java code?

Assuming I write new Java code, and new PHP code, and use Quercus to run my PHP code on the JVM and call into my Java code, which pieces fall under the GPL?

Also, assume that the result is commercial software that I want to distribute.

答:
Let me (IANAL) try to understand what you are saying:

You link a GPL module into your program

You wonder if that makes your program GPL

If so, the answer is "yes". I may not understand what you mean by "use Quercus to run my PHP code on the JVM and call into my Java code", but it certainly sounds like it's bundled into your code. If you only need to have something that is a "PHP interpreter in Java" and can provide another one, you could probably have documentation stating "You can, if you want, use Quercus".

I think the real answer here is to consult a lawyer, specializing in electronic copyright.


答:
One BIG Pro.

You can support multiple DB's simply swapping out the SQL files.
So you have multiple sets of SQL Code for the different DB you want to support.

Title: Storing Dynamic SQL in text files vs inline code

Body:
Our Architecture team is proposing a framework that would see our SQL queries moved from coded strings within our applications, into a file based system where we would invoke them with function calls. Our application makes heavy use of SQL queries ranging from the mundane, to very complex. This is a .NET solution.

The idea is that each query would be written to text files, and we would be able to tag fields, joins, and conditions with attributes. When calling our SQL functions, we could pass arguments to toggle these attributes on/off based on our business logic, allowing for only the portions of the SQL we need to be executed.

Although I like the idea of abstracting away our SQL, I am skeptical that this system will result in any tangible benefits. The major driver of this is our past experience where many coders created some massively bungled dynamic SQL functions which were impossible to understand. The idea is that this will make it easier to define your queries, will make all queries more easily testable, and clearly define the business logic involved. I am unsure if this will survive the test of reality.

I’d like to get some feedback on the pros/cons of this approach.

Also, before anyone suggests it, the Entity Framework was rejected due to questionable support from our database provider (Teradata).


问:
Java style classes in c++
I came across this article proposing a style of coding in c++ that looks a bit weird at first. But after reading it over and pondering for a bit I'm really considering giving it a try.

The most appealing benefit is the ease of refactoring methods. I find myself constantly changing method names, parameters and so on while writing a new class and in c++ it's quite annoying having to change a method name in two files (.h, .cpp).

I tried to find something wrong with this style but apart from the fact that the code will look and feel really strange to seasoned c++ programmers I can't spot any major flaw. But since I am quite a inexperienced c++ programmer I hope that someone here might alert me to any potential dangers.

So my question is:

Are there any serious drawbacks of using this style of coding?

答:
Yes, you're going to confuse other C++ programmers if you write all your code like that.  I have never seen non-template C++ code written that way, with everything in the header file.  This has been discussed in depth in a Stack Overflow question as well.

As for actual technical problems with it, a few things come to mind.

All your code effectively becomes inline.  Your compile times will likely increase.

Every recompile will compile the world simply because it has to.

You'll have to be careful to not run afoul of the One Definition Rule.  Variable names will have to be unique across all source files, since it effectively becomes one giant file.

You also might want to check out the D programming language, which I hear solves a lot of these problems.  The D compiler is designed with this style in mind and doesn't have 30 years of C backward compatibility to support.

Title: Java style classes in c++


问:
Good implementation strategies for encapsulating shared data in a software pipeline
I'm working on re-factoring certain aspects of an existing web service. The way the service APIs are implemented is by having a kind of "processing pipeline", where there are tasks that are performed in sequence. Unsurprisingly, later tasks may need information computed by earlier tasks, and currently the way this is done is by adding fields to a "pipeline state" class.

I've been thinking (and hoping?) that there's a better way to share information between pipeline steps than having a data object with a zillion fields, some of which make sense to some processing steps and not to others. It would be a major pain to make this class thread-safe (I don't know if it would even be possible), there is no way to reason about its invariants (and it's likely it doesn't have any).

I was paging through the Gang of Four design patterns book to find some inspiration, but I didn't feel like there was a solution in there (Memento was somewhat in the same spirit, but not quite). I also looked online, but the second you search for "pipeline" or "workflow" you get flooded with either Unix pipes information, or proprietary workflow engines and frameworks.

My question is - how would you approach the issue of recording the execution state of a software processing pipeline, so that later tasks can use information computed by earlier ones? I guess the major difference with Unix pipes is that you don't just care about the output of the immediately preceding task.

As requested, some pseudocode to illustrate my use case:

The "pipeline context" object has a bunch of fields that the different pipeline steps can populate/read:

```<code>public class PipelineCtx {
    ... // fields
    public Foo getFoo() { return this.foo; }
    public void setFoo(Foo aFoo) { this.foo = aFoo; }
    public Bar getBar() { return this.bar; }
    public void setBar(Bar aBar) { this.bar = aBar; }
    ... // more methods
}
</code>```

Each of the pipeline steps is also an object:

```<code>public abstract class PipelineStep {
    public abstract PipelineCtx doWork(PipelineCtx ctx);
}

public class BarStep extends PipelineStep {
    @Override
    public PipelineCtx doWork(PipelieCtx ctx) {
        // do work based on the stuff in ctx
        Bar theBar = ...; // compute it
        ctx.setBar(theBar);

        return ctx;
    }
}
</code>```

Similarly for a hypothetical FooStep, which might need the Bar computed by BarStep before it, along with other data. And then we have the real API call:

```<code>public class BlahOperation extends ProprietaryWebServiceApiBase {
    public BlahResponse handle(BlahRequest request) {
        PipelineCtx ctx = PipelineCtx.from(request);

        // some steps happen here
        // ...

        BarStep barStep = new BarStep();
        barStep.doWork(crx);

        // some more steps maybe
        // ...

        FooStep fooStep = new FooStep();
        fooStep.doWork(ctx);

        // final steps ...

        return BlahResponse.from(ctx);
    }
}
</code>```

答:
A first solution I can imagine is to make the steps explicit. Each of them becomes an object able to process a piece of data and transmit it to the next process object. Each process produces a new (ideally immutable) product, so that there is no interaction between the processes and then there is no risk due to data sharing. If some processes are more time consuming than some others, you can place some a buffer between two process. If you correctly exploit a scheduler for the multithreading, it will allocate more ressources to flush the buffers.

A second solution could be to think "message" instead of pipeline, possibly with a dedicated framework. You have then some "actors" receiving messages from other actors and sending other messages to other actors. You organize your actors in a pipeline and give your primary data to a first actor who initiates the chain. There is no data sharing since the sharing is replaced by messages sending. I know the Scala's actor model can be used in Java, since there is nothing Scala specific here, but I have never use it in a Java program.

The solutions are similar and you can implement the second one with the first one. Basically, the main concepts are to deal with immutable data to avoid the traditional problems due to the data sharing and to create explicit and independent entities representing the processes in your pipeline. If you satisfy these conditions, you can easily create clear, simple pipelines and use them in a parallel program.


答:
If you want to Java-style classes, then program in Java !

He makes many conjectures in his article that are flat out wrong. In no particular order:

Compile time

This is not issue either. Assuming you have all operating
  system headers and frequently used containers (STL) or math libraries
  in precompiled headers, and assuming that if your program is really
  huge, you have separated it into components as per above, the
  remaining amount of code is absolutely negligible for a modern C++
  compiler.

This is just wrong, and it shows that he has never worked on a large scale C++ program. Download any large open source C++ program, compile the program, and tell me if you want to wait that long every time you forget a semi-colon.

Declare before Use

There is a C++ feature very few programmers seem to know about (or at
  least, have exploited): and that is that inside a class, declare
  before use doesn't hold (!). Clearly Bjarne was aware of this legacy
  problem in C++ and fixed it for the inside of classes, but couldn't do
  the same for top-level declarations because of backwards compatibility
  with C (why? there must be some intricacy I am missing here).

[...much much more, each line more painful than the last...]

Ok, first off, it is not a feature that "very few programmers seem to know about." Second, this is a complete misunderstanding of forward declaration and what it is used for. Google's coding style guide has a halfway decent introduction: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Forward_Declarations

They're meant to simplify the compiler and they reduce compile time substantially.

Title: Java style classes in c++

Body:
I came across this article proposing a style of coding in c++ that looks a bit weird at first. But after reading it over and pondering for a bit I'm really considering giving it a try.

The most appealing benefit is the ease of refactoring methods. I find myself constantly changing method names, parameters and so on while writing a new class and in c++ it's quite annoying having to change a method name in two files (.h, .cpp).

I tried to find something wrong with this style but apart from the fact that the code will look and feel really strange to seasoned c++ programmers I can't spot any major flaw. But since I am quite a inexperienced c++ programmer I hope that someone here might alert me to any potential dangers.

So my question is:

Are there any serious drawbacks of using this style of coding?


答: IP(v4) addresses are just four byte long integers presented in a human readable format. You can just store an IP address as an unsigned integer.</p>

Title: How to efficiently store IP addresses?

Body:
Background

I have a requirement where I need to remove a few nodes in a network based upon a command given by the user. To keep the nodes from transmitting or receiving data I thought of changing its IP address to some other address.  Before I change the address  I want to save the node's IP so that I can re-assign the original IP back to the node after the simulated network outage is over.

My problem is how to efficiently save the nodes' IP addresses. Should I use a linked list or a hash table?


问:
Have I understood OOP correctly?
I had originally posed this on StackOverflow. The question was closed and I was asked to post this here instead. Here is the original question I had posted there:

I have been programming using procedural method for a while now. I have done some good amount of reading pertaining to OOP and I know how to use it. It's just that I am not sure if whether I still know how to use it correctly? So to put this to a test I am presenting a skeleton of a plugin which I have developed using OOP. The plugin is supposed to fetch values like subscribers, follows etc from various social networks.

```<code>// This is an abstract class used by all Social Network classes
abstract class Social_Network {
    protected $service_url,$service_identifier,$icon_url,$refresh_data;

    function __construct($arguments) {
        // Code to populate the protected variables declared above
    }

    protected function get_value_internal() {
        // Internal here means get data from cache.

        // Call get_value_external If cache data has expired or does not exist
    }

    protected function parse_json_data($data) {
        // This function parses data and gets the requested value from it
    }

    public function display_value() {
        // This is a public function which outputs the value

        // Call get_value_internal

        // Display the value with icon, etc.
    }

    //This will be different for all networks because every network would have a different method for retrieving data
    abstract function get_value_external();
}

class Facebook_Social_Network extends Social_Network {
    function get_value_external() {
        // Unique code for retrieving data from Facebook

        // Process the data fetched above and parse it using the parse_json_data function defined in our abstract class
        return $this - > parse_json_data($data);
    }
}

class Twitter_Social_Network extends Social_Network {
    function get_value_external() {
        // Unique code for retrieving data from Twitter

        // Process the data fetched above and parse it using the parse_json_data function defined in our abstract class
        return $this - > parse_json_data($data);
    }
}

class YouTube_Social_Network extends Social_Network {
    function get_value_external() {
        // Unique code for retrieving data from YouTube

        // Data returned by YouTube is processed differently so this doesn't use the shared method parse_json_data

        // Process the data and put it inside a variable named $value which will be returned below

        return $value;
    }
}
</code>```

I will appreciate if someone good at OOP can take a quick look and tell me if I am on target with my understanding, close to the target or way off?

One thing that's bothering me is whether I should have just used one class which would handle all Networks?

答:
The basic design looks OK, except for having get_value_internal() and get_value_external() as separate public methods, one getting cached data and one getting the value from the net. A client should not have to decide which to call - it should be handled internally by the class (maybe have a public method invalidate_cache() if needed).

Additionally, it might be better to separate the functionalities for getting the data and displaying it - display_value() would be better as method of the object returned by the get_value(), or perhaps in a Formatter class of its own, if the display functionality is complex.

Title: Have I understood OOP correctly?


答:
One thing that's bothering me is whether I should have just used one class which would handle all Networks?

That will become really bad as soon as your code will grow enough. You definitely should have base class and/or some interfaces/traits.

Your code sample looks OK, but it's way too small to judge how well you've grasped the OOP concepts.

IMO, you understand OOP deep enough to design big systems (this knowledge is required but not sufficient) if you understand:

use cases for single/multiple inheritance, composition, interfaces and traits

polymorphism in general (just basic understanding)

SOLID principles

design patterns

Title: Have I understood OOP correctly?

Body:
I had originally posed this on StackOverflow. The question was closed and I was asked to post this here instead. Here is the original question I had posted there:

I have been programming using procedural method for a while now. I have done some good amount of reading pertaining to OOP and I know how to use it. It's just that I am not sure if whether I still know how to use it correctly? So to put this to a test I am presenting a skeleton of a plugin which I have developed using OOP. The plugin is supposed to fetch values like subscribers, follows etc from various social networks.

```<code>// This is an abstract class used by all Social Network classes
abstract class Social_Network {
    protected $service_url,$service_identifier,$icon_url,$refresh_data;

    function __construct($arguments) {
        // Code to populate the protected variables declared above
    }

    protected function get_value_internal() {
        // Internal here means get data from cache.

        // Call get_value_external If cache data has expired or does not exist
    }

    protected function parse_json_data($data) {
        // This function parses data and gets the requested value from it
    }

    public function display_value() {
        // This is a public function which outputs the value

        // Call get_value_internal

        // Display the value with icon, etc.
    }

    //This will be different for all networks because every network would have a different method for retrieving data
    abstract function get_value_external();
}

class Facebook_Social_Network extends Social_Network {
    function get_value_external() {
        // Unique code for retrieving data from Facebook

        // Process the data fetched above and parse it using the parse_json_data function defined in our abstract class
        return $this - > parse_json_data($data);
    }
}

class Twitter_Social_Network extends Social_Network {
    function get_value_external() {
        // Unique code for retrieving data from Twitter

        // Process the data fetched above and parse it using the parse_json_data function defined in our abstract class
        return $this - > parse_json_data($data);
    }
}

class YouTube_Social_Network extends Social_Network {
    function get_value_external() {
        // Unique code for retrieving data from YouTube

        // Data returned by YouTube is processed differently so this doesn't use the shared method parse_json_data

        // Process the data and put it inside a variable named $value which will be returned below

        return $value;
    }
}
</code>```

I will appreciate if someone good at OOP can take a quick look and tell me if I am on target with my understanding, close to the target or way off?

One thing that's bothering me is whether I should have just used one class which would handle all Networks?


问:
How deep should we dive into testing different layers, i.e. Drupal's db_query?
We use Drupal 7 as our base CMS tool.

For one specific product, something like an ERP, we've created sort of a non-drupal layer, to keep our specific business code in.

It would be something like this:

```<code>-------------
|  Business | -> This would be our business specific code layer
-------------
|    Glue   | -> This is where we connect with the basic Drupal API as we need
-------------
|   Drupal  | -> This is Drupal API
-------------
</code>```

We have the concept of Repository, which is a basic class that retrieves something from the database in the form of an Entity or a ArrayObject of Entities.

This layer is connected to Drupal, since it needs access to the db_query() method, from the Drupal 7 API.

Our whole Business layer is tested using PHPUnit, with 100% coverage.

Now we are trying to test the Glue layer as well, the unit of the Repositories, their return values and parameters.

In order to do that, we came to the conclusion that we would need to mock the Drupal database access API.

But to do that, what would be the correct or best approach?

Wrap the db_query function from Drupal into a class that could be mocked in the tests?

Not test the Repositories at all?

答:
Well, as in many cases the answer to your question starts with... "It depends."

First, you should ask yourself "Is there any logic in the Repository / Glue layer?" I mean other than adapting to and from the D7 API. If the repositories for example have methods that offer a custom query language for you to find specific objects or set of objects, methods that do selecting and sorting these objects, than you probably wish to test the Repository.

The ideal way to do it would be as you suggested, with a Mock of an intermediary class to db_query(). But before you jump into this and start coding take a minute and think about your repositories. Maybe it is acceptable to test it with a real database specially prepared with objects you know and can control for testing purposes. I find that most of the time, these very rarely changing parts of your design can be tested at this higher level. The test will run a little bit slower, but maybe you can get away with running them together with the functional / integration tests you may have on your system. After all, the whole "glue" thing is for integration.

You may also speed up the tests with databases by creating the databases in RAM only, or on a mount point serving as ram-disk.


答:
Based on your additional comments, I personally would not bother mocking any class up to simulate the Drupal API. It sounds as if you've designed Glue to abstract the Drupal API a bit from the Business layer, to make it easier to work with.

To provide reasonable test coverage for Glue without going overboard, I might suggest doing some basic black-box unit tests against the Drupal API calls you intend to use to ensure they are working as expected. You'll have confidence that the Drupal API is doing what is expected, and that you're integrating against a working API. Then you should test Glue and the Drupal API together. Once you've defined your tests and you execute them to your satisfaction, I would consider Glue tested sufficiently.

Under this approach, since you're not intending to use Glue with any other API other than Drupal, I think you'll have tested Glue adequately without burning extra cycles creating more work for yourself than needed.

Title: How deep should we dive into testing different layers, i.e. Drupal's db_query?

Body:
We use Drupal 7 as our base CMS tool.

For one specific product, something like an ERP, we've created sort of a non-drupal layer, to keep our specific business code in.

It would be something like this:

```<code>-------------
|  Business | -> This would be our business specific code layer
-------------
|    Glue   | -> This is where we connect with the basic Drupal API as we need
-------------
|   Drupal  | -> This is Drupal API
-------------
</code>```

We have the concept of Repository, which is a basic class that retrieves something from the database in the form of an Entity or a ArrayObject of Entities.

This layer is connected to Drupal, since it needs access to the db_query() method, from the Drupal 7 API.

Our whole Business layer is tested using PHPUnit, with 100% coverage.

Now we are trying to test the Glue layer as well, the unit of the Repositories, their return values and parameters.

In order to do that, we came to the conclusion that we would need to mock the Drupal database access API.

But to do that, what would be the correct or best approach?

Wrap the db_query function from Drupal into a class that could be mocked in the tests?

Not test the Repositories at all?


问:
Scientific software design
I asked this question over at stackoverflow and it was suggested a tighter form be posted here.

Many early career numerical researchers face the prospect of having to create performance critical software from the ground up. Most are ill equipped to do so, and my lab is no different. I currently work extending a sophisticated C application that is typical of a lot of academic code -- it is a nightmare to work with and adding new features takes much longer than it should.

I want to learn how to do it better, and I learn by doing. With that in mind, I would like to jump in the deep end and create an application that is parallel (OpenMPI + maybe OpenCL), combines script driven Python UI with C++ for the heavy lifting, and most importantly, makes use of appropriate design patterns to make the code as modular as possible. The primary reason for doing so is to learn the major gotcha's and some general performance techniques that can be documented and shared around the lab.

I have read some of the books around OO and pattern's, but I find it challenging to take their abstract nature and apply it to the problem domain in a useful way.

I guess the question I am asking is: if you were given the task to design this kind of software, what would be the focus of your first hour in front of a whiteboard?

答:
In one hour on a whiteboard, I'd focus on the following:

Requirements: what does the system do?  Who will be using it?  What are their minimal expectations? With an extant code-base you may have a head start on this, so if high-level stuff like that is already known, I'd imagine that for scientific software you can tighten the focus to data: what are the inputs?  What pre-processing/cleaning do they need?  Then what are the main processes/transformations the system does (think workflows and dataflows here)?  What are the outputs that matter?  How should they be formatted and/or presented to users?

Architecture: nothing fancy needed, just boxes of related functionality, e.g. a simple 3-block structure of Inputs -> Processing -> Outputs may seem too naive, but you can build a discussion from there with colleagues, and start breaking out pieces, e.g. Inputs -> time-series, parameters, vectors vs. scalars; Processing -> what's serial and what's potentially parallel?  what models are needed?; Outputs -> charts/graphs? csv dumps?  The point is to separate and modularize at this level when it's cheap and easy to do so, before much sunk-time/energy in code.

I suspect the above will easily consume several hours. :)  Also, for scientific code that's data-centric, OO may or may not be a good fit.  Don't use "design patterns" for their own sake, a lot of those patterns are convoluted work-arounds for weaknesses in languages that don't have higher-order functions.  Hope this helps.

Title: Scientific software design


问:
Quality Assurance activities

Possible Duplicate:

  Verification of requirements question

Having asked but deleted the question as it was a bit misunderstood. If Quality Control is the actual testing, what are the commonest true quality assurance activities? I have read that verification (reviews, inspections..) but it does not make much sense to me as it looks more like quality control as mentioned here:

DEPARTMENT OF HEALTH AND HUMAN SERVICES
ENTERPRISE PERFORMANCE LIFE CYCLE FRAMEWORK
Practices guide

Verification - “Are we building the product right?” Verification is a
  quality control technique that is used to evaluate the system or its
  components to determine whether or not the project’s products satisfy
  defined requirements. During verification, the project’s processes are
  reviewed and examined by members of the IV&V team with the goal of
  preventing omissions, spotting problems, and ensuring the product is
  being developed correctly.

  Some Verification activities may include
  items such as: • Verification of requirement against defined
  specifications • Verification of design against defined specifications
  • Verification of product code against defined standards •
  Verification of terms, conditions, payment, etc., against contracts

And the opposite (project management knowledge scope - google result)
Verification is a quality assurance process or technique applied by ...

答:
In many ways, trying to find the dividing line between Quality Assurance and Quality Control is akin to finding the exact demarcation between Verification and Validation - and whilst the comparison may imply equivalence, it isn't that clear cut either.

What is really important is that you undertake all necessary Verification AND Validation, and the whole development is undertaken with appropriate levels of Quality Assurance AND of Quality Control.

Ultimately Product Quality is everyone's responsibility.

For reference, the applicable ISO standard is ISO/IEC 12207 - Software Lifecycle Processes - it is a good read (if you are an insomniac) and available from the ISO store

Title: Quality Assurance activities


问:
How to plan a client/server app networking architecture to cope with multiple unrelated exchanges of data?
I'm coding a server/client application pair in Java, as I learn about it. I have basic functionality of sending a message to the server and parsing it but in thinking about the big picture of their communication, I'm stumped about where to go from here.

Both the client and the server have to be able to initiate an exchange of data so I need to have one thread reading at each side, at all times. On top of that, when one initiates an exchange, it needs to listen for the reply. If I do that, though, I'd have two threads reading data, which I guess wouldn't end well since, from my understanding, I wouldn't be able to make sure the data gets read in the thread I want.

I see a few options but I'm not confident at going too far with each solution since my knowledge doesn't let me think too far ahead.

Use only the first thread that was originally waiting for data before the exchange, to also read the reply for the query that was just sent by a different thread, and forward the data where it belongs.

This sounds difficult. If I read the data in the same thread that requested it, it would be very straightforward compared to this.

Start reading the InputStream in the same thread that requested data and make the thread that was originally listening, wait.

My problem with this is that, if there's other data arriving by the same client that is unrelated with the query that was just made, it would be fetched by this thread instead of the other one, which kinda defeats the purpose of reading the data here.

Establish another connection from the client, to another port, after the first is established. Then I could use one socket for exchanges initiated by the other side, and the other to listen for replies of queries made in the meantime.

This way I'd know exactly what is going where, but wouldn't I have this same problem further down the road if I have two queries waiting for data at the same time?

This sounds like simple functionality, trivial to find in many applications, so I'm guessing there's some tried and true method out there and there's no reason for me to try and reinvent the wheel here.

So, to sum it up, what's the recommended way to set up client/server applications that can cope with possibly overlapping dialogs, initiated by either one, at unpredictable times?

I started to modify some parts of the question to make it a bit clearer but I ended up almost rewriting it completely. If it's still a bit confusing is because I am confused. I think I'm missing some simple point but I haven't been able to find examples that show this.

答:
A common way to do it would be to have the client maintain a persistent TCP connection to the server (i.e. once the client connects to the server, it stays connected until the client quits).

Since TCP connections are bi-directional, the client and the server are both free to send data across the TCP socket at any time.

(Note that the more difficult part of this setup is the receiving of data:  Instead of doing a synchronous model where your client sends something, then blocks waiting for the return data to come back, your client must be ready to receive data from the server at any time... but it also needs to be able to handle other tasks, such as GUI events, simultaneously.  This can be done by dedicating a thread to receiving data, and/or by using an asynchronous I/O model)

OwnerDisplayName: Smig

OwnerDisplayName: Jeremy Friesner


问:
Working with clients who don't know what they want
I have recently started a job that has me working on an existing system. It requires tweaks and updates as well as new code. I have done several maintainance/feature adding projects now, and several of them have ended up being significantly different from what was actually requested. So, I had to program the item several times to get it to where the requester wanted.

Now, I don't mind reprogramming the feature if that's what needs to be done. However, I would like to decrease turnaround time on my projects. The bottleneck seems to be in the requester's perception of what needs to be done. Do you have any ideas on what I could do to figure out what the requester needs more quickly?

答:
I feel your pain....

The bad news is: depending on exactly what kind of clients you're dealing with, this might be business as usual.

A common general problem is basically that clients don't know what they want. They usually know what they want to be achieved, in terms of a business goal, but they often have no idea how it should look in terms of the software solution. So in many cases you'll find yourself in this iterative cycle where a project bounces back and forth for five times as long as the initial estimate was, because the client keeps changing their mind and wants the solution tweaked and re-tweaked. And yes, it's not unusual for the final result to be morphed into something entirely different to what the initial goal looked like.

I had an epic example of this happen a couple of years ago - a project that initially took 10 weeks to code turned into a 15 month re-iteration grind. In that case, it was mainly because different managers and departments at the client company wanted different things, so they kept sending the work back, to be tweaked and re-tweaked (our software is subscription based and this was a major client, so this was no financial skin off our back - just a big technical annoyance really).

So basically my advice is this:

If this is the way your particular industry and these clients are (that's a big IF), then just get used to it. Think of it as being an Agile, maintenance-oriented job (this is how my current gig is, more or less). :)

If this isn't the way things are meant to be done, and you are catching blame for the long turnarounds, then speak up to your bosses. Explain to them that there are communication problems and that the specifications that are coming through to you from the clients are not clear enough for you to implement the desired solution. You don't want to find yourself in the situation where you're catching blame for not giving the clients what they want, if you're not getting all the required information to give them what they want.


问:
Language for Chess Position Evaluation (experimental)
My aim is to, via pattern analysis and statistics, (as well as piece mobility and position) build a chess position evaluation analyzer (rather than simply going brute force ply-searching).

Id like to hear some thoughts a language that will be interesting/fun/challenging to learn and reason with. Ideally the language would have be well suited for:

Statistical Analysis

Pattern Analysis

Native Array and Vector Operations

Native Mathematical Functions

Note:

I have no need for a GUI, and may not even get to the point of a 'move engine' but simply stop at a position evaluation engine

I am not interested in speed.

I am personally most comfortable with Python but I might be interested in trying something else. (though feel free to suggest this if you think it fits).

I am particularly curious about how good a fit a functional language would be in this context.

答:
I think your problem scope falls exactly into the purpose of R, though I have never written or worked with R. I have heard good things about it, and would strongly suggest you start looking into it.

http://www.r-project.org/

Coming from python this will be a large shift I'm betting since it's functional, but I don't know how pure it is so it may not be too bad if it's got good multi-paradigm facilities.

If this doesn't come out to be in your opinion elegant, I would then suggest two other languages:

The one I find to be most elegant of any I've ever seen, Haskell, which is declarative (which sounds like what you're asking for in the way you frame your approach) and good for processing data sets.

And another one which facilitates declarative programming while having meta-programming facilities that has been shown to be invaluable in writing systems that analyze things with a bit more intelligence, LISP(or Scheme).


问:
Why do so many namespaces start with com
I've noticed that a lot of companies use "reverse domain name" namespaces and I'm curious where that practice originated and why it continues. Does it merely continue because of rote practice, or is there an outstanding architecture concept I might be missing here?

Also note questions such as: https://stackoverflow.com/questions/189209/do-you-really-use-your-reverse-domain-for-package-naming-in-java that sort of answer my question but not 100%

(If it makes you feel any better, I'm really curious if I should be using it for my javascript namespacing efforts, but I'm more curious about then when and why, and that should help guide me on the javascript answer, nota bene: "window")

Example of this practice extending to folders and files:

答:
It's because using namespaces reduces the chances of name conflicts tremendously, and because using your domain name (which has already been regulated) is a good way to create a global namespace.

By reversing the domain part in the namespace, you make it sortable; all names that belong to your little chunk of the namespace universe are sorted together.

And last but not least, the TLD .com is the most popular TLD on the internet, so it's used by more software developers than any other TLD.

In any case, the practice started with Java, where each and every class needs to have it's own file, and to play in a larger ecosystem the global namespace scheme was introduced to help keep classes easy to qualify.


答:
Reverse Domain Notation has its origins in Java, but is widely used in many platforms, such as Android Packages, Mac OS X Packages, JavaScript, ActionScript, and more.

The practice is extremely useful because it provides a decentralized system for namespacing software. There is no need to apply to a centralized agency for a namespace; simply use the domain name you own (reversed) and manage that within your own organization. By naming packages like this, one can be almost certain that code won't conflict with other packages.

From Oracle's Java Tutorials:

Companies use their reversed Internet domain name to begin their package names
  for example, com.example.mypackage for a package named mypackage created by a
  programmer at example.com.

Name collisions that occur within a single company need to be handled by
  convention within that company, perhaps by including the region or the
  project name after the company name (for example,
  com.example.region.mypackage).

It's more than a rote practice, it's good practice because it's a complete and fully specific namespace. If there were two companies named Acme and both chose the namespace acme., their code would conflict. But only one of those companies can own the domain acme.com, so they get to use the com.acme. namespace.

Reversing the domain name allows for a top-down architecture. com would contain code for companies (or anyone who owns own a .com domain name), and underneath that would company (domain) names. Then, deeper within that would be the structure of the organization and/or the actual namespace. (For example, if it was code from a network called internal.acme.com, that gives this department their own sub-namespace of com.acme.) This top-down structure is used in a number of applications, including in systems administration. (It's similar to reverse IP address lookups.)

Personally, I use it for all new JavaScript code I write for my company. It ensures that the code will never conflict with any other code, even if I later write the same code for another company. It can make accessing the code cumbersome (typing com.digitalfruition. can get a bit much) but that can easily be worked around with a closure and a local variable (var DF = com.digitalfruition).

Title: Why do so many namespaces start with com

Body:
I've noticed that a lot of companies use "reverse domain name" namespaces and I'm curious where that practice originated and why it continues. Does it merely continue because of rote practice, or is there an outstanding architecture concept I might be missing here?

Also note questions such as: https://stackoverflow.com/questions/189209/do-you-really-use-your-reverse-domain-for-package-naming-in-java that sort of answer my question but not 100%

(If it makes you feel any better, I'm really curious if I should be using it for my javascript namespacing efforts, but I'm more curious about then when and why, and that should help guide me on the javascript answer, nota bene: "window")

Example of this practice extending to folders and files:


答:
Endianness

I'm not a java expert, but as to the general pattern this is just another permutation of big-endian vs little-endian, metaphorically speaking.

"Endianness" is sometimes used to describe the order of the components
  of a domain name, e.g. 'en.wikipedia.org' (the usual modern
  'little-endian' form) versus the reverse-DNS 'org.wikipedia.en'
  ('big-endian', used for naming components, packages, or types in
  computer systems, for example Java packages, Macintosh ".plist" files,
  etc.). URLs can be considered 'big-endian', even though the host part
  could be a 'little-endian' DNS name.

In this case, its presumably for organizational purposes to allow for natural grouping / tree branching. It keeps things tidy at a higher level, and you dig down for more specific detail.

The alternative would be very flat, and meaningful / potentially useful grouping would have to be interpreted vs being intrinsic to the structure.


问:
Does low latency code sometimes have to be "ugly"?
(This is mainly aimed at those who have specific knowledge of low latency systems, to avoid people just answering with unsubstantiated opinions).

Do you feel there is a trade-off between writing "nice" object orientated code and writing very fast low latency code? For instance, avoiding virtual functions in C++/the overhead of polymorphism etc- re-writing code which looks nasty, but is very fast etc?

It stands to reason- who cares if it looks ugly (so long as its maintainable)- if you need speed, you need speed?

I would be interested to hear from people who have worked in such areas.

答:
Not to be different, but here's what I do:

Write it clean and maintainable.

Do performance diagnosis, and fix the problems it tells you, not the ones you guess. Guaranteed, they will be different from what you expect.

You can do these fixes in a way that is still clear and maintainable, but, you will have to add commentary so people who look at the code will know why you did it that way. If you don't, they will undo it.

So is there a tradeoff? I don't really think so.


问:
Storing Dynamic SQL in text files vs inline code
Our Architecture team is proposing a framework that would see our SQL queries moved from coded strings within our applications, into a file based system where we would invoke them with function calls. Our application makes heavy use of SQL queries ranging from the mundane, to very complex. This is a .NET solution.

The idea is that each query would be written to text files, and we would be able to tag fields, joins, and conditions with attributes. When calling our SQL functions, we could pass arguments to toggle these attributes on/off based on our business logic, allowing for only the portions of the SQL we need to be executed.

Although I like the idea of abstracting away our SQL, I am skeptical that this system will result in any tangible benefits. The major driver of this is our past experience where many coders created some massively bungled dynamic SQL functions which were impossible to understand. The idea is that this will make it easier to define your queries, will make all queries more easily testable, and clearly define the business logic involved. I am unsure if this will survive the test of reality.

I’d like to get some feedback on the pros/cons of this approach.

Also, before anyone suggests it, the Entity Framework was rejected due to questionable support from our database provider (Teradata).

答:
If your problem is "impossible to understand" SQL, focus on that problem. Can not imagine that SQL with attributes does anything to make it easier to understand.

Instead it will create a maintenance burden on parsing attributes etc on an already complex language like sql. Sooner or later your extensions will prevent you from using some nice database feature. How much training is needed to teach new employees/contractors your version of sql?
Extra files create a more complicated deployment process and possible support problems. How do you know the version of the file that is in use or if it has been altered by the customer or your own support to solve another issue? Everything can be solved of course but only you knows if it is worth it.

Spend your time setting up strict guidelines for writing readable/maintainable SQL first. Once that is in place and everyone agrees on the rules you can move to the next problem.

What is readable and maintainable sql varies but here is a subset of our rules. (For sql-server)

you must be able to easily copy/paste code to/from database and run it
I.e. No string concatenations of variables in code.
Use parameters or string.Replace where parameters are not allowed in sql.

one column per line pefixed with table/alias

explicit AS

ansi joins

descriptive aliases (not t1, t2 etc)

use CTE/CROSS APPLY to reduce complexity

use parameters with descriptive name for both variables and "magic" numbers.


答: If you said the architects wanted you to extract the SQL and put it in stored procedures inside the database, I'd have said "Give them boys a cookie!".  But switching from SQL assembled via string construction to SQL assembled via templating is too minor a step to deserve a reward.</p>


问:
When do I need to use Session Replication?
I am working on a number of web projects for a firm. Most of the projects are about one or two pages of input and then doing a save to a MySQL database. My system administrators are pushing to try to get session replication working in JBoss, but I don't really see any need for it and all of its overhead. We need load balancing and clustering so if the server does go down we can move the new requests to the backup server, but I am not to big in session replication.

This is very low volume projects. In my eyes, what are the odds of a user being in the project as the server goes down on the one or two pages? I am trying to convince the system administrators that session replication is an unnecessary complication in this instance.

In my situation, should I be using session replication? If not, what are the best reasons to not use it so I can convince the system administrators?

答:
We typically use a pattern, where a session's content is split between what is only needed on this server (often, but not allways an empty subset)and what has to persist between servers. The latter part is then written to a temp store (mostly memcached) on session save, recalled on session load.

This allows not only passing round between servers, but also between different platforms: Think of a Webapp that is gradually moved from e.g. PHP to JBoss.

In my experience, the memcached overhead is far lower than the session replication overhead, especially as the number of servers grows.


问:
Maintenance wise, is `else while` without intervening braces considered safe?
Is else while without intervening braces considered "safe" maintenance wise?

Writing if-else code without braces like below...

```<code>if (blah)
    foo();
else
    bar();
</code>```

...carries a risk because the lack of braces make it very easy to change the meaning of the code inadvertently.

However, is below also risky?

```<code>if (blah)
{
    ...
}
else while (!bloop())
{
    bar();
}
</code>```

Or is else while without intervening braces considered "safe"?

答:
What is so wrong with braces that so many people is trying to avoid writing them ?

What problem does exactly else while solve ?

Braces are cheap and good, and they make code intention evident and plain as opposed to clever and witty.

Quoting Unix Philosophy:

Rule of Clarity: Clarity is better than cleverness.

Because maintenance is so important and so expensive, write programs
  as if the most important communication they do is not to the computer
  that executes them but to the human beings who will read and maintain
  the source code in the future (including yourself).


问:
How to handle timezone for dates?
With a YYYY-MM-DD HH:MM:SS date I always store the UTC time. When I pull to display I translate timezones with built-in PHP functions and classes.

I believe that is one correct way to do it and it makes sense to me.

May I handle YYYY-MM-DD the same way?

答:
That would depend on how you interpreted the date.

If you use the date as though it were YYYY-MM-DD 00:00:00 (or any specific time) then you would probably want to take account of time zones.

If you use the date as just on indication of the day then you probably don't.

This is vague as without the context of what you are doing with the dates, it is just guesswork.

Title: How to handle timezone for dates?


问:
Representing domain objects
This is related to my recent question regarding naming awkward domain objects.  A number of answers indicated I was using the wrong representation for the domain objects.  To summarize, I chose to use an enum to represent some domain objects used as keys in lookups.

For this question, I want to review my decision to use an enum and identify alternatives.  Jump to the bottom of my question for the TL;DR.

Domain Description

My application is responsible for performing some calculations involving chemical compounds.

Some basic equations are:

calculating the number of moles of a compound

calculating the specific gravity or density of a compound at various concentrations

These equations could be handled as methods within a Chemical class like:

Chemical.GetMolesFromMass(double mass_grams) or

Chemical.GetDensity(double concentration)

or they could be implemented as methods off of a generic chemical properties class like:

Chemical.GetMolesFromMass(Compound cmpd, double mass_grams) or

Chemical.GetDensity(Compound cmpd, double concentration)

I think from an object responsibility point of view, the first option of methods off of the Chemical class would be a better representation.

Some advanced equations involve:

calculating quantities of a compound consumed by a business process

calculating storage requirements of compounds

optimizing deliveries based upon standard container sizes

In these equations, the chemical compound is an input to the method.

StorageTankCluster.Generate(Compound cmpd, double requiredVolume)

The StorageTankCluster needs to know about the chemical because the dimensions and spacing of the tanks within the cluster will change based upon the chemical and required volume.  The chemical being stored can affect tank material selection as well as impacting safety clearances between tanks.

At the moment, I'm considering those parameters (spacing, material, ...) as lookup items instead of elements that the compound is responsible for knowing about.

Likewise, the delivery optimization as affected by the chemical compound but it's arguable on whether or not those aspects are the compound's responsiblity.

Both the StorageTankCluster and the delivery optimization components are intended to be reused by other non-chemical aspects of the application.  As this question is already getting complicated, we can just call those other elements Foo and Bar.  Both Foo and Bar could utilize the delivery optimization, but only Foo can be used with the StorageTankCluster.

It's not in the application now, but all of the various properties discussed so far will need to be stored within a database / persistence layer.  I realize that shouldn't affect a good design, but I thought it was worth mentioning.

I'll admit that some of my decisions have been biased because I'm porting this application from another source that forces everything to be done in a structured manner.  Writing out this question has highlighted a few areas where I should have better examined what object had responsibility for that functionality.

My design so far has been oriented around lookup tables and I'm using the enum values as the keys to those tables.  It is their use as keys that causes me to treat them as named objects within the program instead of treating them as objects the system would operate upon.  This has pretty much relegated the chemical compounds to 2nd-tier class status, and I'm wondering if that was the right decision.  On the other hand, I'm concerned about the chemical compound class becoming bloated beyond usefulness.

TL;DR

My implementation is / must be in C#. So was using an enum the right choice, or what should I have done and why?

答:
We want to code to be as simple as possible. We don't want it cluttered up with domain knowledge that the programmer shouldn't need to know. Thus, whenever possible, we want to avoid putting something as domain specific as chemical products into the code. That's why we think that putting chemical products as an enum into your code is probably a bad idea unless proven otherwise.

As a similar case, consider a course registration system. You wouldn't want the code to contain any references to various courses that people should be taking. CSI101 may be "Introduction to Computer Graphics", but that should not be in the code at all. That information should only be in a database row for the course. The course registration system code treats all classes the same, only perhaps considering properties of the course such as name, prerequisites, credit hours, etc.

So the first question is whether you actually need to have references to the various chemical compounds in your code. This is independent of whether or not you are using lookup tables. Chemical.GetDensity(Compound cmpd, double concentration) can work just the same whether Compound is a enum, object, string, or int. StorageTankCluster.Generate(Compound cmpd, double requiredVolume), is the same, the function works the same whether or not the Compounds are actually named entities in the code. None of these things remotely require you to reference compounds in your code.

Of course, somewhere you have to specify which compound is being considered. It can't always be a parameter to your function. It is the nature of that specification that determines whether or not you need to have reference to the chemicals in your code. Your statements seem to indicate that the business process determines which compounds need to be considered. I gather that the business process is written into code, and that's why you need to refer the chemical compounds in code. But the question is whether the business process really needs to be implemented in code.

To see what I mean, lets look back at the course registration. Suppose that you've got a class with a complicated rules for whether you are allowed to take it.

```<code>boolean CSI250::MayTake(Student student)
{
    // if the student has special permission, he can always take the course
    if( student.HasOverrideForCourse("CSI250") ) return true;

    // Student must have taken 101 first
    if( !student.HasTaken("CSI101") ) return false;

    // Student must have at least a B in CSI 101
    if( student.GetGrade("CSI101") < Grades.B) return false

    // Student must have taken either CSI150 or CSI201
    if( !student.HasTaken("CSI150") || !student.HasTaken("CSI201") ) return false;

    return true;
}
</code>```

If I understand correctly, you need an enum because you are referring to various chemical products in your process like I've done for courses above. (I've used strings, but I could have done enums just as well.) But the above code wouldn't be a good idea, because it puts too much domain information into the process. It'll be a pain maintaining it as the powers that be tweak and adjust things. So what we'd rather do is store the prerequisite information in the database, something like:

```<code>Course   Prereq    Grade Required   Alternate    Grade Required
CSI250   CSI101    B
CSI250   CSI150    D                CSI200       B
</code>```

Now the prerequisite information is moved from the code into the database. It can be manipulated by the administration, the code is simpler, etc. The question is whether you can do the same for your business processes. There are many benefits to be had by moving something like that out of the code into data. Maybe you can't, but its what I'd look to do.

I'd probably avoid enum even if you have to put these entities into the code. enums are pretty stupid. I think it'd be better to be able to say: Chemicals.SodiumPhosphate.GetMolesFromMass(1000) than to say GetMolesFromMass(Chemicals.SodiumPhosphate, 1000). It also gives you future flexibility because the method can do whatever it wants. It can use a lookup table, or store the data inside, or whatever.

Title: Representing domain objects

Body:
We want to code to be as simple as possible. We don't want it cluttered up with domain knowledge that the programmer shouldn't need to know. Thus, whenever possible, we want to avoid putting something as domain specific as chemical products into the code. That's why we think that putting chemical products as an enum into your code is probably a bad idea unless proven otherwise.

As a similar case, consider a course registration system. You wouldn't want the code to contain any references to various courses that people should be taking. CSI101 may be "Introduction to Computer Graphics", but that should not be in the code at all. That information should only be in a database row for the course. The course registration system code treats all classes the same, only perhaps considering properties of the course such as name, prerequisites, credit hours, etc.

So the first question is whether you actually need to have references to the various chemical compounds in your code. This is independent of whether or not you are using lookup tables. Chemical.GetDensity(Compound cmpd, double concentration) can work just the same whether Compound is a enum, object, string, or int. StorageTankCluster.Generate(Compound cmpd, double requiredVolume), is the same, the function works the same whether or not the Compounds are actually named entities in the code. None of these things remotely require you to reference compounds in your code.

Of course, somewhere you have to specify which compound is being considered. It can't always be a parameter to your function. It is the nature of that specification that determines whether or not you need to have reference to the chemicals in your code. Your statements seem to indicate that the business process determines which compounds need to be considered. I gather that the business process is written into code, and that's why you need to refer the chemical compounds in code. But the question is whether the business process really needs to be implemented in code.

To see what I mean, lets look back at the course registration. Suppose that you've got a class with a complicated rules for whether you are allowed to take it.

boolean CSI250::MayTake(Student student)
{
    // if the student has special permission, he can always take the course
    if( student.HasOverrideForCourse("CSI250") ) return true;

    // Student must have taken 101 first
    if( !student.HasTaken("CSI101") ) return false;

    // Student must have at least a B in CSI 101
    if( student.GetGrade("CSI101") < Grades.B) return false

    // Student must have taken either CSI150 or CSI201
    if( !student.HasTaken("CSI150") || !student.HasTaken("CSI201") ) return false;

    return true;
}

If I understand correctly, you need an enum because you are referring to various chemical products in your process like I've done for courses above. (I've used strings, but I could have done enums just as well.) But the above code wouldn't be a good idea, because it puts too much domain information into the process. It'll be a pain maintaining it as the powers that be tweak and adjust things. So what we'd rather do is store the prerequisite information in the database, something like:

Course   Prereq    Grade Required   Alternate    Grade Required
CSI250   CSI101    B
CSI250   CSI150    D                CSI200       B

Now the prerequisite information is moved from the code into the database. It can be manipulated by the administration, the code is simpler, etc. The question is whether you can do the same for your business processes. There are many benefits to be had by moving something like that out of the code into data. Maybe you can't, but its what I'd look to do.

I'd probably avoid enum even if you have to put these entities into the code. enums are pretty stupid. I think it'd be better to be able to say: Chemicals.SodiumPhosphate.GetMolesFromMass(1000) than to say GetMolesFromMass(Chemicals.SodiumPhosphate, 1000). It also gives you future flexibility because the method can do whatever it wants. It can use a lookup table, or store the data inside, or whatever.


答: I'd suggest python with numpy and scipy. Since you are already familiar with python, and numpy and scipy give you the array and math functions you need. </p>

Title: Language for Chess Position Evaluation (experimental)

Body:
My aim is to, via pattern analysis and statistics, (as well as piece mobility and position) build a chess position evaluation analyzer (rather than simply going brute force ply-searching).

Id like to hear some thoughts a language that will be interesting/fun/challenging to learn and reason with. Ideally the language would have be well suited for:

Statistical Analysis

Pattern Analysis

Native Array and Vector Operations

Native Mathematical Functions

Note:

I have no need for a GUI, and may not even get to the point of a 'move engine' but simply stop at a position evaluation engine

I am not interested in speed.

I am personally most comfortable with Python but I might be interested in trying something else. (though feel free to suggest this if you think it fits).

I am particularly curious about how good a fit a functional language would be in this context.


问:
Better php framework for shared hosting
I need to develop an app for booking appointments. This is going to be hosted in a shared server. So performance is the most important thing. I have used symfony2. I quite liked the framework. But seems to be heavy.

Which framework would suit me considering my requirements? I have shortlisted three frameworks yii, symfony2 and ZF2. I am not asking which framework is better.

All the three are good frameworks. I want to know which will suit my requirements. My first priority would be performance (I will be using AJAX wherever possible), second would be maintenance and development time and third community support. Or should I use my own handlers to separate views and logic and just use raw php?

答:
Performance isn't your most important factor. If it was, your app wouldn't be hosted on a single shared server, it would be hosted on a cluster of dedicated servers.

If you want to do the best job you can on this project, then use whichever framework you already understand best. You'll better know how to get good performance out of it because of your experience with it, and that may make up for whatever advantage some other framework has.

It's likely the code you write will have the most impact on performance.

Also, it's likely your app won't see enough traffic for this to really matter. In the event it does, at some point you'll want to move it off of a shared server to a dedicated server, regardless of what framework you use. Eventually you'll be running it on a cluster of servers with a load balancer in front of it, and your challenge will be things like how to shard your database.

Edit:
Here are some benchmarks of a variety of PHP frameworks, which include both symfony and yii, and zf1 but not 2.

In that particular benchmark, it looks like symfony2 is faster than yii which is faster than symfony1, which is faster than zend. They're all of course slower than raw html or raw php.

I think choosing a framework based on a benchmark is a bad idea though. Your own code will be doing something different, and perform completely different.

You might find their methodology useful though. You might want to run siege yourself and see how well your site performs, and what difference making various changes makes. (Although if you're on shared hosting, you probably shouldn't run siege against it, you might bring down everyone's site!)

For "maintenance and development time", your familiarity with the framework is probably going to matter more than the framework itself. And your own ability to be productive and write maintainable code is even more important, regardless of framework choice.

Good luck on your project!

Title: Better php framework for shared hosting


答:
A date alone is pretty meaningless without the location/timezone.

http://en.wikipedia.org/wiki/Coordinated_Universal_Time

http://en.wikipedia.org/wiki/Time_zone

http://en.wikipedia.org/wiki/List_of_UTC_time_offsets

UTC offsets range from -12:00 to +14:00. That's a span of 26 hours, plus the 24 hours the day will last. This means that yesterday's doomsday (yesterday relative to my local timezone) lasted for a total of 50 hours. I.e. for 50 hours, somewhere on the world it is the 21st Dec. 2012. And then there's the daylight saving time.

Did you see any end-of-the-world-agenda (2:00pm - The Mayans will return to earth with an alien spaceship) or end-of-the-world-24h-countdown that included the timezone?

Title: How to handle timezone for dates?

Body:
With a YYYY-MM-DD HH:MM:SS date I always store the UTC time. When I pull to display I translate timezones with built-in PHP functions and classes.

I believe that is one correct way to do it and it makes sense to me.

May I handle YYYY-MM-DD the same way?