问:
Moving from TFS to Distributed SCM
I am currently playing with the idea of pitching DSCM to management in my company. We currently use the full vertical TFS stack (SCM, Bug Tracking, Project Management etc.) - however I want to specifically target the source control (as I don't think retraining QA with something like Redmine would be achievable).

Probably the biggest issue here is re-training a very large amount of developers to use the new SCM (and this includes the distributed train of thought) - which is probably not feasible at all. There needs to be some form of skills migration with the new system: this is where GIT fails horribly, as that would take months to catch on (and we are not a little startup shop - this is a very large company with real commitments).

The next issue is the fact that we currently require check-ins to be associated with a real bug or task (work item) - I doubt management would bite if we couldn't control this. Ideally the developer machines should be zero-configuration, i.e. it should prevent 'illegal' pushes even if you just have the bare-bones SCM client installed. Being able to update TFS work items would also be a big plus - even if I had to write custom code, but once again this should be controlled by the central repository and not on developer machines.

I know that in the long run DSCM alleviates many of the problems that we are facing day-to-day, but we can't afford the time of developers having merge issues or such. For example, my first GIT merge took me a good 2 days to figure out, because I was so used to the TFS mindset. This isn't acceptable when real deadlines are taken into consideration.

Tooling is a big concern: it's incredibly easy to push in a merge marked-up file directly back into source control; which would result in a build failure - TFS doesn't allow you to do anything silly like this.

Finally, having 'nice things' to show would probably help the pitch. We have a review process, showing off GitHub FI Commit Comments would be a strong example of why this stuff could be better - however, as stated, GIT is probably really the wrong route to go.

TLDR; I have found most DSCMs to be tools and not frameworks (e.g. GIT is designed to be this); allowing you to easily shoot yourself in the foot - TFS is a framework and that is something valuable in the company.

Has anyone ever tackled these types of issues when migrating to DSCM? What DSCM platforms did you use? What challenges did you face? Do you have any ideas on how this process could be streamlined and almost made painless?

答:
Kiln might be a good option for you.

It is based on mercurial and has full support by fog creek and good documentation to boot.

Title: Moving from TFS to Distributed SCM


问:
General checklist before releasing software
I'm currently building a tool that my company intends to sell. I'm the sole developer on the project and it is being developed outside our normal code base and to a certain extent outside our normal process.

I'm trying to put together a checklist of items to check before I deem the software ready to release for testing.

These are the items that I've come up with so far:

Is code commented appropriately?

Does the code adhere to the defined Company Standards?

Is there error handling in place?

Is there appropriate security?

Is there appropriate logging?

Is localisation required?

Have release notes and any accompanying documentation been produced?

Has all testing and debugging code been removed?

Has sensitive data been such as passwords and licence keys been removed?

Has performance been checked? Any memory leaks?

Can anybody suggest items that could be added to this list and explain why you would think it would be useful? My goal is to have a template checklist that I can then customise on a project by project basis.

答:
A few ones:

Do all the unit tests pass?

Has the software been tested on a preproduction environment / on all the supported OSes?

Has the software been tested by non-technical people? Any usability issues?

ContentLicense: CC BY-SA 3.0


答:
Is there a generated change log?

Is everything checked into the VCS?

Have we added and successfully run tests for each bug discovered in the previous release?

Has anybody deployed it on a running system?

Has anybody used it to do something non-trivial?

Is there a working downgrade procedure?

Does the package update user editable files (such as configuration) gracefully?

Title: General checklist before releasing software

Body:
I'm currently building a tool that my company intends to sell. I'm the sole developer on the project and it is being developed outside our normal code base and to a certain extent outside our normal process.

I'm trying to put together a checklist of items to check before I deem the software ready to release for testing.

These are the items that I've come up with so far:

Is code commented appropriately?

Does the code adhere to the defined Company Standards?

Is there error handling in place?

Is there appropriate security?

Is there appropriate logging?

Is localisation required?

Have release notes and any accompanying documentation been produced?

Has all testing and debugging code been removed?

Has sensitive data been such as passwords and licence keys been removed?

Has performance been checked? Any memory leaks?

Can anybody suggest items that could be added to this list and explain why you would think it would be useful? My goal is to have a template checklist that I can then customise on a project by project basis.


问:
Random number for HTTPS MAC
Recently I found that Netscape used quite simple algorithm to generate random number for Message Authentication Code to establish an HTTPS connection (Nestscpe used time, process identification number, and parent-process identification number). So now I wonder what source of seed do modern browsers use to guarantee true randomness?</p>

答: This question and this question over on security.SE have some answers describing sources and the randomness available.

Title: Random number for HTTPS MAC


问:
People's experience of Cloud Computing (using Force.com)
I would like to know about people's experience of working with APEX and the SalesForce.com platform, was it easy to work with? How similar to Java and C# is it? What did you like? What don't you like? Would you recommend it? Do you think cloud computing has a long term successful future?

My reason for asking is that I am currently looking at a new position which involves working with APEX on the SalesForce.com platform. The position interests me but I just want to try and understand what I might be signing up for with regards the languages/platform as it is completely different from what I have worked with before.

I have seen lots of videos/blog posts online (mainly from the recent Dreamforce event) and they obviously are very positive but I was just after some experiences from developers, both positive and negative.

I find cloud computing a very interesting idea, but I am very new to the subject. The position I am looking at offers a fantastic opportunity but I was just after some opinions on APEX and the platform as I have no real world experience just what I have seen from the online videos.

I guess ultimately what I am asking is:

Are APEX and the SalesForce.com platform good to get involved in? Is development on the Force.com just a "career dead end"?

Is cloud computing just a fad? Or does it have a long term future?

Apologies in advance if this is the wrong place to ask such a question.

Thanks

答:
Cloud computing is very expensive, very limited and over-hyped, IMHO, the only good thing about it is that you can accommodate an unexpected demand. So if someone DOS your web page, you can fire up more instances than the bot-net has, and the site will still be available.

Otherwise:

automation is as hard as in local cluster

you still need a sane system administrators

lightning takes down clouds just like any other solution

your information is stored at the 3rd party

expenses are higher over 1 year period

hardware is more limited

capabilities are limited by the platform

I think best solution is local farm with fail-over/scaling to cloud on unexpected demand.


答:
Maybe you want to consider this:

What security privs are required to install the software?

Is the installation drive independent?

Does the install process test for space availability?

Is the connection string to the database automatically built or statically coded and requires user change?

Does your code handle dialect specific data such as date correctly?

Would your security use MS Windows security? Did you test that?

What are the other software dependencies assumed at the target client machine (such as .NET
Framework, ODBC, OLEDB, etc.) - Does your installation take care of this?

Does the install script have an un-install that safely removes the software?

If your software alters the registry during install, do you make a backup of the registry before altering it?

Does your software expect the certain ports to be open on the firewall so that it runs? Do you check for this?

If your software is browser based, do you tell the user about supported browsers?

If your software is windows based, do you tell the user about the windows resolution you see best (unless the application supports all resolutions)?

Sometimes, compliance with handicapped users may be required.

Do your user have means to contact you when things don't work as expected?

Do you have license agreement in place. Does the install process takes that in consideration

Have you checked all due copyrights?

Did you confirm that the licensing mechanism (generating userid/password) work?


答: "Cloud Computing" is a bit of a marketing buzz word and not properly defined. Each specific implimentation has its own plus and minus points. </p>

Title: People's experience of Cloud Computing (using Force.com)

Body:
I would like to know about people's experience of working with APEX and the SalesForce.com platform, was it easy to work with? How similar to Java and C# is it? What did you like? What don't you like? Would you recommend it? Do you think cloud computing has a long term successful future?

My reason for asking is that I am currently looking at a new position which involves working with APEX on the SalesForce.com platform. The position interests me but I just want to try and understand what I might be signing up for with regards the languages/platform as it is completely different from what I have worked with before.

I have seen lots of videos/blog posts online (mainly from the recent Dreamforce event) and they obviously are very positive but I was just after some experiences from developers, both positive and negative.

I find cloud computing a very interesting idea, but I am very new to the subject. The position I am looking at offers a fantastic opportunity but I was just after some opinions on APEX and the platform as I have no real world experience just what I have seen from the online videos.

I guess ultimately what I am asking is:

Are APEX and the SalesForce.com platform good to get involved in? Is development on the Force.com just a "career dead end"?

Is cloud computing just a fad? Or does it have a long term future?

Apologies in advance if this is the wrong place to ask such a question.

Thanks


问:
How do you manage refactoring with a large code base and many developers?
I would like to prevent a situation where two developers refactor the same code simultaneously without talking about it first, probably using a tool of some kind, maybe an Eclipse plug-in. Can you help?

We've got 4.5 million lines of code, and more than 20 teams of developers on four continents.

Ideally I would like the second of the developers mentioned earlier to notice that someone else is working on the same piece of code and talk to the first one before modifying anything.

Do you know of a solution?

答:
Developers locking files in source control should solve your problem easily, but then I think you might have bigger problems.

4.5 Million LOC's is a massive sandbox to play in so in a well architected and designed solution you should rarely run into a situation where multiple teams of developers are stepping on each others toes.  The fact that this happens more than coincidentally is telling of a some serious potential design flaws that should be looked into.


问:
DRY with Dynamic SQL vs. prepared statements
When dealing with data, one finds that, essentially, the same code is repeated in various incarnations:

```<code>-- MySQL:
CREATE TABLE users (
    id int NOT NULL auto_increment PRIMARY KEY,
    name varchar(255) NOT NULL,
    email varchar(255) NOT NULL,
    UNIQUE KEY akUser (email)
)

// PHP
class User extends DBModel {
    protected $id;
    protected $name;
    protected $email;

    function __construct() {
        $this->queries = array(
            'getById' => 'SELECT id, name, email FROM users WHERE id = :id',
            'addUser' => 'INSERT INTO users (name, email) VALUES (:name, :email)',
            'updateUser' => 'UPDATE users SET name = :name, email = :email WHERE id = :id',
        );
    }

    public function loadById($id) {
        $stmt = $this->getPreparedStatement('getById');
        $stmt->bindValue(':id', $id);
        $stmt->execute();
        $stmt->setFetchMode(PDO::FETCH_INTO, $this);
        return $stmt->fetch();
    }
    public function save() {
        if ($this->id === NULL) {
            $this->add();
        }
        else {
            $this->update();
        }
    }
    public function add() {
        $stmt = $this->getPreparedStatement('addUser');
        $stmt->bindValue(':name', $this->name);
        $stmt->bindValue(':email', $this->email);
        $stmt->execute();
    }
    public function update() {
        $stmt = $this->getPreparedStatement('updateUser');
        $stmt->bindValue(':name', $this->name);
        $stmt->bindValue(':email', $this->email);
        $stmt->bindValue(':id', $this-id);
        $stmt->execute();
    }
}
</code>```

If you notice, the fields 'name' and 'email' each occur 7 times throughout PHP and MySQL. While this is not much of a problem with this small example, with large tables, and a large number of tables, this gets out of hand fairly quickly.

As a quick side-note: with PHP running as a web service, the application lifetime is very short. Many of the queries that get executed -- adding a user, for instance -- would get executed only once in the application lifetime, so prepared statements really don't offer much of an advantage. Even with connection sharing, the individual instances don't have access to the previously prepared statement (unless I'm missing something), so it would re-prepare the statement anyway.

With some basic database-level reflection (the results of which are either cached, or automatically generated before deployment), SQL statements can be created automatically, eliminating the need to code the basic SELECT/INSERT/UPDATE/DELETE statements individually - cutting down on code considerably.

```<code>-- (table create statement, of course, stays the same)

class User {
    protected $id;
    protected $name;
    protected $email;

    public function getById($id) {
        return MyDb::getById('Users', $id, $this);
    }
    public function save() {
        return MyDb::save('Users', $this);
    }
}
</code>```

My question: is the duplication of code worth the few CPU cycles and more complex code & maintenance needs?

答:
My question: is the duplication of code worth the few CPU cycles and
  more complex code & maintenance needs?

No, it's not worth the CPU cycles and the additional code. Most data access frameworks I know generate queries if you don't supply a custom one.

Your intended use makes the database the bottleneck. Keep your generalized DAL extensible, so that you can override the default behaviour with something customized when the need arises.

Even with connection sharing, the individual instances don't have
  access to the previously prepared statement (unless I'm missing
  something), so it would re-prepare the statement anyway.

This is of no concern here. It's the database that manages such statements. Most of the time they are cached on the RDBMS, regardless of whether they were generated dynamically on the client or the connection was closed. Dynamic query generation and prepared statements do not exclude each other, so I encourage you to use them, at least for the sake of preventing SQL-injections.


问:
When do you rebuild an application or keep on fixing the existing one

Possible Duplicates:

  When is a BIG Rewrite the answer?

  Have you ever been involved in a BIG Rewrite?

I am at a customer where I have been tasked to fix a number of issues they have in their existing systems. These systems are all quite old and was built in older technologies to really low development standards.

All of this makes it quite difficult and frustrating to properly maintain these systems, because of the two thoughts that often come to mind while working on this:

A. It would have been so much easier / quicker to do this in one of the newer technologies.

B. I would not have coded this feature like this. There are many better ways to design this application to make it more maintainable and better performing. (examples are bad OO design, code is often repeated, settings are hard coded, etc.. the list is long).

So under the circumstances I try to make the best of it and fix everything to the best of my ability without complaining too much, but my question is now:

How do you decide when it is time to rebuild a system with newer technology, versus keeping on plugging holes in an old one? And how do you make a case for rebuilding? How can you persuade the powers-that-be it is necessary to rebuild the system?

答:
It is a tough call.

Obligatory Joel reference: Things You Should Never Do, Part I

That said, there are of course cases when it is still better to rewrite from scratch than to keep fixing the fundamentally broken. If all of the following applies to your case, you probably have a reason to rewrite from scratch:

there are no automated tests,

the original project team is gone, and noone knows how the product is implemented, thus making any changes is incredibly difficult and results are unpredictable,

the product is so low quality that replacing it with a new, necessarily bug-fraught implementation would not make a major difference,

the technology used is obsolete, and there is a pressing need to replace it with something new (e.g. in order to enable some desired major feature, or to deploy it on a new platform - @Thorbjörn's answer contains a good example for the latter).

(If only some of these applies... well, that's the tough one to decide, and there is no general answer there.) At any rate, you would also need the following conditions to give you at least a chance of making such a move successful:

time-to-market is not an issue - customers are patient enough to wait a looong time for a promised, fundamentally better version and there are no competitors,

there exists live, detailed knowledge (ideally in well written specifications, but also in several people's heads - and these people are accessible to answer developers' questions) on how the damn thing should actually behave in any specific situation,

management is at least open to the idea, and ideally they understand the potential costs vs benefits.

All in all, you must take into account that a complete rewrite from scratch is going to take a lot more time, effort and pain than anticipated. So if you can, try to partition the job into smaller chunks, to replace only modules/components of the old code one by one. This way

you can start by building a suite of regression tests around the existing program, which then make it much easier to preserve (and if necessary, improve) the old functionality with the new code,

you will have a working, up-to-date program most of the time (thus way happier users and management),

you may save rewriting (potentially significant) parts of the code which do not need to change and "just work".


答: When it gets to a stage that the fixes you're repeatedly making are as time consuming as redeveloping the program then you can start thinking about it. You've got to of course factor in the time for testing/Q&A but if you think that it's becoming a time sink then it's definitely worthwhile considering it.</p>

Title: When do you rebuild an application or keep on fixing the existing one

Body:
Possible Duplicates:

  When is a BIG Rewrite the answer?

  Have you ever been involved in a BIG Rewrite?

I am at a customer where I have been tasked to fix a number of issues they have in their existing systems. These systems are all quite old and was built in older technologies to really low development standards.

All of this makes it quite difficult and frustrating to properly maintain these systems, because of the two thoughts that often come to mind while working on this:

A. It would have been so much easier / quicker to do this in one of the newer technologies.

B. I would not have coded this feature like this. There are many better ways to design this application to make it more maintainable and better performing. (examples are bad OO design, code is often repeated, settings are hard coded, etc.. the list is long).

So under the circumstances I try to make the best of it and fix everything to the best of my ability without complaining too much, but my question is now:

How do you decide when it is time to rebuild a system with newer technology, versus keeping on plugging holes in an old one? And how do you make a case for rebuilding? How can you persuade the powers-that-be it is necessary to rebuild the system?


答:
Someone once commented Premature optimization is the root of all evil on one of the questions that had asked. You can never build a completely optimal solution to a problem. Certainly, correcting somebody else's code is one of the most frustrating tasks when you that you could have coded better.

But with reference to that, if you find yourself changing the source code too often, maybe you need to be stop being quiet about it. :) If you're the only one maintaining it and if the technology is completely outdated, if newer (and better) alternatives are available, if the holes are too much, you may very well talk to your higher authorities about the same. I see no point in keeping on plugging holes when you can actually rebuild the same.


答:
When the whole base architecture, framework or foundation is incompatible with new business requirements.

IMHO, core changes are the only ones when you start from scratch. And expect them to be expensive.


答:
Essentially you're asking whether code cleanliness is more important than performance; well, that can vary depending on the situation.  Without really knowing more about the exact situation, I would say:

Performance is unlikely to be noticably worse with an ORM solution in this case.  Unless CPU usage is a known bottleneck on your web server, your code is most likely spending orders of magnitude more time waiting for the DB to respond than it is preparing the SQL statement.  When it comes to performance questions though, a good idea is to measure (the answer is often not what seems the most obvious).

I am a firm believer in ORM solutions.  They go a long way to standardise how you access the DB, allow the rest of the system to be less DB oriented, take away the ability to make simple mistakes, and keep repetitions to a minimum.  There are some (complex) cases where you will have to jump through hoops to make the ORM perform acceptably well, but querying a single table is not it (and in these cases, you can usually hand-code whatever you need).  I don't know many people who have tried it and have gone back to not using them.

Title: DRY with Dynamic SQL vs. prepared statements

Body:
When dealing with data, one finds that, essentially, the same code is repeated in various incarnations:

```<code>-- MySQL:
CREATE TABLE users (
    id int NOT NULL auto_increment PRIMARY KEY,
    name varchar(255) NOT NULL,
    email varchar(255) NOT NULL,
    UNIQUE KEY akUser (email)
)

// PHP
class User extends DBModel {
    protected $id;
    protected $name;
    protected $email;

    function __construct() {
        $this->queries = array(
            'getById' => 'SELECT id, name, email FROM users WHERE id = :id',
            'addUser' => 'INSERT INTO users (name, email) VALUES (:name, :email)',
            'updateUser' => 'UPDATE users SET name = :name, email = :email WHERE id = :id',
        );
    }

    public function loadById($id) {
        $stmt = $this->getPreparedStatement('getById');
        $stmt->bindValue(':id', $id);
        $stmt->execute();
        $stmt->setFetchMode(PDO::FETCH_INTO, $this);
        return $stmt->fetch();
    }
    public function save() {
        if ($this->id === NULL) {
            $this->add();
        }
        else {
            $this->update();
        }
    }
    public function add() {
        $stmt = $this->getPreparedStatement('addUser');
        $stmt->bindValue(':name', $this->name);
        $stmt->bindValue(':email', $this->email);
        $stmt->execute();
    }
    public function update() {
        $stmt = $this->getPreparedStatement('updateUser');
        $stmt->bindValue(':name', $this->name);
        $stmt->bindValue(':email', $this->email);
        $stmt->bindValue(':id', $this-id);
        $stmt->execute();
    }
}
</code>```

If you notice, the fields 'name' and 'email' each occur 7 times throughout PHP and MySQL. While this is not much of a problem with this small example, with large tables, and a large number of tables, this gets out of hand fairly quickly.

As a quick side-note: with PHP running as a web service, the application lifetime is very short. Many of the queries that get executed -- adding a user, for instance -- would get executed only once in the application lifetime, so prepared statements really don't offer much of an advantage. Even with connection sharing, the individual instances don't have access to the previously prepared statement (unless I'm missing something), so it would re-prepare the statement anyway.

With some basic database-level reflection (the results of which are either cached, or automatically generated before deployment), SQL statements can be created automatically, eliminating the need to code the basic SELECT/INSERT/UPDATE/DELETE statements individually - cutting down on code considerably.

```<code>-- (table create statement, of course, stays the same)

class User {
    protected $id;
    protected $name;
    protected $email;

    public function getById($id) {
        return MyDb::getById('Users', $id, $this);
    }
    public function save() {
        return MyDb::save('Users', $this);
    }
}
</code>```

My question: is the duplication of code worth the few CPU cycles and more complex code & maintenance needs?


答:
Rewriting an application at some point is a necessary decision.
Leaving stale code can mean nightmare for maintenances - for fixing bugs and adding new features. An application never ends up doing only what is was originally designed for and the environment it was designed never remains the same.

The real question is "How to rewrite it?"

If the original application was written in a truly modular manner it can be rewritten in phases.

If it was not (which is often the case with legacy systems), then the development must be branched, were one branch keeps struggling with upgrading the old systems and another creates a new one. This requires more investment, but it keeps the company alive without leaving behind.

The optimal solution is to try and develop components for the new application that with some effort may be integrated into the old one, so that the new development will somewhat contribute to the old system.

Some guidelines to prevent reaching a situation were the entire application must be rewritten with no option of integrating new code into it:

Design and write modular code, use dependency injection.

Refactor your code often, do not write work arounds on work arounds.

Use clear coding standards, give good names in correct English, do not use Hungarian notation.

Write external documentation and internal documentation, do not auto generate it.

I can not emphasize enough the importance of fully automated unit tests, integration tests, & system tests to enable updating of both existing modules and future updating of new modules.


答:
A good one to prompt a rewrite is when the implementation technology is not supported anymore.

I recently had the experience that Windows 7 (64 bit) explicitly said that it disliked the Visual Basic 6 installation cd when inserted.  We used that as a strong hint that it was time to port our VB6 applications (to Java as that is what we do).


答:
I'm a big fan of Github. The hardest part for me with Git was actually setting it up (properly) SSH keys, managing them, etc. It can be a pain, especially for those that are use to a clean wrapper around it like GitHub.

GitHub, of course, is a managed service. However, there is an option of GitHub Firewall Install - basically an on-promise setup of GitHub, which alleviates a lot of that headache, and is fully supported. It doesn't come cheap, but if your organization is willing to shell out for TFS, then I don't see how this wouldn't be a potential option.

As far as getting developers involved, and trained - that's tough. The nice thing about Git is that it's really hard to do permanent damage (but possible). Git allows history re-writing. I'm not fond of that, but it's very useful when something unintentional or unexpected happens. It does require a lot of knowledge of Git to even be able to do that though.

There are GUI wrappers around Git, like Tortoise-Git, that make it more manageable for people that don't like / aren't comfortable with the command line.

Another possible option for you is Veracity. It has built in bug-tracking, etc. It doesn't quite have all of the features of Git - but it has all of the needed ones and then some. Perhaps that's a good thing for your team. It's easy to set up, and is aggressively being developed.

Title: Moving from TFS to Distributed SCM

Body:
I am currently playing with the idea of pitching DSCM to management in my company. We currently use the full vertical TFS stack (SCM, Bug Tracking, Project Management etc.) - however I want to specifically target the source control (as I don't think retraining QA with something like Redmine would be achievable).

Probably the biggest issue here is re-training a very large amount of developers to use the new SCM (and this includes the distributed train of thought) - which is probably not feasible at all. There needs to be some form of skills migration with the new system: this is where GIT fails horribly, as that would take months to catch on (and we are not a little startup shop - this is a very large company with real commitments).

The next issue is the fact that we currently require check-ins to be associated with a real bug or task (work item) - I doubt management would bite if we couldn't control this. Ideally the developer machines should be zero-configuration, i.e. it should prevent 'illegal' pushes even if you just have the bare-bones SCM client installed. Being able to update TFS work items would also be a big plus - even if I had to write custom code, but once again this should be controlled by the central repository and not on developer machines.

I know that in the long run DSCM alleviates many of the problems that we are facing day-to-day, but we can't afford the time of developers having merge issues or such. For example, my first GIT merge took me a good 2 days to figure out, because I was so used to the TFS mindset. This isn't acceptable when real deadlines are taken into consideration.

Tooling is a big concern: it's incredibly easy to push in a merge marked-up file directly back into source control; which would result in a build failure - TFS doesn't allow you to do anything silly like this.

Finally, having 'nice things' to show would probably help the pitch. We have a review process, showing off GitHub FI Commit Comments would be a strong example of why this stuff could be better - however, as stated, GIT is probably really the wrong route to go.

TLDR; I have found most DSCMs to be tools and not frameworks (e.g. GIT is designed to be this); allowing you to easily shoot yourself in the foot - TFS is a framework and that is something valuable in the company.

Has anyone ever tackled these types of issues when migrating to DSCM? What DSCM platforms did you use? What challenges did you face? Do you have any ideas on how this process could be streamlined and almost made painless?


问:
Is it common to have downtime at a programming job?
At my company, I find that there are some days that there are very few tasks to do.  I make it a point to do research to learn new things about my craft on these days.

I would say that on average, I have about one day per week that there is not much to do (or some combination of time over the week).

I would like to know if this is a common situation in software development environments, and does the answer to this question vary between full-time and contract work.

答: In my company I get a couple of weeks like that(yes weeks) for every two months or so. I am not sure if being weeks without work is common, but yes, you could always improve yourself during free time.</p>


问:
Do speakers get paid for tech talks?
I'm curious if speakers (bloggers, google employees like Matt Cutts) get paid for speaking at conferences. If they do, how much? If they don't, or they get paid so little that it's as though they don't, why do it? What are the attractions beyond money that lead a developer into public speaking?</p>

答:
It varies. I have had speaking gigs where I spent my own money to get there, to eat, and so on, and didn't get paid to speak. I would say my norm for a conference where attendees pay is free admission, economy travel and hotel covered (but not meals, cab fare and the like), and possibly a small honorarium (eg $500 per talk.) For a conference where attendees do not pay there is no honorarium and often no travel covered either.

Some large conferences offer a few selected speakers a pre-conference which can pay a full week's billable rate or more for a single day (because, of course, you put a lot of time into preparing that day of training). I have heard of conferences that actually ask speakers to pay to get in the door in addition to covering their own travel expenses.

For me, the benefit of being there for the week and the benefit of being able to say "I've spoken at ten Tech Ed US, four Tech Ed Europe, and three Tech Ed Africa" (so far - fifth Tech Ed Europe is next month) is what has to balance against my time spent preparing the talks and being there. The honorarium rarely factors into it. (How much speaking do I do? http://www.gregcons.com/KateBlog/CategoryView.aspx?category=Speaking)

OwnerDisplayName: FluffyCoder

Title: Do speakers get paid for tech talks?

ContentLicense: CC BY-SA 2.5


答:
How do you decide when it is time to rebuild a system with newer technology, versus keeping on plugging holes in an old one?

With businesses, it usually boils down to money.  Their purpose is to make money, and they tend to think in terms of it.  If it makes more sense, financially, to do a rewrite, then it's a strong indication that you should go ahead (and, hopefully, that you've considered many different sides to the equation).

Beware though, as many others have pointed out, developers tend to underestimate heavily.  Also, it's usually not quite as simple as "it will cost X to rewrite, Y to fix, and X < Y"; you might need to think in terms of licensing, risk of a new implementation, risk of the old implementation, missed business opportunities (all of these can pretty much be expressed in terms of money), documentation, training, and many more.  What seems like a good idea one minute might not seem so great if you take a step back and think about it for a second.

And how do you make a case for rebuilding? How can you persuade the powers-that-be it is necessary to rebuild the system?

This follows pretty simply from the above - you make a case by showing an estimated difference in cost between the two solutions, over time.  Yes, you are definitely sticking your neck out when you do this, but if you're going to make recommendations that have a large financial impact, you should not do so lightly.


问:
How important is multithreading in the current software industry?
I have close to 3 years experience writing web applications in Java using MVC frameworks (like struts). I have never written multithreaded code till now though I have written code for major retail chains.

I get a few questions on multithreading during interviews and I answer them usually (mostly simple questions). This left me wondering how important is Multithreading in the current industry scenario ?

答: It is getting ever more important as modern processors have more and more cores. A decade ago most of the existing computers had only a single processor, so multithreading was important only on higher-end server applications. Nowadays even basic laptops have multicore processors. In a few years even mobile devices... So more and more code is required to use the potential performance advantages of concurrency and to run correctly in a multithreaded environment.</p>


问:
License validation and calling home
I am developing an application that, when bought, can be activated using a license.

Currently I am doing offline validation which is a bit troubling to me. I am aware there is nothing to do against cracks (i.e modified binaries), however, I am thinking to trying to discourage license-key pirating. Here is my current plan:

When the user activates the software and after offline validation is
successful, it tries to call home and validate the license. If home
approves of the license or if home is unreachable, or if the user
is offline, the license gets approved. If home is reached and tells
the license is invalid, validation fails.

Licensed application calls home the same way every time during startup (in background). If license is revoked (i.e pirated license or generated via keygen), the license get deactivated.

This should help with piracy of licenses - An invalid license will be disabled and a valid license that was pirated can be revoked (and its legal owner supplied with new license). Pirate-users will be forced to use cracked version which are usually version specific and harder to reach.

While it generally sounds good to me, I have some concerns:

Users tend to not like home-calling and online validation. Would that kind of validation bother you? Even though in case of offline/failure the application stays licensed?

It is clear that the whole scheme can be thwarted by going offline/firewall/etc. I think that the bother to do one of these is great enough to discourage casual license sharing, but I am not sure.

As it goes in general with licensing and DRM variations, I am not sure the time I spend on that kind of protection isn't better spent by improving my product.

I'd appreciate your input and thoughts.

Thanks!

答:
With anything like this you should ask yourself (or your boss) the following question:

Are the costs of developing and maintaining an anti-piracy scheme less than or greater than the losses due to piracy?

If they are less then by all means go for it. In this case I assume that your software is high value (like Microsoft Word or AutoCAD) and people are not going to fret about it calling home once in a while, especially in today's "always online" world.

If they are greater then I'd seriously suggest you don't implement anything too complex (or indeed anything at all) and put effort into earning money from the software in other ways. You could charge for support, or for people to be on the developer program, or any number of other things.

Another thing to bear in mind is that if someone is determined to pirate your software they will and adding more layers won't stop them, but will potentially annoy your legitimate users.

Title: License validation and calling home

ContentLicense: CC BY-SA 4.0


答:
Sounds like you're already writing multithreaded code.

Most Java web applications can handle multiple requests at the same time, and they do this by using multiple threads.

Therefore I'd say it's important to know the basics at least.

Title: How important is multithreading in the current software industry?

Body:
I have close to 3 years experience writing web applications in Java using MVC frameworks (like struts). I have never written multithreaded code till now though I have written code for major retail chains.

I get a few questions on multithreading during interviews and I answer them usually (mostly simple questions). This left me wondering how important is Multithreading in the current industry scenario ?


答: It's still important in situations where you need it, but like a lot of things in development it's the right tool for the right job. I went for 3 years without touching threading, now practically everything I do has some grounds in it. With multi-core processors there's still a great need for threading, but all the traditional reasons are still valid, you still want responsive interfaces and you still want to be able to deal with sync and get on with other things at once.</p>


答:
Just a warning about multithreading: More threads don't mean better efficiency. If not managed properly, they may slow down the system. Scala's actor improve upon Java's threading and maximize system usage (mentioned it as you're a Java developer).

EDIT:
Here's are some things to keep in mind about the downsides of multithreading:

interference of threads with each other when sharing hardware resources

Execution times of a single thread are not improved but can be degraded, even when only one thread is executing. This is due to slower frequencies and/or additional pipeline stages that are necessary to accommodate thread-switching hardware.

Hardware support for multithreading is more visible to software, thus requiring more changes to both application programs and operating systems than Multiprocessing.

Difficulty of managing concurrency.

Difficulty of testing.

Also, this link might be of some help about the same.


答:
Understanding how to leverage threading to improve performance is a critical skill in today's software environment, for most industries and applications.

At a minimum, understanding the issues involved with concurrency should be a given.

The obvious note that not all applications or environments will be able to take advantage of it applies, for example in many embedded systems. However it seems as though the Atom processor (et al) seem to be working to change that (lightweight multicore starting to become more common).


答:
This is not really a war that you can win with the approach you have lined out.  As others have pointed out, simply disabling the network, or clicking "no" when the firewall asks you whether or not to allow your application to phone home, will bypass the phone-home.  Aside from that, users absolutely hate this type of thing, and you may be required to explicitly have the user tick a checkbox saying that they understand what the system is about to phone home (according to the law in some countries).

So, what can you do?  My advice would be:

Try to reward your paying customers with value-adds (frequent updates, online tutorials, etc), rather than effectively punishing them.

Don't worry too much about pirates.  In many cases, they are unlikely to have purchased your software in the first place, the least they can do is spread awareness of your application.

If you really can't handle the fact that your software is going to be pirated, make it an online app (if the nature of the software is such that this is possible).  There was an interesting article by a developer who made this move, and found that his web version sold far better, was far easier to identify what features users actually used (since it's not really calling home if you're already on the server), and there was far less reluctance for people to whip out their credit cards (sorry - can't find the link).

Title: License validation and calling home

Body:
I am developing an application that, when bought, can be activated using a license.

Currently I am doing offline validation which is a bit troubling to me. I am aware there is nothing to do against cracks (i.e modified binaries), however, I am thinking to trying to discourage license-key pirating. Here is my current plan:

When the user activates the software and after offline validation is
successful, it tries to call home and validate the license. If home
approves of the license or if home is unreachable, or if the user
is offline, the license gets approved. If home is reached and tells
the license is invalid, validation fails.

Licensed application calls home the same way every time during startup (in background). If license is revoked (i.e pirated license or generated via keygen), the license get deactivated.

This should help with piracy of licenses - An invalid license will be disabled and a valid license that was pirated can be revoked (and its legal owner supplied with new license). Pirate-users will be forced to use cracked version which are usually version specific and harder to reach.

While it generally sounds good to me, I have some concerns:

Users tend to not like home-calling and online validation. Would that kind of validation bother you? Even though in case of offline/failure the application stays licensed?

It is clear that the whole scheme can be thwarted by going offline/firewall/etc. I think that the bother to do one of these is great enough to discourage casual license sharing, but I am not sure.

As it goes in general with licensing and DRM variations, I am not sure the time I spend on that kind of protection isn't better spent by improving my product.

I'd appreciate your input and thoughts.

Thanks!


答:
I get a few questions on multithreading during interviews...

Well for passing the interviews, multithreading might be quite important. Quoting self, "when interviewing candidates for our team, I ask concurrency questions not because these skills are important in our project (these are not) but because these somehow make it easier for me to evaluate general knowledge of language we use..."


答:
My observation is that it depends a lot on the vertical market where you're distributing your application. Some are much more prone to piracy and other unauthorized use than others. For example, I'll never release another product to the Internet marketing and SEO market without doing a "phone home" and other protections. Widespread and casual piracy is the rule in that niche. Other niche markets that I've worked in, such as medical claims processing, I'd be more comfortable with looser copy protection.

As Daniel B mentioned, moving the app online, in whole or in part, is a potential option. This is my current plan for a new app that I'm in the design phase on right now.

Title: License validation and calling home


问:
PHP vs C# performance
I have a application that is part console application written in C# and part PHP web application.

The console application connects to multiple serial devices and reads data pertaining to moisture and temperature in a Grain Dryer. [The application] then stores the information in a MySQL database.

The PHP reads the MySQL database and displays the information to the user (simple).

I have also written a PHP script to email / sms the user if one of the temperatures of moistures reaches alarm levels (alarm levels are read off the device and stored in the MySQL database).

Currently, I post to the PHP page with each "update" from the device (10 seconds) and check each value against it's limits. If an alarm is required I send it off and update the database indicating an alarm has been sent.

This looks like (pseudo code)

```<code>IF moisture IS GREATER THAN moisture_high_critical_limit THEN
  IF moisture_high_critical_alarm_has_been_sent IS FALSE THEN
    SEND_ALARM();
    moisture_high_critical_alarm_has_been_sent = TRUE;
  END IF
ELSE IF moisture IS GREATER THAN moisture_high_warning_limit THEN
  IF moisture_high_warning_alarm_has_been_sent IS FALSE THEN
    SEND_ALARM();
    moisture_high_warning_alarm_has_been_sent = TRUE;
  END IF
ELSE IF moisture IS LESS THAN moisture_low_critical_limit THEN
  IF moisture_low_critical_alarm_has_been_sent IS FALSE THEN
    SEND_ALARM();
    moisture_low_critical_alarm_has_been_sent = TRUE;
  END IF
ELSE IF moisture IS LESS THAN moisture_low_warning_limit THEN
  IF moisture_low_warning_alarm_has_been_sent IS FALSE THEN
    SEND_ALARM();
    moisture_low_warning_alarm_has_been_sent = TRUE;
  END IF
END IF
</code>```

The above IF statement is repeated for every temperature and moisture reading from the device, which can be quite a few.

Should this type of processing be happening in my Console application? Then if a Alarm notification is required post to the page only to send the email / SMS?

Processing this information in the console application will reduce my total number of handshakes with the MySQL Database. But if the MySQL Database is hosted locally will this have much impact?

I will eventually benchmark both (if it seems the doing the processing in the console application is in fact the right approach), however there is a lot of code to port over so I thought I'd come here and ask first.

答:
From a performance standpoint if you can query the database or a config file for the critical values and then pre-process the incoming data before it is sent to the database, then you should have a very high performance sensor and code.    This type of conditional logic shouldn't take long to go through and if you want to pick up speed you can always have it recoded in a compiled language.  You can certainly send an SMTP message from the code when the sensor picks up a bad set of data.

I would have suggested looking at a MYSQL Insert trigger to run your logic, but the MYSQL references I consulted suggested that using an SMTP interface to automatically send email from the server trigger or stored procedure was not as refined as Microsoft's or ORACLE's offerings.  Perhaps this is something to consider for the future if your needs grow and you want to have less intelligent sensors deployed in remote locations to pull/push data.

Title: PHP vs C# performance


答:
In general, multi-threading is already quite important, and is only going to get more important in the next few years (as Péter Török) pointed out - it is how processors will scale for the forseeable future (more cores instead of higher MHz).

In your case, however, you seem to be working mainly with web applications.  Web applications, by their nature, are multi-threaded due to the way your web server processes requests for each user (i.e. in parallel).  While it's probably important for you to understand concurrency and thread-safety (especially when dealing with caches and other shared data), I doubt you will run into too many cases where it's beneficial to multi-thread the web application code internally (i.e. multiple worker threads per request).  In that sense, I think being an expert at multi-threading is not really necessary for a web developer.  It's often asked in interviews, because it is quite a tricky subject, and also because many interviewers just google up a few questions 10 minutes before you get there.


答:
A few things:

Separate modules to work-on

Talking about changes before they are made [with all devs]

Unit testing [for verification and avoidance for breaking related things]

As the others mentioned a VCS

Title: How do you manage refactoring with a large code base and many developers?

Body:
I would like to prevent a situation where two developers refactor the same code simultaneously without talking about it first, probably using a tool of some kind, maybe an Eclipse plug-in. Can you help?

We've got 4.5 million lines of code, and more than 20 teams of developers on four continents.

Ideally I would like the second of the developers mentioned earlier to notice that someone else is working on the same piece of code and talk to the first one before modifying anything.

Do you know of a solution?


问:
How to publish paid Android apps if you're not from US/UK
I was pretty excited while creating one of my apps but as it turns out you can't actually sign up for Google Checkout if you don't live either in the USA or in the UK. And since Google Checkout is the only way Android Market will pay you, all my efforts seem to be going in vain. So because I live in India, I can't sell my apps.

I tried contacting Google by various means on this, but haven't got any response so far. I tried searching the web as well just to find out that one can't be paid via any other way.

I am pretty sure that many people here might have gone through the same problem. How did you solve it?

I have a PayPal account and an AdSense account as well. Can they help in any way?

And if nothing works out, how am I supposed to be selling my app?

答:
There are other ways to monetize your app. You can for instance publish a free version without some features and offer in-app purchase (it can be done through paypal if you want).

Also, you could add ads to your app... that's also a way to get some money. In fact, sometimes it is more profitable than publishing a paid app. I usually publish two version of my applications: free and pro (paid)... and always free generates more money with ads than pro.


答:
In my experience, it depends entirely on the industry and who is leading the project.

Something tells me that the answers to this question will be strongly biased since the only people with the time to read and comment on this site are those without much work to do.  In my past job, there was NEVER downtime.  It had a lot to do with how well projects were decoupled and organized.  If not well organized, working multiple projects at the same time can lead to problems when trying to merge changes and it's actually more cost effective to do nothing for a bit than to overcomplicate matters.

Title: Is it common to have downtime at a programming job?

Body:
At my company, I find that there are some days that there are very few tasks to do.  I make it a point to do research to learn new things about my craft on these days.

I would say that on average, I have about one day per week that there is not much to do (or some combination of time over the week).

I would like to know if this is a common situation in software development environments, and does the answer to this question vary between full-time and contract work.


答: One concern that does not appear to be addressed here is "you've gone out of business". While this may appear to be a variation of "network is down", it is a more permanent situation. I've come across this in several developer products. </p>

Title: License validation and calling home


问:
Recommend a design pattern/approach to exposing/tolerating/recovering from system errors, Exception handling (e.g.s in Java, C++, Perl, PHP)
Can you recommend a design pattern/approach to exposing/tolerating/recovering from system errors, Exception handling (Java, C++, Perl, PHP)?

Some errors need to be reported.

Some errors can be handled internally (by a retry or are inconsequential (can be ignored).

How do you structure the code to catch them?

But all errors need to be logged.

What best practises are there?

And for simulating them to be able to fully test components that are impacted by them?

General non-programming-language specific question applicable to several modern programming languages but would welcome example illustrations of patterns, approaches and philosophies in Java, C++, PHP and Perl.

(Also asked in stackoverflow: https://stackoverflow.com/questions/7432596/recommend-a-design-pattern-approach-to-exposing-tolerating-recovering-from-system
but I thought it should be asked on programmers too because I think the programmers Q&A covers wider software/programming issues whereas stackoverflow is more about technical implementation IMHO).

答:
Build your objects the right way, don't worry about external factors. If you choose to take advantage of exceptions, then make your objects throw exceptions if they fail at something.

Once all your objects are working correctly, it should be fairly easy to come up with a clean error-handling responsibility hierarchy in your design.


问:
How can I improve the way I make changes to an Index page?
We have index pages, running on an Apache Tomcat server, with links to other pages.

Welcome, you.  What would you like to do?

Goto page x

Goto page y

These links are hard coded.

I want to be able to manage the index pages in a more dynamic way. So that I don't have to pull down the page, cause temporary down time, change / add links, and then have to redeploy.

What route should I take?

答:
Instead of overwriting the file, simple copy the new file with a different name, remove the old file and then rename the new one to the old one's name.

Script it up and you've got maybe a 1ms downtime.


答:
Fail fast is a great design approach, and perhaps it can be counted as a pattern: http://en.wikipedia.org/wiki/Fail-fast

I've also found a number of principles to be useful:

Consider exceptions as part of the interface to each function / modules - i.e. document them and where appropriate / if your language supports it then use checked exceptions.

Never fudge a failure - if it failed, don't try to continue with some attempt to "assume" how to proceed. For example, special handling for null cases is often a code smell to me: if your method needs a non-null value, it should be throwing an exception immediately if it encounters a null (either NullPointerException or ideally a more descriptive IllegalArgumentException).

Write unit tests for exceptional cases as well as normal ones - sometimes such tests can be tricky to set up but it is worth it when you want to be sure that your system is robust to failures

Log at the point where the error was caught and handled (assuming the error was of sufficient severity to be logged) . The reason for this is that it implies you understood the cause and had an approach to handle the error, so you can make the log message meaningful.....

Use exceptions only for truly unexpected conditions/failures. If your function "fails" in a way that is actually expected (e.g. polling to see if more input is available, and finding none) then it should return a normal response ("no input available"), not throw an exception

Fail gracefully (credit to Steven Lowe!) - clean up before terminating if at all possible, typically by unwinding changes, rolling back transaction or freeing resources in a "finally" statement or equivalent. The clean-up should ideally happen at the same level at which the resources were committed for the sake of clarity and logical consistency.

If you have to fail, fail loudly - an exception that no part of your code was able to handle (i.e. percolated to the top level without being caught + handled) should cause an immediate, loud and visible failure that directs your attention to it. I typically halt the program or task and write a full exception report to System.out.

Title: Recommend a design pattern/approach to exposing/tolerating/recovering from system errors, Exception handling (e.g.s in Java, C++, Perl, PHP)

Body:
Can you recommend a design pattern/approach to exposing/tolerating/recovering from system errors, Exception handling (Java, C++, Perl, PHP)?

Some errors need to be reported.

Some errors can be handled internally (by a retry or are inconsequential (can be ignored).

How do you structure the code to catch them?

But all errors need to be logged.

What best practises are there?

And for simulating them to be able to fully test components that are impacted by them?

General non-programming-language specific question applicable to several modern programming languages but would welcome example illustrations of patterns, approaches and philosophies in Java, C++, PHP and Perl.

(Also asked in stackoverflow: https://stackoverflow.com/questions/7432596/recommend-a-design-pattern-approach-to-exposing-tolerating-recovering-from-system
but I thought it should be asked on programmers too because I think the programmers Q&A covers wider software/programming issues whereas stackoverflow is more about technical implementation IMHO).


答:
It is extremely important.

What is more important though is to understand that multithreading is just one way to solve the asynchrony problem. The technical environment in which many people are now writing software differs from the historical software development environment (of monolithic applications performing batch computations) in two key ways:

Many-core machines are now common. We can no longer expect clock speeds or transistor densities to increase by orders of magnitude. The price of computation will continue to fall, but it will fall because of lots of parallelism. We're going to have to find a way to take advantage of that power.

Computers are now heavily networked and modern applications rely upon being able to fetch rich information from a variety of sources.

From a computational standpoint, these two factors essentially boil down to the same core idea: information increasingly will be available in an asynchronous fashion. Whether the information you need is being computed on another chip in your machine or on a chip halfway around the world doesn't really matter. Either way, your processor is sitting there burning billions of cycles a second waiting for information when it could be doing useful work.

So what matters now, and what will matter even more in the future, is not multithreading per se, but rather, dealing with asynchrony. Multithreading is just one way to do that -- a complicated, error-prone way that is only going to get more complicated and more error-prone as weak-memory-model chips become more widely used.

The challenge for tools vendors is to come up with some way better than multithreading for our customers to deal with the asynchronous infrastructure they'll be using in the future.


答:
Multi-threading is a red herring.
Multi-threading is a implementation detail to the real problem which is Concurrency. Not all threaded programs are concurrent because of locks and what not.

Threads are only one model and implementation pattern for implementing concurrent programs.

For instance you can write highly scalable and fault tolerant software without every doing any multi-threading in languages such as Erlang.


答:
Having worked with exceptions in Java and .NET AND after reading a lot of articles about how/when/why catching exceptions, I finally came up with the following steps that I go through in my head whenever I see a potential exception happening, or an exception I must catch (Java)... even if it never happens (sigh...). And it seem to be working, at least for me:

Is there anything useful I can do with that exception, (except logging) ? If the answer is yes, write the workaround code, and if the workaround may throw exceptions, go to 2:

Wrap the exception around a runtime exception, throw it, go to 3.

In the higher-level class where a possible database/process transaction has been initiated, catch the exception, rollback the transaction, rethrow the exception.

At the top-level class (which may be the one where the transaction has been initiated), log the exception using a logging framework such as slf4j (coupled with log4j for example), or log4net. If possible, directly email the exception to a distribution list that is composed of developers of the application.

If there is a GUI, display an error message indicating in the most user-friendly way what caused the problem; do not display the exception/stacktrace, the user doesn't care and doesn't need to know it was a NullPointerException.

I should also add the step 0, where I am purposely throwing what I call a "business" exception (a new exception that I create by extending the "Exception" class) when some complex treatment cannot be executed because of data errors, BUT that are known to happen as they have been identified as exception cases during the analysis.

Except for the logging part, I fully agree with the points written by "mikera"; I will just add that the exception should be logged once only.

Also, the steps I listed may be different if what you are writing is an API/Framework. There, throwing well designed exceptions is mandatory to help developers understand their mistakes.

As for testing the exceptions, using mock objects you should be able to test nearly everything, be it exception-al or not, provided that your classes respect the "one class to do one thing" best practice. I also personally make sure to mark the most important but hidden methods as "protected" instead of "private" so that I can test them without too much hassle. Apart from that, testing exceptions is simple, just provoke the exception and "expect" an exception to occur by catching it. If you don't get an exception, then you have a unit test case error.


问:
Are database schema migrations a problem in production environments?
In discussions about NoSQL vs SQL databases, I sometimes hear that companies prefer to use schemaless NoSQL databases because it is problematic to migrate the schema to a new version. But is that really a big problem when doing upgrades? Are relational databases bad for such operations?

I read this blog post on the MongoDB blog: Why Schemaless?

答:
But is that really a big problem when doing upgrades?

It can be.

Some organizations are -- well -- disorganized, and do a very bad job of schema migration.

"Migration Weekend".  Stop the servers.  Back up and export all the data.  Build the new schema (often by modifying the existing schema).  Reload data or attempt to restructure in place.

"Continuous Tweaking".  Alter tables to the extent permitted by SQL.  Without tracking the sequence of ALTER's performed.  With no way to go back to  a previous schema version.  Where necessary, create new tables from existing tables, hopefully adjusting all applications to use the new tables.  But -- lacking good QA -- leaving the old tables in place "just in case".

"Full Panic".  Simply prevent schema modifications.  Make a big stink.  Claim the risk is too high.  Block all efforts in this direction.  Take the schema hostage until forced to adopt some more sensible approach.

Are relational databases bad for such operations?

Any schema is a pain to migrate.

The largest issue is not technical.

It's semantic.

One principle reason for a schema change is that the previous schema doesn't match the problem domain very well.  Since the semantics have changed, the database (and applications) need to change.  Sometimes these are profound changes that require rethinking the way the applications work with the data.

Revising semantics of database can be very difficult.

What folks do instead of schema changes is just misuse the physical schema.  They start loading wrong data into existing fields because they can.  A "comment" field suddenly starts having an important piece of customer management information followed by "//" followed by the real comment.  That grows to have to pieces of data "field 1 - field 2 // comment".  The users have a spreadsheet that extracts this additional data from the comment field because the "real" application software had a schema to hard to change that IT refused to change it.


答:
My machine has 8 cores. In Task Manager, I have 60 processes running. Some, like VS, use up to 98 threads. Outlook uses 26. I expect most of my memory usage is the stacks allocated to each of those idle threads.

I'm personally waiting for the 300-core computer to come out so that I don't have to wait for Outlook to respond. Of course by then Outlook will use 301 threads.

Multi-threading only matters if you are building systems that will be the only important process on the computer at a particular time (e.g., calculation engines). Desktop apps would probably do the user a favour by not using up every available core. Web apps using the request/response model are inherently multi-threaded.

It matters to framework and language designers, and back-end systems programmers - not so much to application builders. Understanding some basic concepts such as locking and writing async code is probably worthwhile though.


答:
It depends.

First, if you have a really big database spanning multiple machines, then everything (not just database update) is going to be pain. (no matter how much you planned ahead of time).

Second, updating a database is NOT just a database thing -- it also depends on the bigger system of which the DB is part. This also includes the database deployment (many database servers, multiple data-centers, master-slave setups, etc.)

The pain can be eased by architecturing you system components such that they all have some sort of 'cognizance' of the DB schema change event. This means that the entire system should be tolerant of schema changes and can respond to it in a 'sane' way.

You can check out a utility developed by Facebook for tackling MySQL schema updates.

Also, there are standard best practices like turning you master read-only, making changes to slaves or on development copy, etc.

In any case, having a full backup and extensive test suite is a MUST. Only then, can you do any changes confidently and safely.

Title: Are database schema migrations a problem in production environments?

Body:
In discussions about NoSQL vs SQL databases, I sometimes hear that companies prefer to use schemaless NoSQL databases because it is problematic to migrate the schema to a new version. But is that really a big problem when doing upgrades? Are relational databases bad for such operations?

I read this blog post on the MongoDB blog: Why Schemaless?


答: The nice thing about Android is that end users can use one or more app stores to get apps. Amazon is probably the next biggest (no numbers, just an assumption on my part, probably wrong). So if you can not get on the Google's Android Market, try Amazon's, as it appears to be open to India. </p>

Title: How to publish paid Android apps if you're not from US/UK

Body:
I was pretty excited while creating one of my apps but as it turns out you can't actually sign up for Google Checkout if you don't live either in the USA or in the UK. And since Google Checkout is the only way Android Market will pay you, all my efforts seem to be going in vain. So because I live in India, I can't sell my apps.

I tried contacting Google by various means on this, but haven't got any response so far. I tried searching the web as well just to find out that one can't be paid via any other way.

I am pretty sure that many people here might have gone through the same problem. How did you solve it?

I have a PayPal account and an AdSense account as well. Can they help in any way?

And if nothing works out, how am I supposed to be selling my app?

Body: The nice thing about Android is that end users can use one or more app stores to get apps. Amazon is probably the next biggest (no numbers, just an assumption on my part, probably wrong). So if you can not get on the Google's Android Market, try <a href="https://developer.amazon.com/welcome.html?login=https://www.amazon.com/ap/signin?openid.assoc_handle=mas_dev_portal&openid.identity=http://specs.openid.net/auth/2.0/identifier_select&openid.ns=http://specs.openid.net/auth/2.0&openid.claimed_id=http://specs.openid.net/auth/2.0/identifier_select&openid.return_to=https://developer.amazon.com/ap_login/68747470733A2F2F646576656C6F7065722E616D617A6F6E2E636F6D2F686F6D652E68746D6C.html&openid.mode=checkid_setup&openid.pape.max_auth_age=60" rel="nofollow">Amazon's, as it appears to be open to India.


答:
Since you asked about Salesforce and Apex specifically, I'll give you my opinion on it.

I have developed an application using Apex on the Force.com platform and found the tools and provided libraries lacking. Their implementation of the MVC paradigm is more like ASP.Net Code Behind than anything else.

They are slow to add new features for developer and instead are trying to turn Salesforce into some sort of social networking platform.

I think as a CRM, it is excellent, but as a platform for developing cloud based applications, it stops making sense for anything other than relatively basic data capture/reporting style apps.

As a developer, I can't help but think it's a career dead end.

That said, their REST API is nice enough and dealing with that will get you exposure to OAuth, JSON and all of that. I certainly enjoyed writing code related to that more than the core Force.com app.


问:
Long parameter list versus long state variable list
In a C++ book, the author says we no longer need a function with a long parameter list because most of the parameters can be refactored into state variables in a class.
On the other hand,  a functional programming book says state variables are evil because it causes side-effects which cause bug-prone and hard to parallelize code.
I'm getting puzzled. Should the code avoid relying on state variables as much as possible by moving its state variable into the function parameter list?</p>

答:
No, state variables per se do not cause side effects.

Calling a setter method (on a data structure that is visible elsewhere) is a side effect.

You can have data structures to hide long parameter lists ansd yet avoid side effects if you construct them accordingly. Here is a small example (in Java, untested):

```<code>class ManyParams {
    final String theName = null;
    final int    theAge = 0:
    ManyParams() {}
    ManyParams(String a, int b) { theName=a; theAge = b; }
    public withName(String n) {
        return new ManyParams(n, this.theAge);
    }
    public withAge(int i) {
         return new ManyParams(theName, i);
    }
}
/// to be used like this
foo(new ManyParams.withName("John").withAge(42));
</code>```

Of course, the constructor of ManyParams will still have a long parameter list this way.
But its hidden.

Body:
No, state variables per se do not cause side effects.

Calling a setter method (on a data structure that is visible elsewhere) is a side effect.

You can have data structures to hide long parameter lists ansd yet avoid side effects if you construct them accordingly. Here is a small example (in Java, untested):

class ManyParams {
    final String theName = null;
    final int    theAge = 0:
    ManyParams() {}
    ManyParams(String a, int b) { theName=a; theAge = b; }
    public withName(String n) {
        return new ManyParams(n, this.theAge);
    }
    public withAge(int i) {
         return new ManyParams(theName, i);
    }
}
/// to be used like this
foo(new ManyParams.withName("John").withAge(42));

Of course, the constructor of ManyParams will still have a long parameter list this way.
But its hidden.


问:
Functions with side-effects in Delphi/Pascal
What is the proper approach to functions that have side-effects in Delphi/Pascal?

For example, I could have a boolean function DeleteFile that returns True if the file was deleted and False otherwise. How do I collect the return value?

1) The very explicit form would be:

```<code>if DeleteFile(MyFilePath) then
begin
  IsMyFileDeleted := True;
end;
else
begin
  IsMyFileDeleted := False;
end;
</code>```

2) Less bulky would be:

```<code>IsMyFileDeleted := False;
if DeleteFile(MyFilePath) then
begin
  IsMyFileDeleted := True;
end;
</code>```

3) Or even shorter, but discouraged by JEDI - perhaps it is acceptable just to collect return values:

```<code>IsMyFileDeleted := False;
if DeleteFile(MyFilePath) then IsMyFileDeleted := True;
</code>```

My problem with 2 and 3 is that I explicitly state something (X := False) that I may not know for sure.

4) I would rather not set the variable beforehand and have its value completely determined by the function:

```<code>IsMyFileDeleted := DeleteFile(MyFilePath);
</code>```

Here the issue is that it is a bit misleading, because assigning a value to a boolean has a pretty serious side-effect. I'm not sure if this usage is desirable.

Some argue that functions should never have side-effects, but I think some of Pascals internal functions violate that.

5) The alternative would be making it procedures with a result variable to be filled by the procedure:

```<code>DeleteFile(MyFilePath, IsMyFileDeleted);
</code>```

That might go against the trend to keep parameter use to a minimum (Clean Code).

4 and 5 would be the only ways to collect a return value other than boolean, I suppose? Does that mean anything for boolean functions?

Yes, there are many ways to do the same thing and maybe I'm just worried about nothing really, but I'm trying to develop a good style and I wonder if there are any best practices. For a beginner, many principles seem to be in conflict all the time.

答:
To be clearer about what's going on, you should probably do something like this:

```<code>IsMyFileDeleted := False;
if (CanDeleteFile(MyFilePath)) then
begin
    DeleteFile(MyFilePath);
    IsMyFileDeleted := True;
end
</code>```

The first line is true at the point it has been run (unless the file doesn't exist).

Using CanDeleteFile(...) allows you to separate the true/false features of the code's intent from the exceptional behavior of being unable to delete something that should have been deleted.  So, if you can delete the file, then DeleteFile should raise an exception if it can't.

Edited

If I were writing in C#, the first situation would have looked like this.  Using exception handling would likely be better in Delphi/Pascal, if available.  In this model, DeleteFile() returns nothing at all.  Either it works, or it supplies information about why it didn't work.

```<code>try
{
    DeleteFile(MyFilePath);
}
catch (IOException ex)
{
    // Do whatever you would have done if DeleteFile() returned false.
}
</code>```

Body:
To be clearer about what's going on, you should probably do something like this:

IsMyFileDeleted := False;
if (CanDeleteFile(MyFilePath)) then
begin
    DeleteFile(MyFilePath);
    IsMyFileDeleted := True;
end

The first line is true at the point it has been run (unless the file doesn't exist).

Using CanDeleteFile(...) allows you to separate the true/false features of the code's intent from the exceptional behavior of being unable to delete something that should have been deleted.  So, if you can delete the file, then DeleteFile should raise an exception if it can't.

Edited

If I were writing in C#, the first situation would have looked like this.  Using exception handling would likely be better in Delphi/Pascal, if available.  In this model, DeleteFile() returns nothing at all.  Either it works, or it supplies information about why it didn't work.

try
{
    DeleteFile(MyFilePath);
}
catch (IOException ex)
{
    // Do whatever you would have done if DeleteFile() returned false.
}


问:
Should I include a selfdestruct-method to my applications?
I recently had a negative experience, where client bailed from the bill, but my middle-man already uploaded our software and design to the clients server. Client turned out be a known criminal, and of course he changed all possible passwords of the server.

However, I can still access the admin-panel of the CMS. Sadly it turns out, that my software is very secure.. Tried to SQL-injection, fake the image-upload etc etc. However, I cannot hack my own software.. Anyways, I preparing to sue this person, so that is not the problem.. I'm just thinking now, that maybe there should be some backend selfdestruct-method. So, if similar case occur, I have the option to kill the software.

My own idea is to hide some function in the core files. Encode it with base64, so it wouldn't be obvious. So something like this:

```<code>eval(base64_decode('ZWNobyAnSGVsbG8gd29ybGQhJzs=')); // echo 'Hello world!';
</code>```

And basically make a small script, that takes all the software's files, chmod's them to be sure and then deletes them.

My newer versions of the CMS, all have filemanagers that I could use for easier hacking. But what if the access to the admin-panel is limited.

To be very clear, this is meant only for the development-stage software's, in my personal server or the clients server (last part being the ethically questionable.) So if my client should steal my software.. This wont be included inside a commercial-software.

And to be even more clear, we are talking about those rare freelance jobs. I think its fairly logical, that contract-work doesn't need such methods. So we are talking about those jumprisk-clients, only in development mode -- when the project is ready, then obviously this would be a very very unethical backdoor to have inside your software.

Ethically is this a good idea? (Keeping in mind, that obviously I will remove it, when project has been 100% and everything is paid for)

Have you guys ever had to hack your own software, because of similar issues with the client(s)?

Any recommendations on this idea, code and method wise?

What may be the possible drawbacks or repercussions of selfdestruct-scripts?

My conclusion on this

Is a little bit sad, that all answers were targeted on the contracted cases. It was my fault really, that I didn't make it more clear in my question.. just thought, that it is fairly clear, that there is no point in the kill-switch.. when you are protected by the contract.

However, if you are doing a contract work.. then this should be stated in the contract -- this makes it legal, even inside the clients own server. However, having kill-switches inside my own personal server is really nobodies business (this is what I really wanted to know.)

I decided to make the kill-switch script for my CMS. Mainly, because it seems an interesting challenge. But also, that I could use this for my non-contracted works where the client is a friend of a friend of a friend.. I probably wont use this on the clients server, but..for the cases, where the client or some middlemen have access to my server .. And my software gets stolen, or "moved without my knowledge", then I don't get paid and they cut the access to the software.

I have read trough alot of topics here, where they recommend to send a warning and then take down the page. Well, I saw a problem in it, as when Im dealing with a person.. who will just copy it to somewhere else (maybe re-brand it and sell it) and tells me, that it has been taken down. And also, I wouldn't "turn the site off", but delete it. Though, I guess its still illegal to access my clients server and to delete it. Or at-least, access it trough backend and not from the FTP. For this I thank all of you, who answered.

答:
This seems like a phenomenally bad idea that could potentially land you in jail.

It's unethical. Bad behavior of your client doesn't make it right for you to hack their system.

It's illegal. This has happened before, with bad outcomes for the offending parties.

It's pointless. What would you possibly do with this backdoor that wouldn't get you in trouble? Would you blackmail the client?

It's dumb. Even if you could do this without getting caught, the potential risks far outweigh any possible gain.


答:
No. If your clients found out you would be lynched. It's not at all secure. Someone, some how will find out how to trigger it and then suddenly you have the task of contacting all your clients to tell them about it and why they have to do an emergency patch.

If you do hack it you are also opening yourself up to criminal proceedings. I assume you have proof you still own the site? That you have the right to access it? The cost to his business could be "astronomical"

There are acceptable alternatives. Put a watermark on the site, so every page displays a message. On payment you can remove the watermark.

Title: Should I include a selfdestruct-method to my applications?

Body:
I recently had a negative experience, where client bailed from the bill, but my middle-man already uploaded our software and design to the clients server. Client turned out be a known criminal, and of course he changed all possible passwords of the server.

However, I can still access the admin-panel of the CMS. Sadly it turns out, that my software is very secure.. Tried to SQL-injection, fake the image-upload etc etc. However, I cannot hack my own software.. Anyways, I preparing to sue this person, so that is not the problem.. I'm just thinking now, that maybe there should be some backend selfdestruct-method. So, if similar case occur, I have the option to kill the software.

My own idea is to hide some function in the core files. Encode it with base64, so it wouldn't be obvious. So something like this:

```<code>eval(base64_decode('ZWNobyAnSGVsbG8gd29ybGQhJzs=')); // echo 'Hello world!';
</code>```

And basically make a small script, that takes all the software's files, chmod's them to be sure and then deletes them.

My newer versions of the CMS, all have filemanagers that I could use for easier hacking. But what if the access to the admin-panel is limited.

To be very clear, this is meant only for the development-stage software's, in my personal server or the clients server (last part being the ethically questionable.) So if my client should steal my software.. This wont be included inside a commercial-software.

And to be even more clear, we are talking about those rare freelance jobs. I think its fairly logical, that contract-work doesn't need such methods. So we are talking about those jumprisk-clients, only in development mode -- when the project is ready, then obviously this would be a very very unethical backdoor to have inside your software.

Ethically is this a good idea? (Keeping in mind, that obviously I will remove it, when project has been 100% and everything is paid for)

Have you guys ever had to hack your own software, because of similar issues with the client(s)?

Any recommendations on this idea, code and method wise?

What may be the possible drawbacks or repercussions of selfdestruct-scripts?

My conclusion on this

Is a little bit sad, that all answers were targeted on the contracted cases. It was my fault really, that I didn't make it more clear in my question.. just thought, that it is fairly clear, that there is no point in the kill-switch.. when you are protected by the contract.

However, if you are doing a contract work.. then this should be stated in the contract -- this makes it legal, even inside the clients own server. However, having kill-switches inside my own personal server is really nobodies business (this is what I really wanted to know.)

I decided to make the kill-switch script for my CMS. Mainly, because it seems an interesting challenge. But also, that I could use this for my non-contracted works where the client is a friend of a friend of a friend.. I probably wont use this on the clients server, but..for the cases, where the client or some middlemen have access to my server .. And my software gets stolen, or "moved without my knowledge", then I don't get paid and they cut the access to the software.

I have read trough alot of topics here, where they recommend to send a warning and then take down the page. Well, I saw a problem in it, as when Im dealing with a person.. who will just copy it to somewhere else (maybe re-brand it and sell it) and tells me, that it has been taken down. And also, I wouldn't "turn the site off", but delete it. Though, I guess its still illegal to access my clients server and to delete it. Or at-least, access it trough backend and not from the FTP. For this I thank all of you, who answered.


答:
Short answer: Very.

Longer answer: Electronic (transistor-based) computers are fast approaching the physical limits of the technology. It is becoming harder and harder to squeeze more clocks out of each core while managing heat generation and the quantum effects of microscopic circuits (circuit paths are already being placed so close together on modern chips that an effect called "quantum tunneling" can make an electron "jump the tracks" from one circuit to another, without needing the proper conditions for a traditional electrical arc); so, virtually all chip manufacturers are instead focusing on making each clock able to do more, by putting more "execution units" into each CPU. Then, instead of the computer doing just one thing per clock, it can do 2, or 4, or even 8. Intel has "HyperThreading", which basically splits one CPU core into two logical processors (with some limitations). Virtually all manufacturers are putting at least two separate CPU cores into one CPU chip, and the current gold standard for desktop CPUs is four cores per chip. Eight is possible when two CPU chips are used, there are server mainboards designed for "quad quad-core" processors (16 EUs plus optional HT), and the next generation of CPUs is likely to have six or eight per chip.

The upshot of all of this is that, to take full advantage of the way computers are gaining computing power, you must be able to allow the computer to "divide and conquer" your program. Managed languages have at least a GC thread which handles memory management separately from your program. Some also have "transition" threads which handle COM/OLE interop (as much for protecting the managed "sandbox" as for performance). Beyond that, though, you really have to start thinking about how your program can do multiple things simultaneously, and architect your program with features designed to allow pieces of the program to be handled asynchronously. Windows, and windows users, will practically expect your program to perform long, complicated tasks in background threads, which keep the UI of your program (which runs in the program's main thread) "responsive" to the Windows message loop. Obviously, problems that have parallelizable solutions (like sorting) are natural candidates, but there are a finite number of types of problems that benefit from parallelization.


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

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

答:
Relationship between length and quality

If you want me to give you a two-hour presentation, I am ready today.  If you want only a five-minute speech, it will take me two weeks to prepare.

  — Mark Twain

The shortest version:

If I had more time, I would have written a shorter letter.

  — Marcus T. Cicero

The near-perfectionist's version:

You know that I write slowly. This is chiefly because I am never satisfied until I have said as much as possible in a few words, and writing briefly takes far more time than writing at length.

  — Karl Friedrich Gauss

Several more discuss this concept from various angles.

LastEditorDisplayName: Roger Pate


答:
Please don't ask programmers, ask a lawyer.  I would imagine at the least you would want to include a clause in your contract saying you have a right to do what your question contemplates doing.  (Doesn't the "irreparable harm" clause of some contracts let you get a court order to shut down the software immediately until the court has a chance to sort it out?)  I think a court order would be lot safer for you than a code bomb (which could be considered criminal, if a court found you didn't own the software it could be destruction of property, in the U.S. it might possibly fall under the breaking digital encryption sections of the Digital Millennium Act, etc.  I could imagine winning damages in civil court and still being convicted in criminal court).

The rules will vary depending on where you and your client live and operate, so I really think you would want a lawyer.


答:
Ethically is this a good idea?

Absolutely not. Not only does it make you look unprofessional to honest, upstanding clients, but I feel that it's also detrimental to the profession as a whole. Software engineers do have a responsibilities to their client or employer, including delivering software that is of the highest quality. Should there be a dispute over payment or contracts, there are appropriate channels. Reducing the quality of your software is not an appropriate channel.

Have you guys ever had to hack your own software, because of similar issues with the client(s)?

Never, although I have never done contract or freelance work. I've always been an employee of a larger organization (which, in some cases, was working under a contract). To me, the thought is unthinkable. I would rather deliver software that I'm proud to have my name attributed to and get cheated by a small percentage of customers than reduce the quality of my software as well as my ethical responsibilities to the users of the system.

Any recommendations on this idea, code and method wise?

Don't do it.

What may be the possible drawbacks or repercussions of selfdestruct-scripts?

Besides the obvious ethical issues, I'd be worried about legal problems. I'm not sure if sabotaging your own work is legal, and even if it is, using such an exploit might not be.


答: We upgrade production databases adding tables and (nullable) columns with no problems. Previous versions of the application work fine with the upgraded database, they just don't reference the new stuff. We avoid removing tables or columns, or changing how existing data is stored, though when this is necessary we produce appropiate conversion scripts. Whether your database has a declared type safe schema or not, changes in data structure require data conversion and application upgrades to interact with the new structure.</p>


答:
I'm not a lawyer. It sounds like you already have one for the purposes of suing your client; while you have him or her on retainer I would recommend getting their advice on this.

There are some other questions on this site that deal with "kill switches" and other ways to disable software for which the developer has not received compensation. It is usually considered a bad idea to simply build one in to "turnkey" software (where you will develop it and then transfer full rights to the client), without the contract having stipulated this possibility.

First off, if your contract does not specifically state that you can disable the software for non-payment, or that the client does not have any rights to the software until payment is received in full, then you cannot flip any "kill switch" without being in breach of contract. Absent any words to the contrary, "possession is nine-tenths of the law", so it's his software once he is given possession, and to destroy it would be akin to dynamiting a new office building you'd built for him if he didn't pay for it.

The second point follows; any contract you offer to any client should have a clause to the effect of: "Intellectual property transfers on satisfaction of contract". That means that even if you have given him a copy of the software to use, until he's paid you in full, he doesn't own it. This WOULD give you the right to disable his or any copy of the software for any reason until full payment has been received, because it's still yours and you can do as you please. Now, he's breached the contract, and you haven't, so the case is MUCH easier for your lawyer to present, and meanwhile your client doesn't get any benefit from his ill-gotten goods.

The analogy to a building contractor holds: once a building under construction is able to be secured against unlawful entry, it is, and the contractor will generally keep all copies of all keys to the premises until the work is complete and signed off on, and payment received in full. Even after the keys are handed over, if payment falls through he can attach a lien on the property and in the extreme have it repossessed. The same holds true here; you may give the client a key to get into the software, but you hold the "master" key, and he doesn't get administrative access until you're paid in full. If he can get in now, and doesn't pay you, you can just "change the locks" and lock him out of the software.

However, you have given your client the "master" key to the software, and he's gone and changed all the locks so now YOU can't get in. That's not the way it should work. You can still claim damages, but in the meantime your crooked client can use the software, copy it elsewhere (that's a big thing that can't happen to a contractor; if he takes his building back he doesn't have to worry that you've made an exact free copy on another lot), etc etc. Basically, your only remedy is to enforce payment in full, because you cannot guarantee that you have reclaimed all copies of the software. You probably wouldn't be happy getting your software back even if you could guarantee he had no further copies; it's likely custom work you can't just turn around and sell to someone else.

Understand that regardless of your rights to the software, his data belongs to him. You cannot touch it. You can stop his access to the software that you built, but if you destroy his data, that's like burning his possessions after repoing the building you built him that he didn't pay for. You have no right whatsoever to that data, and must either leave it in place on his computer intact, or if the data cannot be accessed in a reasonable manner without your software, you must remove it from the entanglement with your software and give it to him in a useable format (such as a human-consumable database, or printed or electronic copies).