问:
Legitimate reasons for circular references in C++
I have project written in C++ that I am working on which has a parent-child relationship where each child has only one parent. I had previously decided after looking at this post that I would make the children know nothing of their parents.

A little background on my project before I go into my question: The parents in this situation are objects representing a collection of interlinked computational "blocks". The parent (The "Model" class) takes in one or more input values, runs them through its blocks, and the blocks return back one or more output values. The child objects are the Blocks and a Block is owned by exactly one Model. The issue is that a certain kind of Block can contain a Model so that I can nest them and re-use models. Although most blocks know nothing of the Model class, the ModelBlock (inheriting Block) knows about Models and is allowed to encapsulate a Model.

The Question: The above seemed to be working pretty well, at least in the console version of my application. However, I need a GUI to be able to create any large Model without losing my mind and so I have started making one. The issue has reared its ugly head again when I realized that the Blocks in general need to know about their Model so that ModelBlocks can inform a Model when it is being used inside of another Model. This is so that I can easily find "orphaned" Models that are not the root model and not used in any other context (meaning they will never be run). I guess I could make it specific to ModelBlocks, but if I'm going to do something like that, why not make it apply to all the blocks?

In C#, its seemingly not a bad practice to use a circular reference to accomplish this (Entity Framework does it up the wazoo...it wreaks havoc with serializers). However, it seems very taboo in C++ to use circular references. So, I am wondering if the above is a legitimate use. Were I to do this, Blocks would be informed of their parent Model's destruction so that they know if they are orphans. Even if the above isn't, are the legitimate uses for circular references in C++ since they seem to be relatively common other languages (of course, that's assuming that those programs in those other languages using circular references don't have serious design issues)?

If I didn't explain my question well enough just let me know and I'll try to clarify.

EDIT: I should mention that the actual implementations are separate from all this since I am using interfaces (classes with all pure virtual functions) to define how a block looks or how a model looks.

Here is a partial class diagram with my proposed changes:

Here is the source: https://github.com/kcuzner/Simulate/tree/develop.
If you feel like building it, it depends on Qt >= 4.7, boost >= 1.52. The projects are Qt-Creator projects. Console and GUI depend on Engine.

答:
You know there are problems where the only good answer is to use a system with better garbage collection than any portable C++ library supplies.

I could name some, but they're pretty involved. Examples involve things like prolog embedded in C++ and expression trees used in a compiler.

I've got a portable mark and sweep garbage collection library working and 90% finished at the moment.  Since C++ has limitations it's not as unrestricted as C#'s - the basic restriction being that objects belong to a thread, each thread has its own garbage collector, and references ACROSS threads have to fall back on atomically handled reference counts like shared_ptr and boost's intrusive_ptr so cycles that involve ownership by more than one thread won't be collected. Also in the current version, weak pointers are only available in the owning thread.

After lots of thought, these limits seem like the best compromise you can get with a portable C++ library.

ContentLicense: CC BY-SA 4.0


问:
How long does a Comp Sci degree last?
I keep hearing from people that if I don't become a programmer soon after graduation my degree will be a useless piece of paper, they claim it will become outdated.  I kind of find this hard to believe considering what I was taught at a fairly good school has been standard practice for some time.

So is this a true belief in industry?  That somehow I become less desirable after a year or two, even though the graduates who comes after me pretty much get the same identical education.

答:
Although the technologies in CS change rapidly, most of the principles you've learned will last a long time.

That said, it's true that the practical value of a CS degree to a new grad will diminish over time if the grad doesn't actively practice what they've learned. This is, of course, true for any degree; the only way to maintain the value of a degree is to use what you've learned. For example, if you participate in an open source project, you will be adding to the knowledge gained from your degree.

As far as employment goes, I doubt your CS degree will "degrade" over time to potential employers, but if you haven't been working on projects of some kind post-graduation, you will likely have trouble with the technical interviews.

ContentLicense: CC BY-SA 2.5

Title: How long does a Comp Sci degree last?


问:
What's wrong with circular references?
I was involved in a programming discussion today where I made some statements that basically assumed axiomatically that circular references (between modules, classes, whatever) are generally bad.  Once I got through with my pitch, my coworker asked, "what's wrong with circular references?"

I've got strong feelings on this, but it's hard for me to verbalize concisely and concretely.  Any explanation that I may come up with tends to rely on other items that I too consider axioms ("can't use in isolation, so can't test", "unknown/undefined behavior as state mutates in the participating objects", etc.), but I'd love to hear a concise reason for why circular references are bad that don't take the kinds of leaps of faith that my own brain does, having spent many hours over the years untangling them to understand, fix, and extend various bits of code.

Edit: I am not asking about homogenous circular references, like those in a doubly-linked list or pointer-to-parent.  This question is really asking about "larger scope" circular references, like libA calling libB which calls back to libA.  Substitute 'module' for 'lib' if you like.  Thanks for all of the answers so far!

答:
In my opinion having unrestricted references makes program design easier, but we all know that some programming languages lack support for them in some contexts.

You mentioned references between modules or classes. In that case it's a static thing, predefined by the programmer, and it's clearly possible for the programmer to search for a structure that lacks circularity, though it might not fit the problem cleanly.

The real problem comes in circularity in run time data structures, where some problems actually can't be defined in a way that gets rid of circularity. In the end though - it's the problem that should dictate and requiring anything else is forcing the programmer to solve an unnecessary puzzle.

I'd say that's a problem with the tools not a problem with the principle.

Title: What's wrong with circular references?

ContentLicense: CC BY-SA 3.0


问:
What percent of your college course work is unit-tested code?
As a college student do you write unit-test for the project code you write?  Do you know how to properly use TDD?  Have you been taught to use testing frameworks (jUnit for example)?

I've just recently heard that a major company's project team was delivering software to User Acceptance Testing group that had only 7% line code coverage for unit testing.  While that shocks me, it just tells me that this company's software engineering practice are immature.  However I wonder if they could just hire a few recent graduates and raise the bar on the teams practices - assuming that these newly minted programmers were trained in the best practices.

Are you 2008 - 2010 CS graduates using best practices of unit testing your code?

答:
I don't write unit-tests for the software I write for assignments, I usually just do some of my own testing and debugging.

Honestly, CS at my university is fairly broken, half the students are diehard passionate programmers who have learned nearly everything on their own. The other half can barely write a hello world in Java, and know no other languages and have extreme problems with even trivial programs. Students barely get much programming experience, most manage to squeak by copy & pasting code form books and the internet without really understanding it.

As part of the degree plan, you have to take courses on architecture and management that involve agile and the concepts of software testing and test driven development. However, these courses are taken pretty late (senior year) and are certainly not utilized in other courses.

If I had more time, I'd probably unit-test my code properly; unfortunately I'm working and taking 19 hours, so I've got alot of assignments and I can usually bang them out pretty quick and test them enough. I have gotten dinged a couple points for a bug here or there though, and unit-testing my code would certainly help get better grades on the assignments.

Sadly, my experience is that any REAL software development, any type of real-world systems programming or coding standards or best practice is done by those who write code on the weekends, and read about it on their own, and look for it on their own. The students who just go to class, I can't imagine how they're going to get hired. You get shown what all exists and that you need to know it in class, but not enough implementation.

Professors can't grade 50 students' programming assignments every week, so if they want to have lots of actual practice, they have us do group work. This results in the one or two good programmers doing almost all the work, and the rest follow along and try to read and modify their code. Maybe other Universities are better, and I think they claim to be; but I think in practice they aren't really any different.

OwnerDisplayName: David Koontz


问:
Fixed duration Jobs need to be scheduled across fixed number of queues

Say I have 9 jobs with estimates of how long they will take to complete, and 3 queues that process these jobs - this constitutes one batch. Note that all the jobs are allocated to a queue beforehand and not at run-time. So with poor-scheduling, some queues may remain idle while others continue to process a job.

All these jobs should be distributed across the queues in such a way that the total time to complete all the queues is nearly equal.

Consider:

1.Below Q2,Q3 complete in 15mins and remain idle while Q1 takes another 10mins to complete.

Batch1:

```<code>+------+----+----+----+
|  #   | Q1 | Q2 | Q3 |
+------+----+----+----+
| 1    |  5 |  5 |  5 |
| 2    | 15 |  5 |  5 |
| 3    |  5 |  5 |  5 |
+------+----+----+----+
| Time | 25 | 15 | 15 |
+------+----+----+----+
| Total| 25           |
+------+----+----+----+
</code>```

2.Now ideally the jobs should be distributed as...

```<code>+------+----+----+----+
|  #   | Q1 | Q2 | Q3 |
+------+----+----+----+
| 1    | 15 |  5 |  5 |
| 2    |  - |  5 |  5 |
| 3    |  - |  5 |  5 |
| 4    |  - |  5 |  5 |
+------+----+----+----+
| Time | 15 | 20 | 20 |
+------+----+----+----+
| Total| 20           |
+------+----+----+----+
</code>```

This seems to be a straightforward scheduling problem, but I am dealing with hundreds of such jobs, divided into multiple batches. Where each batch will start only on the completion of the first. So I would require some algorithm to decide the schedule. Any ideas..? Thanks

Update:

Adding more information based on feedback...

The jobs in a batch are fixed.

There are no dependencies between jobs within a batch, but there are dependencies between batches. So we can look at solving the problem for a single batch and the solution will apply across all batches.

Real-world problem: I am modelling a problem on loading data (ETL) and the entire load process takes 5-6hrs, which has several batches. Looking for ways to reduce the overall time.

答:
Are the jobs in a batch fixed for example batchA - has the jobs jobA1, jobA2 etc.

Or we just have a lots of jobs, and we need to decide the batches as well as the queues in the batches.

It can be considered as a knapsack problem and you need to find three kanpsacks with not very much difference in the values.

The three knapsacks are the three scheduling queues.

If you can explain about the relationship between the jobs then it would help us all in finding the solution.

For example Job1 DEPENDS_ON Job2 and similarly.


问:
Find number of occurrence of a word in a 2D matrix of Characters
Given a two dimensional matrix of alphabets, search the given word in all directions. Below is an example to search for the word "TEAM":

No of occurrences is 4 in matrix below.

What is the best approach to solve this?
Its not a dictionary word. Its simply sequence searching in all the directions.

答:
You can use backtracking for solving this problem, proceed till you find the word completing else backtrack.

While proceed there is a constraint which to proceed in the same direction with which you started.

For example if you are going "UP" then from next character you should go "UP" Only.


问:
Using a list of tuples vs a list of custom objects
I have a situation where I have several text documents and I want to create a list that contains the words in those documents.  But I also need to record several properties of each word.  These properties are

The index of the word within all the words in the documents (Integer)

The word itself (String)

The document that the word is in (Integer)

The topic value associated with this word (Integer)

I can think of two ways of doing this.  The first is simply creating a list of tuples of the form (word,doc,topic) where the word index is given by the index of the tuple in the list.  My second idea is to create a word class where the given properties are member variables in the class.  Then just create a list of objects from this class.

So my question is which is the best solution - the list of tuples or the list of word objects?  And a related question is what are the situations when either of these approaches is preferable?

答:
The answer to this question will depend also on how the words will be searched, will the search key be whole words or can they be incomplete words, will you search on basis of document etc. etc.

Also how are you planning to use the words and properties.


答:
This is related to the knapsack problem, except that you have multiple, variable-sized knapsacks. That makes it enormously easier.

A simple algorithm is to sort the jobs by size and then, starting from the largest job, assign each (one at a time) to the queue with the least work assigned to it (so yes, you'll need to keep a handle on how much work is already assigned to each queue from the batch). I'm not 100% sure if this will produce a best solution, but it will produce a pretty good one and it is easy to implement correctly.

Where things get more complex is when you have uncertainty in the costs, dependencies between jobs or where you have high priority tasks coming through and pausing some of the queues occasionally. You didn't mention any of those, so I'd suggest going with the simple algorithm.

Let's try assigning the jobs [5,5,15,5,5,5] to two queues to demonstrate.

Sort the jobs:

[15,5,5,5,5,5]

Assign the jobs in order:

A: [] (size 0), B: [] (size 0)

A: [15] (size 15), B: [] (size 0)

A: [15] (size 15), B: [5] (size 5)

A: [15] (size 15), B: [5,5] (size 10)

A: [15] (size 15), B: [5,5,5] (size 15)

A: [15,5] (size 20), B: [5,5,5] (size 15)

A: [15,5] (size 20), B: [5,5,5,5] (size 20)

That looks balanced.

Title: Fixed duration Jobs need to be scheduled across fixed number of queues

Body:
Say I have 9 jobs with estimates of how long they will take to complete, and 3 queues that process these jobs - this constitutes one batch. Note that all the jobs are allocated to a queue beforehand and not at run-time. So with poor-scheduling, some queues may remain idle while others continue to process a job.

All these jobs should be distributed across the queues in such a way that the total time to complete all the queues is nearly equal.

Consider:

1.Below Q2,Q3 complete in 15mins and remain idle while Q1 takes another 10mins to complete.

Batch1:

```<code>+------+----+----+----+
|  #   | Q1 | Q2 | Q3 |
+------+----+----+----+
| 1    |  5 |  5 |  5 |
| 2    | 15 |  5 |  5 |
| 3    |  5 |  5 |  5 |
+------+----+----+----+
| Time | 25 | 15 | 15 |
+------+----+----+----+
| Total| 25           |
+------+----+----+----+
</code>```

2.Now ideally the jobs should be distributed as...

```<code>+------+----+----+----+
|  #   | Q1 | Q2 | Q3 |
+------+----+----+----+
| 1    | 15 |  5 |  5 |
| 2    |  - |  5 |  5 |
| 3    |  - |  5 |  5 |
| 4    |  - |  5 |  5 |
+------+----+----+----+
| Time | 15 | 20 | 20 |
+------+----+----+----+
| Total| 20           |
+------+----+----+----+
</code>```

This seems to be a straightforward scheduling problem, but I am dealing with hundreds of such jobs, divided into multiple batches. Where each batch will start only on the completion of the first. So I would require some algorithm to decide the schedule. Any ideas..? Thanks

Update:

Adding more information based on feedback...

The jobs in a batch are fixed.

There are no dependencies between jobs within a batch, but there are dependencies between batches. So we can look at solving the problem for a single batch and the solution will apply across all batches.

Real-world problem: I am modelling a problem on loading data (ETL) and the entire load process takes 5-6hrs, which has several batches. Looking for ways to reduce the overall time.


答:
The stuff you learn while getting a degree usually forms the basics of Computer Science. The principles you learned then, provide a helping hand to all the technologies you'll probably learn in future.

Even if there are variations in technology, you can always use your basics to derive new technologies from them.

IMO, a degree doesn't have any kind of shelf life. People recruit you for your abilities, alongwith your degree ofcourse.

Eventually, it boils down to what you learn and how you hone your skills between the graduated and the employed period.

Title: How long does a Comp Sci degree last?

Body:
I keep hearing from people that if I don't become a programmer soon after graduation my degree will be a useless piece of paper, they claim it will become outdated.  I kind of find this hard to believe considering what I was taught at a fairly good school has been standard practice for some time.

So is this a true belief in industry?  That somehow I become less desirable after a year or two, even though the graduates who comes after me pretty much get the same identical education.


答:
I did something similar time ago. You should take advantage of the fact that words are a ordered set of characters. So, you perform a linear search over the matrix for the first letter, then you recursively call the directional search.

To simplify computational complexity you can add some constraint, eg, if word.length > number of characters on that direction don't start searching.

The recursive function signature would be like:

```<code>boolean search(string word, int direction)
</code>```

with terminal case

```<code>if (word.length==1) return isNextLetterInDirection(word, direction);
</code>```

and the search being

```<code>search(substring(word, 0, word.length-1), direction);
</code>```

This algorithm also cover palindrome cases and words including their syllables.

Title: Find number of occurrence of a word in a 2D matrix of Characters

Body:
Given a two dimensional matrix of alphabets, search the given word in all directions. Below is an example to search for the word "TEAM":

No of occurrences is 4 in matrix below.

What is the best approach to solve this?
Its not a dictionary word. Its simply sequence searching in all the directions.

Body:
I did something similar time ago. You should take advantage of the fact that words are a ordered set of characters. So, you perform a linear search over the matrix for the first letter, then you recursively call the directional search.

To simplify computational complexity you can add some constraint, eg, if word.length > number of characters on that direction don't start searching.

The recursive function signature would be like:

boolean search(string word, int direction)

with terminal case

if (word.length==1) return isNextLetterInDirection(word, direction);

and the search being

search(substring(word, 0, word.length-1), direction);

This algorithm also cover palindrome cases and words including their syllables.


问:
How are the skills used in typical interview questions applied in the real job?
For SQL and C# app dev jobs, the interviewers usually ask questions about tree,graph and linked list traversals using pure C and pointers.  In the 3 years I've spent in my job, I've never had to actually

find the path to the 1st node to the right of a given node which is a multiple of
  the given node

for example

I can see that these skills might be used in jobs where you need to write compilers, drivers and work on the OS kernel.  Other than those, where else are these skills used?

答:
From my experience in my company where I did many interviews, there is a good chance that the person interviewing has no clue on how to do that properly. So they prepared a set of technical questions and calculate a score of that and make that your resume. This however has many drawbacks and should not be done for the following reasons:

You ask point knowledge. If the programmer happens to never have done something in that area, he/she still might be an excellent co-worker, but just doesn't know that particular answer. On the contrast: if someone had prepared for the interview and found the answer to that particular question on the net, you get the right answer, but that person might not have a clue about the actual topic at all.

People are nervous in job interviews. The brain has this great feature to shut down many higher-level areas (like logic) if in panic, which means: if you are nervous, you might not deliver the quality of answers you would in a day-to-day situation. Some people can deal with a stressful situation like an interview, many can not.

With a single, correct answer, you test that persons skill to find that particular answer. This is one of many skills an it co-worker needs, but not the one and only required. Therefore one or two of those questions should be enough to test that area of knowledge, and then other skills should be queried. An interview that only contains problem-solving questions tests the same skill over and over again.

What are good programming tasks questions?

Those famous "Can you write a short program" questions have the huge problem that most programmers cannot write a single line of code without their IDE helping them. But that is in day-to-day working situations no issue at all, because the programmer always has his IDE helping him. So asking things like "Find the error", "Write 50 lines of code that do..." or even simple questions need to take into account, that the applicant does not have his tools (IDE, Google) available.

I for example can answer you basically any question within 1 minute if I have Google helping me, but without Internet connection I appear to be helpless. I call that outsourced memory, and instead of hindering me, it very much helps me to focus on what is really important - understanding the underlaying mechanics - because everything else can be looked up. But don't ask me about details from any random APIs, because I don't know those, I have Google for that.

That said, a good programming task question should not focus on knowing APIs, or special coding skills unless this is an absolute requirement for the job. Knowledge can be gained, so it is better to find out how good that person is in gaining knowledge than to ask what he/she already knows.

A good question for a programming task should be short, simple, able to be coded in every language with only a few lines of code and it - especially - should tell you as much as possible about how the person works and finds answers. Example:

"Write a function in the language of your choice that takes an array of integers and re-orders them in a way that the first integer is afterwards the last, and all others shift accordingly."

The first any applicant should ask at this point is: "Sorry... can you please explain the task?". Because no programmer has been given a clear description on what to do ever. This is followed by the explanation, that the code in questions should do a left-shift of the content of the array with the overflow being added to the right.

This task is so simple, that anyone who graduated any form of programming level should be able to answer properly. This takes into account that the programmer has to work without his tools and that being nervous reduces the ability to think logically. It however still tells you how people solve problems just from the way the question is worded and from the way how people approach it, simply because a left-shift is against the common 'left-to-right' instinct and forces people to think for a second.

There are many possible answers to this question, so taking a close look to the way the code is developed is the important part, not if the solution would actually work. Does the applicant test for null? How is the overflow stored? Is a loop or a mem-set used? How does the applicant verify code correctness? This one simple question tells you an entire biography about how that person works.

What are good general knowledge questions?

Good questions are easy to answer, allow for a broad amount of answers (so called 'open questions') and allow you to learn as much as possible about the applicant as you can in the short time you have.

Examples:

(Asking a C++ programmer): "What other languages beside C++ do you know?"

This is an entry level questions, which gives the applicant a fair chance to bail out at this moment should he not know anything about the topic asked. A 'no' at this point is better than to torment him/her with several more questions that he/she all has to answer with: "Sorry, I don't know anything about that."

I addition it tells you first of all which other languages that person knowns, furthermore you learn how interested that person is to get a more broad view of the programming world, or if you have someone with only a singular language (and therefore feature/techniques) view.

(Next after that, lets say he knows Java): What are the top three differences between C++ and Java in your opinon?"

This is an open question that allows for many answers, so the applicant has a good chance to find at least three. Asking for the (personal opinion) top three not only limits the possible answers, but also forces the applicant to sort based on priority. Still it is (or should be) easy to answer.

This is a simple question that tests a lot of in-depth knowledge about different programming languages. How deep is the knowledge of those topics really? From those answers you can tell a lot about the knowledge and actual understanding of the underlaying mechanics of programming languages. How much that person spent with the dirty details, or if he/she is just someone who links together various API functions with no real clue what happens beneath those.

This concept of entry-level questions followed by simple in-depth knowledge questions can be used for most other topics as well. Always in this scheme: bail-out question, verification question, in-depth question. Another example (from a Java interview):

"How would you rate your experience with multi-threaded development?"

"Please name what you think are the top three most important things to consider when developing a multi-threaded application."

"Please name three classes from the Java API that can help you on developing those applications and give a short description on what they are used for."

These three questions will tell you more than any technical question what the applicant really knows about those topics, while being fair to answer considering point-knowledge and stress level.

So the next time someone asks you 20 coding questions in a row, you know that he or she has basically no idea on how to interview someone properly. ;)


答:
Degrees last forever.*

Any time after you get the degree and apply for a job where a bachelor or master's degree is a requirement, your degree will fulfill that requirement.

Prospective employers are not going to say, "Well, when did you get the degree, because we only accept degrees that are less than 10 years old."  They will never say that.

Note that having a degree does not necessarily guarantee employment.  You must still have the skills and experience they are looking for.

* and so do really big fonts.

Title: How long does a Comp Sci degree last?


问:
What should plugins use: hooks, events or something else?
Consider an app that allows plugins to react to its program flow.

I know 2 ways to achieve this: hooks and events

1. Hooks

Use calls to empty functions inside the main program flow. These functions can be overriden by plugins.

For example, Drupal CMS implements hooks which are available to modules and themes. Here's an example of how hook is implemented in a file_copy function.

```<code>function file_copy(stdClass $source, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
    // ... [File copying routine]

    // Inform modules that the file has been copied.
    module_invoke_all('file_copy', $file, $source);

    return $file;
    // ...
}
</code>```

A module can implement a modulename_file_copy($file, $source) function which will be called by the module_invoke_all in file_copy. After this function finishes, the file_copy will resume execution.

2. Events

Have the app dispatch events, which can be listened to by the plugins. After receiving an event that it's been subscribed to, a plugin will intercept the program flow and perform neccessary operations.

For example, a jQuery gallery plugin Fotorama implements several events. As an example, here's a part of its show method that fires the fotorama:show event.

```<code>  that.show = function (options) {
    // ... [show the new frame]

    // [fire the event]
    options.reset || triggerEvent('show', {
      user: options.user,
      time: time
    });

    // ... [do lots of other stuff with navigation bars, etc.]
  };
</code>```

A script can listen to this event and do something when it fires:

```<code>$('.fotorama').on(
  'fotorama:show',
  function (e, fotorama, extra) {
    console.log(e.type + (extra.user ? ' after user’s touch' : ''));
    console.log('transition duration: ' + extra.time);
  }
);
</code>```

QUESTION

Are there other mainstream ways to implement such plugin behaviour?

If not, when should one use hooks, and when should one use events? Considering the ultimate goal is to make the code more maintanable and readable, from both the app and the plugin developer's perspective?

答:
Definitely events, it allows for the necessary abstraction already on the architectural level.

Do not expect that anyone writing a plugin actually does so as documented or in any way correct. I have been maintaining a well-documented API with millions of users and I can tell you from a very painful experience that basically no one ever reads the documentation and almost no one uses the API correctly.

Take the following example with hooks: You have a system where 20 plugins are running. One of those plugins calls the file_copy method in the way it is documented and expects a result as documented. But some other plugin has hooked that function and therefore one of the following issues causes a crash or malfunction:

The hook function simply crashes. All other plugins are screwed now,
because they can no longer file_copy or the function works differently from what is expected.

The input is correct based on the documentation, but the other plugin does not expect it and delivers strange results or crashes.

The call runs fine, but the result is no longer what is expected according to the documentation so the plugin fails or crashes.

If you do the same as above with events with the same issues inside those plugins the following happens:

The event function of plugin X crashes, but all others work fine. But since those plugins are not related, you can simply disable that crashing plugin while the others continue to work fine.

Strange input can be properly handled by your function and you can properly check for all possible things for each plugin individually. The plugin developer now has a stable and reliable way of actually testing his plugin, which allows him to be sure that if it works for him it will work for everyone. If one plugin provides incorrect input, it can be isolated to that one plugin.

Equally the result can be checked and defined properly under all circumstances, so the plugin developer has a stable and reliable answer from that function that he/she can test.


问:
Is Entity Framework 6 agnostic enough different sql server and OS platforms?
It's my first time using sql server, I usually go with MySQL, so I'm unsure how to do this.

The project I'm assigned will be deployed to multiple platforms particularly PC's with different SQL server ranging from 2008 to 2014, some of them are express edition, some are standard edition and in Windows ranging from XP, 7, 8 and 8.1 for both x86 and 64 bit systems

If I use entity framework 6 in my development PC, 64-bit windows 8.1 and SQL Server 2012 Express. Will this pose a problem during deployment?

答:
Entity Framework (EF) uses mostly basic syntax and keywords: select, join, distinct, etc. This basic syntax doesn't change too much from version to version.

Between SQL Server 2008 and SQL Server 2014, additional features were added, but they are outside the scope of EF.

If we study the head revision (04548560f3bc at the moment of writing) and especially the part of the source of EF which generates the queries, we can see that:

EF differentiates pre- and post-Katmai versions (Katmai is the codename of SQL Server 2008); see line 309.

Adapts himself to different versions of SQL Server.

Has very specific statements for the version 8.0 (SQL Server 2000); see line 450. It looks like SQL Server 2000 support is a nightmare even for EF.

This being said, make sure you run integration and system tests for every version of SQL Server you need to support.

Profiling is a different beast. If you notice issues with a query on some versions of SQL Server but not others, you may have to specify the SQL query manually, including having different queries depending on the version of the SQL Server.


问:
What license is HTML released under?
All products seem to be released with a license, I'm curious to know how one would go about finding out the license of technologies like HTML, CSS and JavaScript?</p>

答:
HTML, CSS, and Javascript as you are thinking of them are implementations of particular standards of the W3C (HTML and CSS) and ECMA respectively.

The actual implementations are licensed depending on the implementer. Adobe, Apple, Google, Microsoft, the Mozilla Foundation, and Opera Software are the most prominent of these.

Each will have their own licensing, Mozilla for instance uses MIT.

If you wanted to do your own implementation for your own from scratch web browser, then you'd have control of the licensing as they would be your implementations of the standard.

Otherwise, I'd go with whatever license the base implementation you're using uses. That is, whatever layout engine and JS VM you're building on. For instance, node.js is built on top of Google's V8 engine.

Title: What license is HTML released under?


问:
Can recursion be done in parallel? Would that make sense?
Say, I am using a simple recursive algo for fibonacci , which would be executed as:

```<code>fib(5) -> fib(4)+fib(3)
            |      |
      fib(3)+fib(2)|
                fib(2)+fib(1)
</code>```

and so on

Now, the execution will still be sequential. Instead of that, how would I code this so that fib(4) and fib(3) are calculated by spawning 2 separate threads, then in fib(4), 2 threads are spawned for fib(3) and fib(2). Same for when fib(3) is split to fib(2) and fib(1) ?

(I'm aware that Dynamic programming would be a much better approach for Fibonacci, just used it as an easy example here)

(if someone could share a code sample in C\C++\C# as well, that would be ideal)

答:
Of course it's possible, but for such a small example (and, indeed, for many that are much larger) the amount of plumbing/concurrency control code you'd have to write would obscure the business code to the point that it wouldn't be a good idea unless you really, really, really need Fibonacci numbers computed very fast.

It's almost always more readable and maintainable to formulate your algorithm normally and then let a concurrency library/language extension such as TBB or GCD take care of how to actually distribute the steps to threads.


答:
This is possible but a really bad idea; work out the number of threads you will spawn when calculating fib(16), say, and then multiply that by the cost of a thread. Threads are insanely expensive; doing this for the task you describe is like hiring a different typist to type each character of a novel.

That said, recursive algorithms are often good candidates for parallelization, particularly if they split the job into two smaller jobs that can be performed independently. The trick is to know when to stop parallelizing.

In general, you want to parallelize only "embarrassingly parallel" tasks. That is, tasks which are computationally expensive and can be computed independently. Many people forget about the first part. Threads are so expensive that it only makes sense to make one when you have a huge amount of work for them to do, and moreover, that you can devote an entire processor to the thread.  If you have 8 processors then making 80 threads is going to force them to share the processor, slowing each one of them down tremendously. You do better to make only 8 threads and let each have 100% access to the processor when you have an embarrassingly parallel task to perform.

Libraries like the Task Parallel Library in .NET are designed to automatically figure out how much parallelism is efficient; you might consider researching its design if this subject interests you.

Title: Can recursion be done in parallel? Would that make sense?

Body:
Say, I am using a simple recursive algo for fibonacci , which would be executed as:

```<code>fib(5) -> fib(4)+fib(3)
            |      |
      fib(3)+fib(2)|
                fib(2)+fib(1)
</code>```

and so on

Now, the execution will still be sequential. Instead of that, how would I code this so that fib(4) and fib(3) are calculated by spawning 2 separate threads, then in fib(4), 2 threads are spawned for fib(3) and fib(2). Same for when fib(3) is split to fib(2) and fib(1) ?

(I'm aware that Dynamic programming would be a much better approach for Fibonacci, just used it as an easy example here)

(if someone could share a code sample in C\C++\C# as well, that would be ideal)


答:
In your example you are calculating fib(3) twice, which leads to double execution of the whole fib(1) and fib(2), for higher numbers it is even worse.

You will gain probably speed over the nonrecursive solution, but it will cost a lot more in resources (processors) than it's worth.


问:
Standardized Programming Languages
Is there an organization similar to W3C that creates standards for programming languages?

If so, are there any programming languages, like browsers would using W3C standards, that implement these standards?

I have done my own research and I have been unsuccessful thus far hence the question. The answers and most of the comments so far are very useful but essentially I'm looking for a language or list of languages that have an open and reliable licensing system.

I think W3C has been the most successful at this up until now with HTML so I am looking for a language that has a similar licensing structure. Java has certain specifications like the EE servlet specification which has providers like Tomcat implement it but then at the end of the day that is still an Oracle owned standard isn't it?

答: It's very unclear to me what you mean with "standards", but there is for example the Java Language Specification which determines how a JVM should work and thus provides a guideline for people that want to write their own JVM implementation.</p>

Title: Standardized Programming Languages


问:
Do markup languages have the equivalent concept of `semantics` that you can find in C or C++?
Maybe I miss something, but do the so called markup languages have the equivalent concept of semantics that you can find in C or C++?

Judging from how you parse the language, you don't really have too many options, there isn't too much context, you just parse your tokens and apply them to the source code.

I'm tempted to say that not only semantics doesn't exist in this case, but this only happens in markup languages: am I right?

答:
A language is defined (a) by its syntax which includes the grammar and the lexical structure or vocabulary, and (b) the semantics, which is the meaning. In C, the snippet a + 1 has the meaning “add the contents of variable a and the integer 1”. In HTML, the snippet
foo bar
 has the meaning “a paragraph element containing the text foo bar”.

So markup languages do have semantics (i.e. a meaning). However, semantics have nothing to do with parsing. During parsing, the input is broken up according to the lexical structure. These tokens are then arranged according to the grammar of the language. E.g. the English snippet you asked a question might be arranged as

```<code>subject: 'you',
predicate: (verb: 'ask',
            tense: past,
            object: (article: indefinite,
                     noun: 'question'))
</code>```

This structure helps figuring out the meaning, but it's not the same as the actual meaning.

There can also be well-formed sentences that do not have valid semantics. For example, the above C example a + 1 makes no sense if a holds a struct instead of a numeric type. In English, Colorless green ideas sleep furiously would be an example of a well-formed, but nonsensical sentence.

Body:
A language is defined (a) by its syntax which includes the grammar and the lexical structure or vocabulary, and (b) the semantics, which is the meaning. In C, the snippet a + 1 has the meaning “add the contents of variable a and the integer 1”. In HTML, the snippet <p>foo bar</p> has the meaning “a paragraph element containing the text foo bar”.

So markup languages do have semantics (i.e. a meaning). However, semantics have nothing to do with parsing. During parsing, the input is broken up according to the lexical structure. These tokens are then arranged according to the grammar of the language. E.g. the English snippet you asked a question might be arranged as

subject: 'you',
predicate: (verb: 'ask',
            tense: past,
            object: (article: indefinite,
                     noun: 'question'))

This structure helps figuring out the meaning, but it's not the same as the actual meaning.

There can also be well-formed sentences that do not have valid semantics. For example, the above C example a + 1 makes no sense if a holds a struct instead of a numeric type. In English, Colorless green ideas sleep furiously would be an example of a well-formed, but nonsensical sentence.


答:
It’s questionable whether there is any other organization similar to the W3C; it really depends on your definition for similarity.

There are standards organizations in the strict sense (W3C is not a standards organization but an industry consortium) that define standards for programming languages, most importantly ISO, working together with the IEC in this area. They have a joint technical group, which has subcommittee SC 22 for “programming languages, their environments and system software interfaces”, which has created several standards.

There are other players in the field, too, like the ECMA association, which works on a few languages, such as JavaScript, which they call ECMAScript.

There are also many languages that have not been standardized, so that the closest equivalent to a standard is a vendor’s or language designer’s description or manual.

Title: Standardized Programming Languages

Body:
Is there an organization similar to W3C that creates standards for programming languages?

If so, are there any programming languages, like browsers would using W3C standards, that implement these standards?

I have done my own research and I have been unsuccessful thus far hence the question. The answers and most of the comments so far are very useful but essentially I'm looking for a language or list of languages that have an open and reliable licensing system.

I think W3C has been the most successful at this up until now with HTML so I am looking for a language that has a similar licensing structure. Java has certain specifications like the EE servlet specification which has providers like Tomcat implement it but then at the end of the day that is still an Oracle owned standard isn't it?


答:
There are no standards organizations specifically for programming languages.

ANSI (American National Standards Institute), ISO (International Standards Organization)(I think) exist to write standards.  When someone wants to put a standard together for something, they put a pitch together and present it to the organization.  If the organization agrees that it is time, they will help run the standard-writing and balloting process.

ANSI standards exist for FORTRAN and Ada.  The Ada standard is unusual in that it is a joint standard, with identical standard number, between ANSI and the US Department of Defense (ANSI/MIL-STD-1815A, if memory serves me).  Ada started as a DoD effort, and a decision was made to pursue ANSI standardization as well, to gain wider exposure for the language.  (This was successful, to a degree.  Ada is heavily used in commercial, non-military work, in Europe.)

ANSI and ISO standards exist for PASCAL.  They define different, slightly incompatible languages.  I don't recall the details now.

C++ is covered by an ANSI standard.  Something similar almost happened for C++.  During the ANSI effort, the European contingent tipped their hand that they were planning on making the ISO standard different, because of some issues that they felt the ANSI committee was not addressing adequately.  To their credit, the ANSI C++ committee, after saying "Say WHAT!?", backed up and addressed the issues.

There is an ANSI standard for FORTH.

ECMA (European Computer Manufacturers Association) has also done a few standards for languages.

Title: Standardized Programming Languages


问:
What are some famous one-liner or two-liner programs and equations?
I'm experimenting with a new platform and I'm trying to write a program that deals with strings that are no longer than 60 characters and I'd like to populate the data store with some famous or well-known small chunks of code and equations, since programming and math goes along with the theme of my software. The code can be in any language and the equations from any discipline of mathematics, just so long as they're less than a total of 60 characters in length. I suspect people are gonna break out some brainfuck for this one.

For example,

```<code>#include<stdio.h>
int main(){printf ("Hi World\n");return 0;}
</code>```

60 characters exactly!

Thanks so much for your wisdom!

答:
The largest number that can be represented by 8 Byte (Python)

```<code>print '\n'.join("%i Byte = %i Bit = largest number: %i" % (j, j*8, 256**j-1) for j in (1 << i for i in xrange(8)))
</code>```

Body:
The largest number that can be represented by 8 Byte (Python)

print '\n'.join("%i Byte = %i Bit = largest number: %i" % (j, j*8, 256**j-1) for j in (1 << i for i in xrange(8)))


问:
Planning poker with visually impaired colleague
At the office we just got a new colleague who is visually impaired.

I'm in charge of organizing the planning poker sessions and the new colleague must participate as a member of the team. We have these nice sets of poker cards with planning poker numbers on them, but that doesn't help of course for our new colleague.

Until now we fixed this problem by just naming the estimates, letting the new colleague say their estimate right after the rest had put down their card, then the rest flips their card and I name the estimates in a row.

My question(s): Is there any one who has experience with this kind of situation and have a better solution? Is there such a thing as Braille poker cards?

The current solution does work, but I think this can be improved for us all by for example Braille poker cards.

答:
You can solve this problem with a free and simple solution.

In our team, if we ever forget our planning poker cards we instead use our hands i.e. We clench our fists and show our estimates all at the same time. We find that this approach works very well as usually our estimates are on average at most eight points and any 13 point estimates are followed by a longer than usual discussion anyway.

I think this method would work great for you and your visually impaired colleague, as he/she would be able to give their estimate at exactly the same time as their team mates. When you all show your hands you then can go around the table and each member can speak out loud the estimate they gave. Yes, it won't be ideal if your team regularly estimates above 13 points, but I think it'll work great if your team usually estimates below this level.


问:
Where, in an object oriented system should you, if at all, choose (C-style) structs over classes?
C and most likely many other languages provide a struct keyword for creating structures (or something in a similar fashion). These are (at least in C), from a simplified point of view like classes, but without polymorphism, inheritance, methods, and so on.

Think of an object-oriented (or multi paradigm) language with C-style structs. Where would you choose them over classes? Now, I don't believe they are to be used with OOP as classes seem to replace their purposes, but I wonder if there are situations where they could be preferred over classes in otherwise object-oriented programs and in what kind of situations. Are there such situations?

答:
1) Network structs: structures that are transmitted over the wire.

More generally and formally, any class that you require to be POD, trivial, standard-layout, or a related concept. For an excellent discussion of these concepts, with examples, see this answer (it is for C++11).

2) Functors (predicates in particular), that you would pass over to functions like std::remove_if. Otherwise put, classes similiar to / inherited from std::binary_function or the like.

3) Meta-programming concepts, which may contain only public constexprs, and/or typedefs.

Edit: Note: This answer applies to C++ classes vs structs.


问:
How to simulate an ATM terminal in a POS
Recently I started same projects to improve my programming skills, so I tried to develop a point of sale software. I started to bay the required hardware (ticket printer, Barcode Scanner….) to make my personal lab, but I’m unable to find how to implement the payment process using an ATM terminal.

Is there any possibility to simulate the payment process whiteout having the equipment?

答:
An 'ATM terminal' is often a magnetic stripe reader (MSR).

There are several different approaches for this:

Keyboard 'wedge' or USB.  It hooks into the USB system and acts as another keyboard.  Magtek makes some (admittedly, this is a higher end brand).

Integrated keyboard mag stripe reader are actually part of a keyboard as can be seen with this Cherry Keyboard.

NFC devices.

Dedicated card readers with displays (such as those by VeriFone and Ingenico)

As some of these just act as keyboards themselves, yes, you can simulate it by typing the data in from a keyboard.  Otherwise, if you want to support things such as cherry keyboards and VeriFone 870 you will probably need to get one.  Especially consider that these devices are often dedicated computers of their own, with their own programming languages and operating systems (in the case of the 870 I linked, its an embedded linux system).

There are libraries that try to abstract away the 'card reader' (and then you can go about making something that works with JavaPOS or the like, but from experience, these can be very frustrating to work with as they often target the lowest common denominator of devices (and that can be very low).


问:
Bitwise-OR vs Adding Flags
I've seen others use Bitwise-OR to combine flags before:

```<code>#define RUN 0x01
#define JUMP 0x02
#define SHOOT 0x04

const byte madPerson = RUN | JUMP | SHOOT;
</code>```

That's also the way I do it.

But I've also seen some (not as many) combine flags using addition:

```<code>#define RUN 0x01
#define JUMP 0x02
#define SHOOT 0x04

const byte madPerson = RUN + JUMP + SHOOT;
</code>```

Which one is more "readable"? (Which one do you think more people will recognize?) What is the "standard" way to do it? Which one do you prefer?

答:
Bitwise-OR.

Addition is dangerous.

Consider an example where a bandit is a person, and an angry bandit is a bandit that speaks and shoots. Later, you decide all bandits should shoot, but you've forgotten about the angry bandit definition and don't remove its shooting flag.

```<code>#define PERSON 1 << 0
#define SPEAKS 1 << 1
#define SHOOTS 1 << 2
#define INVINCIBLE 1 << 3
const byte bandit = PERSON | SHOOTS;                    // 00000101
const byte angryBandit_add = bandit + SPEAKS + SHOOTS;  // 00001011 error
const byte angryBandit_or = bandit | SPEAKS | SHOOTS;   // 00000111 ok
</code>```

If you used angryBandit_add your game would now have the perplexing logic error of having angry bandits that can't shoot or be killed.

If you used angryBandit_or the worst you'd have is a redundant | SHOOTS.

For similar reasons, bitwise NOT is safer than subtraction for removing flags.

Title: Bitwise-OR vs Adding Flags

Body:
Bitwise-OR.

Addition is dangerous.

Consider an example where a bandit is a person, and an angry bandit is a bandit that speaks and shoots. Later, you decide all bandits should shoot, but you've forgotten about the angry bandit definition and don't remove its shooting flag.

#define PERSON 1 << 0
#define SPEAKS 1 << 1
#define SHOOTS 1 << 2
#define INVINCIBLE 1 << 3
const byte bandit = PERSON | SHOOTS;                    // 00000101
const byte angryBandit_add = bandit + SPEAKS + SHOOTS;  // 00001011 error
const byte angryBandit_or = bandit | SPEAKS | SHOOTS;   // 00000111 ok

If you used angryBandit_add your game would now have the perplexing logic error of having angry bandits that can't shoot or be killed.

If you used angryBandit_or the worst you'd have is a redundant | SHOOTS.

For similar reasons, bitwise NOT is safer than subtraction for removing flags.


问:
Should event listeners be held in weak references?
Usually event listeners shouldn't outlive object that registered them.

Does it mean that event listeners should be held by weak references by default (stored in weak collections by the object listeners are registered on)?

Are there valid cases when listener should outlive its creator?

Or maybe situation like that is a mistake and it shouldn't be allowed?

答:
Why shouldn't event listeners outlive the object that registered them? It seems like you are assuming event listeners should registered by methods of controls(if we take the GUI example) - or more precisely, methods by objects of classes that inherit the GUI toolkit's controls. That's not a necessity - you could, for example, use a specialized object for registering event listeners and ditch that object afterwards.

Also, if event listeners were weakly referred, you would have to actually keep references to them even if you never use that reference. Failing to do so will make the listener be collected at a random time. So, we get a bug that is

Easy to create by mistake(all you have to do is to forget storing an object in a reference variable that you'll never use).

Hard to notice(you'll only get that bug if the GC collect that object).

Hard to debug(in the debug session - which always works like a release session - you'll only encounter that bug if the GC collected the object).

And if avoiding that bug is not good enough incentive, here are some more:

You'll have to think of a name for each listener you create.

Some languages use static anlysis that'll generate a warning if you have a private member field that's never get written or never get read. You'll have to use have a mechanism for overriding that.

The event listener does something, and once the object that has it's strong reference is collected it'll stop doing that something. You now have something that affects the program's state and depends on the GC - which means the GC affects the concrete state of the program. And this is BAD!

Handling weak references is slower, since you have another level of indirection and since you need to check if the reference was collected. This wouldn't be a problem if having event listeners in weak references was necessary - but it isn't!


答:
The question has two answers, actually.

Can recursion be done in parallel? Would that make sense?

Yes, of course. In  most (all?) cases, a recursive algorithm can be rewritten in a way without recursion, leading to an algorithm that is quite often easily parallelizable. Not always, but often.

Think Quicksort, or iterating through a directory tree. In both cases a queue could be used to hold all the intermediate results resp. sub-directories found. The queue can be processed in parallel, eventually creating more entries until the task has been completed successfully.

What about the fib() example?

Unfortunately, the Fibonacci function is a bad choice, because the input values complety depend on previously calculated results. This dependency makes it hard to do it in parallel if you start every time with 1 and 1.

However, if you need to do Fibonacci calculations more often, it could be a good idea to store (or cache) pre-calculated results in order to avoid all calculations up to that point. The concept behind is quite similar to rainbow tables.

Lets say, you cache every 10th Fibo number pair up to 10.000. Start this initialization routine on a background thread. Now, if someone asks for Fibo number 5246, the algorithm simply picks up the pair from 5240 and start calculation from that point forward. If the 5240 pair is not yet there, just wait for it.

This way the calculation of many randomly choosen fibo numbers could be done very efficiently and in parallel, because it is very unlikely that two threads will have to calculate the same numbers - and even then, it would not be much of a problem.


问:
Dealing with technical debt and nearing release
Say you have a project that is a tangled mess. No code structure and breaking one area breaks the entire thing. Fixing one area breaks another area. The closest you can fix things is writing the code that's almost like redoing the entire thing. But then, the release is in the next week.

Here's some facts that actually worsen the situation:

There's very minimal testing. Makes breaking hard to find.

The code has no structure. Imagine one app has everything in one file.

No documentation. Very hard to replicate server requests when there's no documentation about the parameters to send, and what to expect.

What should one do to address this situation? The best thing to do is extend the project release, but I'm not the one who calls the shots. I did comment on the issue though.

答:
Sometimes the best thing to do is do nothing.

Leave the refactoring until after the release.  A week away from release, your number one priority should be finalising the current build.  The only code changes should really be bugfixes.

Don't extend the release.  Unreleased software doesn't sell.

Do schedule time specifically to address technical debt AFTER the release.

Do break down the technical debt into work items.  This way you will get specific flaws in the code structure addressed.

Do set a time limit for addressing technical debt.  Version 2 needs to be developed and good software probably won't hit its strides financially until around version 5.

The thing about software development is that imperfect software makes money.  Infinitely more money than unreleased software.  The purpose of software is to solve the customer's problems.  The purpose is not to have a beautifully engineered masterpiece.

In summary, release the software on schedule and allocate time to fix the worst technical debt problems.


问:
MVC4 : How to create model at run time?
In my project I am dynamically creating table by giving table name (ex. student) and adding fields to that table and then save table. Now, my table is created in SQL Server database.

Assume table has data and I want to show the data of table (ex student) on WebGrid. But, the problem is I have no model for that table (ex. student). So, how I can create model for newly created table or how I can show the the data on WebGrid?

答:
Don't do that

You really shouldn't be modifying table schema at runtime.  All sorts of things can go wrong.  You could have someone try to create a column that turns out to be a reserved word.  The access you are giving the user to be able to do these changes allows for things like dropping tables too.

You really shouldn't be modifying table schema at runtime.  It means you are not using much of what a database is good at.

Try an EAV table structure instead

If you are going to be writing dynamic data where columns change and are arbitrarily created, consider using an EAV table structure instead.  It is well known and understood how it works.

Yes, various DBAs and purists will fuss at at it, but will you suggest your proposed solution of adding columns at runtime, they will probably give in.  You can even find libraries that will let you write a model for it (such as EAV @ CodePlex).

Maybe try something out of NoSQL

Maybe you don't want a relational database at all.  Maybe you want something that has a document model and you're just sticking json in there.  Then mongo or couch would work acceptably.  Or maybe you want a column oriented database like Cassandra.  I'm not sure, but its something to explore if you really are after that 'creating columns at runtime' type thought.

Ok, you're really doing that

You can get the metadata from a table back.  In the Java world, this would be something like ResultSetMetaData which lets you find out the specifics of all of the columns, the types of data they store and other bits about it.

In C#, apparently this is stored in the DataColumn class.  From Retrieving metadata (table name) from a SQL statement on Stack Overflow:

```<code>SqlConnection con = new SqlConnection(connString);
String queryString = "Select CUSTOMER_NAME from CUSTOMER_DETAIL";
SqlCommand cmd = new SqlCommand(queryString, con);
DataTable myTable = new DataTable();
myTable.Load(cmd.ExecuteReader());
DataColumn column = myTable.Columns[0];
// zero based index of column, alternatively use column name
string typeOfColumn = column.DataType.Name;
// or column.DataType.FullName to get the fully qualified name of the System.Type
</code>```

Title: MVC4 : How to create model at run time?

Body:
Don't do that

You really shouldn't be modifying table schema at runtime.  All sorts of things can go wrong.  You could have someone try to create a column that turns out to be a reserved word.  The access you are giving the user to be able to do these changes allows for things like dropping tables too.

You really shouldn't be modifying table schema at runtime.  It means you are not using much of what a database is good at.

Try an EAV table structure instead

If you are going to be writing dynamic data where columns change and are arbitrarily created, consider using an EAV table structure instead.  It is well known and understood how it works.

Yes, various DBAs and purists will fuss at at it, but will you suggest your proposed solution of adding columns at runtime, they will probably give in.  You can even find libraries that will let you write a model for it (such as EAV @ CodePlex).

Maybe try something out of NoSQL

Maybe you don't want a relational database at all.  Maybe you want something that has a document model and you're just sticking json in there.  Then mongo or couch would work acceptably.  Or maybe you want a column oriented database like Cassandra.  I'm not sure, but its something to explore if you really are after that 'creating columns at runtime' type thought.

Ok, you're really doing that

You can get the metadata from a table back.  In the Java world, this would be something like ResultSetMetaData which lets you find out the specifics of all of the columns, the types of data they store and other bits about it.

In C#, apparently this is stored in the DataColumn class.  From Retrieving metadata (table name) from a SQL statement on Stack Overflow:

SqlConnection con = new SqlConnection(connString);
String queryString = "Select CUSTOMER_NAME from CUSTOMER_DETAIL";
SqlCommand cmd = new SqlCommand(queryString, con);
DataTable myTable = new DataTable();
myTable.Load(cmd.ExecuteReader());
DataColumn column = myTable.Columns[0];
// zero based index of column, alternatively use column name
string typeOfColumn = column.DataType.Name;
// or column.DataType.FullName to get the fully qualified name of the System.Type


问:
Is there really Object-relational impedance mismatch?
It is always stated that it is hard to store applications objects in relational databases - the object-relational impedance mismatch - and that is why Document databases are better.

However, is there really an impedance mismatch? And object has a key (albeit it may be hidden away by the runtime as a pointer to memory), a set of values, and foreign keys to other objects. Objects are as much made up of tables as it is a document. Neither really fit.

I can see a use for databases to model the data into specific shapes for scenarios in the application - e.g. to speed up database lookup and avoid joins, etc., but won't it be better to keep the data as normalized as possible at the core, and transform as required?

答:
The wiki article provides a reasonable overview but not necessarily real world experience.

The complexities of mapping a relational database to an OO scheme are vast and there is no such thing as "better".

It depends on a lot of things and consequently I often end up creating my own ORM implementations. A document database is only useful if your access pattern respects the one-way tree structure that a document database permits. If you need something else you may find yourself needing a graph database which wont prove any better than relational databases for typical usage scenarios.

Keeping data normalised as possible does give the most flexibility but not necessarily performance. Personally, I tend to find document databases more useful as advanced result caches than for anything else. This is a bit misleading because if you want to use your document data in any other way than your model caters too while anything may be possible it will be much slower. Performance depends on your access patterns and there is no "best" solution. I would recommend anyone to start with a relational database as this is likely to cater to most needs and give the best flexibility. It will also help give a measure of access patterns which will make any choice to use a document database reasonable.

I think that actually, apart from minor problems, it's very easy to match objects to relational data and vice versa. This is assuming you're not using any complicated features such as triggers.

The real problems occur during runtime and in the dataflow. You have problems with consistency, concurrency, performance, transactions, etc.

There are two hard problems that I always have with ORM:

You are storing data from the Database in RAM so there's an instant mismatch there because another process can come along in the background and change something. This is partly why even object databases are difficult to use. Sure, you can lock things, but if you peer below you can see why that might not work out so well.

Your libraries are writing most of the SQL for you just in time but have no chance in hell of being able to optimise as well as you can by hand. This is a just what you need scenario versus pull all the stops just in case. ORM cannot anticipate exactly what you need so you must either carefully tune it or it must try to cater for every scenario. In short, ORM is naive.

Consider that you have a table with a very large column and a number of smaller basic statistical columns. Most of the time you don't want to fetch the large column for performance. Here you must either find a way to tell the ORM to fetch only that column on demand in which case you have a potential consistency issue with the data already acquired, stick with poor performance, risk having to lock naively, change the schema to better suit the ORM with vertical partitioning, etc. It's not impossible to deal with but one of hundreds of problems, some more difficult than others. The point here is that in plain old SQL you would not have to think twice about this, you would just get what you need when you need without having to anticipating and unravel the ORM. The automatic nature of ORM makes it that much harder to anticipate especially when there is no one ORM pattern or implementation so you have to learn how your ORM operates under the hood to really use it properly. There are cases where ORM's can perform better but in > 90% of those cases you can achieve the same with a query cache or something simple as ultimately that is what ORM is doing in those cases.

ORM is meant to do things for you but it really can't anticipate all your needs. It ends up working like handwriting recognition on a touch screen where half the time rather than it recognising your handwriting, you have to make writting that it can recognise (some letters wont work unless you write then backwards such as e, etc). It's very common with ORM to be constrained to a specific schema layout beginning with primary keys for everything (but who doesn't do that anyway).

I have found that personally, what works best for me in most cases is a system of models for each table that auto generate the obvious queries that is inherited to provide custom queries for anything that needs it and a few separate models to provide categorisations to avoid god classes or misplaced queries. On top of this, I only really like to use ORM for view data where consistency tends to not matter as much anyway since it's going to be sent to a client where we have no control over and it's a last step process that occurs after all processing so will not directly affect writes.


问:
Can GPL v2 code link to an LGPL v3 library
If I write a library that is released under the terms of the GPL v2 (or higher, at option); may that library depend on another library released under the LGPL v3 (or higher), without implicitly enforcing GPL v3. That is, I am purely linking to that library.

Reading this and this, I understand that the LGPL v3 and GPL v2 are not "compatible". But it is not clear to me, whether compatibility means only mixing of code, or whether it extends to the linking (without modifying the LGPL'ed library).

答:
According to the License compatibility matrix from GNU, if you link your GPLv2 (or later) software with an LGPLv3 library, the effective license for the product becomes GPLv3.

The copyleft nature of the GPL licenses means that everything your software depends on must be available under the same terms as the part that actually carries the GPL license. That includes libraries you link to (with an explicit exception for major OS components and standard libraries).

The code doesn't have to be all licensed under the GPL, but the GPL does require that you have the freedom to modify all parts of an application that contains GPL code and that you have the freedom to distribute the application with or without modifications.

What it means for a license X to be compatible with the GPL is that the license X gives you, the user, at least as much freedom as the GPL does, so that in a product that contains both GPL code and code that uses license X, the distribution of that product doesn't violate any terms and conditions of either license.

GPLv3 and GPLv2 are not compatible with each other, because GPLv3 has put additional requirements in place, which is not allowed under GPLv2. This is also the reason why a combination of GPLv2 (or later) and LGPLv3 effectively 'upgrades' the GPLv2 code to GPLv3, which is possible under the "or later" permission.


问:
Serve content from server to remote embed HTML
The title is very bad so let me explain what I need to know. I have a server with let's say different images. What I want to achieve is be able to embed a frame, into any HTML site, and be the server the one that determines what image to show on that remote frame.

Imagine the situation where you want to add a piece of advertising to your site, but you just need to paste a piece of JS or HTML into your HTML and be the advertising seller be in charge of showing whatever he wants on the size of the frame.

My question is what is this technique/technology named ? What should I know, is it websockets ?, is it embedding ? How could I achieve this ?

Thanks !

答:
One way to achieve it is to use  element in HTML which is use to embed another document inline of the current HTML document.

http://www.w3schools.com/tags/tag_iframe.asp

Otherway to do it, would be to use JavaScript. You would have a JavaScript file which adds dynamic elements to the site. You could host it on your server and ask websites to include it via Link.

Body:
One way to achieve it is to use <iframe> element in HTML which is use to embed another document inline of the current HTML document.

http://www.w3schools.com/tags/tag_iframe.asp

Otherway to do it, would be to use JavaScript. You would have a JavaScript file which adds dynamic elements to the site. You could host it on your server and ask websites to include it via Link.


答:
When considering licenses for programming and markup languages (such as HTMP, CSS and Javascript), there are two copyright licenses to consider:

The copyright license of the language specification. This license covers the actual text that describes the definition of the language. The licenses can vary between languages, but they typically do not allow modification of the text and sometimes do not even allow copying (especially if the organization that publishes the specification tries to make money from selling copies).

The copyright license of the language's implementation. This license covers the program that interprets/compiles programs written in the language or renders a document. In the case of HTML/CSS/Javascript, this would be the browser and Javascript engine. Any (software) copyright license can be used here, varying between closed source, copyleft and permissive open source.

The two licenses under 1 and 2 are not related to each other in any way and for any specification you can have multiple implementations using a variety of licenses.

In a sense, the language itself is considered to be no more than an idea, which can't be copyrighted. The specification and implementations are different expressions of that idea and are independent as far as copyright is concerned.

Title: What license is HTML released under?

Body: All products seem to be released with a license, I'm curious to know how one would go about finding out the license of technologies like HTML, CSS and JavaScript?</p>


问:
Why prefer non-static inner classes over static ones?
This question is about whether to make a nested class in Java to be a static nested class or an inner nested class. I searched around here and on Stack Overflow, but couldn't really find any questions regarding the design implications of this decision.

The questions I found are asking about the difference between static and inner nested classes, which is clear to me. However, I have not yet found a convincing reason to ever use a static nested class in Java -- with the exception of anonymous classes, which I do not consider for this question.

Here's my understanding of the effect of using static nested classes:

Less coupling: We generally get less coupling, as the class cannot directly access its outer class's attributes. Less coupling generally means better code quality, easier testing, refactoring, etc.

Single Class: The class loader need not take care of a new class each time, we create an object of the outer class. We just get new objects for the same class over and over.

For an inner class, I generally find that people consider access to the outer class's attributes as a pro. I beg to differ in this regard from a design point of view, as this direct access means we have a high coupling and if we ever want to extract the nested class into its separate top-level class, we can only do so after essentially turning it into a static nested class.

So my question comes down to this: Am I wrong in assuming that the attribute access available to non-static inner classes leads to high coupling, hence to lower code quality, and that I infer from this that (non-anonymous) nested classes should generally be static?

Or in other words: Is there a convincing reason why one would prefer a nested inner class?

答:
Joshua Bloch in Item 22 of his book "Effective Java Second Edition" tells when to use which kind of nested class and why. There are some quotes below:

One common use of a static member class is as a public helper class, useful only in conjunction with its outer class. For example, consider an enum describing the operations supported by a calculator. The Operation enum should be a public static member class of the Calculator class. Clients of Calculator could then refer to operations using names like Calculator.Operation.PLUS and Calculator.Operation.MINUS.

One common use of a nonstatic member class is to define an Adapter that allows an instance of the outer class to be viewed as an instance of some unrelated class. For example, implementations of the Map interface typically use nonstatic member classes to implement their collection views, which are returned by Map’s keySet, entrySet, and values methods. Similarly, implementations of the collection interfaces, such as Set and List, typically use nonstatic member classes to implement their iterators:

```<code>// Typical use of a nonstatic member class
public class MySet<E> extends AbstractSet<E> {
    ... // Bulk of the class omitted

    public Iterator<E> iterator() {
        return new MyIterator();
    }

    private class MyIterator implements Iterator<E> {
        ...
    }
}
</code>```

If you declare a member class that does not require access to an enclosing instance, always put the static modifier in its declaration, making it a static rather than a nonstatic member class.

Body:
Joshua Bloch in Item 22 of his book "Effective Java Second Edition" tells when to use which kind of nested class and why. There are some quotes below:

One common use of a static member class is as a public helper class, useful only in conjunction with its outer class. For example, consider an enum describing the operations supported by a calculator. The Operation enum should be a public static member class of the Calculator class. Clients of Calculator could then refer to operations using names like Calculator.Operation.PLUS and Calculator.Operation.MINUS.

One common use of a nonstatic member class is to define an Adapter that allows an instance of the outer class to be viewed as an instance of some unrelated class. For example, implementations of the Map interface typically use nonstatic member classes to implement their collection views, which are returned by Map’s keySet, entrySet, and values methods. Similarly, implementations of the collection interfaces, such as Set and List, typically use nonstatic member classes to implement their iterators:

// Typical use of a nonstatic member class
public class MySet<E> extends AbstractSet<E> {
    ... // Bulk of the class omitted

    public Iterator<E> iterator() {
        return new MyIterator();
    }

    private class MyIterator implements Iterator<E> {
        ...
    }
}

If you declare a member class that does not require access to an enclosing instance, always put the static modifier in its declaration, making it a static rather than a nonstatic member class.


问:
Does C++ compiler remove/optimize useless parentheses?
Will the code

```<code>int a = ((1 + 2) + 3); // Easy to read
</code>```

run slower than

```<code>int a = 1 + 2 + 3; // (Barely) Not quite so easy to read
</code>```

or are modern compilers clever enough to remove/optimize "useless" parentheses.

It might seems like a very tiny optimization concern, but choosing C++ over C#/Java/... is all about optimizations (IMHO).

答:
The parentheses are there solely for your benefit - not the compilers. The compiler will create the correct machine code to represent your statement.

FYI, the compiler is clever enough to optimise it away entirely if it can. In your examples, this would get turned into int a  = 6; at compile time.


答:
Depends if it is floating point or not:

In floating point arithmetic addition is not associative so the optimizer can't reorder the operations (unless you add the fastmath compiler switch).

In integer operations they can get reordered.

In your example both will run the exact same time because they will compile to the exact same code (addition is evaluated left to right).

however even java and C# will be able optimize it, they will just do it at runtime.

Title: Does C++ compiler remove/optimize useless parentheses?

Body:
Will the code

```<code>int a = ((1 + 2) + 3); // Easy to read
</code>```

run slower than

```<code>int a = 1 + 2 + 3; // (Barely) Not quite so easy to read
</code>```

or are modern compilers clever enough to remove/optimize "useless" parentheses.

It might seems like a very tiny optimization concern, but choosing C++ over C#/Java/... is all about optimizations (IMHO).


问:
How long does a Comp Sci degree last?
I keep hearing from people that if I don't become a programmer soon after graduation my degree will be a useless piece of paper, they claim it will become outdated.  I kind of find this hard to believe considering what I was taught at a fairly good school has been standard practice for some time.

So is this a true belief in industry?  That somehow I become less desirable after a year or two, even though the graduates who comes after me pretty much get the same identical education.

答:
I think that some posters here are trying to console or assure themselves of something when they think that a degree is somehow eternal.

Unless you've possibly got an eidetic memory then knowledge and skills, un-maintained, will degrade over time.

The implication here is: the importance lies in what you've been doing since you graduated. Honestly, if someone got a comp-sci degree 10 years ago, and has been delivering the mail1 and not actively working in their field (paid or not), then their degree means little to nothing.

If, on the other hand, you haven't been able to get work for a couple of years, but you've contributed to some OS projects, worked on some hobby projects, published an article or two, made a website for your uncle's bakery and maintained a blog about whatever your programming interest are, then you're just as good (or better in some cases) as someone who graduated and has worked full-time since.

1 Occupation chosen at random, there's nothing wrong with delivering the mail - it's just not programming related.

Title: How long does a Comp Sci degree last?


答:
My suggestion is to use paper / cards & sounds.

Have everyone make their estimates with their cards / paper.  Then everyone shows their estimate at the same time.

At this point the visual members look around and you even hear folks say, hmm, 5,5, 2, hey bob, what's up with your 2? etc

So expand a little more on that verbal part.

Have everyone make their estimates, show their card / paper and very quickly have everyone (in turn) say their numbers.  Do that one-by-one (but quickly) so within 2-3 seconds you hear 5,2,5,4,5,5.  The visually impaired person will then know the range of values and also who's voice goes with with ticket which is probably essential (and also helps avoid the need for everyone to sit in the same spot each time).

Similarly if folks change their estimates during discussion make sure they verbalize any changes.

To avoid the all-critical 'influenced by' consider having members write down their initial choices on scraps of paper (or use playing cards).  Folks would choose the intended card initially and put the others down.  Then, when the 'going around' is done people would hold up their initially selected and only card AND say the points at that moment.

This is pretty close to what you are doing, the main change being to have each member verbalize their choice themselves, rather than you reading them all "for Bob" - which makes the "read for Bob" a distinct process which is not good socially for Bob.  It singles him out as being different and having special needs.

Try to make these techniques integral to your flow so that an outsider wouldn't notice differences easily.  Avoid any sort of "now lets 'say' our choices' or 'whoops I forgot about Bob'.  You can forget but if you do just say the number without discussion and apology and move on immediately.

Braille cards are good but remember that they make "Bob"'s impairment stand out, new/visiting team members have to be coached, Bob can't work on other scrum teams without them learning how the cards will be used.  All of which is a lot of focus for Bob which is one of the things you want to avoid for someone with special needs.  This is why I think the verbal approach avoid much of that.

Title: Planning poker with visually impaired colleague

Body:
At the office we just got a new colleague who is visually impaired.

I'm in charge of organizing the planning poker sessions and the new colleague must participate as a member of the team. We have these nice sets of poker cards with planning poker numbers on them, but that doesn't help of course for our new colleague.

Until now we fixed this problem by just naming the estimates, letting the new colleague say their estimate right after the rest had put down their card, then the rest flips their card and I name the estimates in a row.

My question(s): Is there any one who has experience with this kind of situation and have a better solution? Is there such a thing as Braille poker cards?

The current solution does work, but I think this can be improved for us all by for example Braille poker cards.


答:
You are correct in assuming that the attribute access available to non-static inner classes leads to high coupling, hence to lower code quality, and (non-anonymous and non-local) inner classes should generally be static.

Design implications of decision to make inner class non-static are laid out in Java Puzzlers, Puzzle 90 (bold font in below quote is mine):

Whenever you write a member class, ask yourself, Does this class really need an enclosing instance? If the answer is no, make it static. Inner classes are sometimes useful, but they can easily introduce complications that make a program difficult to understand. They have complex interactions with generics (Puzzle 89), reflection (Puzzle 80), and inheritance (this puzzle). If you declare Inner1 to be static, the problem goes away. If you also declare Inner2 to be static, you can actually understand what the program does: a nice bonus indeed.

In summary, it is rarely appropriate for one class to be both an inner class and a subclass of another. More generally, it is rarely appropriate to extend an inner class; if you must, think long and hard about the enclosing instance. Also, prefer static nested classes to non-static. Most member classes can and should be declared static.

If you're interested, a more detailed analysis of Puzzle 90 is provided in this answer at Stack Overflow.

It is worth noting that above is essentially an extended version of the guidance given in Java Classes and Objects tutorial:

Use a non-static nested class (or inner class) if you require access to an enclosing instance's non-public fields and methods. Use a static nested class if you don't require this access.

So, the answer to the question you asked in other words per tutorial is, the only convincing reason to use non-static is when access to an enclosing instance's non-public fields and methods is required.

Tutorial wording is somewhat broad (this may be the reason why Java Puzzlers make an attempt to strengthen it and narrow it down). In particular, directly accessing enclosing instance fields has never been really required in my experience - in the sense that alternative ways like passing these as constructor / method parameters always turned easier to debug and maintain.

Overall, my (quite painful) encounters with debugging inner classes directly accessing fields of enclosing instance made strong impression that this practice resembles use of global state, along with known evils associated with it.

Of course, Java makes it so that damage of such a "quasi global" is contained within enclosing class, but when I had to debug particular inner class, it felt like such a band aid didn't help to reduce pain: I still had to keep in mind "foreign" semantic and details instead of fully focusing on analysis of a particular troublesome object.

For the sake of completeness, there may be cases where above reasoning doesn't apply. For example, per my reading of map.keySet javadocs, this feature suggests tight coupling and as a result, invalidates arguments against non-static classes:

Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa...

Not that above would somehow make involved code easier to maintain, test and debug mind you, but it at least could allow one to argue that complication matches / is justified by intended functionality.

Title: Why prefer non-static inner classes over static ones?

Body:
This question is about whether to make a nested class in Java to be a static nested class or an inner nested class. I searched around here and on Stack Overflow, but couldn't really find any questions regarding the design implications of this decision.

The questions I found are asking about the difference between static and inner nested classes, which is clear to me. However, I have not yet found a convincing reason to ever use a static nested class in Java -- with the exception of anonymous classes, which I do not consider for this question.

Here's my understanding of the effect of using static nested classes:

Less coupling: We generally get less coupling, as the class cannot directly access its outer class's attributes. Less coupling generally means better code quality, easier testing, refactoring, etc.

Single Class: The class loader need not take care of a new class each time, we create an object of the outer class. We just get new objects for the same class over and over.

For an inner class, I generally find that people consider access to the outer class's attributes as a pro. I beg to differ in this regard from a design point of view, as this direct access means we have a high coupling and if we ever want to extract the nested class into its separate top-level class, we can only do so after essentially turning it into a static nested class.

So my question comes down to this: Am I wrong in assuming that the attribute access available to non-static inner classes leads to high coupling, hence to lower code quality, and that I infer from this that (non-anonymous) nested classes should generally be static?

Or in other words: Is there a convincing reason why one would prefer a nested inner class?


答:
In general, yes, weak references should be used. But first we have to be clear about what you mean by “event listeners”.

Callbacks

In some programming styles, especially in the context of asynchronous operations, it is common to represent a part of a calculation as a callback that gets executed on a certain event. For example a Promise [1] may have a then method that registers a callback upon completion of the previous step:

promise =
    Promise.new(async_task)                # - kick off a task
    .then(value => operation_on(value))    # - queue other operations
    .then(value => other_operation(value)) #   that get executed on completion
... # do other stuff in the meanwhile
# later:
result = promise.value # block for the result
```

Here, the callbacks registered by then have to be held by strong references, as the promise (the event source) is the only object holding a reference to the callback. This is not an issue as the promise itself has a limited lifetime, and will be garbage collected after the chain of promises is completed.

Observer Pattern

In the observer pattern, a subject has a list of dependent observers. When the subject enters some state, the observers are notified according to some interface. Observers can be added to and removed from the subject. These observers do not exist in a semantic vacuum, but are waiting for events for some purpose.

If this purpose does no longer exist, the observers should be removed from the subject. Even in garbage-collected languages, this removal might have to be performed manually. If we fail to remove an observer, it will be kept alive via the reference from the subject to the observer, and with it all objects that the observer references. This wastes memory and degrades performance as the (now useless) observer will still be notified.

Weak references fix this memory leak, as they allow the observer to be garbage collected. When the subject goes around to notify all observers and finds that one of the weak references to an observer is empty, that reference can be safely removed. Alternatively the weak references might be implemented in a way that allows the subject to register a cleanup callback that will remove the observer upon collection.

But note that weak references are only a band-aid that limit the damage by forgetting to remove an observer. The correct solution would be to make sure that an observer is removed when no longer needed. Options include:

Doing it manually, but that's prone to errors.

Using something akin to try-with-resource in Java or using in C#.

Deterministic destruction, such as via the RAII idiom. Note that in a language with deterministic garbage collection, this might still require weak references from the subject to the observer in order to trigger the destructor.

Title: Should event listeners be held in weak references?

Body:
Usually event listeners shouldn't outlive object that registered them.

Does it mean that event listeners should be held by weak references by default (stored in weak collections by the object listeners are registered on)?

Are there valid cases when listener should outlive its creator?

Or maybe situation like that is a mistake and it shouldn't be allowed?

Body:
In general, yes, weak references should be used. But first we have to be clear about what you mean by “event listeners”.

Callbacks

In some programming styles, especially in the context of asynchronous operations, it is common to represent a part of a calculation as a callback that gets executed on a certain event. For example a Promise [1] may have a then method that registers a callback upon completion of the previous step:

promise =
    Promise.new(async_task)                # - kick off a task
    .then(value => operation_on(value))    # - queue other operations
    .then(value => other_operation(value)) #   that get executed on completion
... # do other stuff in the meanwhile
# later:
result = promise.value # block for the result

Here, the callbacks registered by then have to be held by strong references, as the promise (the event source) is the only object holding a reference to the callback. This is not an issue as the promise itself has a limited lifetime, and will be garbage collected after the chain of promises is completed.

Observer Pattern

In the observer pattern, a subject has a list of dependent observers. When the subject enters some state, the observers are notified according to some interface. Observers can be added to and removed from the subject. These observers do not exist in a semantic vacuum, but are waiting for events for some purpose.

If this purpose does no longer exist, the observers should be removed from the subject. Even in garbage-collected languages, this removal might have to be performed manually. If we fail to remove an observer, it will be kept alive via the reference from the subject to the observer, and with it all objects that the observer references. This wastes memory and degrades performance as the (now useless) observer will still be notified.

Weak references fix this memory leak, as they allow the observer to be garbage collected. When the subject goes around to notify all observers and finds that one of the weak references to an observer is empty, that reference can be safely removed. Alternatively the weak references might be implemented in a way that allows the subject to register a cleanup callback that will remove the observer upon collection.

But note that weak references are only a band-aid that limit the damage by forgetting to remove an observer. The correct solution would be to make sure that an observer is removed when no longer needed. Options include:

Doing it manually, but that's prone to errors.

Using something akin to try-with-resource in Java or using in C#.

Deterministic destruction, such as via the RAII idiom. Note that in a language with deterministic garbage collection, this might still require weak references from the subject to the observer in order to trigger the destructor.