问:
EAV - is it really bad in all scenarios?
I'm thinking to use an entity-attribute-value (EAV) model for some of the stuff in one of the projects, but all questions about it in Stack Overflow end up to answers calling EAV an anti-pattern.

But I'm wondering if it is that wrong in all cases.

Let's say shop product entity, it has common features, such as name, description, image, and price, that take part in logic many places and has (semi)unique features, like watch and beach ball would be described by completely different aspects. So I think EAV would fit for storing those (semi)unique features.

All this is assuming, that for showing product list, it is enough info in product table (that means no EAV is involved) and just when showing one product/comparing up to 5 products/etc. data saved using EAV is used.

I've seen such approach in Magento commerce and it is quite popular, so are there cases when EAV is reasonable?

答:
Let's say shop product entity, it has common features, like name, description, image, price, etc., that take part in logic many places and has (semi)unique features, like watch and beach ball would be described by completely different aspects. So I think EAV would fit for storing those (semi)unique features?

Using an EAV structure for has several implications that are trade offs.

You are trading off a 'less space for the row because you don't have 100 columns that are null' against 'more complex queries and model'.

Having an EAV typically means the value is a string that one can stuff any data into.  This then has implications on validity and constraint checking.  Consider the situation where you've put the number of batteries used as something in the EAV table.  You want to find a flashlight that uses C sized batteries, but less than 4 of them.

select P.sku
from
  products P
  attrib Ab on (P.sku = Ab.sku and Ab.key = "batteries")
  attrib Ac on (P.sku = Ac.sku and Ac.key = "count")
where
  cast(Ac.value as int) < 4
  and Ab.value = 'C'
  ...
```

<p>The thing to realize here is that you can't use an index reasonably on the value. You also can't prevent someone from putting in something that isn't an integer there, or an invalid integer (uses '-1' batteries) because the value column is used again and again for different purposes.</p>

<p>This then has implications in trying to write a model for the product.  You'll have the nice typed values... but you're also going to have a <code>Map<String,String></code> just sitting there with all sorts of <em>stuff</em> in it.  This then has further implications when serializing it to XML or Json and the complexities of trying to do validation or queries against <em>those</em> structures.</p>

<p>Some alternatives or modifications to the pattern to consider is instead of a free form key, to have another table with valid keys.  It means instead of doing string comparisons in the database, you are checking against the equality of foreign key ids. Changing the key itself is done in one spot.  You've got a known set of keys which means that they can be done as an enum.</p>

<p>You could also have related tables that contain attributes of a specific class of product.  A grocery department could have another table that has several attributes associated with it that the building materials doesn't need (and vice versa).</p>

```+----------+    +--------+    +---------+
|Grocery   |    |Product |    |BuildMat |
|id (fk)   +--->|id (pk) |<---+id (fk)  |
|expiration|    |desc    |    |material |
|...       |    |img     |    |...      |
+----------+    |price   |    +---------+
                |...     |
                +--------+
```

There are times that especially call for a EAV table.

Consider the situation where you aren't just writing a inventory system for your company where you know every product and every attribute.  You are now writing an inventory system to sell to other companies.  You can't know every attribute of every product - they will need to define them.

One idea that comes out is "we'll let the customer modify the table" and this is just bad (you get into meta-programming for table structures because you no longer know what is where, they can royally mess up the structure or corrupt the application, they've got the access to do wrong things and the implications of that access become significant).  There's more about this path at MVC4 : How to create model at run time?

Instead, you create the administrative interface to an EAV table and allow that to be used.  If the customer wants to create an entry for 'polkadots' it goes into the EAV table and you already know how to deal with that.

An example of this can be seen in the database model for Redmine you can see the custom_fields table, and the custom_values table -- those are parts of the EAV that allows the system to be extended.

Note that if you find your entire table structure to look like EAV rather than relational, you might want to look at the KV flavor of NoSQL (cassandra, redis, Mongo,. ...).  Realize that these often come with other tradeoffs in their design that may or may not be appropriate to what you are using it for.  However, they are specifically designed with the intent of an EAV structure.

You may wish to read SQL vs NoSQL for an inventory management system

Following this approach with a document oriented NoSQL database (couch, mongo), you could consider each inventory item to be a document on a disk... pulling up everything in a single document is fast.  Furthermore, the document is structured so that you can pull out any one single thing fast.  On the other hand, searching all the documents for things that match a particular attribute can have less performance (compare using 'grep' against all the files)... its all a trade off.

Another approach would be LDAP where one would have a base with all of its associated items, but would then also have additional object classes applied to it for the other types of items. (see System Inventory Using LDAP)

Once you go down this path, you may find something that exactly matches what you are looking for... though everything comes with some tradeoffs.

Body:
Let's say shop product entity, it has common features, like name, description, image, price, etc., that take part in logic many places and has (semi)unique features, like watch and beach ball would be described by completely different aspects. So I think EAV would fit for storing those (semi)unique features?

Using an EAV structure for has several implications that are trade offs.

You are trading off a 'less space for the row because you don't have 100 columns that are null' against 'more complex queries and model'.

Having an EAV typically means the value is a string that one can stuff any data into.  This then has implications on validity and constraint checking.  Consider the situation where you've put the number of batteries used as something in the EAV table.  You want to find a flashlight that uses C sized batteries, but less than 4 of them.

select P.sku
from
  products P
  attrib Ab on (P.sku = Ab.sku and Ab.key = "batteries")
  attrib Ac on (P.sku = Ac.sku and Ac.key = "count")
where
  cast(Ac.value as int) < 4
  and Ab.value = 'C'
  ...

The thing to realize here is that you can't use an index reasonably on the value. You also can't prevent someone from putting in something that isn't an integer there, or an invalid integer (uses '-1' batteries) because the value column is used again and again for different purposes.

This then has implications in trying to write a model for the product.  You'll have the nice typed values... but you're also going to have a Map<String,String> just sitting there with all sorts of stuff in it.  This then has further implications when serializing it to XML or Json and the complexities of trying to do validation or queries against those structures.

Some alternatives or modifications to the pattern to consider is instead of a free form key, to have another table with valid keys.  It means instead of doing string comparisons in the database, you are checking against the equality of foreign key ids. Changing the key itself is done in one spot.  You've got a known set of keys which means that they can be done as an enum.

You could also have related tables that contain attributes of a specific class of product.  A grocery department could have another table that has several attributes associated with it that the building materials doesn't need (and vice versa).

+----------+    +--------+    +---------+
|Grocery   |    |Product |    |BuildMat |
|id (fk)   +--->|id (pk) |<---+id (fk)  |
|expiration|    |desc    |    |material |
|...       |    |img     |    |...      |
+----------+    |price   |    +---------+
                |...     |
                +--------+

There are times that especially call for a EAV table.

Consider the situation where you aren't just writing a inventory system for your company where you know every product and every attribute.  You are now writing an inventory system to sell to other companies.  You can't know every attribute of every product - they will need to define them.

One idea that comes out is "we'll let the customer modify the table" and this is just bad (you get into meta-programming for table structures because you no longer know what is where, they can royally mess up the structure or corrupt the application, they've got the access to do wrong things and the implications of that access become significant).  There's more about this path at MVC4 : How to create model at run time?

Instead, you create the administrative interface to an EAV table and allow that to be used.  If the customer wants to create an entry for 'polkadots' it goes into the EAV table and you already know how to deal with that.

An example of this can be seen in the database model for Redmine you can see the custom_fields table, and the custom_values table -- those are parts of the EAV that allows the system to be extended.

Note that if you find your entire table structure to look like EAV rather than relational, you might want to look at the KV flavor of NoSQL (cassandra, redis, Mongo,. ...).  Realize that these often come with other tradeoffs in their design that may or may not be appropriate to what you are using it for.  However, they are specifically designed with the intent of an EAV structure.

You may wish to read SQL vs NoSQL for an inventory management system

Following this approach with a document oriented NoSQL database (couch, mongo), you could consider each inventory item to be a document on a disk... pulling up everything in a single document is fast.  Furthermore, the document is structured so that you can pull out any one single thing fast.  On the other hand, searching all the documents for things that match a particular attribute can have less performance (compare using 'grep' against all the files)... its all a trade off.

Another approach would be LDAP where one would have a base with all of its associated items, but would then also have additional object classes applied to it for the other types of items. (see System Inventory Using LDAP)

Once you go down this path, you may find something that exactly matches what you are looking for... though everything comes with some tradeoffs.


问:
Does it make sense to write tests for legacy code when there is no time for a complete refactoring?
I usually try to follow the advice of the book Working Effectively with Legacy Code. I break dependencies, move parts of the code to @VisibleForTesting public static methods and to new classes to make the code (or at least some part of it) testable. And I write tests to make sure that I don't break anything when I'm modifying or adding new functions.

A colleague says that I shouldn't do this. His reasoning:

The original code might not work properly in the first place. And writing tests for it makes future fixes and modifications harder since devs have to understand and modify the tests too.

If it's GUI code with some logic (~12 lines, 2-3 if/else block, for example), a test isn't worth the trouble since the code is too trivial to begin with.

Similar bad patterns could exist in other parts of the codebase, too (which I haven't seen yet, I'm rather new); it will be easier to clean them all up in one big refactoring. Extracting out logic could undermine this future possibility.

Should I avoid extracting out testable parts and writing tests if we don't have time for complete refactoring? Is there any disadvantage to this that I should consider?

答:
If you're dealing with large amounts of legacy code that isn't currently under test, getting test coverage now instead of waiting for a hypothetical big rewrite in the future is the right move.  Starting by writing unit tests is not.

Without automated testing, after making any changes to the code you need to do some manual end to end testing of the app to make sure it's working.  Start by writing high level integration tests to replace that.  If your app reads files in, validates them, processes the data in some fashion, and displays the results you want tests that capture all of that.

Ideally you'll either have data from a manual test plan or be able to get a sample of actual production data to use.  If not, since the app's in production, in most cases it's doing what it should be, so just make up data that will hit all the high points and assume the output is correct for now.  It's no worse than taking a small function, assuming it's doing what it's name or any comments suggest it should be doing, and writing tests assuming it's working correctly.

```<code>IntegrationTestCase1()
{
    var input = ReadDataFile("path\to\test\data\case1in.ext");
    bool validInput = ValidateData(input);
    Assert.IsTrue(validInput);

    var processedData = ProcessData(input);
    Assert.AreEqual(0, processedData.Errors.Count);

    bool writeError = WriteFile(processedData, "temp\file.ext");
    Assert.IsFalse(writeError);

    bool filesAreEqual = CompareFiles("temp\file.ext", "path\to\test\data\case1out.ext");
    Assert.IsTrue(filesAreEqual);
}
</code>```

Once you've got enough of these high level tests written to capture the apps normal operation and most common error cases the amount of time you'll need to spend pounding on the keyboard to try and catch errors from the code doing something other than what you thought it was supposed to do will go down significantly making future refactoring (or even a big rewrite) much easier.

As you're able to expand unit test coverage you can pare down or even retire most of the integration tests.  If your app's reading/writing files or accessing a DB, testing those parts in isolation and either mocking them out or having your tests begin by creating the data structures read from the file/database are an obvious place to start.  Actually creating that testing infrastructure will take a lot longer than writing a set of quick and dirty tests; and every time you run a 2 minute set of integration tests instead of spending 30 minutes manually testing a fraction of what the integration tests covered you're already making a big win.

ContentLicense: CC BY-SA 3.0

Body:
If you're dealing with large amounts of legacy code that isn't currently under test, getting test coverage now instead of waiting for a hypothetical big rewrite in the future is the right move.  Starting by writing unit tests is not.

Without automated testing, after making any changes to the code you need to do some manual end to end testing of the app to make sure it's working.  Start by writing high level integration tests to replace that.  If your app reads files in, validates them, processes the data in some fashion, and displays the results you want tests that capture all of that.

Ideally you'll either have data from a manual test plan or be able to get a sample of actual production data to use.  If not, since the app's in production, in most cases it's doing what it should be, so just make up data that will hit all the high points and assume the output is correct for now.  It's no worse than taking a small function, assuming it's doing what it's name or any comments suggest it should be doing, and writing tests assuming it's working correctly.

IntegrationTestCase1()
{
    var input = ReadDataFile("path\to\test\data\case1in.ext");
    bool validInput = ValidateData(input);
    Assert.IsTrue(validInput);

    var processedData = ProcessData(input);
    Assert.AreEqual(0, processedData.Errors.Count);

    bool writeError = WriteFile(processedData, "temp\file.ext");
    Assert.IsFalse(writeError);

    bool filesAreEqual = CompareFiles("temp\file.ext", "path\to\test\data\case1out.ext");
    Assert.IsTrue(filesAreEqual);
}

Once you've got enough of these high level tests written to capture the apps normal operation and most common error cases the amount of time you'll need to spend pounding on the keyboard to try and catch errors from the code doing something other than what you thought it was supposed to do will go down significantly making future refactoring (or even a big rewrite) much easier.

As you're able to expand unit test coverage you can pare down or even retire most of the integration tests.  If your app's reading/writing files or accessing a DB, testing those parts in isolation and either mocking them out or having your tests begin by creating the data structures read from the file/database are an obvious place to start.  Actually creating that testing infrastructure will take a lot longer than writing a set of quick and dirty tests; and every time you run a 2 minute set of integration tests instead of spending 30 minutes manually testing a fraction of what the integration tests covered you're already making a big win.


问:
How can we make agile enjoyable for developers that like to personally, independently own large chunks from start to finish
We’re roughly midway through our transition from waterfall to agile using scrum; we’ve changed from large teams in technology/discipline silos to smaller cross-functional teams.

As expected, the change to agile doesn’t suit everyone. There are a handful of developers that are having a difficult time adjusting to agile. I really want to keep them engaged and challenged, and ultimately enjoying coming to work each day. These are smart, happy, motivated people that I respect on both a personal and a professional level.

The basic issue is this: Some developers are primarily motivated by the joy of taking a piece of difficult work, thinking through a design, thinking through potential issues, then solving the problem piece by piece, with only minimal interaction with others, over an extended period of time. They generally complete work to a high level of quality and in a timely way; their work is maintainable and fits with the overall architecture. Transitioning to a cross-functional team that values interaction and shared responsibility for work, and delivery of working functionality within shorter intervals, the teams evolve such that the entire team knocks that difficult problem over. Many people find this to be a positive change; someone that loves to take a problem and own it independently from start to finish loses the opportunity for work like that.

This is not an issue with people being open to change. Certainly we’ve seen a few people that don’t like change, but in the cases I’m concerned about, the individuals are good performers, genuinely open to change, they make an effort, they see how the rest of the team is changing and they want to fit in. It’s not a case of someone being difficult or obstructionist, or wanting to hoard the juiciest work. They just don’t find joy in work like they used to.

I’m sure we can’t be the only place that hasn’t bumped up on this. How have others approached this? If you’re a developer that is motivated by personally owning a big chunk of work from end to end, and you’ve adjusted to a different way of working, what did it for you?

答:
I will try to illustrate some aspects that have not been addressed by other answers and that, IMO, are important.

The basic issue is this: Some developers are primarily motivated by the joy of taking a piece of difficult work, thinking through a design, thinking through potential issues, then solving the problem piece by piece, with only minimal interaction with others, over an extended period of time. They generally complete work to a high level of quality and in a timely way; their work is maintainable and fits with the overall architecture.

This kind of developers may find it difficult to adapt to an agile environment and their attitude is often dismissed as "unwillingness to change", possibly related to ego or to being old-fashioned.

What is often ignored is that in order to solve complex problems one needs to handle a lot of information, and that this may need a lot of analysis, thinking, trying, sketching a solution, throwing it away, trying another one.
Such a complex problem may require from a few hours to a few weeks of focused work until you have a finished solution.

One approach is that a developer takes the problem specification, goes to her room, and comes back two / three weeks later with a solution. At any time (when needed), the developer can initiate some interaction with other members of the team or with stakeholders (asking questions on specific issues) but most
of the work gets done by the developer who is assigned the task.

What happens in an agile scenario? The team breaks up the problem into small chunks (user stories) after a quick analysis (grooming). The hope is that the user stories are independent from each other but often this is not the case: in order to break up a complex problem into really independent chunks you would need a knowledge that you normally only get after working on it for several days.
In other words, if you are able to break up a complex problem into small independent parts, it means you have basically solved it already and that you only have diligence work left. For a problem that requires, say, three weeks work, this will probably be the case during the second week, not after a couple of hours grooming done at the very beginning of the sprint.

So, after a sprint has been planned, the team works on different chunks of a problem that have probably dependences between each other. This generates a lot of communication overhead trying to integrate different solutions that may be equally good but are, well, different from each other. Basically, the trial-and-error work is distributed over all the team members involved, with an additional communication overhead (increasing quadratically).
I think some of these problems are illustrated very well in this article by Paul Graham, in particular point 7.

Of course, sharing the work between team members reduces the risk related to one team member leaving the project. On the other hand, knowledge about the code can be communicated in other ways, e.g. using code reviews or giving technical presentations to the colleagues. In this respect, I do not think there is a silver bullet valid for all situations: shared code ownership and pair programming are not the only option.

Furthermore, "delivery of working functionality within shorter intervals" results in an interruption of the work flow. This may be OK if the chunk of functionality is "add a cancel button in the login page" that can be completed by the end of a sprint, but when you are working on a complex task you do not want such interruptions: it is like trying to drive a car 100 km as fast as you can and stopping every 5 minutes to check how far you have gotten. This is only going to slow you down.

Of course, having frequent checkpoints is meant to make a project more predictable, but in some cases the interruption can be very frustrating: one can barely gain speed that it is already time to stop and present something.

So, I do not think that the attitude described in the question is related only to ego or resistance to change. It can also be that some developers consider the approach to problem-solving described above more effective because it allows them to have a better understanding of the problems they are solving and of the code they are writing. Forcing such developers to work in a different way can result in cutting down their productivity.

Also, I do not think that having some members of the team work in isolation on specific, difficult problems is against agile values. After all, teams should be self-organizing and use the process that they have found to be the most effective over the years.

Just my 2 cents.

OwnerDisplayName: Kris


问:
Are there theoretical reasons why arrays in C take less RAM than Java?
My experience is that Java requires about twice as much RAM compared to C (comparing char arrays or other comparisons). I also read in a hardware book that Java takes about twice RAM than C. Is is based solely on empirical evidence or also has a theoretical explanation? Is there a theoretical limit that limits Java from minimizing its memory usage?</p>

答:
Typically they don't (I know, I know) as an array of primitive types are allocated in the same way as C arrays - contiguous blocks of memory for each item. However, an array of objects is a bit different as you get an array of pointers that reference the java objects. C would allocate a contiguous block of memory to hold the actual objects.

A char in Java is 2 bytes though, maybe this is what you're noticing (or if you end up with wrappered types - a char that is retrieved from a JDK method might require wrapping in which case it takes up 16 bytes), or maybe you're noticing that Java arrays take up 12 bytes just to get started, and then are rounded off to the nearest memory alignment block (ie 8 bytes)

See an overview of memory saving techniques in Java.

16 bytes per char in Java if you're not very careful.. ouch.


问:
Correct process for creating builds reliant on 3rd party packages
I work on a Symfony 2 codebase.

We use a number of third-party packages (most are in the Symfony Standard Edition).

We use composer for dependencies.

We current have all of our third-party code committed in our repository (after changing .gitignore files) to ensure stability.

According to Proper Programming Practices™, we are not supposed to have any third-party packages in our repo.  We are supposed to pull them down and include them at build time.

How are we to do proper QA and debugging when at any given time our dependencies could push an update that breaks functionality?

答:
I don't know who told you to pull them at build time, but that person is, perhaps, not in your industry. Pulling at build time means every build is susceptible to upstream changes breaking things in your code. That's BAD.

You need to be keeping a close eye on those upstream repos and pull them frequently when they change (you don't want to get too far behind), but grabbing latest every build? No thank you.

I would recommend doing exactly what you are doing, with the addition that it needs to be someone's job to watch the packages you use and pull changes in as soon as feasible.


问:
In which object should I implement wait()/notify()?
I'm working in an Android project with multithreading. Basically I have to wait to the server to respond before sending more data.

The data sending task is delimited by the flag boolean hasServerResponded so the Thread will loop infinitely without doing anything until the flag becomes true.

Since this boolean isn't declared as volatile (yet), and also looping without doing anything  wastes resources, I thought maybe I should use AtomicBoolean and also implement wait() / notify() mechanism.

Should I use the AtomicBoolean object notify() and wait() methods or should I create a lock Object?

答: IMO, working with low level wait/notify is bug prone and usually a poor idea.  Java has wonderful higher level concurrency constructs.  In this example, use a Queue.</p>

OwnerDisplayName: Christopher Francisco


问:
Javascript: Machine Constants Applicable?
I write numerical routines for students of science and engineering (although they are freely available for use by anybody else as well) and am wondering how to properly use machine constants in a JavaScript program, or if they are even applicable.

For example, say I am writing a program in C++ that numerically computes the roots of the following equation:

exp(-0.7x) + sin(3x) - 1.2x + 0.3546 = 0

A root-finding routine should be able to compute roots to within the machine epsilon. In C++, this value is specified by the language: DBL_EPSILON. C++ also specifies the smallest and largest values that can be held by a float or double variable.

However, how does this convert to JavaScript? Since a Javascript program runs in a web browser, and I don't know what kind of computer will run the program, and JavaScript does not have corresponding predefined values for these quantities, how can I implement my own version of these constants so that my programs compute results to as much accuracy as allowed on the computer running the web browser?

My first draft is to simply copy over the literal constants from C++:

FLT_MIN:  1.17549435082229e-038

FLT_MAX:  3.40282346638529e+038

DBL_EPSILON: 2.2204460492503131e-16

I am also willing to write small code blocks that could compute these values for each machine on which the program is run. That way, a supercomputer might compute results to a higher accuracy than an old, low-level, PC.

BUT, I don't know if such a routine would actually reach the computer, in which case, I would be wasting my time.

Anybody here know how to compute and use (in Javascript) values that correspond to machine constants in a compiled language?

Is it worth my time to write small programs in Javascript that compute DBL_EPSILON, FLT_MIN, FLT_MIN, etc. for use in numerical routines?
Or am I better off simply assigning literal constants that come straight from C++ on a standard Windows PC?

答:
The issue is actually the opposite of what you state. C++ is the language where you can't depend on particular values for those metrics because floating point implementations vary while JavaScript mandates 64-bit floating point values based on IEEE 754.

Very few people do this sort of work in JavaScript, so I doubt you'll find anything that helps you that's directly tied to the language, but metrics for 64-bit floating point using IEEE 754 can be found on wikipedia.


问:
How can you predict the time it will take for two processes in two different machines in a cluster to communicate?
I am trying to develop a computing application which needs a lot of memory (>500gb). Buying a single machine for that is overly expensive. I can, though, buy ~100 small instances on Digital Ocean or similar, divide the memory in blocks and use TCP to emulate shared memory between the instances.

Now, my question is: how can I measure/predict the time it will take for two processes in two different machines like that to share information, in comparison to IPC and shared memory? Are there rules of thumb? I don't want exact values, but knowing more or less how much faster one is would be very helpful in visualising the feasibility of this approach.

答:
This sounds weird, the network IO lag would erase most of the benefit of in memory data accessing on individual machine. I would wonder if your approach would even be faster than buying a single machine with lot of SSDs to run as virtual memory, or even machine running on virtual memory using regular HDD.

Secondly, you have to redesign your logic before you turn your system into a distributed system. You cannot split one big one into smaller ones and then make these smaller ones so tightly coupled via network. The coupling and sharing should happen only on the end results (or special intermediate results that are complete enough to stay on the file system). Not results so intermediate and temporary that they stay (or can stay) in memory.


答: If you are not using the volatile yet and to get atomic features it is OK to use AtomicBoolean. And if you are using AtomicBoolean it is better to use its own methods and it may give you some sort of a performance advantage. </p>

Title: In which object should I implement wait()/notify()?

Body:
I'm working in an Android project with multithreading. Basically I have to wait to the server to respond before sending more data.

The data sending task is delimited by the flag boolean hasServerResponded so the Thread will loop infinitely without doing anything until the flag becomes true.

Since this boolean isn't declared as volatile (yet), and also looping without doing anything  wastes resources, I thought maybe I should use AtomicBoolean and also implement wait() / notify() mechanism.

Should I use the AtomicBoolean object notify() and wait() methods or should I create a lock Object?


问:
Why Beta versions have so many bugs?
When I worked in Microsoft on MSE antivirus, we had several stages of pre-release: Alpha, Beta, RC. The biggest difference between these stages were bug fixes. Each time we fixed more bugs, and usually updated some minor features.

Apple works in the same way. Look here:
http://www.techrepublic.com/article/pro-tip-how-to-create-a-bootable-usb-installer-for-os-x-yosemite/

They released a beta of Yosemite OS, but the beta is full of bugs.

Why do these big companies work like this? Isn't it better to release a beta version that was tested very thoroughly but one that just doesn't provide all the features that the final version will provide?

答:
bugs are found and not pre-known

Having one phase doesn't help much with enhancing the code base, you can't figure out all the bugs in one phase.

Having multiple phases let the organization reorder its priorities, gets feedback from the users and enhance the code accordingly. Priorities change with testing, developer discussions, and code base mature with each phase, if you only want one phase this means that you have to deliver without any feedback, you might be focusing in one area before finding out that you were doing it totally wrong, and because bugs are found, some parts of the application might be more buggy than others, again it helps you figure it out.

From a project management point of view, this helps set milestones for the project and managing the project resources..

Title: Why Beta versions have so many bugs?


问:
Multiuser's impact on Access Database
Can someone explain to me how are effected the performances of an Access 2003 DB when it's used by a lot (30) of users on the same LAN?

I'm working on a vb6 project with this access 2003 DB wich performs ok on my local PC, but it's terrible when used across 20-30 users.

It's there something I can do to improve performance? How can I understand what's the cause of this degradation in performance?

答:
Main problem of a shared Access database is that each client is modifying the physical database file(s) directly. That means for example that when one of the clients wants to update record, it must make a lock on that record - writes that information into a file (slow operation, particularly when its done over network) for other clients to acknowledge it, writes the change and releases the lock (another disk operations over a network). Whreas when this operation is done on databases like SQL Server, only commands are sent by clients over the network, and the database system in question handles the operation - and it is WAY faster because on its end all operations are made directly, not over network and can be far better optimized (eg. locks/records stored in memory).

What you can do to improve performance:
1) move the database to SQL Server if it is possible - really, you save yourself alot of trouble
2) the faster the network it runs on is, the better - for 30 clients 1000Mbps is a must (it also depends on database size)
3) if any client accesses the database over WiFi its BAD - it slows the database down, and risk of database file corruption increases alot - again; the bigger database file, the worse
4) index for performance
5) do "Compact and repair database" often - at least once overy month on databases >100MB

Title: Multiuser's impact on Access Database


问:
How do you show the exception handler in a class diagram?
I have one exception handler class. I want to show this class in the uml -- class diagram. But, I do not know how to represent relationship between class <X> and exception handler class. How can I represent relationship between class in class diagram?

答:
From what I've seen, stereotype is usually used to represent the relationship to an exception.

a better approach would be to use UML’s stereotype notation with the keyword exception as the stereotype enclosed in guillemets, as in «exception».

Source: How can I represent an exception in UML?

This answer on Stack Overflow also suggests stereotypes, but uses <<throws>> instead. The author is confident that it's ok to use a stereotype which doesn't exist conventionally, and in this particular case, I agree with him.

As for the proper term, given that a stereotype can be a noun or a verb, both <<exception>> and <<throws>> seem equally correct. The proper terminology also depends on the language you use. For example in Python, you don't throw, but raise an error or an exception, so <<raises>> looks as the most appropriate one; unless your intention is to separate errors and exceptions, in which case <<exception>> and <<error>> may be more expressive.

Finally, Agile Modeling suggests (search for Figure 4) to embed the name of the exception like this:

```<code>+ findAllInstances(): Vector {exceptions=NetworkFailure, DatabaseError}
</code>```

but IMO, while it's well suited for well-known exceptions used by the framework, it is too poor for custom exceptions you have created, because the relation is not visual enough.

Body:
From what I've seen, stereotype is usually used to represent the relationship to an exception.

a better approach would be to use UML’s stereotype notation with the keyword exception as the stereotype enclosed in guillemets, as in «exception».

Source: How can I represent an exception in UML?

This answer on Stack Overflow also suggests stereotypes, but uses <<throws>> instead. The author is confident that it's ok to use a stereotype which doesn't exist conventionally, and in this particular case, I agree with him.

As for the proper term, given that a stereotype can be a noun or a verb, both <<exception>> and <<throws>> seem equally correct. The proper terminology also depends on the language you use. For example in Python, you don't throw, but raise an error or an exception, so <<raises>> looks as the most appropriate one; unless your intention is to separate errors and exceptions, in which case <<exception>> and <<error>> may be more expressive.

Finally, Agile Modeling suggests (search for Figure 4) to embed the name of the exception like this:

+ findAllInstances(): Vector {exceptions=NetworkFailure, DatabaseError}

but IMO, while it's well suited for well-known exceptions used by the framework, it is too poor for custom exceptions you have created, because the relation is not visual enough.


问:
Is there an easy way to type in common math symbols?
Disclaimer: I'm sure someone is going to moan about easy-of-use, for the purpose of this question consider readability to be the only factor that matters

So I found this site that converts to easting northing, it's not really important what that even means but here's how the piece of javascript looks.

```<code>/**
 * Convert Ordnance Survey grid reference easting/northing coordinate to (OSGB36) latitude/longitude
 *
 * @param   {OsGridRef} gridref - easting/northing to be converted to latitude/longitude
 * @returns {LatLonE} latitude/longitude (in OSGB36) of supplied grid reference
 */
OsGridRef.osGridToLatLong = function(gridref) {
    var E = gridref.easting;
    var N = gridref.northing;

    var a = 6377563.396, b = 6356256.909;         // Airy 1830 major & minor semi-axes
    var F0 = 0.9996012717;                        // NatGrid scale factor on central meridian
    var φ0 = 49*Math.PI/180, λ0 = -2*Math.PI/180; // NatGrid true origin
    var N0 = -100000, E0 = 400000;                // northing & easting of true origin, metres
    var e2 = 1 - (b*b)/(a*a);                     // eccentricity squared
    var n = (a-b)/(a+b), n2 = n*n, n3 = n*n*n;    // n, n², n³

    var φ=φ0, M=0;
    do {
        φ = (N-N0-M)/(a*F0) + φ;

        var Ma = (1 + n + (5/4)*n2 + (5/4)*n3) * (φ-φ0);
        var Mb = (3*n + 3*n*n + (21/8)*n3) * Math.sin(φ-φ0) * Math.cos(φ+φ0);
        var Mc = ((15/8)*n2 + (15/8)*n3) * Math.sin(2*(φ-φ0)) * Math.cos(2*(φ+φ0));
        var Md = (35/24)*n3 * Math.sin(3*(φ-φ0)) * Math.cos(3*(φ+φ0));
        M = b * F0 * (Ma - Mb + Mc - Md);              // meridional arc

    } while (N-N0-M >= 0.00001);  // ie until < 0.01mm

    var cosφ = Math.cos(φ), sinφ = Math.sin(φ);
    var ν = a*F0/Math.sqrt(1-e2*sinφ*sinφ);            // nu = transverse radius of curvature
    var ρ = a*F0*(1-e2)/Math.pow(1-e2*sinφ*sinφ, 1.5); // rho = meridional radius of curvature
    var η2 = ν/ρ-1;                                    // eta = ?

    var tanφ = Math.tan(φ);
    var tan2φ = tanφ*tanφ, tan4φ = tan2φ*tan2φ, tan6φ = tan4φ*tan2φ;
    var secφ = 1/cosφ;
    var ν3 = ν*ν*ν, ν5 = ν3*ν*ν, ν7 = ν5*ν*ν;
    var VII = tanφ/(2*ρ*ν);
    var VIII = tanφ/(24*ρ*ν3)*(5+3*tan2φ+η2-9*tan2φ*η2);
    var IX = tanφ/(720*ρ*ν5)*(61+90*tan2φ+45*tan4φ);
    var X = secφ/ν;
    var XI = secφ/(6*ν3)*(ν/ρ+2*tan2φ);
    var XII = secφ/(120*ν5)*(5+28*tan2φ+24*tan4φ);
    var XIIA = secφ/(5040*ν7)*(61+662*tan2φ+1320*tan4φ+720*tan6φ);

    var dE = (E-E0), dE2 = dE*dE, dE3 = dE2*dE, dE4 = dE2*dE2, dE5 = dE3*dE2, dE6 = dE4*dE2, dE7 = dE5*dE2;
    φ = φ - VII*dE2 + VIII*dE4 - IX*dE6;
    var λ = λ0 + X*dE - XI*dE3 + XII*dE5 - XIIA*dE7;

    return new LatLonE(φ.toDegrees(), λ.toDegrees(), GeoParams.datum.OSGB36);
}
</code>```

I found that to be a really nice way of writing an algorythm, at least as far as redability is concerned. Is there any way to easily write the special symbols. And by easily write I mean NOT copy/paste them.

答:
I thought what a funny question until I realized that you want to make use of the fact that some languages allow more than the plain ASCII characters in their identifiers and go towards a notation that fits the problem domain more, like in intentional programming. Here the problem domain being geometry.

The answer to your question depends on your environment.
I suppose you want to enter Unicode charcters.
On a windows machine you would use a different tool than on an iPhone or Mac or X11 machine.
Most of these systems feature some kind of extended keyboard application.

In general I think the advantage of improved understanding would be not worth the hassle to edit these lines using this primitive method.

But that changes if the system is well done:

In fact I enjoy the MathJax editor on math.stackexchange very much which allows me to enter and view LaTeX mathematical formulas in an acceptable way.

I would love to hove something like this in my general programming environments Emacs (alas that would need one better integrated with the GUI) and the JetBrains IDEs.

I still believe in Knuth's literate programming.
But all this is not well integrated in real world / industry environments yet, sadly.

Thanks for your question because it made me revisiting intentional programming and there I noted that intentional has released (see above Fowler link) and that there is a DSL IDE from JetBrains: Meta Programming System!


问:
High-level strategy for distinguishing a regular string from invalid JSON (ie. JSON-like string detection)
Disclaimer On Absence of Code:

I have no code to post because I haven't started writing; was looking for more theoretical guidance as I doubt I'll have trouble coding it but am pretty befuddled on what approach(es) would yield best results. I'm not seeking any code, either, though; just direction.

Dilemma

I'm toying with adding a "magic method"-style feature to a UI I'm building for a client, and it would require intelligently detecting whether or not a string was meant to be JSON as against a simple string.

I had considered these general ideas:

Look for a sort of arbitrarily-determined acceptable ratio of the frequency of JSON-like syntax (ie. regex to find strings separated by colons; look for colons between curly-braces, etc.) to the number of quote-encapsulated strings + nulls, bools and ints/floats. But the smaller the data set, the more fickle this would get

look for key identifiers like opening and closing curly braces... not sure if there even are more easy identifiers, and this doesn't appeal anyway because it's so prescriptive about the kinds of mistakes it could find

try incrementally parsing chunks, as those between curly braces, and seeing what proportion of these fractional statements turn out to be valid JSON; this seems like it would suffer less than (1) from smaller datasets, but would probably be much more processing-intensive, and very susceptible to a missing or inverted brace

Just curious if the computational folks or algorithm pros out there had any approaches in mind that my semantics-oriented brain might have missed.

PS: It occurs to me that natural language processing, about which I am totally ignorant, might be a cool approach; but, if NLP is a good strategy here, it sort of doesn't matter because I have zero experience with it and don't have time to learn & then implement/ this feature isn't worth it to the client.

答:
So what you want is a JSON sniffer. Something to look at a string and make a heuristic guess. So what to look for and how to look?

First off, a JSON parser is pretty useless. You call that after you've guess it's probably JSON.

I can think of three approaches.

Smoking gun. If the string has JSON or json-schema.org in it, that's a match. Maybe there are some other common words you might know of.

Regex it. Think up some regexes that would be highly likely to be matched. If over half the lines match one or more suitable regexes it's a match.

Tokenise it. JSON typically has lots of individual quoted strings, numbers, commas, brackets, braces and colons. Any string that is over 50% made up of those tokens is a match. (Make sure you don't let an unmatched quote swallow the whole string.)

Your suggestions could work too, but I think mine are simpler.

I've used sniffing code in the past and it's surprisingly easy to get it right most of the time. The mistakes are usually when you get (say) a text message with a piece of JSON quoted in it. You can't win them all.

OwnerDisplayName: Jonline


答:
Why do big companies work this way?

Because by the nature of their size, they also have big install bases. Part of the purpose of releasing a Beta product is to test on real-world combinations of hardware/software that the company could not do internally. There are simply too many combinations to simulate everything in-house. So after Alpha, some of the mid-cycle testing is outsourced to the end-user.

Release Candidates are when everything all comes together, thorough testing and reasonably complete feature set. You are putting too much expectation on Beta products. Beta is still very much representative of a product in active development, full of bugs, missing features, etc.

Title: Why Beta versions have so many bugs?

Body:
When I worked in Microsoft on MSE antivirus, we had several stages of pre-release: Alpha, Beta, RC. The biggest difference between these stages were bug fixes. Each time we fixed more bugs, and usually updated some minor features.

Apple works in the same way. Look here:
http://www.techrepublic.com/article/pro-tip-how-to-create-a-bootable-usb-installer-for-os-x-yosemite/

They released a beta of Yosemite OS, but the beta is full of bugs.

Why do these big companies work like this? Isn't it better to release a beta version that was tested very thoroughly but one that just doesn't provide all the features that the final version will provide?


答:
First-order rough-order-of-magnitude analysis is the first step.

It takes (nominally) one instruction to access one word of local memory.  Assuming it takes 1000 instructions to format the TCP/IP packet and queue it for transmission, and another 1000 instructions at the far end to receive, dequeue, and interpret it, and realizing that an "access" requires two packets to go, one in each direction, you're talking a minimum of 4000 instructions per access.

At that point, your 4 GHz Intel screamer is, on non-local accesses, performing about like a 4 MHz 8086.

That's before you consider network overhead.  Assuming 100 physical machines ("instances"), assuming 16-port routers, you need 8 routers: one at the center of a star, connected to the other seven, with each of those connected to about 16 machines.  Assuming that non-local accesses are uniformly distributed, each non-local access will take three router hops: one to the local router, one to the star center, one back down to a local router.  (Because you assume uniform distribution, only about 1/7 of your accesses will be to a machine sharing your local router.  For a first-order analysis, you can ignore that lucky break.)  Because you have to go there and back, you're talking 6 router hops and 4000 instructions, NOT INCLUDING ROUTER OPERATIONS, to do one non-local access.

First-order rough-order-of-magnitude analysis would seem to indicate that your application will die of old age waiting on packets in the router queues.

Title: How can you predict the time it will take for two processes in two different machines in a cluster to communicate?

Body:
I am trying to develop a computing application which needs a lot of memory (>500gb). Buying a single machine for that is overly expensive. I can, though, buy ~100 small instances on Digital Ocean or similar, divide the memory in blocks and use TCP to emulate shared memory between the instances.

Now, my question is: how can I measure/predict the time it will take for two processes in two different machines like that to share information, in comparison to IPC and shared memory? Are there rules of thumb? I don't want exact values, but knowing more or less how much faster one is would be very helpful in visualising the feasibility of this approach.


问:
Efficient algorithm to find a the set of numbers in a range
If I have an array of sorted numbers and every object is one of the numbers or multiplication. For example if the sorted array is [1, 2, 7] then the set is {1, 2, 7, 1*2, 1*7, 2*7, 1*2*7}. As you can see if there's n numbers in the sorted array, the size of the set is 2n-1.

My question is how can I find for a given sorted array of n numbers all the objects in the set so that the objects is in a given interval. For example if the sorted array is [1, 2, 3 ... 19, 20] what is the most efficient algorithm to find the objects that are larger than 1000 and less than 2500 (without calculating all the 2n-1 objects)?

答:
The brute force solution to this problem should take only seconds on a modern CPU, given that there are only about a million numbers to check. But that would be too easy.

I am assuming that each product contains each integer once only. [You didn't say.]

Allocate a stack of integers. TOS is the top value. P is the product of integers on the stack.

It would be possible to ignore the number 1. It could be trivially added at the end if needed, but why bother? Pseudocode:

```<code>Push 1 on the stack.
Forever do
  If P > 1000 and P < 2500
    Found one: save stack contents
  If TOS == 20
    Pop while TOS == 20
    End if stack is empty
    Increment TOS
  Elsif P >= 2500
    Pop
    Increment TOS
  Else
    Push TOS+1
</code>```

Looks like it should work (assuming I understood the problem correctly.) I leave the code as an exercise.

Body:
The brute force solution to this problem should take only seconds on a modern CPU, given that there are only about a million numbers to check. But that would be too easy.

I am assuming that each product contains each integer once only. [You didn't say.]

Allocate a stack of integers. TOS is the top value. P is the product of integers on the stack.

It would be possible to ignore the number 1. It could be trivially added at the end if needed, but why bother? Pseudocode:

Push 1 on the stack.
Forever do
  If P > 1000 and P < 2500
    Found one: save stack contents
  If TOS == 20
    Pop while TOS == 20
    End if stack is empty
    Increment TOS
  Elsif P >= 2500
    Pop
    Increment TOS
  Else
    Push TOS+1

Looks like it should work (assuming I understood the problem correctly.) I leave the code as an exercise.


问:
license and copyright assignment
I'm currently working on a wordpress plugin. My client gives me a specs doc (a powerpoint presentation, if you can call that a specs doc), and I code the requested functionality.

Every time I send him code every file containing code starts with these lines:

```<code>Author: My Name
Copyright: The_client's_company.com
License: MIT Expat (http://en.wikipedia.org/wiki/Expat_License)
</code>```

My intention being giving my client complete right to relicense and distribute the code under any other license (as the TOS of the freelancing website requires, plus I know he intends to sell it under a proprietary license), but at the same time giving myself the right to expand and redistribute the plugin under MIT license if I wish to (not that I do).

The reason is I am paid only 10USD/hour (this is my first gig) so I want to at least keep the right to reuse parts of the code in other projects or expand it if I want to start a similar project myself when I finish the contract (unlikely, but who knows...) or show it to potential employers. The contract we agreed upon doesn't include any licensing specifications but I've informed him on the emails we've interchanged that although all my work is licensed by default as MIT I'm giving my clients the copyright of the code I produce so they can relicense it at will before distribution.

Is this the correct way of achieving that?

答:
This is an interesting problem, and I regret to say, carries some risk. You have several things to consider.

When you transfer the copyright to your customer (as it appears you have) you lose all rights to impose any kind of licensing obligations on that code. It is up to your customer to decide what licence they want to use.

It is perfectly reasonable for you to retain the rights to use the code for other purposes, but since you do not own the copyright you can only do with the code what your customer has explicitly agreed to. In effect, your customer is granting you a licence to use your own code, and you only do what is in the licence. That's legalese for: if you later do something the customer doesn't like, you could get sued.

No, you should not assume you have the rights to redistribute the plugin (see previous point).

I agree with what @robert that transferring copyright is not such a great idea and probably completely unnecessary (unless you really have to).

At this point I suggest you either renegotiate the deal with your customer, or kiss that code goodbye when you finish the job.

I had not noticed this was Odesk. In this case you really must read the Ts&Cs and especially 3.5, 3.6 and 3.7. You're working for the client and it simply is not your code once you have finished. No licence, no rights, just walk away.

Title: license and copyright assignment


问:
Extract all related class type aliasing and enum into one file or not
I have many models in my project, and some other classes just need the class declaration and pointer type aliasing. It does not need to know the class definition, so I don't want to include the model header file. I extract all the model's declaration into one file to let every classes reference one file.

model_forward.h

```<code>class Cat;
typedef std::shared_ptr<Cat> CatPointerType;
typedef std::shared_ptr<const Cat> CatConstPointerType;

class Dog;
typedef std::shared_ptr<Dog> DogPointerType;
typedef std::shared_ptr<const Dog> DogConstPointerType;

class Fish;
typedef std::shared_ptr<Fish> FishPointerType;
typedef std::shared_ptr<const Fish> FishConstPointerType;

enum CatType{RED_CAT, YELLOW_CAT, GREEN_CAT, PURPLE_CAT}

enum DogType{HATE_CAT_DOG, HUSKY, GOLDEN_RETRIEVER}

enum FishType{SHARK, OCTOPUS, SALMON}
</code>```

Is it acceptable practice? Should I make every unit, which needs a class declaration, depends on one file? Does it cause high coupling?

Or I should put these pointer type aliasing and enum definition inside the class back?

cat.h

```<code>class Cat
{
    typedef std::shared_ptr<Cat> PointerType;
    typedef std::shared_ptr<const Cat> ConstPointerType;

    enum Type{RED_CAT, YELLOW_CAT, GREEN_CAT, PURPLE_CAT}
    ...
};
</code>```

dog.h

```<code>class Dog
{
    typedef std::shared_ptr<Dog> PointerType;
    typedef std::shared_ptr<const Dog> ConstPointerType;

    enum Type{HATE_CAT_DOG, HUSKY, GOLDEN_RETRIEVER}
    ...
}
</code>```

fish.h

```<code>class Fish
{ ... };
</code>```

Any suggestion will be helpful.

答:
My instant response is: don't do that! When you mix declarations of classes together in the same file you introduce dependencies and coupling that will come back to bit you.

But beneath that I detect another problem. You have CPP files and H files, and the H files contain details of the private implementation (what you call the model header, I think). You quite rightly don't want to expose details of the implementation to every caller, and this is the solution you are considering.

This is a well known problem in C++, and there are solutions to it (although they all have their own problems). Probably the best known in PIMPL (for private implementation).

So my advice is to focus on tackling the problem of concealing the implementation from casual users of your classes, perhaps using PIMPL, and resist the temptation to create one header to rule them all.

OwnerDisplayName: Chen OT


答:
There are a few things to consider:

Not all bugs are going to be found until "something" gets released,
so why wait until you smash the very last bug when you know they'll
be more anyway.

Some bugs may not affect as many users or in many use cases.

Bugs can be found/created at a rate much faster than can be debugged.

Some power users (like programmers) like to see the software in
action sooner rather than later regardless of the bugs.

They release apps with known bugs, so why would Beta versions be any better?

Title: Why Beta versions have so many bugs?


问:
Does double-shifting as a PM affect your developer-productivity?
Has it ever happened to you that you are a good developer but suddenly you need to lead a team or are responsible for some PM activities as well? Did you find that it affected your productivity? How did you handle it?

I love my job, but I sometimes feel I was much happier as a programmer and the additional burden of being a Project Manager is currently affecting my productivity as a developer. What do you guys suggest as remedies to this?

I do not have an alternative currently to quit from my job - basically because Im working for a startup that I co-founded.

答:
Delegate.

I've worked in a team lead role multiple times and I'm currently doing more dev management stuff.  I delegate as much as possible to particular people who I know can do those tasks.  This has the dual benefit of getting those people exposure to the bigger picture of the SDLC, while preparing/judging their ability to become leaders in the future.

ContentLicense: CC BY-SA 2.5


答:
In my experience, having both roles at the same time, in the same project, causes severe problems. As a developer, you are acutally reporting to yourself, so you are basically unmanaged. If you consider yourself a better programmer than your peers, you are likely to avoid delegating difficult tasks to them, so in addition to your PM tasks, you are also working on the most sophisticated parts of the project. Parttime, that is.

A few days ago, someone posted this link, and I think it fits here, too.

Title: Does double-shifting as a PM affect your developer-productivity?

Body:
Has it ever happened to you that you are a good developer but suddenly you need to lead a team or are responsible for some PM activities as well? Did you find that it affected your productivity? How did you handle it?

I love my job, but I sometimes feel I was much happier as a programmer and the additional burden of being a Project Manager is currently affecting my productivity as a developer. What do you guys suggest as remedies to this?

I do not have an alternative currently to quit from my job - basically because Im working for a startup that I co-founded.


答:
The work patterns for PM and developer are pretty badly aligned.

For the most parts developers need long periods of concentration where PMs tend to be dealing with things being thrown at them from all directions all the time.  As a result if you try and do the two simultaneously you're almost certain to fail.

The best way to do it is disciplined time management.

Assuming a 50 / 50 split (adjust if that's not true), then I'd make mornings your PM time and afternoon's your development time.  During your development time redirect your phones to voicemail, close e-mail, disable instant messaging and so on.  Then at the end of the day check messages and e-mails for anything urgent, deal with those and then leave the rest for your next PM slot.

You'll need to explain to your co-founder what you're doing and why and get their buy in and you're going to need to be disciplined but it is possible, so long as you don't try to do both at once.


问:
Does it make sense to make a field mandatory which has a default value?
Consider a drop down "Duration" which has 3 options

```<code>1. 30 days
2. 60 days
3. 90 days
</code>```

and by default 30 days will be the selected value. Does it make sense to make this dropdown mandatory? Do we really need to put a * (Mandatory mark) for this field?

答:
In general, it doesn't make sense, unless:

It is possible to reject the default value, and return an empty value instead.

Adding the mandatory mark has security or other benefits.

For example, in ASP.Net, making a field mandatory using a validator makes the field mandatory on both the client and the server. As well as providing client-side feedback if the mandatory field is not completed (not useful in your case), it also provides a measure of security on the server. The idea is that the server must reject a submission where the mandatory field has not been populated. Although this shouldn't happen if you provide a default value, it isn't impossible. Indeed, it can occur when:

The use has deliberately altered the client-side code to send invalid data back to the server

The user's session has been meliciously compromised by a 3rd party (virus etc)

There is a client-side programming error

In these three cases, the server-side validator will ensure that the empty field will not be processed.


问:
Should I be worried if I solve a lot of my problems the same way?
I really enjoy programming games and puzzle creators/games. I find myself engineering a lot of these problems the same way and ultimately using similar technique to program them that I'm really comfortable with.

To give you brief insight, I like to create graphs where nodes are represented with objects. These object hold data such as coordinates, positions and of course references to other neighboring objects. I'll place them all in a data structure and make decisions on this information in a "game loop".

While this is a brief example, its not exact in all situations. It's just one way I feel really comfortable with. Is this bad?

答:
No, it's fine.

The point of practical programming is to find solutions that will possibly be useful in many similar developments. You just found one.

You can't and shouldn't be creating different solutions just for the sake of them being different. But you definitely should have a critical look at your solutions each time and ask yourself if they're still good or maybe the industry has progressed since and you need to align with it accordingly.


答:
Realistically in our day jobs we tend to get posed a fair number of pretty similar problems.

In these situations sticking with what you know can be good.  I've seen more examples of bad solutions from people implementing something they didn't understand that someone using a non-ideal technique well.

If you know something well the chances are you can flex it as needed and that your implementation will be solid and effective.  Those things probably won't be true from your first attempts at new techniques.

But the flip side is if all you have is a hammer, everything looks like a nail.  You should be doing things to make yourself aware of alternatives and when you're perhaps pushing your favourites too far.

Perhaps pick a few non-urgent / non-critical changes and use them to get up to speed with alternative solutions?

Title: Should I be worried if I solve a lot of my problems the same way?

Body:
I really enjoy programming games and puzzle creators/games. I find myself engineering a lot of these problems the same way and ultimately using similar technique to program them that I'm really comfortable with.

To give you brief insight, I like to create graphs where nodes are represented with objects. These object hold data such as coordinates, positions and of course references to other neighboring objects. I'll place them all in a data structure and make decisions on this information in a "game loop".

While this is a brief example, its not exact in all situations. It's just one way I feel really comfortable with. Is this bad?


问:
What is the one bit of computer science theory I should know?
Speaking as someone with an Electronic Engineering rather than Computer Science degree, what is the one bit of computer science I should know to make me a better real world programmer?

(By real world I mean something I'm going to use and benefit from in my day to day job as a programmer - for instance I'd suggest understanding database normalisation is of more practical use than understanding a quick sort for which there are lots of libraries).

答:
Problem Solving and the desire to continue learning!

They serve me far better than knowing quick sort and database normalization.


答:
Learn about data structures, algorithms and complexity.

Not too much just to get an understanding that a machine is not a magic box with unlimited power. You can't throw anything at it and expect it to crunch it in milliseconds. It has limits you know. You need to learn to not test them out with your code.

Also have a look at common approaches to solve particular design problems in programming. Design patterns namely. Don't worship them just take the ideas they communicate.

Knowledge of database modeling is essential as well.

After that it's just different programming languages, frameworks and libraries that implement or let you implement the core concepts. Pick up whatever you like and practice with those.

Title: What is the one bit of computer science theory I should know?

Body:
Speaking as someone with an Electronic Engineering rather than Computer Science degree, what is the one bit of computer science I should know to make me a better real world programmer?

(By real world I mean something I'm going to use and benefit from in my day to day job as a programmer - for instance I'd suggest understanding database normalisation is of more practical use than understanding a quick sort for which there are lots of libraries).


答:
From a code point of view no.

From a UI point of view (which is how your question is phrased) I'd say yes.

The reason I say this is that although it's specified, many people read "mandatory" as "significant" (how many people skim web forms only filling in the smallest amount of data?).

If the specific value in the field is important you may wish to use the mandatory * to show that it shouldn't just be skimmed over but that the user should give it some consideration.

Plus for pedants (and we're all computer programmers so that should be most of us) surely we should be saying it IS mandatory so should be marked as such, regardless of the UI component being used.

This may also protect you from the change down the line when someone says "let them pick any value and replaces it with a text box".

Title: Does it make sense to make a field mandatory which has a default value?

Body:
Consider a drop down "Duration" which has 3 options

```<code>1. 30 days
2. 60 days
3. 90 days
</code>```

and by default 30 days will be the selected value. Does it make sense to make this dropdown mandatory? Do we really need to put a * (Mandatory mark) for this field?


答: This is a question, everyone will have a different answer on. I would say: complexity theory is the most important piece, that you don't directly learn as a programmer anyway (like algorithms and data-structures), but what may impact your work. It helps if I know, that a problem is has cubic complexity, I know that it will scale badly if the problem size is increased.</p>


答: As long as the problem is getting solved in efficient way, there is no need to worry. </p>


答: If I have to choose just one bit, which is a difficult decision, I'd say go for the Big O notation. Understanding the implications of O(n), O(ln n), O(n²), O(2^n), O(n!) helps you to avoid a lot of expensive mistakes, the kind of which work well in the test environment but disastrously fail in production.


答: If it works well, call it a design pattern. If it doesn't, but you don't know better, it's the golden hammer antipattern.</p>


问:
Good example of complex code using TDD
What would be a good example of the use of TDD in large, real-life, complex, projects?  All the examples I've seen so far are toy projects for the purpose of a book or a paper...

Can you name an open-source project that heavily uses TDD? Preferably in C++ but I can read Java and C# or other similar languages.

答:
My first project done completely in TDD was an open source one in 2002.
You can still find it here:

http://sourceforge.net/projects/camelos/

Now at work I'm working mostly in TDD but not everybody in our team does, that's fine provided the wrote the tests at the end of the day.

We also wrote a complete gwt-gae application using TDD for the core part.
http://netnumero.appengine.com/company/mycompany

I cannot release that code but I'm working on a complete example project done in TDD for GWT, that is using TDD also in the UI.

As soon as I'll finish (Christmas holidays) I'll post it here
https://github.com/ubertob/gwt-tdd-example

Title: Good example of complex code using TDD


问:
What's the most absurd myth about programming issues?
To put it another way... What is the most commonly held and frustrating misunderstanding about programming, you have encountered?

Which widespread and longstanding myths/misconceptions do you find hard for programmers to dispel/correct.

Please, explain why this is a myth.

答: Why do programmers insist on writing bugs? (Coming from a marketing+tester person that can never get a bug report done right).</p>

OwnerDisplayName: Dorin Lazăr


答: I think graph is a suitable design for designing games to represent decisions\choices. Just keep in mind that probably this can be refined and made more efficient, and this may not be the best solution for other domains.</p>


问:
Method for integrating various version control systems or choosing one over others, due to mergers and acquisitions?
Companies acquire other companies that use different version control systems.

Is there a common wisdom on how to integrate such systems together, for example using a Subverson-GIT bridge or even deciding on using just one tool over another - and how to migrate between systems?

Do people use a set of criteria for such decision making, for example an equivalent to the "Joel" test on software development?

答:
On the managerial side, it is mainly a question of:

support: will the company releasing the VCS still be there in case of trouble.

It is sadly one of the main reason why such obsolete products like ClearCase are still considered (ClearCase being since 2003 an... IBM product)

license cost: even if there are freeware alternatives, sometimes "group licenses" for a VCS can be negotiated or actually included within a much larger contract including servers, networks, support, etc... A global licence for this kind of product can end up costing a lot less than the public price.

On the project side, it is also a question of:

administration: on which server will you install a VCS (or many VCS if we are talking about Git, SVN, and others)? With what backup policy? What DRP (Disastry Recovery Plan)?

local support: who will take the level 1 support,? level 2?

market knowledge: are you sure to find enough developers and/or administrators with the right knowledge set to leverage this VCS and all its feature?

Freeware or not, remember a "free" software is free as in "free speech" (you are free to choose and deploy the one you want), not as in "free beer" (it will still cost a lot of money in server, backup, administration, support, ...)

The criteria mentions above are a start to determine what VCS to keep, what to abandon.

But in the latter case, you need to consider:

migration strategy: can you export/import a project history from one VCS to another?

bridge strategy: does it make sense to have an history in two different VCS?

project obsolescence: if a project is in maintenance/End Of Life status, it might be better to support an old VCS for a short while.


答:
To answer the migration question from personal experience of several migrations:

Don't be afraid to just put the current version of the software into the new source control system as the base line and work from there.

The vast majority of the time you won't need the history. This means it's one less task to perform during the integration and one less thing to go wrong.

Files/projects that are being actively developed will soon generate a new history. So when you need to find out why a change was made the chances are that the history will be in the current repository as it will be a recent change.

Files/projects that were stable before the migration should (all things being equal) remain stable after the migration so you won't need to refer to the history. We found that if we had to investigate a bug in such an old file/project having the history wasn't really of any benefit. As long as you keep the old repository available for 6 months/a year you'll have the reference in such cases.

Title: Method for integrating various version control systems or choosing one over others, due to mergers and acquisitions?

Body:
Companies acquire other companies that use different version control systems.

Is there a common wisdom on how to integrate such systems together, for example using a Subverson-GIT bridge or even deciding on using just one tool over another - and how to migrate between systems?

Do people use a set of criteria for such decision making, for example an equivalent to the "Joel" test on software development?


答: Lot's of good answers. One other thing to think about is don't let team members get away with thinking switching the VC is such a big deal. There will be a setback with migration, a learning curve, etc., but if they have have too many problems, they need to question their level of ability and/or cooperation.</p>


问:
Which language features are considered harmful?
Please, explain why and list which languages have the (mis)feature implemented As far you know.

Post what you consider a harmful feature, not what you dislike.

答: Access modifiers in Java with package private language default and private programming convention default.</p>


答:
Programming

From the Department of Mathematics and Computer Science Hobart and William Smith Colleges comes Computer Science 124 Introduction to Programming:

Topics include control structures,
  objects, classes, inheritance, simple
  data structures, and basic concepts of
  software development.

If you can't program, you're not going very far in real world computing.

And, yes, I've noted that you are programmer. This is to improve your overall knowledge of programming theory and what other approaches there are available to you.

Is programming Computer Science as we know it?

In response to the comment from @Thomas Owens, who pointed out (quite rightly) that programming is not strictly Computer Science, I'd like to quote from Wikipedia's Computer Science article:

... the focus of computer science is
  more on understanding the properties
  of the programs used to implement
  software such as games and
  web-browsers, and using that
  understanding to create new programs
  or improve existing ones ...

Thus, as I read it, by programming you are demonstrating your understanding of programming theory. This should in turn help you to create simple, elegant code that is a joy for others to work with.


问:
Does giving a developer a slower development machine result in faster/more efficient code?
Suppose I give my developers a screaming fast machine.  WPF-based VS2010 loads very quickly.  The developer then creates a WPF or WPF/e application that runs fine on his box, but much slower in the real world.

This question has two parts...

1) If I give a developer a slower machine, does that mean that the resulting code may be faster or more efficient?

2) What can I do to give my developers a fast IDE experience, while giving 'typical' runtime experiences?

Update:

For the record, I'm preparing my even-handed response to management. This isn't my idea, and you folks are helping me correct the misguided requests of my client.  Thanks for giving me more ammunition, and references to where and when to approach this.  I've +1'ed valid use cases such as:

- specific server side programming optimizations

- test labs

- the possibly buying a better server instead of top of the line graphics cards

答:
I say developers need the best development system available - but that doesn't necessarily mean the fastest. It may well mean a modern but relatively slow system with all-passive cooling, to keep noise to a minimum, for example.

One thing - a development system should be reasonably new, and should absolutely have multiple cores.

An old PC may sound attractive in a show-performance-issues-early kind of way, but a Pentium 4, for example, may actually be faster (per core) than some current chips. What that means is that by limiting a developer to using a P4 system (actually what I'm using now - though that's my personal budgeting issue)...

You encourage the development of non-concurrent software that will not benefit from the current mainstream multi-core systems.

Even if multi-thread software is developed, bugs may not be noticed (or at least not noticed early) because concurrency-related issues may not show up in testing on a single-core system.

Multi-threaded software can cause serious performance issues that may get much worse with multi-core processors. One would be causing disk head thrashing (which can result in many thousands of times slower access to data) where individual threads are doing sequential access, but each to a different part of the disk. This can even go away on older slower PCs, by e.g. having two old 160GB drives instead of one 1TB drive, those threads may no longer be fighting each other for access to the same disk.

There are also issues with PCs that are too limited to support virtual machines well - e.g. for testing in multiple platforms.


答:
This is a bit of a difficult question.

All aspects of Computer science are important in one way or another.

In terms of what you will benefit on a day to day basis, probably a generalised overview of how your code works "under the hood" from code to CPU.

Understanding Big O Notation is important, and also understanding how your code may be executed is also very important in real world situations.


答:
Do you really have a need for integrating different systems ? In our team, each project lives in its own repository, and their histories are thus independant. We have no problem here to work with some projects under subversion and some other under mercurial, even if there are dependencies between them.

If you choose to migrate from one VCS to another, look at the conversion tools available. There is, from my experience, no technical reason to drop the projects' histories.

Edit

I think I understood something, which was implicit in the question and in other answers. It's the fact that VCS are also used to manage dependencies. I know it's quite common to use VCS features like svn:externals to integrate one repo (the dependency) with another.

I think the (technical) reason our team doesn't feel the need to bridge (or integrate) our 2 different systems is that we have a separate tool to manage dependencies. Our repo don't know each other.


答:
Competitive use cases of data structures.

There are situations where a map with red-black trees is required to guarantee performance and others where you cannot use an array, again to guarantee performance. Knowing when to choose what data structure is an invaluable skill.


答:
Good question, and I have to admit this is something that haunts me too.

When is this fine? Do a performance analysis of your code -- if you see that you are in O(log n) or O(n) or O(n log n) and as such the problem is mappable to known data structures you are generally okay.

When is this not fine? Your time or space complexity is O(n ^ 2) or worse, or the problem by definition is NP complete. In these situations you need to apply a fair bit of heuristics, apply knowledge from other domains etc.

Quick example: In chip design, choosing how to arrange the gates in the circuit for minimal power is NP-complete. Just graphs alone won't do you much good although it's a must need. You need to read additional material, a lot of it inter-disciplinary at times and apply the knowledge in your domain. For e.g. genetic algorithms (algorithms that mimic genetic crossovers and mutation, as defined in biology 101) have a lot of application in designing hardware chips.


答:
Not necessarily, if it's a good way of solving them :)

Usually when working on a "solution", I go for these things in order:

simplicity,

reusability,

and only last performance.

Not that performance doesn't matter: I design with performance in mind, but without pushing it too far (so if I need to do to calls to a utility method like StringUtils.isEmpty or something like that in the same flow, I won't mind). If performance is then needed (business case or user experience issue), then I go for a different approach than the simple and reusable one. Being pragmatic.

Strangely though, when coding in C, I care a lot more about performance than when coding in Java... Force of habit :))


问:
Why are more programmers not freelance these days?
Leaving the whole pie to only a few of them, amplifying the huge differences between the two status. Pay is a (huge) one, not having to do overtime is another.

I leave the question open to hopefully get many great answers on all the different subjects that affects that feeling and decision not to go.

While this question is really global, I'll be interested in any studies, facts, articles, opinions regarding local markets such as US, India and even Australia in which I'm in love with.

答: For some of us, being part of a team beats being a lone ranger.</p>


答:
there are only three numbers that matter:

zero

one

many


问:
Type casting variables in PHP, what is the practical reason for doing this?
PHP, as most of us know, has weak typing.  For those who don't, PHP.net says:

PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used.

Love it or hate it, PHP re-casts variables on-the-fly.  So, the following code is valid:

```<code>$var = "10";
$value = 10 + $var;
var_dump($value); // int(20)
</code>```

PHP also allows you to explicitly cast a variable, like so:

```<code>$var = "10";
$value = 10 + $var;
$value = (string)$value;
var_dump($value); // string(2) "20"
</code>```

That's all cool...  but, for the life of me, I cannot conceive of a practical reason for doing this.

I don't have a problem with strong typing in languages that support it, like Java.  That's fine, and I completely understand it.  Also, I'm aware of - and fully understand the usefulness of - type hinting in function parameters.

The problem I have with type casting is explained by the above quote.  If PHP can swap types at-will, it can do so even after you force cast a type; and it can do so on-the-fly when you need a certain type in an operation.  That makes the following valid:

```<code>$var = "10";
$value = (int)$var;
$value = $value . ' TaDa!';
var_dump($value); // string(8) "10 TaDa!"
</code>```

So what's the point?

Take this theoretical example of a world where user-defined type casting makes sense in PHP:

You force cast variable $foo as int → (int)$foo.

You attempt to store a string value in the variable $foo.

PHP throws an exception!! ← That would make sense.  Suddenly the reason for user defined type casting exists!

The fact that PHP will switch things around as needed makes the point of user defined type casting vague.  For example, the following two code samples are equivalent:

```<code>// example 1
$foo = 0;
$foo = (string)$foo;
$foo = '# of Reasons for the programmer to type cast $foo as a string: ' . $foo;

// example 2
$foo = 0;
$foo = (int)$foo;
$foo = '# of Reasons for the programmer to type cast $foo as a string: ' . $foo;
</code>```

A year after originally asking this question, guess who found himself using typecasting in a practical environment?  Yours Truly.

The requirement was to display money values on a website for a restaurant menu.  The design of the site required that trailing zeros be trimmed, so that the display looked something like the following:

Menu Item 1 .............. $ 4
Menu Item 2 .............. $ 7.5
Menu Item 3 .............. $ 3
```

<p>The best way I found to do that wast to cast the variable as a float:</p>

```$price = '7.50'; // a string from the database layer.
echo 'Menu Item 2 .............. $ ' . (float)$price;
```

PHP trims the float's trailing zeros, and then recasts the float as a string for concatenation.

答:
You're mixing the weak/strong and dynamic/static type concepts.

PHP is weak and dynamic, but your problem is with the dynamic type concept.  That means, variables don't have a type, values do.

A 'type casting' is an expression that produces a new value of a different type of the original; it doesn't do anything to the variable (if one is involved).

The one situation where I regularly type cast values is on numeric SQL parameters.  You're supposed to sanitize/escape any input value you insert into SQL statements, or (much better) use parameterized queries.  But, if you want some value that MUST be an integer, it's much easier to just cast it.

Consider:

```<code>function get_by_id ($id) {
   $id = (int)$id;
   $q = "SELECT * FROM table WHERE id=$id LIMIT 1";
   ........
}
</code>```

if I left out the first line, $id would be an easy vector for SQL injection.  The cast makes sure that it's a harmless integer; any attempt to insert some SQL would simply result in a query for id=0

Body:
You're mixing the weak/strong and dynamic/static type concepts.

PHP is weak and dynamic, but your problem is with the dynamic type concept.  That means, variables don't have a type, values do.

A 'type casting' is an expression that produces a new value of a different type of the original; it doesn't do anything to the variable (if one is involved).

The one situation where I regularly type cast values is on numeric SQL parameters.  You're supposed to sanitize/escape any input value you insert into SQL statements, or (much better) use parameterized queries.  But, if you want some value that MUST be an integer, it's much easier to just cast it.

Consider:

function get_by_id ($id) {
   $id = (int)$id;
   $q = "SELECT * FROM table WHERE id=$id LIMIT 1";
   ........
}

if I left out the first line, $id would be an easy vector for SQL injection.  The cast makes sure that it's a harmless integer; any attempt to insert some SQL would simply result in a query for id=0


答:
If it works, it's OK.

If you worry about overrelying on one single technique, try as an exercise to come up with variations of some solved problem that would make your solution unworkable.  Extra points if you can generalize the changes to define the applicability space of your usual process.


问:
Best books on the theory and practice of software architecture?
I have a couple of developers at my company who wish to move from programming into architecture. What are the best books out there on the theory and practice of software architecture? Include a cover picture if you can.

Feel free to include general books, and also books that relate to a specific technology.

答:
I wont't cite ones that have already been by other, so I'll add this one:

Concepts Techniques and Models of Computer Programming, by peter Van Roy and Seif Haridi

The obvious problem is that it used the now (sort-of) defunct Mozart Programming System and the amazing Oz programming language. Which then spawned other interesting experiments like the Alice ML programming language.

It is, however, an amazing book, both to learn computer programming and to get a deep understanding of CS concepts and a good overview of architecture concepts without using buzzwords.

A bit verbose at times, but very well written.

Maybe more of a CS theory book in the end than an enterprise architecture book, but I find its teachings very valuable to apply to industry software.


答: This is my number #1 choice right now. Best book about how to build (grow) application now.

Title: Best books on the theory and practice of software architecture?

Body:
I have a couple of developers at my company who wish to move from programming into architecture. What are the best books out there on the theory and practice of software architecture? Include a cover picture if you can.

Feel free to include general books, and also books that relate to a specific technology.


答: this would be my #2 choice. Good book on practices and good code. A bit pedantic sometimes.


答:
One example is objects with a __toString method:
$str = $obj->__toString(); vs
$str = (string) $obj;. There is much less typing in the second, and the extra stuff is punctuation, which takes longer to type. I also think it's more readable, although others may disagree.

Another is making a single-element array:
array($item); vs (array) $item;. This will put any scalar type (integer, resource, etc.) inside an array.

Altenatively, if $item is an object, its  properties will become keys to their values. However, I do think that object->array conversion is a bit strange: private and protected properties are part of the array, and renamed. To quote the PHP documentation: private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name.

Another use is converting GET/POST data into appropriate types for a database. MySQL can handle this itself but I think the more ANSI-compliant servers might reject the data. The reason I only mention databases is that in most other cases, the data will have an operation performed on it according to its type at some point (i.e. int/floats will usually have calculations performed on them, etc.).

Title: Type casting variables in PHP, what is the practical reason for doing this?

Body:
PHP, as most of us know, has weak typing.  For those who don't, PHP.net says:

PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used.

Love it or hate it, PHP re-casts variables on-the-fly.  So, the following code is valid:

```<code>$var = "10";
$value = 10 + $var;
var_dump($value); // int(20)
</code>```

PHP also allows you to explicitly cast a variable, like so:

```<code>$var = "10";
$value = 10 + $var;
$value = (string)$value;
var_dump($value); // string(2) "20"
</code>```

That's all cool...  but, for the life of me, I cannot conceive of a practical reason for doing this.

I don't have a problem with strong typing in languages that support it, like Java.  That's fine, and I completely understand it.  Also, I'm aware of - and fully understand the usefulness of - type hinting in function parameters.

The problem I have with type casting is explained by the above quote.  If PHP can swap types at-will, it can do so even after you force cast a type; and it can do so on-the-fly when you need a certain type in an operation.  That makes the following valid:

```<code>$var = "10";
$value = (int)$var;
$value = $value . ' TaDa!';
var_dump($value); // string(8) "10 TaDa!"
</code>```

So what's the point?

Take this theoretical example of a world where user-defined type casting makes sense in PHP:

You force cast variable $foo as int → (int)$foo.

You attempt to store a string value in the variable $foo.

PHP throws an exception!! ← That would make sense.  Suddenly the reason for user defined type casting exists!

The fact that PHP will switch things around as needed makes the point of user defined type casting vague.  For example, the following two code samples are equivalent:

```<code>// example 1
$foo = 0;
$foo = (string)$foo;
$foo = '# of Reasons for the programmer to type cast $foo as a string: ' . $foo;

// example 2
$foo = 0;
$foo = (int)$foo;
$foo = '# of Reasons for the programmer to type cast $foo as a string: ' . $foo;
</code>```

A year after originally asking this question, guess who found himself using typecasting in a practical environment?  Yours Truly.

The requirement was to display money values on a website for a restaurant menu.  The design of the site required that trailing zeros be trimmed, so that the display looked something like the following:

Menu Item 1 .............. $ 4
Menu Item 2 .............. $ 7.5
Menu Item 3 .............. $ 3
```

<p>The best way I found to do that wast to cast the variable as a float:</p>

```$price = '7.50'; // a string from the database layer.
echo 'Menu Item 2 .............. $ ' . (float)$price;
```

PHP trims the float's trailing zeros, and then recasts the float as a string for concatenation.


答: Software Development Life Cycle is something I'd suggest knowing if you don't already.  Granted this was introduced in a second year Computer Science course and is something used repeatedly within software projects.  This can be useful to get a general idea of how does a project go from start to finish, though if you want to more in-depth there are methodologies like Waterfall or Agile that you could study to get more specific knowledge.</p>


问:
What happens if you're unable to solve a problem?
I'm a year away from graduating from university, and I'm really looking forward to solving practical problems. Especially non-trivial ones which require a bit of research and a lot of thinking.

But at the same time, that is also my greatest fear - being faced with a problem that I'm unable to solve, no matter how hard I try. And with pressure to deliver code on impending deadlines just around the corner, it does look a bit scary when viewing it from the safe playgrounds on uni (where the worst thing that can happen is that you have to redo a course or exam).

So for those who have been in industry for any longer length of time, what would happen if you were told to solve a problem that you couldn't? Has it happened, and if so, what did happen? Did they just drop it and said "Oh well, guess we can make do with something else"? Were there consequences? Were you reprimanded, or even fired?

答:
I'm going to have to go with a simple answer: I ask for help.  Just like others sometimes ask me for help when they're stuck trying to find a solution for something.

Edit: I should mention that I often find the solution just by describing the problem to a co-worker, or sometimes even when I start posting a question on sites like StackOverflow.


答:
Two things to remember if you're stuck with a seemingly unsolvable problem:

Let other folks know you're stuck as soon as possible. It will help them to adjust the estimate in time before it's too late.

If you see one way of solving a problem doesn't work - drop it before you've wasted too much time. Ask for help or try out a different approach. It's not about proving yourself hard and smart, it's about getting things done.

Title: What happens if you're unable to solve a problem?

Body:
I'm a year away from graduating from university, and I'm really looking forward to solving practical problems. Especially non-trivial ones which require a bit of research and a lot of thinking.

But at the same time, that is also my greatest fear - being faced with a problem that I'm unable to solve, no matter how hard I try. And with pressure to deliver code on impending deadlines just around the corner, it does look a bit scary when viewing it from the safe playgrounds on uni (where the worst thing that can happen is that you have to redo a course or exam).

So for those who have been in industry for any longer length of time, what would happen if you were told to solve a problem that you couldn't? Has it happened, and if so, what did happen? Did they just drop it and said "Oh well, guess we can make do with something else"? Were there consequences? Were you reprimanded, or even fired?


答:
Look at from different angles

I've come across this many a times, usually what happens is:

You have a problem, initially you have an idea in your head how you would solve it.

When it comes to actually implementing your solution, it turns out that is doesn't work (probably due to the weak model of the actual problem).

After struggling to solve the problem, be it more research or asking others. None of it works, the pure frustration!

Finally you opt for what you didn't want to do ->

"The Dirty Hack"

It works, but you feel dirty...


答:
I go to StackOverflow ;)

But all joking aside, do not fear the unknown. Your whole career will be facing the unknown, because if you already solved it, it won't be a problem the next time.


答: I haven't heard of anything happening like this. First of all you are never given a problem which can not be solved at all. The problem may be hard and may take time to solve. When given a problem, you will have to tell this is the time I will require. If in your research you think that this problem really can not be solved, you have to raise a flag and tell your manager that this problem will take some more time, or is really difficult to solve. It's all about the schedule. If you promise something and will not be able to deliver then it's problem. But if you keep telling your status and concerns, it is the responsibility of manager to take care of it. He should redirect you to proper person who can help, or adjust the schedule.  </p>