问:
How do you support your code post employment end?
What is the process for leaving a company (or even a group/division) in terms of code support?

Is it best to handle all questions? Do you give the remaining developers access to yourself as a future resource? If so, is there a way to not give full access?

I've experienced first hand where answers about the general software arthitecture from the initial developer would be invaluable.

I understand that if serious assistance is needed, than it becomes a typical case of employment negotiation as a support contract. However, should serious assistance be required, what steps can you make to ease that process of contacting you?

I was thinking of doing something like making a (YOUR_NAME)_codesupport @ (YOUR_FAVORITE_EMAIL_CLIENT).com address.

My Situation Specifics:

I'm a co-op student, and as such bounce around companies on 4-month stints. This means introducing myself to a lot of new code bases, as well as leaving a fair share of orphaned code behind when I leave a company. I feel bad if I leave junk code around.

答:
Few things I would like to mention.

In business, money is above sentiments. The employer usually do not have the same sentiments you have from your own side. Once you leave the company, the deal is done. The negotiations and the notice period stuffs are steps to mitigate their risks.

Of course people helps each other with their personal choices but companies really don't expect you to come back fix the things for them even you wrote in the past. But there are exceptions but it depends on how you're important to the work.

One of my friends had left his company 1 year back and recently he was contacted by one of the project managers to fix an issue with the code he wrote few years back. Considering the turnaround and the complexity to fix the issue, he was the easiest option. Finally he helped them to fix the issue; but on his personal interests and ethics. And note that several employers can't agree with this. i.e he's going back to his old company and fixing issues.

Things you've to notice is that,

Those who do serious business act professionally in this situation. They don't want you anymore.

The highest chance to get a call from ex-employer is a personal call. Usually it will not be an organizational decision to approach you and fix the code. Also they do respect your time and current assignments before asking your time.

Corporate companies maintains at most secrecy for their code and design. They don't want to expose even to ex-employees.

Mostly the employees who quit the company will be joining in companies with similar domain. And the ex-company and the new company could be competitors. If you're holding patents and the based on the nature of the company's operating principle, most of the companies won't allow ex-employees to work with them even if the ex-employee wants to.

In your specific case, I suspect how a 4 months stint can make you very critical to the organization and project unless until you're giving them radically something new born in your heads.


问:
How can I send a signal to a program via external hardware
I am trying to find a piece of hardware that will signal a program to start a timer when it is moving and stop when it stops. The hardware can just be a ball that moves and is connected to the computer through USB, I was thinking of something similar to the way a mouse would work. For the programing I would like to use c# or possibly ActionScript with adobe air. I am a web developer and have not had any experience with hardware or drivers and would appreciate any ideas on where to start. Maybe there is some piece of simple hardware out there that I can use to send signals to the computer or some literature of articles for beginners that you can point me to. Thanks in advance</p>

答: You could also go for a Digital USB-Module that you can directly address hardware via USB. </p>

ContentLicense: CC BY-SA 3.0


问:
Rush to client-side in web development
In the past few months, I recognized a big excitement about client-side scripting in web development. But while server-side technologies are mature, stable and well accepted by backend-developers, client-side technologies are immature (i.e. compared to big server-side framework) and disliked by many long-established developers. Nevertheless everyone is doing client-side development these days. I personally expect those big server-side frameworks to disappear in like 2-5 years, watching the current trend.

Why is that so? How could the new and "diffuse" client-side developing in HTML5/JS possibly be superior to big and well thought server-side solutions?

答: Another factor which is driving enthusiasm for client-side solutions is the growth of mobile apps. If you make a website heavily based on client-side JavaScript and AJAX, and also build native iOS and Android apps, there's a good chance that all three can use the same REST services to do all of their data to'ing and fro'ing.</p>

Title: Rush to client-side in web development


问:
Enterprise Integration: File Exchange vs Web Services
TL;DR

Sort of brainstorming: why integrating systems by means of exchanging loosely-structured files (as opposed to XML web services integration) is a bad idea?

TL Part

We're offering an online solution for enterprise customers (big ones) and in implementing this we often need to integrate with their internal systems (HR databases, CRM and ERP systems, you know the drill).

One of the most common integration point is that we need to have information about their employees in our internal databases. To that end, we're advocating information exchange via XML Web Services with either us calling their WS Endpoint on a regular basis and asking for changes since timestamp or them invoking our WS and supplying all the information required. Enterprisey and buzzwordy enough, sure.

Now, what we're offered is: every week we'll manually export our HR data into an Excel workbook, email it to you and expect this data to be where it belongs. Slightly better option: automatically exported Excel file is shared on a network drive accessible over VPN.

Naturally, this is error-prone and doesn't scale, but that's the only cost-effective option for our customers. We need somehow to persuade them to switch over to Web Services, but since the final decision on whether our system will be implemented or not is made by someone without technical background we need to either present non-techincal arguments or present them in a way that's understandable by a mere mortal.

答:
The more the input is loosely-structured, the harder is to parse it. In this way, XML is already loosely-structured. When I get <price/> tag, I expect it to be a number, like <price>59.90</price>, but nothing, in XML, ensures that I will actually receive a number. What about <price>USD59.90</price>, or <price>59,90 €</price>, or <price>I don't know what to put here because I'm lazy to read the API</price>?

The nice part is that you can validate XML with DTD. The same is not true for Excel.

The closer the data format is to the user, the more random this data would be. Just because users appreciate the ability for them to add sheets in Excel or reorder columns, etc., and they expect any parser using the data from the Excel being able to still understand where the data is and how is it saved.

I had to work on an application which parsed some PDF documents. Once, the phone rung in the IT support department. The customer was screaming about how the application sucks: when he sends his PDF, the application responds that the PDF contains no text. When the customer finally sent us the PDF, we immediately understood what was wrong: it was a scanned document with no OCR: every page contained just a bitmap with the scanned text. For this customer, it was still text and our app was expected to read it as any other text document.

This randomness makes it very difficult to work with those files. In XML, you at least expect some structure. What if you had to parse:

```<code><product>
    <product <title>Product 1
    price="59.90
    in-stock >19<

    <product> title=Product 2
    price="Fourty nine USD ;
    inStock = 62
</products>
</code>```

This is still XML, and the user would not understand why your stupid app can't parse something like this, while it's very clear.

Now, let's get back to the arguments you can give to your stakeholder with no technical background:

1. How the integration service would be notified?

With a web service, it's easy. You invoke it, sending the HR data to it, and that's all.

With an Excel file on a network drive, things become complicated:

Either the integration service constantly checks for new files on this drive, in which case this will have an important impact in terms of bandwidth (also, if the network drive is unreliable, this may arise even more issues),

Or the integration service must be called after saving the Excel file, in which case instead of directly using the web service, you are using the network drive, then a web service.

2. Loading data from Excel is expensive

    2. a. In terms of immediate cost

Any decent programming language can parse XML. None, I believe, can read Excel files. In order to read them, you must either use Microsoft Excel COM (which is limited to the desktop version, and can't be done server-side), or some paid third party products.

    2. b. In terms of resources

I don't have profiler results to support this, but very probably loading data from an Excel file would cost much more in terms of CPU then parsing XML.

3. Loading data from Excel is error-prone

Excel files have one problem: they are modified by users, and users may do any change they want. What if they rename a column? What if they add a sheet before the one you need to parse? What if they export the Excel data in a format you didn't expect?

Here's the conclusion for the stakeholder with no technical background:

Cost effective, you say?

Let's see. With the Excel on a network drive approach, you would need to develop two systems instead of one, given that one of the systems will be hugely error prone (heavily increasing the maintenance cost) and would require buying licenses and more powerful servers.

Higher infrastructure cost;

Higher development cost;

Higher maintenance cost.

Body:
The more the input is loosely-structured, the harder is to parse it. In this way, XML is already loosely-structured. When I get <price/> tag, I expect it to be a number, like <price>59.90</price>, but nothing, in XML, ensures that I will actually receive a number. What about <price>USD59.90</price>, or <price>59,90 €</price>, or <price>I don't know what to put here because I'm lazy to read the API</price>?

The nice part is that you can validate XML with DTD. The same is not true for Excel.

The closer the data format is to the user, the more random this data would be. Just because users appreciate the ability for them to add sheets in Excel or reorder columns, etc., and they expect any parser using the data from the Excel being able to still understand where the data is and how is it saved.

I had to work on an application which parsed some PDF documents. Once, the phone rung in the IT support department. The customer was screaming about how the application sucks: when he sends his PDF, the application responds that the PDF contains no text. When the customer finally sent us the PDF, we immediately understood what was wrong: it was a scanned document with no OCR: every page contained just a bitmap with the scanned text. For this customer, it was still text and our app was expected to read it as any other text document.

This randomness makes it very difficult to work with those files. In XML, you at least expect some structure. What if you had to parse:

<product>
    <product <title>Product 1
    price="59.90
    in-stock >19<

    <product> title=Product 2
    price="Fourty nine USD ;
    inStock = 62
</products>

This is still XML, and the user would not understand why your stupid app can't parse something like this, while it's very clear.

Now, let's get back to the arguments you can give to your stakeholder with no technical background:

1. How the integration service would be notified?

With a web service, it's easy. You invoke it, sending the HR data to it, and that's all.

With an Excel file on a network drive, things become complicated:

Either the integration service constantly checks for new files on this drive, in which case this will have an important impact in terms of bandwidth (also, if the network drive is unreliable, this may arise even more issues),

Or the integration service must be called after saving the Excel file, in which case instead of directly using the web service, you are using the network drive, then a web service.

2. Loading data from Excel is expensive

    2. a. In terms of immediate cost

Any decent programming language can parse XML. None, I believe, can read Excel files. In order to read them, you must either use Microsoft Excel COM (which is limited to the desktop version, and can't be done server-side), or some paid third party products.

    2. b. In terms of resources

I don't have profiler results to support this, but very probably loading data from an Excel file would cost much more in terms of CPU then parsing XML.

3. Loading data from Excel is error-prone

Excel files have one problem: they are modified by users, and users may do any change they want. What if they rename a column? What if they add a sheet before the one you need to parse? What if they export the Excel data in a format you didn't expect?

Here's the conclusion for the stakeholder with no technical background:

Cost effective, you say?

Let's see. With the Excel on a network drive approach, you would need to develop two systems instead of one, given that one of the systems will be hugely error prone (heavily increasing the maintenance cost) and would require buying licenses and more powerful servers.

Higher infrastructure cost;

Higher development cost;

Higher maintenance cost.


问:
Is there a chart for helping me decide between open-source licenses?
The Open Source Initiative lists 9 different licenses in their list of "License that are popular and widely used or with strong communities".

I want to license my project as open-source. Unfortunately, I do not speak legalese. Is there some chart I could consult that will help me make the right choice, or at least point me in the right direction? For example a table summarizing the differences between the licenses, or perhaps a flow-graph using my requirements to guide me into the correct license for me?

I also intend to meet a lawyer, but any information to start with will help.

答:
As you have asked for a chart of Open source licenses comparison:

Please, read this excellent article too: Adopting an Open Source Approach to Software Development, Distribution, and Licensing.


问:
How can I make refactoring a priority for my team?
The codebase I work with daily has no automated tests, inconsistent naming and tons of comments like "Why is this here?", "Not sure if this is needed" or "This method isn't named right" and the code is littered with "Changelogs" despite the fact we use source control. Suffice it to say, our codebase could use refactoring.

We always have tasks to fix bugs or add new features, so no time is put aside to refactor code to be better and more modular, and it doesn't seem to be a high priority.

How can I demonstrate the value of refactoring such that it gets added to our task lists? Is it worth it to just refactor as I go, asking for forgiveness rather than permission?

答:
The code got this way slowly over many small changes.  It will need to fixed that way too.

You can do this as you go along, first of all - increase all estimates by 10% to allow for code enhancement and long term maintenance.   If anyone complains ask them if it better to check the oil in a car engine every week or to wait until the engine completely locks up.

Have a meeting and determine consistant coding standards.

Introduce basic rules to use as you go along:

Whenever new code is introduced into a class automated tests have to be written to prove the class works (not just the new code).

Whenever a bug is fixed automated tests have to be written to prove the class works (not just the fixed code).

Whenever a programmer modifies a file he has to fix all of the compiler warnings in that file and update code so it meets the new coding standards.

After a while the most used code will be up to date and be covered by automated tests.  The older code will be updated when it is changed, if it is never changed then you never need to worry about it.

The important thing is to build these habbits into the standard coding tasks so none of them take a huge amount of time away from 'real' work but they all provide real benefits.  Do not try to make a project out of refactoring old code, it is a horrific, boring, fiddly pain which will look like a lot of time wasting to non technies!


答:
Talk to them and find out who really looks after the technical side of the source system.

Its unlikely that the data is held in a spreadsheet. More likely their system has an fairly easy to use "export to spreadsheet" function which is all the people you are talking to know.

If its a large enterprise customer they are probably using a mega expensive package from one of the tier one vendors. All of these support many interfaces, and, have a variety of facilities for export data to other systems.

If you do go the exchange files route try to get a database extract/unload file, and try to have it generated automatically by "cron" or some other scheduler. Any manual process will fail every six  months or so.

Title: Enterprise Integration: File Exchange vs Web Services

Body:
TL;DR

Sort of brainstorming: why integrating systems by means of exchanging loosely-structured files (as opposed to XML web services integration) is a bad idea?

TL Part

We're offering an online solution for enterprise customers (big ones) and in implementing this we often need to integrate with their internal systems (HR databases, CRM and ERP systems, you know the drill).

One of the most common integration point is that we need to have information about their employees in our internal databases. To that end, we're advocating information exchange via XML Web Services with either us calling their WS Endpoint on a regular basis and asking for changes since timestamp or them invoking our WS and supplying all the information required. Enterprisey and buzzwordy enough, sure.

Now, what we're offered is: every week we'll manually export our HR data into an Excel workbook, email it to you and expect this data to be where it belongs. Slightly better option: automatically exported Excel file is shared on a network drive accessible over VPN.

Naturally, this is error-prone and doesn't scale, but that's the only cost-effective option for our customers. We need somehow to persuade them to switch over to Web Services, but since the final decision on whether our system will be implemented or not is made by someone without technical background we need to either present non-techincal arguments or present them in a way that's understandable by a mere mortal.


问:
When designing an enterprise API, what level is appropriate for separating libraries?
Assume we are developing a REST system for an enterprise company to expose the companies resources in a Java based application. Ultimately you have one web application, and domain libraries. My question is to where components and services should live in these domain libraries and what should exist in the application itself.

For a hypothetical company we may have several domain areas.

Customer Relations

Customer Sales Orders

Manufacturing

Product Structure

Supply Chain

Warehousing

Given these domains we would have domain objects and object services for persistence. We could then further separate these into implementations

Customer Relations

Customer Relations - JDBC Impl

Customer Sales Orders

Customer Sales Orders - JDBC Impl

Manufacturing

Manufacturing - JDBC Impl

Product Structure

Product Structure - JDBC Impl

Supply Chain

Supply Chain - JDBC Impl

Warehousing

Warehousing - JDBC Impl

Now it's starting to look complex only because of how many individual libraries we are managing. I'm wondering if we even need to separate to such a level and could simply have the three.

Business - Interface

Business - JDBC Impl

REST Application

My second part of my question relates to where service classes and management classes should live. Given our Warehousing above we need domain objects to represent pick-faces, a DAO class to manage the pick-face object and finally a service component for our rest application. For this we could see the following structure.

Warehousing

PickFace

PickFaceDAO

Warehousing - JDBC Impl

JdbcPickFaceDAO

ReST application

PickFaceController

On the one hand PickFaceController is best inside the ReST application as the application can then manage the services for this controller manually and may need to customise configuration.

But, on the other hand the PickFaceController might be better inside the Warehousing project as it's only concerned to the warehousing module, yet the ReST application could theoretically use service locators to find services in other libraries.

SO what are the successful approaches being used? When do you know when you've gone to far in separating or not done enough? How do you know the best place to put something?

答:
You should take a look at Onion Architecture - it works very well when with domain driven design.

In summary, the Onion Architecture advocates that you layer your application least-dependent/longest-living to most-dependent/shortest-living. Your domain classes with repository interfaces would remain inside the core while the specific implementations would reside in an outer layer.

Typically, you would have something like this (top has no dependencies, all below depends on what's above):

Common/Shared core functionality

Core Layer - Domain Models, Domain Services, Interfaces

Application Layer - Orchestration and anti-corruption layer

Infrastructure Layer - Typically concrete implementations of domain interfaces

Presentation Layer

The idea here is that the Common/Shared core functionality is available everywhere (mostly helpers, shouldn't contain domain logic per se).

The Application and Infrastructure Layers would depend on the Core Layer and Common/Shared core functionality.

The Presentation Layer would depend on the Application, Infrastructure and Common/Shared core Layers but not directly ontop of the Core Layer to ensure anti-corruption.

There might be more than one Application Layer - This depends on how many endpoints you might have (one Application Layer might be a Web Service). You don't want your presentation layer to depend directly upon your Core Domain Models because it voilates the single responsibility principal (domain logic should apply to domain models - given the domain objects the responsibility of data transfer objects imposes certain limitations upon implementation of domain logic).

I hope that guidance is of worth to you. I can't make the judgement of exactly how you should split up your project into different libraries because that would depend on other factors.

In the end there's nothing stopping you from putting all of it inside a single assembly. You would typically split them up by bounded context (self-contained) in order to ensure dependency inversion on a logical separation level. There are also utilities available out there to combine multiple libraries into a single one for deployment.


问:
Story points for bug fixing tasks: Is it suitable for Scrum?
I'm just wondering if we should assign story points to bug fixing tasks or not. JIRA, our issues-tracking software, does not have story point field for Bug type issues (it's only for Storys and Epics).

Should we add the Bug issue type to the applicable issue types of the Story Points field?  What are the pros and cons? Would it be suitable for Scrum?

答:
I would recommend treating the bug as a user story and assigning it a number of points. I wouldn't necessarily write it in the format of "As a X, I want to Y so that Z" as is common with user stories - I'd write it more as "As a X, when I Y, Z happens, but Z' is the expected behavior".

The advantage of this is that it allows you to prioritize bug fixes right along side new feature requests. The truth is that sometimes, a new feature is more important than fixing a bug. However, it also allows you to properly size the work required, allowing you to fit it into a sprint when you have the capability of doing so.

One thing to keep in mind that it might be difficult to estimate the effort that is required to fix a bug. It could involve multiple components that interact with each other, requiring someone to become very familiar with the interactions of large pieces of the system or multiple people to work on the fix.


问:
What made object oriented programming successful?
What is that feature according to you that has made object oriented programming so much successful ?

Message Passing

Inheritance

Polymorphism

Encapsulation

Or some other feature that you may like to introduce.

Also I would like to know that what is the connection between Abstract Data type and Object Oriented programming?

答:
Abstraction

Providing the necessary services hiding the unnecessary things. See my explanation here-
What is abstraction?

ContentLicense: CC BY-SA 2.5


答:
Ideally, your software should be bug-free after each iteration, and fixing bugs should be part of each sprint, so the work required to fix bugs should be considered when assigning story points (i.e., a task that is more likely to produce bugs should have more story points assigned to it).

In reality, however, bugs surface post-deployment all the time, no matter how rigid your testing; when that happens, removing the bug is just another change, a feature if you will. There is no fundamental difference between a bug report and a feature request in this context: in both cases, the application shows a certain behavior, and the user (or some other stakeholder) would like to see it changed.

From a business perspective, bugfixes and features are also the same, really: either you do it (scenario B), or you don't (scenario A); both scenarios have costs and benefits attached, and a decent business person will just weigh them up and go with whatever earns them more profit (long-term or short-term depending on business strategy).

So yes, by all means, assign story points to bugs. How else are you going to prioritize bugs vs. features, and bugs against bugs? You need some measure of development effort for both, and it better be comparable.

The biggest problem with this is that bugfixes are often harder to estimate: 90% or more of the actual effort lies in finding the cause; once you have found it, you can come up with an accurate estimate, but it is almost impossible to judge how long the search will take. I've even seen a fair share of bugs where most of the time was spent just trying to reproduce the bug. On the other hand, depending on the nature of the bug, it is often possible to narrow down the search with some minimal research before making an estimate.

Title: Story points for bug fixing tasks: Is it suitable for Scrum?

Body:
I'm just wondering if we should assign story points to bug fixing tasks or not. JIRA, our issues-tracking software, does not have story point field for Bug type issues (it's only for Storys and Epics).

Should we add the Bug issue type to the applicable issue types of the Story Points field?  What are the pros and cons? Would it be suitable for Scrum?


答:
Estimating bugs with points is inherently difficult as already pointed out in other answers and yes the ideal solution is that bugs found in a feature AFTER the sprint has been accepted should be considered new features.

This difficulty in point estimation for bugs however is one of many reasons that Agile PM software packages allow for tasks and bugs to be estimated in hours, because it takes dilligence and experience to become skilled at point estimation.  Many projects run into significant problems with properly determining velocity, so many Agile projects use points to determine what stories make it into the sprint, however they use hours when calculating the burndown chart.

It seems counter intuitive but manageable as long as hours estimation is not used as a factor in determining the sprint commitment.  Overcommittment will naturally lead to missed or incomplete features or overtime, so over time all involved are forced to get better at point estimation, at which point estimating hours on tasks and bugs slowly become a meaningless metric.


问:
What are the various branches of the C++ language out there?
Last time I tried to use C++ several years ago I remember having to include different libraries between different IDEs even though I was using the same operating system, which left me somewhat confused about the C++ language.

Are there different standardizations of the C++ language? And if so, what branches of the language exist out there? Is the syntax and/or library names for each standardization different between operating systems? Also, What is primary standardization used nowadays?

答:
The biggest place I've seen this is with C++11, which included most of the Technical Report 1 libraries.  For example, to access the hash table (unordered_map), you used to have to #include <tr1/unordered_map> and it was in the namespace std::tr1.  Now, you just leave the tr1 off of both.

The C++ standard has been revised several times, the most recent being C++11, C++03, and C++98.  However, few compilers implement the full spec in one release, so different releases of different compilers support different parts of the spec.  Plus, since the spec is written in a natural language (English), it has ambiguities, and corner cases can be handled differently by different compilers.

Similarly, in one implementation of the standard library, #include <vector> may automatically #include <algorithm>, whereas in another, it may not.  So in one implementation, you might be able to get away with using the methods in algorithm without including it, even though your program does not technically conform to the C++ spec.

As for the primary standardization, if you're starting a project from scratch now, you should use C++11 and the latest stable release of your favourite compiler.  Not all features are fully implemented by all compilers, but e.g. you should use unique_ptr instead of auto_ptr, use (simple) lambdas, and the auto keyword where it improves readability.


答:
It's difficult to suggest a solution without knowing exactly what it is you are trying to communicate with. There may be existing hardware that you can use, or you may need to create your own.

If there is an existing hardware that you can use, such as a mouse as a simple example, then all you need to do is communicate with the driver via it's API.

If you plan to make your own hardware, then depending on your budget, you may be able to create a custom device and create your own driver and API.

The easiest and most flexible option however, is to use an Arduino, or similar PIC product. An Arduino is a microcontroller, that can be used to interface with and control various sensors and input devices. You would create your custom sensors to detect the movement, and connect these to the arduino. You can then interface to the Arduino via a serial connection within a C# application on the PC.

See www.arduino.cc for more information and lots of tutorials on how to use an Arduino.

Arduino's are great for experimenting or one of projects, but may not be suitable for a commercial product.

Title: How can I send a signal to a program via external hardware

Body: I am trying to find a piece of hardware that will signal a program to start a timer when it is moving and stop when it stops. The hardware can just be a ball that moves and is connected to the computer through USB, I was thinking of something similar to the way a mouse would work. For the programing I would like to use c# or possibly ActionScript with adobe air. I am a web developer and have not had any experience with hardware or drivers and would appreciate any ideas on where to start. Maybe there is some piece of simple hardware out there that I can use to send signals to the computer or some literature of articles for beginners that you can point me to. Thanks in advance</p>


问:
Best approach for writing a chess engine?
I'm a chess enthusiast and a programmer. I recently decided to start making a chess engine using my chess and programming knowledge. So here's my question:

What language (I'm familiar with Java, C++ and Python) and methodology should I adapt while writing a chess engine?

A little guidance would be much appreciated.

Edit:

So I decided to make it in JavaScript. I download this Chess UI from github and now I'm all set! My first step would be to write legal moves for it. So can anybody point me in the right direction? (I'm new to jQuery but have alot of programming experience).

P.S: I'm not trying to make a very efficient engine (I know its way too difficult), I just want to get familiar with the process and learn some new techniques along the way.

答:
For the computer-player-making-decisions part of the game, I can't recommend enough the book "Artificial Intelligence: A Modern Approach" (book website http://aima.cs.berkeley.edu/). Depending on your background in mathematics (graph theory helps) it may be a little high level, but it is written as simply as this academic stuff can be and it contains a very up-to-date overview (and some depth) of techniques to make programs decide things.

It will point out things to you such as stating a goal (i.e. checkmate or a null), evaluating how close a particular state (board layout) is to that goal, how to generate the different possible following states starting from the current one, and how to traverse what is an immense problem space.

One thing that might help in designing an AI algorithm is to figure out how to decide which move to play next as if you had all the time in the world, starting from a situation very close to a won game. You optimize it so that it finds a solution in a reasonable amount of time (hours), then find ways to choose a winning path even though you haven't explored all the outcomes yet, so that you can actually interrupt the "thinking" to a turn's worth of time.

Only then would I look at optimizing the representation of to make the individual calculations faster, such as using long integers as was suggested. No matter how fast so you can make a single comparison, if the way you traverse the problem space does not have a good heuristic, it's going to take ages to do so.


问:
Reasonable test coverage requirements when dealing with a contractor?
We're outsourcing some work to an external developer, so I'm busy writing up a contract about what constitutes a deliverable.

So far I require that the code is shipped with automated tests.

But, what is a reasonable way to specify the detail of tests up-front in the contract in a measurable way?

I'm loathe to say "100% code coverage" because it's been established pretty often that 100% is pretty meaningless, and the diminishing returns above about 70-80% would probably just be pushing up our costs unnecessarily, and possibly even pushing up the complexity of certain things that might otherwise be very simple.

Internally we pretty much leave it up to our developers to decide on the level of tests needed, based on their intuition and experience. With a contractor however there is a fixed price that has to be agreed to up front and we need some way to enforce a certain level of quality.

Any suggestions or recommended reading matter would be appreciated!

答:
If you want a number, 80% is often used.  In fact, where I work presently our continuous integration server (Hudson) displays a yellow light for any project on which the test coverage is below 80%.

The challenge here is that ensuring that a certain percentage of the lines are covered by tests is very different from ensuring that the code is tested in a way that leads to better maintainability.

For one thing, a code-coverage tool can be fooled by a test that exercises the code and ends with Assert.assertTrue(true).

The less malicious concern is that a programmer that doesn't know how to write good tests will not write tests at the appropriate level of granularity, which can lead to a situation where future changes require major changes in the tests, and the tests become a burden to refactoring, rather than a help.

So if I wanted to give a number, I'd use 80%.  But this number is only useful when dealing with an honest developer that knows how to write good tests.


答:
The most correct answer, as far as i know, for your question is: none.

Because a language is a language with or without some headers or some libraries, you can see the most common libraries such as the standard library or the boost library as commodities in your workflow but the language itself does not require them; all you need to code is a text editor and a compiler.

If you can be more specific about this, it would help to answer in a better way but in general it depends on:

what technologies you want to use in your project ( basically what libraries )

what kind of build you want to produce and which compiler are you using, for example some compilers and libraries offers specific macros

Regarding the latest versions of the language, the C++ 11, it was a draft for something like 1 year and was recently approved, some books will be published soon about this topic, but i don't think that we will see C++ 11 in a productive environment soon; the modern C++ is more oriented to meta-programming, a feature like the ability to use templates, is really popular these days and to give you an idea the templates were introduced in the late 90's. The adoption on large scale is slow, you can study from a book or a resource from 5-10 years ago and have good chance to become a modern developer.

Title: What are the various branches of the C++ language out there?

Body:
Last time I tried to use C++ several years ago I remember having to include different libraries between different IDEs even though I was using the same operating system, which left me somewhat confused about the C++ language.

Are there different standardizations of the C++ language? And if so, what branches of the language exist out there? Is the syntax and/or library names for each standardization different between operating systems? Also, What is primary standardization used nowadays?


问:
Issue when Return Message is a collection of objects (Sequence Diagram)
I have a sequence diagram for the following operation. The Activity class uses method present in ActivityBL class. The method is:
      GetActivities(ActivitySearch objt)

The result message is a collection of Activity objects. (Colletion in C#). How do we represent the return message in the sequence diagram? At present, I am listing it as message containing only one Activity object. How to represent it as a collection?

答:
You don't need to include the return value at all, unless it adds clarification about the turn of events in the diagram.

Since the message says "GetActivities" the return value and the fact that there is a return value is kinda obvious isn't it?

If you do include it I would keep it conceptual: "activities" or "activity list". For being more specific about types and data structures, if you must, I'd stick to putting it in a class diagram.


答:
You should not give points to bug resolution. Consider the fact that the bug comes forth from a story where the developers already earned points for completing the story. It should not receive points again where it actually shouldn't have earned the points to begin with.

Bug fixing should have a negative effect on velocity. Otherwise dropping quality ends up being rewarded with an unaffected or even increased velocity!

Perhaps a useful link:

http://www.infoq.com/news/2011/01/story-points-to-bugs


答:
I've done several systems that interoperate with external systems using many different transport mechanisms - serial comms, web services, sockets, MQ, file drops. Of them all, the file drop one was the easiest to implement and understand and debug.

The trouble with it is really that it is a low-tech way of passing documents and tech people don't like that, not when there's a transactional, enterprise, service-oriented, queueing mechanism to pass the same document across a network!

One really big benefit to the file drop is that you can replay messages by, dropping the file in manually. the other benefit is logging - you want to archive all your messages, copy will put them in a different directory. Admin can also see what's happened if things go wrong by simply reading the file. You'd be surprised how many mission critical systems use this approach as it is simple, and simple things tend to work more reliably.

For the communications, chances are you'll still need some 'give me all data' communication mechanism that drives the file-drop transfer, and if this gets implemented as a web service, then you might as well transfer the files using web services too. The implementation cost to your customers should not be underestimated however.

If, on the other hand, you're transferring documents on a regular basis (nightly, weekly or hourly) then you don't need a notification system, when the documents are ready, read the transfer location and take all the waiting documents. Simple. (any that were not ready, eg you read too early, the missed documents will be there for the next transfer).

And of course, you can implement a directory-change API to trigger a read if you want on-demand notifications.

The big benefit of course, is that it is very decoupled. All you need to do is either wait periodically or write your own file-ready notifications. All your customer has to do is write a file. The cost of implementing this is truly minimal, and any shop that doesn't have developers can do this. That's probably the biggest factor in the design decision to make - are your customers tech savvy enough to write code, or not.

(for critical systems, I used a SMS messaging system that only accepted file-drops of sms messages to send, my system did all the fancy processing it usually does, but writes the data to a file instead of a socket or ws or mq. Upon processing, they wrote a status file. From my PoV, it was just another transport layer. From their PoV, they didn't have to work with me to write a 2-way connected comms channel, they just delivered the exe and described the config options).


问:
Combining multiple events into one action/ Defer refreshing
So in a GUI program I have multiple events that trigger a update of a workspace. This update call is costly so I would want it to not happen very often.

A user might pick something from a dropdown ( triggers a refresh ) and then put a check in a checkbox (also triggers a refresh ). If he does this in a short time interval this might result in the first refresh to be irrelevant.

One way to handle this would be to have a refresh button for the user to press, or a toggle to set whether to automatically refresh. But I wouldn't want to put this in the hands of the user.

Is there any other strategy to do this that is proven to be effective and error free?

PS. I'm specifically using .Net 4.0 -> C# -> WPF -> Caliburn.Micro but would like to hear of any method that could be reproduced using .net 4

答:
One way to avoid refreshing too often would be to use a dirty_flag + a Timer; you set the Timer interval to something like 200ms or whatever value you consider optimal.

When en event that requires a refresh happens, you just set the dirty_flag to true, and reinitialize the Timer(that way you make sure that Timer.Tick will be raised at "x" milliseconds after the user action). If another action is taken by the user in that interval of time, you reinitialize the timer again, and so on.

Then, on Timer.Tick: you do the refresh only if the dirty_flag = true, set dirty_flag = false.

An optimization that you can do is to disable the Timer after the refresh, and enable it on the next action that requires a refresh.


问:
What are use cases and advantages of pointers?
I often struggle to see the advantages of pointers (except for low level programming).

Why use of char* instead of a String or char[] or what advantages pointer arithmetic brings.

So what are the pros and use cases of pointers?

答:
With pointers you can allocate and deallocate memory in runtime.

And you can use large data-structures outside it's allowed scope without being copied.

References in C++, Java and other same type of languages are just 'safe pointers'. And these references are used a lot in Java.


问:
What is a suitable replacement for an Access 2003 database required to run an older PC?
Many years ago, I wrote a small Access 2003 database for a non-profit to track the donations they received. They recently wrote me asking for some new features (I was shocked it was still in use, honestly) and I'm wondering if I could rewrite the application with a newer technology/framework. Here are the machine specs:

Pentium 4 2.8 Ghz

1 GB RAM

Onboard Intel video card

Windows XP SP3

What, if any, would be a suitable replacement for the database and UI? I'm mainly a C# developer so Winforms + SQL Compact 4 springs to mind (I don't know how WPF would perform on a machine that old). Perhaps there are other possibilities in Python/Ruby/etc?

Update: I appreciate and agree that rewriting is rarely the right thing to do, but I was hoping to learn via this question, that given the PC's specs and OS, what possibilities would I have for writing an application that could

perform CRUD for donations

generate summary reports (totals by month/year/etc)

Or, put another way, is Access still the appropriate tool for the job?

答:
I would simply leave it in Access 2003 or maybe upgrade to the current ver.

I see no reason to re-write this, they are obviously very happy with it.


答:
There are no actual branches of the language. However, the language standard library is very minimalistic in comparison to many other popular languages like C#, Java or Python. This could very well give an impression of the language being branched, or even chaotic because in order to use higher-level functionality found in other languages such as threads(*) or HTTP facilities, the programmer has to rely on external libraries which are not found in the standard library. As such the programmer is directly dependent on external providers, rather than simply sticking with what the language provides by default.

(*) C++11 includes standard thread facilities, as such there's often no absolute reason to rely on external library such as Boost for threads.


答: Pretty much any computer program needs to inspect and change values in memory (known as peeking and pokeing, to those of us who are old enough). You need to control where in memory those values are, so that the outcome is predictable (and in certain cases, the order is important: loading executable code is one example). Therefore you need to have a data type that represents a location in memory. Even if your programming environment hides that under an abstraction, it's still there.</p>

Title: What are use cases and advantages of pointers?

Body:
I often struggle to see the advantages of pointers (except for low level programming).

Why use of char* instead of a String or char[] or what advantages pointer arithmetic brings.

So what are the pros and use cases of pointers?


答:
A few things to consider:

Rewrites are almost always more expensive than extending an existing solution.

Hardware is cheaper than custom software.

On a zero budget, open source software tends to be a better choice: any Windows version that still works comfortably with such hardware is bound to hit end-of-lifecycle at some point, but a lightweight Linux version works well enough on late 1990's hardware. This is assuming you are donating your time: a brand new entry-level PC costs about $300 or so, and I doubt you could install and configure an OS, install a database and front-end, and re-develop the entire application, on that budget.

Draw your own conclusions.

Title: What is a suitable replacement for an Access 2003 database required to run an older PC?

Body:
Many years ago, I wrote a small Access 2003 database for a non-profit to track the donations they received. They recently wrote me asking for some new features (I was shocked it was still in use, honestly) and I'm wondering if I could rewrite the application with a newer technology/framework. Here are the machine specs:

Pentium 4 2.8 Ghz

1 GB RAM

Onboard Intel video card

Windows XP SP3

What, if any, would be a suitable replacement for the database and UI? I'm mainly a C# developer so Winforms + SQL Compact 4 springs to mind (I don't know how WPF would perform on a machine that old). Perhaps there are other possibilities in Python/Ruby/etc?

Update: I appreciate and agree that rewriting is rarely the right thing to do, but I was hoping to learn via this question, that given the PC's specs and OS, what possibilities would I have for writing an application that could

perform CRUD for donations

generate summary reports (totals by month/year/etc)

Or, put another way, is Access still the appropriate tool for the job?


问:
Do Android developers have to pay sales taxes?
According to blog post by RetroDreamer Android developers have to pay sales taxes for their App sales in countries with have sales taxes while Apple developers don't as Apple pays the taxes directly.

Is this an accurate description? Is so, how do the various people who publish Android apps handle it?

答:
It depends on the laws that are in place in your State, but usually 2 things helps to define the scenario:

you are not who is selling

Google is selling and trading using real money

the second statement could appear strange, but is not that obvious the fact that a digital store or in general some goods or services are being sell using real money, an example is the XBOX marketplace where all the trading happens through virtual money ( called Microsoft Points ) and this adds 1 more level of complexity and sometime is really tricky especially for people and developers outside the US, because you don't know how to consider this money and most advisors can't suggest a good strategy or do the right thing because is an unusual approach.


答:
OpenOffice or LibreOffice are 2 free Office solutions that integrate an application similar to Access, it's named OpenOffice Base or LibreOffice Base.

If you want to do this programmatically there is SQLite that is a public domain project and is also relatively simple to use.

Both solutions are cross-platform and i suggest to use a GNU/linux distribution on that PC, maybe Ubuntu or Debian.


问:
What tools do you use to manage requests from users?
I'm drowning in user emails and I'd like to implement a better way to manage all these requests I get and put them in a queue where those people on a team, as well as users, have access to them and can make common notes. I'm thinking about some sort of task management tool that would allow multiple tasks to be created under a project where emails, comments, ideas, etc. could be dropped/entered and easily accessible.

I need something that all parties can be involved in - users, managers, team leaders, developers. I'm looking for a tool that can allow:

Users to just drag/drop an email to submit a request for maintenance or enhancement.

Developers to just see their queue and the weighted priority of each task/project.

A team of developers to see what everyone is working on in real-time.

Management to keep a a log of time spent on each task.

I I am starting to look in more of a Agile/Scrum direction for solving this problem. I found list of scrum agile sofware project management open source tools. Since I am limited on time, has anyone used these? Which one should I test to see if it will meet my needs? TeamPulse is a good direction, but think it is a little too bloated. I need something simple for all parties.

答:
Used to use XPlanner, but it doesn't seem to be being maintained for several years. We now use a tool called "VersionOne". Its OK. The things it does not do very well are:

reporting - to get its limited statistics to work properly you seem to have to fill everything in at exactly the right time

adding custom fields,  - it actually handles the fields quite nicely, but the process for adding them is convoluted

UI niggles - its main UI is a web UI, its AJAX in places but there are 5 different ways of doing anything and none of them is quite what you intuitively wanted.

Search - its search implementation is terrible. For instance, you can sometimes paste the exact title of a story into the search box and it doesn't find the story.

It does have a pretty good API accessible over HTTP though, so we have ended up creating a custom desktop app interface to display the stories/tasks/management-information in a more concise and useful way!

We couldn't find anything better for us at the time we decided to use it. It has a lot of features, but I leaves me feeling its UI could be much organised and implemented (and save a lot of frustration).


答:
If your refresh is non-blocking you could perhaps add a cancellation. When a refresh overlaps with another refresh, first cancel the earlier refresh then invoke a new one.

If the refresh is really expensive perhaps you can localize it somewhat more. Does the drop-down effect everything or could you logically target a sub-set of presented state?

Title: Combining multiple events into one action/ Defer refreshing

Body:
So in a GUI program I have multiple events that trigger a update of a workspace. This update call is costly so I would want it to not happen very often.

A user might pick something from a dropdown ( triggers a refresh ) and then put a check in a checkbox (also triggers a refresh ). If he does this in a short time interval this might result in the first refresh to be irrelevant.

One way to handle this would be to have a refresh button for the user to press, or a toggle to set whether to automatically refresh. But I wouldn't want to put this in the hands of the user.

Is there any other strategy to do this that is proven to be effective and error free?

PS. I'm specifically using .Net 4.0 -> C# -> WPF -> Caliburn.Micro but would like to hear of any method that could be reproduced using .net 4


问:
Can my company give IP rights away for an application I wrote off hours to another startup?
I am an intern for a health company (unpaid), let's call it Company A and I noticed that they are using a lot of paper form for things that can be done on the computer. Excel files for things that shouldn't be in Excel. So I wanted to improve on my programming and figured that it was the best opportunity to do.

I developed a couple of apps for their use. All these applications were outside company time. One application I did and they love and one of the director has a brother who has a health start up company. He wants me to give over my source code so his brother's company can further develop it and maybe sell it (I am out of the equation).

I have no intention of handing over my code as I put a lot of time outside doing it but I also don't want to burn bridges with anyone in the company. I can't go to the director and tell him "I don't think so".

I am fine with demoing to the brother how it works but the line is giving up my code. If they want to build something like it then they can go right ahead I have no problem with it.

What is the correct way of approaching this and do they have the right to do this to me?

Edit: there is no contract I never signed anything

答:
I can't go to the director and tell him "I don't think so".

Actually, if you own the copyright, that is exactly what you can do, especially as you have been working for free. You should tell him that if his brother wants your code, his brother should come talk to you, and you can do business.

If this guy doesn't like that, consider whether or not you would really want to work there. You've been doing him a favour just by being there. The onus is on him to ask for a further favour, or to bargain with you to buy what you have to sell.


问:
Python and only Python for almost any programming tasks!
Am I wrong if I think that Python is all I need to master, in order to solve most of the common programming tasks?

EDIT
I'm not OK with learning new programming languages if they don't teach me new concepts of programming and problem solving; hence the idea behind mastering a modern, fast evolving, with a rich set of class libraries, widely used and documented, and of course has a "friendly" learning curve programming language.

I think that in the fast evolving tech industry, specialization is key to success.

答:
By the time you've mastered Python, you will know if you can do everything in it.

The answer will come to you naturally.


问:
How does a garbage collector prevent the whole memory from being scanned on every collect?
Some (at least Mono's and .NET's) garbage collectors have a short term memory area which they scan often, and a secondary memory area which they scan less often. Mono calls this a nursery.

To find out which objects can be disposed of, they scan all objects starting from roots, the stack and the registers and dispose all objects that aren't being referenced anymore.

My question is how they prevent all in use memory from being scanned on every collect? In principle, the only way to find out what objects aren't in use anymore is to scan all objects and all their references. However, this would prevent the OS from swapping out memory even though it isn't in use by the application and feels like a huge amount of work that needs to be done, also for "Nursery Collection". It doesn't feel like they're winning much by using a nursery.

Am I missing something or is the garbage collector actually scanning every object and every reference every time it does a collection?

答:
Basically... GC uses "buckets" to separate what is in use and what isn't.
Once it makes it check, it wipes out things that are not in use and moves everything else to 2nd generation (which is checked less often than 1st generation) and then moves things that are still in use in 2nd den to 3rd gen.

So, things in 3rd generation are usually objects that are stuck open for some reason, and GC doesn't check there very often.


答:
The algorithm usually used by this GC is the Naïve mark-and-sweep

you should also be aware of the fact that this is a not managed by the C# itself, but by the so called CLR .

Title: How does a garbage collector prevent the whole memory from being scanned on every collect?

Body:
Some (at least Mono's and .NET's) garbage collectors have a short term memory area which they scan often, and a secondary memory area which they scan less often. Mono calls this a nursery.

To find out which objects can be disposed of, they scan all objects starting from roots, the stack and the registers and dispose all objects that aren't being referenced anymore.

My question is how they prevent all in use memory from being scanned on every collect? In principle, the only way to find out what objects aren't in use anymore is to scan all objects and all their references. However, this would prevent the OS from swapping out memory even though it isn't in use by the application and feels like a huge amount of work that needs to be done, also for "Nursery Collection". It doesn't feel like they're winning much by using a nursery.

Am I missing something or is the garbage collector actually scanning every object and every reference every time it does a collection?


问:
If immutable objects are good, why do people keep creating mutable objects?
If immutable objects¹ are good, simple and offer benefits in concurrent programming why do programmers keep creating mutable objects²?

I have four years of experience in Java programming and as I see it, the first thing people do after creating a class is generate getters and setters in the IDE (thus making it mutable). Is there a lack of awareness or can we get away with using mutable objects in most scenarios?

¹ Immutable object is an object whose state cannot be modified after it is created.

² Mutable object is an object which can be modified after it is created.

答:
A major point not yet mentioned is that having the state of an object be mutable makes it possible to have the identity of the object which encapsulates that state be immutable.

Many programs are designed to model real-world things which are inherently mutable.  Suppose that at 12:51am, some variable AllTrucks holds a reference to object #451, which is the root of a data structure which indicates what cargo is contained in all the trucks of a fleet at that moment (12:51am), and some variable BobsTruck can be used to get a reference to object #24601 points to an object which indicates what cargo is contained in Bob's truck at that moment (12:51am).  At 12:52am, some trucks (including Bob's) are loaded and unloaded, and data structures are updated so that AllTrucks will now hold a reference to a data structure which indicates the cargo is in all the trucks as of 12:52am.

What should happen to BobsTruck?

If the 'cargo' property of each truck object is immutable, then object #24601 will forevermore represent the state that Bob's truck had at 12:51am.  If BobsTruck holds a direct reference to object #24601, then unless the code which updates AllTrucks also happens to update BobsTruck, it will cease to represent the current state of Bob's truck.  Note further that unless BobsTruck is stored in some form of mutable object, the only way that the code which updates AllTrucks could update it would be if the code was explicitly programmed to do so.

If one wants to be able to use BobsTruck to observe the state Bob's truck while still keeping all objects immutable, one could have BobsTruck be an immutable function which, given the value that AllTrucks has or had at any particular time, will yield the state of Bob's truck at that time.  One could even have it hold a pair of immutable functions--one of which would be as above, and the other of which would accept a reference to a fleet state and a new truck state, and return a reference to a new fleet state which matched the old, except that Bob's truck would have the new state.

Unfortunately, having to use such a function every time one wants to access the state of Bob's truck could get rather annoying and cumbersome.  An alternative approach would be to say that object #24601 will always and forevermore (as long as anyone holds a reference to it) represent the current state of Bob's truck.  Code which will want to repeatedly access the current state of Bob's truck wouldn't have to run some time-consuming function every time--it could simply do a lookup function once to find out that object #24601 is Bob's truck, and then simply access that object any time it wants to see the present state of Bob's truck.

Note that the functional approach is not without advantages in a single-threaded environment, or in a multi-threaded environment where threads will mostly just be observing data rather than changing it.  Any observer thread which copies the object reference contained in AllTrucks and then examines the truck states represented thereby will see the state of all the trucks as of the moment that it grabbed the reference.  Any time an observer thread wants to see newer data, it can just re-grab the reference.  On the other hand, having the entire state of the fleet represented by a single immutable object would preclude the possibility of two threads updating different trucks simultaneously, since each thread if left to its own devices would produce a new "fleet state" object which included the new state of its truck and the old states of every other.  Correctness may be assured if each each thread uses CompareExchange to update AllTrucks only if it hasn't changed, and responds to a failed CompareExchange by regenerating its state object and retrying the operation, but if more than one thread attempts a simultaneous write operation, performance will generally be worse than if all writing were done on a single thread; the more threads attempt such simultaneous operations, the worse the performance will get.

If individual truck objects are mutable but have immutable identities, the multi-threaded scenario becomes cleaner.  Only one thread may be allowed to operate at a time on any given truck, but threads operating on different trucks could do so without interference.  While there are ways one could emulate such behavior even when using immutable objects (e.g. one could define the "AllTrucks" objects so that setting state of truck belonging to XXX to SSS would simply require generating an object that said "As of [Time], the state of the truck belonging to [XXX] is now [SSS]; the state of everything else is [Old value of AllTrucks]".  Generating such an object would be fast enough that even in the presence of contention, a CompareExchange loop wouldn't take long.  On the other hand, using such a data structure would substantially increase the amount of time required to find a particular person's truck.  Using mutable objects with immutable identities avoids that problem.


答:
IANAL and YMMV.  Obviously, the legal ramifications in different jurisdictions are quite varied, so I will not try to suggest the correct legal determination.

You may have done the work on your time, but as you stated yourself, you based the work on knowledge gained from observing the procedures and methods for executing their work.  You then  wrote a program based on this knowledge and gave it to them.  To me, this is the entire purpose for IP laws.  The valuable object here is not the program, but the knowledge used to create the program.  Philosophically speaking, anyone could have written the program, if they had the  knowledge.  You have knowledge of their processes and it was gained because of your position as an intern there.  I believe they have a right to control that knowledge and any derivative works.

I would suggest that you play nice and see if they would consider this program as an indication that you are a good enough developer to make a permanent hire.

Title: Can my company give IP rights away for an application I wrote off hours to another startup?

Body:
I am an intern for a health company (unpaid), let's call it Company A and I noticed that they are using a lot of paper form for things that can be done on the computer. Excel files for things that shouldn't be in Excel. So I wanted to improve on my programming and figured that it was the best opportunity to do.

I developed a couple of apps for their use. All these applications were outside company time. One application I did and they love and one of the director has a brother who has a health start up company. He wants me to give over my source code so his brother's company can further develop it and maybe sell it (I am out of the equation).

I have no intention of handing over my code as I put a lot of time outside doing it but I also don't want to burn bridges with anyone in the company. I can't go to the director and tell him "I don't think so".

I am fine with demoing to the brother how it works but the line is giving up my code. If they want to build something like it then they can go right ahead I have no problem with it.

What is the correct way of approaching this and do they have the right to do this to me?

Edit: there is no contract I never signed anything


答:
The GCs you are referring to are generational garbage collectors. They are engineered to get the most out of an observation known as "infant mortality" or "the generational hypothesis", which means that most objects become unreachable very quickly. They indeed scan starting from the roots, but ignore all old objects. Therefore, they do not need to scan most of the objects in memory, they only scan young objects (at the expense of not detecting unreachable old objects, at least not at that point).

"But that's wrong", I hear you scream, "old objects can and do refer to young objects". You're right, and there are several solutions to that, which all revolve around gaining knowledge, quickly and efficiently, which old objects must be checked and which are safe to ignore. They pretty much boil down to recording objects, or small (larger than objects, but much smaller than the whole heap) ranges of memory which contain pointers to younger generations. Others have described those far better than me, so I'll just give you a couple of keywords: Card marking, remembered sets, write barriers. There are other techniques too (including hybrids), but these encompass the common approaches I'm aware of.


答:
The fundamental observations which allow generational garbage-collection to avoid having to scan all older-generation objects are:

After a collection, all objects that still exist will be of some minimum generation (e.g. in .net, after a Gen0 collection, all objects are Gen1 or Gen2; after a Gen1 or Gen2 collection, all objects are Gen2).

An object, or portion thereof, which has not been written since a collection that promoted everything to generation N or higher cannot contain any references to objects of lower generations.

If an object has reached a certain generation, it need not be identified as reachable to ensure its retention when collecting lower generations.

In many GC frameworks, it's possible for the garbage collector to flag objects or portions thereof in such a way that the first attempt to write to them will trigger special code to record the fact that they have been modified.  An object or portion thereof which has been modified, regardless of its generation, must be scanned in the next collection, since it may contain references to newer objects.  On the other hand, it's very common for there to be a lot of older objects that do not get modified between collections.  The fact that lower-generation scans can ignore such objects can allow such scans to complete much more quickly than they otherwise would.

Note, btw, that even if one cannot detect when objects are modified and would have to scan everything on each GC pass, generational garbage collection could still improve the "sweep" stage performance of a compacting collector.  In some embedded environments (especially those where there is little or no difference in speed between sequential and random memory accesses), moving blocks of memory around is relatively expensive compared to tagging references.  Consequently, even if the "mark" phase can't be sped up using a generational collector, speeding up the "sweep" phase may be worthwhile.


答:
I have a class for that purpose.

At ViewModel's initialisation:

```<code>DeferredUpdater m_Updater = new DeferredUpdater(TimeSpan.FromSeconds(3),    //The amount of time between two updates that has to pass for an update in database to be required
                                                TimeSpan.FromSeconds(0.5), //The polling time
                                                OnUpdateRequested);           //The callback to use to update in database.
</code>```

And you'll have to hook up the propertychanged event of your viewmodel:

```<code>this.PropertyChanged += OnPropertyChanged;
void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
   m_Updater.DeferUpdate();
}
</code>```

And of course define the callback:

```<code>void OnUpdateRequested()
{
   //Call to DAL/database.
}
</code>```

It postpones update by checking every X amount of time if Y amount of time passed since the last call to DeferUpdate, and does all that in a thread (through a Task).

As far as I know (I have tested it a lot, and use it in a production scenario) it is thread safe.

Just make sure to get the latest version (V2) which is an improved solution.

Body:
I have a class for that purpose.

At ViewModel's initialisation:

DeferredUpdater m_Updater = new DeferredUpdater(TimeSpan.FromSeconds(3),    //The amount of time between two updates that has to pass for an update in database to be required
                                                TimeSpan.FromSeconds(0.5), //The polling time
                                                OnUpdateRequested);           //The callback to use to update in database.

And you'll have to hook up the propertychanged event of your viewmodel:

this.PropertyChanged += OnPropertyChanged;
void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
   m_Updater.DeferUpdate();
}

And of course define the callback:

void OnUpdateRequested()
{
   //Call to DAL/database.
}

It postpones update by checking every X amount of time if Y amount of time passed since the last call to DeferUpdate, and does all that in a thread (through a Task).

As far as I know (I have tested it a lot, and use it in a production scenario) it is thread safe.

Just make sure to get the latest version (V2) which is an improved solution.

ContentLicense: CC BY-SA 4.0


问:
Algorithm for appointment reminders
My program allows users to store appointments in a calendar.  What has been requested of me is the ability for SMS reminders to be sent to people to remind them of their appointment.  The SMS would need to be sent out about 2 days prior to their appointment.

I thought the best way to achieve this is to choose a time of the day (eg. midday) for the software to check to see which appointments are in 2 days time and then send out the SMS reminders to the people who have those appointments.

Would this be an advisable approach to this problem?  Is it advisable to have this happen at one time of the day, or would it be better to somehow spread it out over a longer time?

I am assuming at this point that a background thread would be a good idea for this type of activity.

答:
This Question should be proposed to the user, as the ramifications to the user far out way the technical concerns.

The frequency that you call your process should have very little baring on the design.

Title: Algorithm for appointment reminders


问:
What exactly do I have to pay attention for when choosing Windows Hosting Provider?
This is my first time choosing a hosting company. It is for a web site made in asp.net mvc3.

So I was thinking choosing a provider would be easy since I found this page
http://www.microsoft.com/web/Hosting/Home which contains hosting offers.

Now hours later, I am still searching.

The reason is that as soon as I start investigating about particular company, something stands out that I do not like.

Here are some examples what I noticed when checking various companies in more detail:

Company "about us" page is lacking in information about their company.

Few of them had just general description what they do and nothing else, while some others had information like company name but had no address.

Checking company name in Business Registry Searches gave no results.

Two of the companies I checked had both company name and address but I was unable to find them in the registry.

Putting company domain into Google gave mostly results from that domain or web hosting review sites but not much else.

I am assuming that good companies should have search results from other sites too.

Low Alexa Traffic Rank.

There was one company which had a site that looked very professional but their alexa traffic ranking was like 2 million.

Are there any other factors I should pay attention to when choosing a hosting company?

Do I have legitimate concerns or am I just too paranoid?

答:
None of the concerns you identified seem particularly relevant for choosing a hosting company, especially traffic rank.  Hosting companies host websites that gain traffic; they don't provide content themselves.  Consequently, I wouldn't expect them to rank particularly high in a Google or Alexa search.

I would be more concerned with things like:

What hosting features do you provide?  Can I run SSMS and access my SQL Server instance directly?  What versions of ASP.NET MVC do you support, and do you keep them current?  Can I expect my application DLL to run properly in your hosting environment?

How well does your service scale, and what are the service options?  Many people choose the cheapest service they can find, and then are surprised when their website suddenly falls down because it's being accessed by more than a dozen people (a good problem to have, by the way).  Some providers allow you to have your own machine; you can even configure it yourself, if you have the need.

What does your security model look like?  Do you run regular security sweeps of your equipment and software?  How do you protect your customers from hackers?  What if I am hosting data that is subject to privacy concerns under HIPAA, or the Sarbanes Oxley act?

What is your customer service like?  Can I readily contact you if I have a genuine problem?

If you're just starting out with a basic site, I would try and find genuine recommendations from  people who are hosting their own ASP.NET MVC website.  Small companies are just fine, and may actually be better for a little website.  Avoid hosting with a phone company.


答:
I am not an acountant / this is not legal advice/ yadda yadda yadda

I dont believe you do need to pay sales tax (in the US).  The reason is you are not the one conducting the sale, the vendor (Apple, Google) is the one conducting the sale.  The money you get would technically be royalties, not sales revenue.  They are the ones selling the app, and you are getting X per copy - much like an author would from a publisher.  Obviously royalties would be a factor in income taxes.

Google, Apple, or the Buyer (via a Use Tax), on the other hand, would be the ones who were responsible for paying sales taxes.

Outside the US... have no idea.  Would depend on local laws.

Title: Do Android developers have to pay sales taxes?

Body:
According to blog post by RetroDreamer Android developers have to pay sales taxes for their App sales in countries with have sales taxes while Apple developers don't as Apple pays the taxes directly.

Is this an accurate description? Is so, how do the various people who publish Android apps handle it?


答:
Since you are already a C# developer, that sounds like a suitable platform to replace the app.  Basically, there are no 'right' answers here - any one of dozens of language/database combinations could be used for this.  So unless you specifically want to work with something new, might as well take advantage of your existing skill set.

You also might consider that if one non-profit finds it useful, others might as well.  Many a startup got going this way.


问:
Alternatives for comparing data from different databases
I have two huge tables on separate databases. One of them has the information of all the SMS that passed through the company's servers while the other one has the information of the actual billing of those SMS.

My job is to compare samples of both of these tables (for example, the records between 1 and 2 pm) to see if there are any differences: SMS that were sent but not charged to the user for whatever reason that may be happening.

The columns I will be using to compare are the remitent's phone number and the exact date the SMS was sent. An issue here is that dates usually are the same on both sides, but in many cases differ by 1 or 2 seconds.

I have, so far, two alternatives to do this:

(PL/SQL) Create two tables where i'm going to temporarily store all the records of that 1hour sample. One for each of the main tables. Then, for each distinct phone number, select the time of every SMS sent from that phone from both my temporary tables and start comparing one by one using cursors. In this case, the procedure would be ran on the server where one of the sources is so the contents of the other one would be looked up using a dblink.

(sqlplus + c++) Instead of storing the 1hour samples in new tables, output the query to a text file. I will have two text files, one for each source. Then, open the first file and load all of it's content on a hash_map (key-value) using c++, where the key will be the phone number and the value a list of times of SMS sent from that phone. Finally, open the second file, grab each line (in this format: numberX timeX), look for numberX's entry on the hash_map (wich will be a list of times) and then check if timeX is on that list. If it isn't, save it somewhere to finally store it on a "uncharged" table (this would also be the final step on case 1)

My main concern is efficiency. These samples have about 2 million records on each source, so just grabbing one record on one side and looking it up on the other would not be possible. That's the reason I wanted to use hash_maps

Which do you think is a better option?

答:
I suggest creating a database link between the two databases, it lets you access a remote table as if it where in the same database.

Once you have the database link, code the solution in  a PL/SQL store procedure.

I suggest PL/SQL Developer as the IDE for writing store procedure.


问:
Materialized View vs POJO View based on Objects representing Oracle tables
I have about 12 Oracle tables that represent data that's being integrated from an external system into my web application.  This data is going to be used in an informational and comparative manner for the clients using my web application.

On one particular page of my web application, I need to combine data from 3 - 5 Oracle tables for display as an HTML table on the page.

We are NOT currently using a framework (Apache Struts for instance) and we're not in a position to move this Java web application into one at this moment (I'm trying to get us there...).

I am certainly not an architect, but I see one of two ways that I can effectively build this page (I know there are other ways, but these seem like they would be good ones...):
1.  Create an Oracle Materialized View that represents what the HTML table should look like and then create a POJO based on the View that I can then integrate into my JSP.
2.  Create POJOs that represent the Oracle tables themselves and then create another POJO that is the View used for the HTML table and then integrate that POJO into my JSP.

To me, it seems the Materialized View would possibly offer quicker results which is always what we strive for in web applications.  But, if I just create 12 POJOs that represent the Oracle tables and then build POJO Views off of those, I have the advantage of keeping all the code in one place for this and possibility for creating any number of different views and reusable components in my web application.

Any thoughts on which one might be the better route?  Or, maybe you know of an even better one?

答:
What I do in that situation and works for me is:

Create a regular view that represents what the HTML table should look like

Create a POJO that reads that view and produces a tab-separated text output

Create a POJO that receives the tab-separated data and paints HTML table

Future functionalities can use the view created at step 1.

Future functionalities can use POJO created at step 2.


答:
Having chosen hosts a number of times, my recommendations:
(1) Avoid both the high end and low end prices.  Low enders don't have the staff to support their customers, and high enders can be absurdly higher priced than the crowd.
(2) Don't overbuy capacity you don't need.  You can always shift hosts or packages when you find you actually do need more.  If you operate your site a few years, you'll end up changing anyway for one reason or another.  There is no "final solution".</p>

Title: What exactly do I have to pay attention for when choosing Windows Hosting Provider?

Body:
This is my first time choosing a hosting company. It is for a web site made in asp.net mvc3.

So I was thinking choosing a provider would be easy since I found this page
http://www.microsoft.com/web/Hosting/Home which contains hosting offers.

Now hours later, I am still searching.

The reason is that as soon as I start investigating about particular company, something stands out that I do not like.

Here are some examples what I noticed when checking various companies in more detail:

Company "about us" page is lacking in information about their company.

Few of them had just general description what they do and nothing else, while some others had information like company name but had no address.

Checking company name in Business Registry Searches gave no results.

Two of the companies I checked had both company name and address but I was unable to find them in the registry.

Putting company domain into Google gave mostly results from that domain or web hosting review sites but not much else.

I am assuming that good companies should have search results from other sites too.

Low Alexa Traffic Rank.

There was one company which had a site that looked very professional but their alexa traffic ranking was like 2 million.

Are there any other factors I should pay attention to when choosing a hosting company?

Do I have legitimate concerns or am I just too paranoid?


问:
What is the difference (if any) between (null != $object) and ($object != null) when using PHP?
I am used to Java and therefore always think conditions are interpreted from left to right, i.e. there is a vital difference in null != $obj and $obj != null

Now this seems not to be the case with PHP.

Can I do something wrong in PHP when I always start with null on the left-hand side? Can I keep my behaviour from Java or do I need to train myself to do something else when dealing with PHP conditions?

答: Regarding your particular case another approach would be to used the built-in php function is_null. So you would end up with is_null($mixedValue) which would do all the work for you and properly do type comparison and everything else.</p>


问:
Object Oriented Programming: getters/setters or logical names
I'm currently thinking about an interface to a class I'm writing. This class contains styles for a character, for example whether the character is bold, italic, underlined, etc. I've been debating with myself for two days whether I should use getters/setters or logical names for the methods which change the values to these styles. While I tend to prefer logical names, it does mean writing code that is not as efficient and not as logical. Let me give you an example.

I've got a class CharacterStyles which has member variables bold, italic, underline (and some others, but I'll leave them out to keep it simple). The easiest way to allow other parts of the program to access these variables, would be to write getter/setter methods, so that you can do styles.setBold(true) and styles.setItalic(false).

But I do not like this. Not only because a lot of people say that getters/setters break encapsulation (is it really that bad?), but mostly because it doesn't seem logical to me. I expect to style a character through one method, styles.format("bold", true) or something like that, but not through all these methods.

There is one problem though. Since you can't access an object member variable by the contents of a string in C++, I would either have to write a big if-statement/switch container for all styles, or I would have to store the styles in an associative array (map).

I can't figure out what the best way is. One moment I think I should write the getters/setters, and the next moment I lean towards the other way. My question is: what would you do? And why would you do that?

答:
One idea you might not have considered is the Decorator Pattern. Rather than setting flags in an object and then applying those flags to whatever you're writing, you wrap the class that does the writing in Decorators, which in turn apply the styles.

The calling code doesn't need to know how many of these wrappers you've put around your text, you just call a method on the outer object and it calls down the stack.

For a pseudocode example:

```<code>class TextWriter : TextDrawingInterface {
    public:
        void WriteString(string x) {
            // write some text somewhere somehow
        }
}

class BoldDecorator : TextDrawingInterface {
    public:
        void WriteString(string x) {
            // bold application on
            m_textWriter.WriteString(x);
            // bold application off
        }

        ctor (TextDrawingInterface textWriter) {
            m_textWriter = textWriter;
        }

    private:
        TextWriter m_TextWriter;
}
</code>```

And so on, for each decorating style. In its simplest usage, you can then say

```<code>TextDrawingInterface GetDecoratedTextWriter() {
    return new BoldDecorator(new ItalicDecorator(new TextWriter()));
}
</code>```

And the code that calls this method doesn't need to know the detail of what it's receiving. As long as it's SOMETHING that can draw text through a WriteString method.

Body:
One idea you might not have considered is the Decorator Pattern. Rather than setting flags in an object and then applying those flags to whatever you're writing, you wrap the class that does the writing in Decorators, which in turn apply the styles.

The calling code doesn't need to know how many of these wrappers you've put around your text, you just call a method on the outer object and it calls down the stack.

For a pseudocode example:

class TextWriter : TextDrawingInterface {
    public:
        void WriteString(string x) {
            // write some text somewhere somehow
        }
}

class BoldDecorator : TextDrawingInterface {
    public:
        void WriteString(string x) {
            // bold application on
            m_textWriter.WriteString(x);
            // bold application off
        }

        ctor (TextDrawingInterface textWriter) {
            m_textWriter = textWriter;
        }

    private:
        TextWriter m_TextWriter;
}

And so on, for each decorating style. In its simplest usage, you can then say

TextDrawingInterface GetDecoratedTextWriter() {
    return new BoldDecorator(new ItalicDecorator(new TextWriter()));
}

And the code that calls this method doesn't need to know the detail of what it's receiving. As long as it's SOMETHING that can draw text through a WriteString method.


问:
Reasonable test coverage requirements when dealing with a contractor?
We're outsourcing some work to an external developer, so I'm busy writing up a contract about what constitutes a deliverable.

So far I require that the code is shipped with automated tests.

But, what is a reasonable way to specify the detail of tests up-front in the contract in a measurable way?

I'm loathe to say "100% code coverage" because it's been established pretty often that 100% is pretty meaningless, and the diminishing returns above about 70-80% would probably just be pushing up our costs unnecessarily, and possibly even pushing up the complexity of certain things that might otherwise be very simple.

Internally we pretty much leave it up to our developers to decide on the level of tests needed, based on their intuition and experience. With a contractor however there is a fixed price that has to be agreed to up front and we need some way to enforce a certain level of quality.

Any suggestions or recommended reading matter would be appreciated!

答:
When subcontracting out, it is up to you to ensure the code being written at least works the way you need it to.  For that reason, your team will need to write some automated acceptance tests.  Provide those tests to your subcontractor, so they can make sure their code works with it.

Anytime you require percentage coverage in your unit tests, it is up to you to provide the tool which will be measuring the code coverage.  I don't know the environment you are running (.Net, Java, Ruby, etc.), but there are usually more than one tool available to measure coverage, and they are not all equal.  You also need to specify, or at least agree to the parameters used (i.e. coverage exclusions, type of coverage, etc.).

It would be unfair and unproductive to require testing of:

Generated classes/methods (some ORM tools generate classes, .Net UI components generate classes and methods, etc.)

System level exception catching code.  The code may be required by the language, and good practice, but if testing it requires hacking the platform itself, it's not worth the investment.

Don't require more of your subcontractors than you would of your own team.  If you are going to require a certain percentage of unit tests as an acceptance criteria, provide a range like 70-80%.  If they beat it, great.  I would consider 50% coverage an absolute minimum, with 70% a decent requirement.  Anything above 70% may cost more, but you'll have better piece of mind about it.

Just a note about metrics like test coverage.  They are just numbers, and anyone can play with numbers.  I think your intent is a good one, but anyone who wants to game the system can.  The coverage number is a rough indication of the thoroughness of the testing, but not the quality of the testing.  In my experience, many programmers who are not used to writing unit tests tend to write integration tests, and merely run the application through the test framework without any assertions whatsoever.  Essentially they are just providing themselves a launching point to step through with a debugger.  It takes time and training to get unit tests that are useful.

I would require an early initial delivery simply to evaluate the effectiveness of their unit testing, and to help fine tune both your expectations and theirs.  That will help both of you to get on the same page, and make future deliveries better.


答:
I'd lean towards the second solution. It looks more elegant and flexible. Although it's difficult to imagine other types than bold, italic and underline (overline?), it would be difficult to add new types using member variables.

I used this approach in one of my latest projects. I have a class which can have multiple boolean attributes. The number and names of the attributes may change in time. I store them in a dictionary. If an attribute is not present I assume its value is "false". I also have to store a list of available attribute names, but that's another story.

Title: Object Oriented Programming: getters/setters or logical names

Body:
I'm currently thinking about an interface to a class I'm writing. This class contains styles for a character, for example whether the character is bold, italic, underlined, etc. I've been debating with myself for two days whether I should use getters/setters or logical names for the methods which change the values to these styles. While I tend to prefer logical names, it does mean writing code that is not as efficient and not as logical. Let me give you an example.

I've got a class CharacterStyles which has member variables bold, italic, underline (and some others, but I'll leave them out to keep it simple). The easiest way to allow other parts of the program to access these variables, would be to write getter/setter methods, so that you can do styles.setBold(true) and styles.setItalic(false).

But I do not like this. Not only because a lot of people say that getters/setters break encapsulation (is it really that bad?), but mostly because it doesn't seem logical to me. I expect to style a character through one method, styles.format("bold", true) or something like that, but not through all these methods.

There is one problem though. Since you can't access an object member variable by the contents of a string in C++, I would either have to write a big if-statement/switch container for all styles, or I would have to store the styles in an associative array (map).

I can't figure out what the best way is. One moment I think I should write the getters/setters, and the next moment I lean towards the other way. My question is: what would you do? And why would you do that?


答:
Yes, getters/setters do break encapsulation - they basically are just an extra layer between directly accessing the underlying field. You might as well just access it directly.

Now, if you want more complex methods to access the field, that's valid, but instead of exposing the field, you need to think what methods the class should be offering instead. ie. instead of a Bank class with a Money value that is exposed using a property, you need to think what types of access a Bank object should offer (add money, withdraw, get balance) and implement those instead. A property on the Money variable is only syntactically different from exposing the Money variable directly.

DrDobbs has an article that says more.

For your problem, I'd have 2 methods setStyle and clearStyle (or whatever) that take an enum of the possible styles. A switch statement inside these methods would then apply the relevant values to the  appropriate class variables. This way, you can change the internal representation of the styles to something else if you later decide to store them as a string (for use in HTML for example) - something that would require all users of your class to be changed too if you used get/set properties.

You can still switch on strings if you want to take arbitrary values, either have a big if-then statement (if there's a few of them), or a map of string values to method pointers using std::mem_fun (or std::function) so "bold" would be stored in a map key with its value being a sts::mem_fun to a method that sets the variable bold to true (if the strings are the same as the member variable names, then you can also use the stringifying macro to reduce the amount of code you need to write)