问:
Paranoid Encryption
Call me paranoid, but I really like to keep my stuff secret, but readily available on the cloud. So, asking this question.

How safe and reliable is encryption software (e.g., truecrypt)? The reason I ask is that, what is I encrypt my data today with this software and after a couple of years, the software is gone ! What happens to my encrypted data?

Is it equally safe to AES encrypt using 7-zip? Will it provide the same level or equivalent level of encryption as truecrypt or other encryption software? (I agree truecrypt will be better because of the container encryption it gives.) And what happens if 7-zip shuts down after 5 years?

I am sorry if I am sounding paranoid, but I am coming back to my original question... Is there any application/software independent encryption? Meaning, can I encrypt with one software and decrypt with another so that I will not be dependent on just one vendor? I want my encryption to depend ONLY on the password and NOT on the encryption program/software?

The next question, can I write my own program that does AES/stronger encryption when I give it a passphrase, so that I don't need to depend on third party software for encryption? If yes, which language supports the same?

Can someone give me a heads up as to where to look for in case of writing my own encryption program?

答:
Don't write your own encryption program.  You will do something wrong.

Media persistence like you talk about is a real problem.  There are tons of old records stored on reel-to-reel tapes and not much equipment left to read it.  You as the data owner will have to make sure you're moving to newer technologies as appropriate.

That said, 7zip is open-source.  You can grab the source, build it yourself, and save that compiled binary.  If 7zip shuts down in 5 years, you still have your copy of the binary -- the same one you used to do the encryption.  Use it to do the decryption.

If you're going to be storing data for long periods, I'd also suggest including some kind of PAR2 recovery data alongside the encrypted container, to repair the container against literal bit rot.

Title: Paranoid Encryption


问:
Why are people so strongly opposed to #region tags in methods?
I hear a lot about keeping methods short and I've heard a lot of programmers say that using #region tags within a method is a sure sign that it is too long and should be refactored into multiple methods. However, it seems to me that there are many cases where separating code with #region tags within a method is the superior solution to refactoring into multiple methods.

Suppose we have a method whose computation can be separated into three rather distinct phases.  Furthermore, each of these stages is only relevant to the computation for this method, and so extracting them into new methods gains us no code reuse. What, then, are the benefits of extracting each phase into it's own method? As far as I can tell, all we gain is some readability and a separate variable scope for each phase (which will help prevent modifications of a particular phase from accidentally breaking another phase).

However, both of these can be achieved without extracting each phase into its own method. Region tags allow us to collapse the code into a form which is just as readable (with the added benefit that we no longer have to leave our place in this file should we decide to expand and examine the code), and simply wrapping each phase in {} creates its own scope to work with.

The benefit to doing it this way is that we don't pollute the class level scope with three methods which are actually only relevant to the inner workings of a fourth method. Immediately refactoring a long method into a series of short methods seems to me to be the code-reuse equivalent to premature optimization; you are introducing extra complexity in order to address a problem which in many cases never arises. You can always extract one of the phases into its own method later should the opportunity for code reuse arise.

Thoughts?

答:
All you should ever care about is for your code to be usable, not reusable. A monkey can transform usable code to reusable code, if there are any transformations to be done at all.

The argument "I need this only here" is poor, to put it politely. The technique you're describing is often referred to as the headlines technique and is generally frowned upon.

You can't test regions, but you can test true methods in isolation.

Regions are comments, not syntactic elements. In the worst case the nesting of your regions and your blocks contradict each other. You should always strive to represent the semantics of your structure with the syntactic elements of the language you are using.

After refactoring to methods, one no longer needs folding to read the text. One might be looking at source code in any tool that doesn't have folding, like a terminal, a mail client, a web-view for your VCS or a diff-viewer.

After refactoring to methods, the resulting method is at least as good as with regions, plus it is simpler to move the individual parts around.

The Single Responsibility Principle suggests that any unit should have one task and one task only. The task of the "main" method is to compose the "helper" methods to get the desired result. The "helper" methods solve a discrete, simple problem in isolation. The class containing all these methods should also only fulfill one task and only contain the methods related to that task. So the helper methods either belong into the class scope, or the code shouldn't be in the class in the first place, but at least in some global method or, better yet, should be injected.

Also relevant: Jeff Atwoods's thoughts on code folding

ContentLicense: CC BY-SA 3.0


问:
Can I use my username in a legal license?
I have an open source project, but I don't want to use my real name in the license file.  Legally, can I just use my project hosting username instead?

I know programmers Are Not Lawyers™, but I'm looking for advice from people who may have dealt with simlar problems.

答: You don't need to put any name in there at all. The license should apply to contributions from other people too anyway, so it shouldn't just be a grant from you. It should be worded as a grant from the individual authors of the various elements.</p>


问:
How to quickly search through a very large list of strings / records on a database
I have the following problem: I have a database containing more than 2 million records.
Each record has a string field X and I want to display a list of records for which field X contains a certain string. Each record is about 500 bytes in size.

To make it more concrete: in the GUI of my application I have a text field where I can enter a string. Above the text field I have a table displaying the (first N, e.g. 100) records that match the string in the text field. When I type or delete one character in the text field, the table content must be updated on the fly.

I wonder if there is an efficient way of doing this using appropriate index structures and / or caching. As explained above, I only want to display the first N items that match the query. Therefore, for N small enough, it should not be a big issue loading the matching items from the database. Besides, caching items in main memory can make retrieval faster.

I think the main problem is how to find the matching items quickly, given the pattern string. Can I rely on some DBMS facilities, or do I have to build some in-memory index myself? Any ideas?

EDIT

I have run a first experiment. I have split the records into different text files (at most 200 records per file) and put the files in different directories (I used the content of one data field to determine the directory tree). I end up with about 50000 files in about 40000 directories. I have then run Lucene to index the files. Searching for a string with the Lucene demo program is pretty fast. Splitting and indexing took a few minutes: this is totally acceptable for me because it is a static data set that I want to query.

The next step is to integrate Lucene in the main program and use the hits returned by Lucene to load the relevant records into main memory.

答: Have you considered a trie?  Basically you build a tree using common prefixes, so all words that start with the same letters are children of the same node.  If you're going to support matching on any substring, then you'll have to generate some sort of permuted index and build your trie from that.  That may wind up blowing your storage requirements way out, though.</p>


问:
What options are there if an SVN repository becomes unavailable?
A project I'm working on was hosted on a svn repository at bettercodes.org. This was under another user's name and that repository is now unavailable.

The person responsible for the project was sent an export from Eclipse and I had a more or less up-to-date project on my machine. I could see no other option than to commit my copy of the project to another repository. It is now possible that some of the most recent changes by another programmer are missing.

Now, what options do I have to bring this project together? Is some of the necessary metadata saved on Eclipse or are all the changes on the original repository? What tools could I use to check what is missing in terms of classes, config files and code?

答:
One option is to ask the community around the project.

If anyone worked via git svn or hgsubversion then you could use their repository (with all of its local history) to create a new svn repository with complete history.

Given the way that these tools maintain a linear history by using rebase before every push, these repositories should be fairly linear, making them easier to convert back to an svn repository.

There are some pointers on how to do this for git in this stackoverflow answer, and there is information on how to do this for mercurial on its wiki

Alternatively, this might be a good time to move your project to git or hg, where you can get the advantages of hosting on sites like github or bitbucket.


答:
My personal rule is that if a method is longer than one screen, say 40 lines, it is too long. If a class is longer than 500 lines, it is too big. I break these rules sometimes, occasionally even by a large multiple, but I generally regret it within the year.

Even a method that is 20 to 30 lines is getting a bit long in most cases. So I would say using regions in a method is usually a bad idea, simply because it would almost never make sense to collapse a region of 20 to 30 lines into multiple sub-regions.

Breaking down functions that are long by this definition has at least two benefits:

You get to put a name on what those sub-functions are doing, which clarifies your present thinking and simplifies the task of later maintainers.

Decomposing into smaller functions forces you to pass only the parameters those smaller functions need, so the scope of the data they require and modify is very clear. This assumes you aren't accessing and modifying object state in a hundred different leaf functions, which I would also discourage.

In my experience, these rules produce code that is easier to write without making common mistakes and can be understood and modified later without breaking subtle behaviors. It doesn't matter if the person who has to understand/modify the code is someone else, or myself after I have slept and forgotten everything.

So I would consider regions in methods to be a "code smell" indicating that unsustainable practices are being applied. As always, there could be exceptions, but they occur so infrequently that they almost aren't worth discussing.

Title: Why are people so strongly opposed to #region tags in methods?

Body:
I hear a lot about keeping methods short and I've heard a lot of programmers say that using #region tags within a method is a sure sign that it is too long and should be refactored into multiple methods. However, it seems to me that there are many cases where separating code with #region tags within a method is the superior solution to refactoring into multiple methods.

Suppose we have a method whose computation can be separated into three rather distinct phases.  Furthermore, each of these stages is only relevant to the computation for this method, and so extracting them into new methods gains us no code reuse. What, then, are the benefits of extracting each phase into it's own method? As far as I can tell, all we gain is some readability and a separate variable scope for each phase (which will help prevent modifications of a particular phase from accidentally breaking another phase).

However, both of these can be achieved without extracting each phase into its own method. Region tags allow us to collapse the code into a form which is just as readable (with the added benefit that we no longer have to leave our place in this file should we decide to expand and examine the code), and simply wrapping each phase in {} creates its own scope to work with.

The benefit to doing it this way is that we don't pollute the class level scope with three methods which are actually only relevant to the inner workings of a fourth method. Immediately refactoring a long method into a series of short methods seems to me to be the code-reuse equivalent to premature optimization; you are introducing extra complexity in order to address a problem which in many cases never arises. You can always extract one of the phases into its own method later should the opportunity for code reuse arise.

Thoughts?


问:
How to protect source code from remote developers?
My company is going to hire an external developer to create some new modules and fix some bugs in our PHP software.

We have never hired an external developer by the hour before. How can we protect the source code? We are not comfortable giving out source code and were thinking that everything remained under a surveillance enabled VPN which external developer would log in to.

Has anyone solved this problem before? If so, how?

Edit: We want the developer to see/modify the code but under surveillance and on our machine remotely. Does anybody have a similar setup?

Edit 2: NDA is just a formality. IMO, even people who are in favor of NDAs know that it'll do nothing to protect their property.

Edit 3: Let me clarify that we aren't worried about the developer copying an algorithm or a solution from the code. Code is coming out of his brain, so naturally he is the creator and he can create that again. But our code is built over several years with tens of developers working on it. Let's say I hire an incompetent programmer by mistake, who steals our years of work and then sells it to the competitor. That can make us lose our cutting edge. I know this is rare, but such a threat has to be taken under consideration if you're in business. I'll make points of my comments so its easy for everyone to communicate:

Why NDA sucks? Take this scenario, if anyone is capable of suggesting a solution to this scenario I will consider the NDA effective. Ok, here goes:
We hire 2 external developers, one of them sells our code as it is to someone else after a year. You are no longer in touch with any of the developers, how are you supposed to find out who ripped you off? NDA does provide a purpose, but you can't rely completely on that. At least we cannot.

I did not meant to offend anyone while I was posting this question, even though unintentionally I did. But again to people answering/commenting like 'I will never ever work with you' or that Men-in-black-gadget thingy: It's not about you, it's a thread about how feasible a given technical solution would be. And if anyone in this community has worked under such an environment.

About 'Trust', of course we won't hire anyone we do not trust. But is that it? Can't someone be deceitful at first? We all trusted a lot of politicians to run our country, did they not fail us ever? So, I'm saying 'trust' is a complete other layer of protection like NDA, and my question was not directed to it. My question is rather directed towards technical measures we can take to avoid such a thing from happening.

答:
The best way to ensure you get a poor developer is to treat him like a criminal with his every move monitored through some surveillance system. No one competent would put up with that for even a couple of seconds.

Do not hire people you can't trust for any postion.


答:
Pseudonyms are accepted for copyright registration, but it's not implicit, you will have to register your work at copyright.gov.

They will ensure that the link is made between you, the real person, and the pseudonym you use. Otherwise, you will have more difficulties to prove you are the original author.

More information about software copyrighting can be obtained in this PDF.

Title: Can I use my username in a legal license?

Body:
I have an open source project, but I don't want to use my real name in the license file.  Legally, can I just use my project hosting username instead?

I know programmers Are Not Lawyers™, but I'm looking for advice from people who may have dealt with simlar problems.


答: Probably 90% of the value in source code is the development team, support team, and user community you build around it. Unless this is some kind of super-secret game-changing start-up, the source code is essentially worthless to a third party. Even Microsoft released Windows NT code under NDAs at one point to certain people outside Microsoft. My advice is to require an NDA and be prepared to defend it with litigation in the extremely unlikely event that your IP is used somehow without your permission.</p>

Title: How to protect source code from remote developers?

Body:
My company is going to hire an external developer to create some new modules and fix some bugs in our PHP software.

We have never hired an external developer by the hour before. How can we protect the source code? We are not comfortable giving out source code and were thinking that everything remained under a surveillance enabled VPN which external developer would log in to.

Has anyone solved this problem before? If so, how?

Edit: We want the developer to see/modify the code but under surveillance and on our machine remotely. Does anybody have a similar setup?

Edit 2: NDA is just a formality. IMO, even people who are in favor of NDAs know that it'll do nothing to protect their property.

Edit 3: Let me clarify that we aren't worried about the developer copying an algorithm or a solution from the code. Code is coming out of his brain, so naturally he is the creator and he can create that again. But our code is built over several years with tens of developers working on it. Let's say I hire an incompetent programmer by mistake, who steals our years of work and then sells it to the competitor. That can make us lose our cutting edge. I know this is rare, but such a threat has to be taken under consideration if you're in business. I'll make points of my comments so its easy for everyone to communicate:

Why NDA sucks? Take this scenario, if anyone is capable of suggesting a solution to this scenario I will consider the NDA effective. Ok, here goes:
We hire 2 external developers, one of them sells our code as it is to someone else after a year. You are no longer in touch with any of the developers, how are you supposed to find out who ripped you off? NDA does provide a purpose, but you can't rely completely on that. At least we cannot.

I did not meant to offend anyone while I was posting this question, even though unintentionally I did. But again to people answering/commenting like 'I will never ever work with you' or that Men-in-black-gadget thingy: It's not about you, it's a thread about how feasible a given technical solution would be. And if anyone in this community has worked under such an environment.

About 'Trust', of course we won't hire anyone we do not trust. But is that it? Can't someone be deceitful at first? We all trusted a lot of politicians to run our country, did they not fail us ever? So, I'm saying 'trust' is a complete other layer of protection like NDA, and my question was not directed to it. My question is rather directed towards technical measures we can take to avoid such a thing from happening.


答:
If your method is complex enough that it can be separated into three distinct phases, then not only should those be three separate methods...but your method should in fact be a separate class, dedicated to that computation.

"But then my class will have only one public method!"

You're right, and there's nothing wrong with that.  The idea of the single responsibility principle is that your class does one thing.

Your class can call each of the three methods in turn, and return the result.  One thing.

As a bonus, now your method is testable because it's not a private method anymore.

But never mind one class; in reality you should have four: One for each of the pieces of your method, plus one that takes each of the three as a dependency and calls them in the proper order, returning the result.

This makes your classes even more testable.  It also makes it easy for you to change one of those three pieces.  Just write a new class inheriting from the old one, and override the changed behavior.  Or create an interface for the behavior of each of your three pieces; and then to replace one, just write a new class implementing that interface and substitute it for the old one in your dependency injection container configuration.

What?  You're not using dependency injection?  Well, you probably haven't seen the need yet, because you're not following the single responsibility principle.  Once you start, you'll find that the easiest way to give each class its dependencies is to use a DI container.

EDIT:

OK, let's set aside the refactoring question.  The purpose of #region is to hide code, which mainly means code that doesn't need to be edited under any normal circumstances.  Generated code is the best example.  It should be hidden in regions because ordinarily you don't need to edit it.  If you do need to, then the act of expanding a region gives you a bit of "Here be dragons"-style warning to make sure you know what you're doing.

Therefore I would say #region should not be used in the middle of a method.  If I open a method, I want to see the code.  Using #region gives me another level of hiding that I don't need, and that becomes an annoyance: I unfold the method...and still can't see any code.

If you're worried about people seeing the structure of the method (and you refuse to refactor it), then add banner comments like this:

```<code>//
// ---------- COMPUTE SOMETHING OR OTHER ----------
//
</code>```

These will help someone browsing the code see the individual parts of your method without having to deal with expanding and collapsing #region tags.

Body:
If your method is complex enough that it can be separated into three distinct phases, then not only should those be three separate methods...but your method should in fact be a separate class, dedicated to that computation.

"But then my class will have only one public method!"

You're right, and there's nothing wrong with that.  The idea of the single responsibility principle is that your class does one thing.

Your class can call each of the three methods in turn, and return the result.  One thing.

As a bonus, now your method is testable because it's not a private method anymore.

But never mind one class; in reality you should have four: One for each of the pieces of your method, plus one that takes each of the three as a dependency and calls them in the proper order, returning the result.

This makes your classes even more testable.  It also makes it easy for you to change one of those three pieces.  Just write a new class inheriting from the old one, and override the changed behavior.  Or create an interface for the behavior of each of your three pieces; and then to replace one, just write a new class implementing that interface and substitute it for the old one in your dependency injection container configuration.

What?  You're not using dependency injection?  Well, you probably haven't seen the need yet, because you're not following the single responsibility principle.  Once you start, you'll find that the easiest way to give each class its dependencies is to use a DI container.

EDIT:

OK, let's set aside the refactoring question.  The purpose of #region is to hide code, which mainly means code that doesn't need to be edited under any normal circumstances.  Generated code is the best example.  It should be hidden in regions because ordinarily you don't need to edit it.  If you do need to, then the act of expanding a region gives you a bit of "Here be dragons"-style warning to make sure you know what you're doing.

Therefore I would say #region should not be used in the middle of a method.  If I open a method, I want to see the code.  Using #region gives me another level of hiding that I don't need, and that becomes an annoyance: I unfold the method...and still can't see any code.

If you're worried about people seeing the structure of the method (and you refuse to refactor it), then add banner comments like this:

//
// ---------- COMPUTE SOMETHING OR OTHER ----------
//

These will help someone browsing the code see the individual parts of your method without having to deal with expanding and collapsing #region tags.


答: Why not give the contractor a company laptop that can only connect to your VPN?  Then put a firewall on the VPN that blocks of any email/bastebin type sites, install a keylogger on the machine, and fill the USB slots with krazy glue.</p>


问:
Why scalability issues cannot be solved by more servers ?
I know that big websites suffer from scalability issues and I guess that more servers (hardware) can help to handle scalabililty issues but I see that big websites are stuck about scalability even if they can handle the cost of new servers.

So why can big companies not handle scalability issues by more servers?

答:
Scalability is best explained as:

The ability to increase performance by adding hardware

So adding hardware doesn't "increase scalability".

Many problems are embarrassingly parallel, (like ray tracing), where many tasks can be undertaken at the same time without requiring synchronization or communication between workers, but this is not the norm.

Large websites tend to have content that is always changing and it is this property that makes systems difficult to scale. Where ever there is communication or synchronization, there is the potential for a bottleneck.

The state of a website is typically stored in a database and so this is where the main bottleneck of many websites lays. A database must remain consistent and available to be useful and this is very difficult to ensure (volumes could be written on this subject).

It boils down to, adding hardware to a problem may increase your ability to compute stuff, but planning the data flow so that adding hardware actually speeds up the job that you are performing, while at the same time having a contingency plan for hardware failure, is extremely difficult.


问:
How to you "sell" support as an career option
We find it relatively easy to hire developers to work on various projects.

The problem arises when the project is finished but still needs to be supported.

We really battle to get people to join the support team. It's seen as dead-end, career-limiting, boring, second-class etc.

Currently, we get round this by getting the project team to assign some of their team to the support team for a while. Part of the assignment is to do a "brain dump" of the project so that the support team understands it. This works as long as the assignment is only for a fixed period.

Trying to hire people to work in support full-time is a problem. There are few applications and the calibre is not particularly high.

(The financial reality though is that support can be very lucrative for a company and once you get a reputation, you get approached by other companies to do their support even though you weren't involved in the original development.)

答:
While I agree that being in support generally does suck, many developers might actually enjoy the prestige that goes along with the "ownership" of the project, even if they did not write the software themselves. That programmer becomes the goto on that project, and they really do become an invaluable expert on the system. While I am primarily involved in new development at the company I work for, many of my colleagues who are more than competent actually are quite respected for their maintenance of our most mission critical software. After all, the software currently being supported is probably the one currently making money (a bird in hand is worth two in the bush).

  I would just say that not everyone sees support as a terrible dungeon job for sub-par programmers, and I would play off that sentiment to attract more people.

ContentLicense: CC BY-SA 2.5


问:
AVL Tree Balancing Problem
Take the following tree:

```<code>          50
        40
      30
    20
  10
</code>```

Which node will be balanced first? 50 or 30

Case 1: 50

The tree is

```<code>             30
          20    40
       10          50
</code>```

Case 2: 30

The tree is

```<code>              40
            /   \
          20     50
       10    30
</code>```

Well, both are AVL Trees, so are both correct?

答:
Your first tree is not an AVL tree. Even minus an element it is not an AVL tree (so we can't even consider it as an AVL tree undergoing balance).

AVL operations are defined on AVL trees to produce a new AVL tree. They are defined in terms of the node that was inserted or deleted.

So, we don't have an AVL tree to start, and we have no information about how we got that tree (was something just inserted or deleted, and if so, what?). In short, I think the question needs to be clarified.

OwnerDisplayName: nbaztec

Title: AVL Tree Balancing Problem


答: It is easier to think about the problem recursively by balancing 30 prior to 50.  Since leaf nodes (with no child nodes) are already balanced, you can balance the tree in a bottom up fashion knowing that all nodes below the current node are balanced trees.</p>

Title: AVL Tree Balancing Problem

Body:
Take the following tree:

```<code>          50
        40
      30
    20
  10
</code>```

Which node will be balanced first? 50 or 30

Case 1: 50

The tree is

```<code>             30
          20    40
       10          50
</code>```

Case 2: 30

The tree is

```<code>              40
            /   \
          20     50
       10    30
</code>```

Well, both are AVL Trees, so are both correct?


答: z5h is right. If you want an AVL tree you have to build it, adding the elements one by one and balancing if necessary.</p>

Title: AVL Tree Balancing Problem

OwnerDisplayName: Kolt


问:
Choosing between two programmers: experience vs. passion
I am in a position where I have to hire a programmer and have the option of 2 candidates, the first has experience but he doesn't have a passion for coding and he says so while the second doesn't have the experience but he has the passion, he did well in the interview and is certified.

We have the resources to train someone, but I really don't want to blow this process and hire someone who will be disappointing. Can anyone help me as to how to approach this situation?

答: IMO depends on why the not-passionate person lost their passion.  Did they have it at all?  Would they rather be doing architecture than fiddling around with APIs and loops?  Have they just been soured on seeing bad code/poor management that it made them just stop caring?  Don't discount someone who says "I'm not passionate about my craft" because there may be valid reasons.  Even the most passionate person will quickly lose their fire when they run into walls every time they try to show passion.  Like the hamster who gets shocked, eventually they'll learn to just tow the party line and the passion gets lost.</p>


问:
Stuff every programmer needs while working
I've been tasked with creating a fun and relaxing environment, one thing I know that I want is ergonomic mice and keyboards, others have suggested exercise balls and bands.

What is it that every programmer needs while working? What might not be necessary but would be nice to have anyway?

Note: this question was asked previously, but has been recommended to be posted here. See this link for the previous responses: https://stackoverflow.com/questions/3911911/stuff-every-programmer-needs-while-working-closed

答: A window manager with multiple workspaces and a terminal-based window manager such as GNU screen.  Multitasking can be very difficult without an organization system.


问:
Translating longer texts (view and email templates) with gettext
I'm developing a multilingual PHP web application, and I've got long(-ish) texts that I need to translate with gettext. These are email templates (usually short, but still several lines) and parts of view templates (longer descriptive blocks of text). These texts would include some simple HTML (things like bold/italic for emphasis, probably a link here or there). The templates are PHP scripts whose output is captured.

The problem is that gettext seems very clumsy for handling longer texts. Longer texts would generally have more changes over time than short texts — I can either change the msgid and make sure to update it in all translations (could be lots of work and very error-prone when the msgid is long), or I can keep the msgid unchanged and modify only the translations (which would leave misleading outdated texts in the templates). Also, I've seen advice against including HTML in gettext strings, but avoiding it would break a single natural piece of text into lots of chunks, which will be an even bigger nightmare to translate and reassemble, and I've also seen advice against unnecessary splitting of gettext strings into separate msgids.

The other approach I see is to ignore gettext altogether for these longer texts, and to separate those blocks in external subtemplates for each locale, and just include the one for the current locale. The disadvantage is that I'm separating the translation effort between gettext .po files and separate templates located in a completely different location.

Since this application will be used as a starting point for other applications in the future, I'm trying to come up with the best approach for the long term. I need some advice for best practices in such scenarios. How have you implemented similar cases? What turned out to work and what turned out a bad idea?

答:
change the msgid and make sure to update it in all translations (could be lots > of work and very error-prone when the msgid is long)

That is something you could easily automate, thus making it less error-prone and also less work.


问:
Should a method comment include both a summary and return description when they're often so similar?
I'm a proponent of properly documented code, and I'm well aware of the possible downsides of it. That is outside of the scope of this question.

I like to follow the rule of adding XML comments for every public member, considering how much I like IntelliSense in Visual Studio.

There is one form of redundancy however, which even an excessive commenter like me is bothered by. As an example take List.Exists().

```<code>/// <summary>
///     Determines whether the List<T> contains elements
///     that match the conditions defined by the specified predicate.
/// </summary>
/// <returns>
///     true if the List<T> contains one or more elements that match the
///     conditions defined by the specified predicate; otherwise, false.
/// </returns>
public bool Exists( Predicate<T> match )
{
    ...
}
</code>```

Summary and returns are basically saying the same thing. I often end up writing the summary more from a returns perspective, dropping the returns documentation altogether.

Returns true when the List contains elements that match the
  conditions defined by the specified predicate, false otherwise.

Additionally, the returns documentation doesn't show up in IntelliSense, so I rather write any immediately relevant information in summary.

Why would you ever need to document returns separately from summary?

Any information on why Microsoft adopted this standard?

答:
I've been torn by the same philosophical question lately and I'm still not sure what a good solution is.  But so far, this has been my approach...

Method documentation only describes what external callers need to know.  It doesn't talk about how this work is done internally, but mentions a) why the caller would want to call this method, b) what would be the expected results of calling the method.  If there's a need to document how the method works, I put that into the code body itself.

If a method has enough complexity to it, then general description and a separate [returns] section seems to be justified.  You don't want the reader to read entire description and attempt to infer how to interpret the return value.

If the method is so simple that the best way to describe what it does is to say something like "This method returns person's address", then I skip the [returns] section as adding would seem to go against the DRY principle and I'm a huge advocate of that.  A lot of one-liner accessor methods seem to fall into this category.


问:
As the team leader/manager, what kind of role should I seek when we switch to Scrum?
My company wants to start using Scrum, and in real scrum there is no place for a real team leader (manager).

What is the next step for the dev team leader? Should I be a (chief) system architect/tech leader  or search for another job in management?

I like the management part and the technical part and the target is VP R&D/CTO.

答:
Just because in the scrum process you may not always take "the lead" you still have hiring, budget and other manager duties.

You going to have a sprint to see if you're going to fire somone?


答: You should start by being the best programmer you can be.  Unless they are totally drinking the cool-aid you will still have those that are stronger leaders.  If you are already leading the team, you may wish to investigate getting trained and assigned to be the Scrum Master.  In this role you will help Shepard the team through the scrum process.  </p>

Title: As the team leader/manager, what kind of role should I seek when we switch to Scrum?

Body:
My company wants to start using Scrum, and in real scrum there is no place for a real team leader (manager).

What is the next step for the dev team leader? Should I be a (chief) system architect/tech leader  or search for another job in management?

I like the management part and the technical part and the target is VP R&D/CTO.


答:
The summary should be as descriptive as might be useful; the descriptions of parameters and return value should be short and sweet. If you have a choice between one word and five, use one. Let's tighten up your example:

true if the List contains one or more elements that match the
  conditions defined by the specified predicate; otherwise, false.

becomes

true if any element of List matches predicate; otherwise false.

Title: Should a method comment include both a summary and return description when they're often so similar?

Body:
I'm a proponent of properly documented code, and I'm well aware of the possible downsides of it. That is outside of the scope of this question.

I like to follow the rule of adding XML comments for every public member, considering how much I like IntelliSense in Visual Studio.

There is one form of redundancy however, which even an excessive commenter like me is bothered by. As an example take List.Exists().

```<code>/// <summary>
///     Determines whether the List<T> contains elements
///     that match the conditions defined by the specified predicate.
/// </summary>
/// <returns>
///     true if the List<T> contains one or more elements that match the
///     conditions defined by the specified predicate; otherwise, false.
/// </returns>
public bool Exists( Predicate<T> match )
{
    ...
}
</code>```

Summary and returns are basically saying the same thing. I often end up writing the summary more from a returns perspective, dropping the returns documentation altogether.

Returns true when the List contains elements that match the
  conditions defined by the specified predicate, false otherwise.

Additionally, the returns documentation doesn't show up in IntelliSense, so I rather write any immediately relevant information in summary.

Why would you ever need to document returns separately from summary?

Any information on why Microsoft adopted this standard?


答:
Best tools for encryption are standards based with the implementation per reviewed. 7 Zip, using AES and being open source meets these needs.

Don't waste anymore energy worrying about the tool you choose if meets those two basic requirements.  For decades the weak point has been the endpoints. No need to break AES, just steal the key,  put a gun to the key holders head if you have to, offer someone who has access a bucket load of money, if it's worth it... it's easier, cheaper and faster than cracking AES.

What you need to concern yourself with is key management and protecting your key. How are you going to stop someone stealing it, and if they do, how are you going to know they have it?   Note that changing the key is hard, as you need to decrypt and re-encrypt all your data. Your backups become useless (unless you keep the old key, which almost defeats changing it).
I suggest some light:) bed time reading - Bruce Schneier - Secrets and Lies would be a good start.

Title: Paranoid Encryption

Body:
Call me paranoid, but I really like to keep my stuff secret, but readily available on the cloud. So, asking this question.

How safe and reliable is encryption software (e.g., truecrypt)? The reason I ask is that, what is I encrypt my data today with this software and after a couple of years, the software is gone ! What happens to my encrypted data?

Is it equally safe to AES encrypt using 7-zip? Will it provide the same level or equivalent level of encryption as truecrypt or other encryption software? (I agree truecrypt will be better because of the container encryption it gives.) And what happens if 7-zip shuts down after 5 years?

I am sorry if I am sounding paranoid, but I am coming back to my original question... Is there any application/software independent encryption? Meaning, can I encrypt with one software and decrypt with another so that I will not be dependent on just one vendor? I want my encryption to depend ONLY on the password and NOT on the encryption program/software?

The next question, can I write my own program that does AES/stronger encryption when I give it a passphrase, so that I don't need to depend on third party software for encryption? If yes, which language supports the same?

Can someone give me a heads up as to where to look for in case of writing my own encryption program?


问:
Quit my job (for a new job). Old job wants me to be available for contracting. Steps to take?
The company I am leaving has asked that I make myself available to answer questions and/or debug programs occasionally should the need arise. I'm not opposed to this. After searching google for some kind of standard contract for this sort of thing, I didn't see any.

Is there a standard contract for this sort of thing that you use?

Are there any other steps I should take to ensure this kind of arrangement works smoothly?

答:
I have done this and in my case my former employer set me up as a "Casual Employee" basically hourly on demand.  They paid my Social Security tax etc. and I just fill out a timesheet when I do work for them.  I have a computer from them and do most of my work remotely when it's needed.  I actually live almost 2000 miles away now.

Go for it.


问:
Best Practices for Handing over Legacy Code
In a couple of months a colleague will be moving on to a new project and I will be inheriting one of his projects. To prepare, I have already ordered Michael Feathers' Working Effectively with Legacy Code.

But this books as well as most questions on legacy code I found so far are concerned with the case of inheriting code as-is. But in this case I actually have access to the original developer and we do have some time for an orderly hand-over.

Some background on the piece of code I will be inheriting:

It's functioning: There are no known bugs, but as performance requirements keep going up, some optimizations will become necessary in the not too distant future.

Undocumented: There is pretty much zero documentation at the method and class level. What the code is supposed to do at a higher level, though, is well-understood, because I have been writing against its API (as a black-box) for years.

Only higher-level integration tests: There are only integration tests testing proper interaction with other components via the API (again, black-box).

Very low-level, optimized for speed: Because this code is central to an entire system of applications, a lot of it has been optimized several times over the years and is extremely low-level (one part has its own memory manager for certain structs/records).

Concurrent and lock-free: While I am very familiar with concurrent and lock-free programming and have actually contributed a few pieces to this code, this adds another layer of complexity.

Large codebase: This particular project is more than ten thousand lines of code, so there is no way I will be able to have everything explained to me.

Written in Delphi: I'm just going to put this out there, although I don't believe the language to be germane to the question, as I believe this type of problem to be language-agnostic.

I was wondering how the time until his departure would best be spent. Here are a couple of ideas:

Get everything to build on my machine: Even though everything should be checked into source code control, who hasn't forgotten to check in a file once in a while, so this should probably be the first order of business.

More tests: While I would like more class-level unit tests so that when I will be making changes, any bugs I introduce can be caught early on, the code as it is now is not testable (huge classes, long methods, too many mutual dependencies).

What to document: I think for starters it would be best to focus documentation on those areas in the code that would otherwise be difficult to understand e.g. because of their low-level/highly optimized nature. I am afraid there are a couple of things in there that might look ugly and in need of refactoring/rewriting, but are actually optimizations that have been out in there for a good reason that I might miss (cf. Joel Spolsky, Things You Should Never Do, Part I)

How to document: I think some class diagrams of the architecture and sequence diagrams of critical functions accompanied by some prose would be best.

Who to document: I was wondering what would be better, to have him write the documentation or have him explain it to me, so I can write the documentation. I am afraid, that things that are obvious to him but not me would otherwise not be covered properly.

Refactoring using pair-programming: This might not be possible to do due to time constraints, but maybe I could refactor some of his code to make it more maintainable while he was still around to provide input on why things are the way they are.

Please comment on and add to this. Since there isn't enough time to do all of this, I am particularly interested in how you would prioritize.

Update: As the hand-over project is over I have expanded this list with my own experiences in this answer below.

答:
Having been in a similar situation, I believe the following would also be worth consideration:

Make sure you can make, and test, a deployment: Do your own deployment of the product, from scratch - and verify that this is identical to one done by the person who's leaving. This would make sure that any scripts and instructions are clear to you, and would catch any accidental oversights such as ingredients not having been checked in to your version control system. (I'm not saying that this would happen, just that if it has happened, it will be a lot easier to deal with now, before the person leaves)

(This may not be relevant for you, e.g. if you already do Continuous Integration or Continuous Deployment, but it's worth mentioning, just in case...)

Writing more tests: This is a really good way to test your understanding of a system. It will enable (or force) you to look more closely at areas of the code, and will either confirm that the code is as bug-free as you suspect, or will reveal areas where you thought you understood the intention, but that actually you need to ask your colleague for clarification before he leaves

Pair-writing of documentation: This is an effective way to write overviews. I'm suggesting that you get your colleague to describe a feature or area, and then you write it up, in documentation, in your own words. We found this was massively easier when done by two people together.

I'd put the writing of tests as a higher priority than writing of documentation, personally, as the tests will probably give you more - or firmer - understanding.

Regarding Refactoring using pair-programming, the only thing I'd say is that there's a danger that this can become a bottom-less pit, especially given that you said you've only got high-level tests. You might find it ends up using way more of the available time than you'd intended.

OwnerDisplayName: PersonalNexus


答: Every scrum needs a scrum master, I'm sure that could be a part of your role.  What do you do as team leader?  As a former development team leader on a project with scrum, I did coding, mentoring, and help guide the team through technical challenges as well as being the scrum master/technical project manager.  I do the coding, mentoring, and technical challenges anyway, so not much difference.  I don't see scrum affecting your role unless as a development team leader you are just managing.</p>


问:
Notation used in 'Pearls of Functional Algorithm Design'
I just purchased the book 'Pearls of Functional Algorithm Design' by Richard Bird.  Unfortunately, the book doesn't have any section that describes the notation that is used.

You can view the contents of the book by going to Amazon's page, and clicking on the book cover to get a sneak peak inside.

http://www.amazon.com/Pearls-Functional-Algorithm-Design-Richard/dp/0521513383

If someone could give me a name, and/or reference to understand the notation used.  That way I could actually read and understand the algorithms.

答:
He mentions in the preface that the reference programs are in Haskell. The formatting is LaTeX so it looks a bit odd.

I did some more digging and it turns out that the Mathematical notation used is called "Z Notation" after the Zermelo–Fraenkel set theory notation. Here is a guide, PDF is the second link in the list. The notation is part of a broader type of notation called Pidgin Code:

In computer programming, pidgin code is a mixture of several
programming languages in the same program, or pseudocode that is a
mixture of a programming language with natural language descriptions.
Hence the name: the mixture is a programming language analogous to a
pidgin in natural languages.

In numerical computation, mathematical
style pseudocode is sometimes called pidgin code, for example pidgin
ALGOL (the origin of the concept), pidgin Fortran, pidgin BASIC,
pidgin Pascal, and pidgin C. It is a compact and often informal
notation that blends syntax taken from a conventional programming
language with mathematical notation, typically using set theory and
matrix operations, and perhaps also natural language descriptions.

It can be understood by a wide range of mathematically trained people,
and is used as a way to describe algorithms where the control
structure is made explicit at a rather high level of detail, while
some data structures are still left at an abstract level, independent
of any specific programming language.

Normally non-ASCII typesetting
is used for the mathematical equations, for example by means of TeX or
MathML markup, or proprietary Formula editor formats.


问:
How should I handle the publishing of an iPhone app under someone else's name?
I've agreed to build an iPhone app for a client that was referred to me. I'm a full-time software engineer by day, but this is only my 2nd iPhone app and I agreed to do it without upfront funding as it would give me a project to further learn the API as well as increase my portfolio of iPhone apps.

The client suggested as payment, that we split the profits 50/50. Normally I would not think this was fair but in a situation like this, I was ok with it since my family's life does not depend on it.

As we are nearing the end of development on the app, I asked the client if they would prefer their personal name be put on the project, or if they minded that it was my name (since I have the developer license). Naturally, they requested their name. I've not told them all that that entails because I would relinquish management of the app and profit divisions to them.

My question to this community, and pardon if this is not the proper place, is am I going about this the right way?

Should I request a partnership be setup?

Should I insist my developer name goes on it? What would you do?

Additionally, I'm going off of his word that this is a niche product with high demand (its in the medical field) so we will be able to charge a bit more for it.

答:
If you think there might be a decent possibility of significant revenue, do a contract, incorporate with both of you as shareholders, and put the app under a company account.

If not, does it really matter whose account?  (consider admin work, bank fees, tax reporting, branding, who will do the marketing, the extra $99/annum, & etc.)

OwnerDisplayName: Kyle Hayes


答:
I highly recommend asking your company to reconsider making the product owner and scrum master the same person.  While it's possible with a disciplined person, the two roles really have a conflict of interest.  Product owners advocate for the customer, scrum masters advocate for the team, and the balance usually works out much better than anticipated.  Team lead-type people generally fall into the scrum master role very well.

Also keep in mind that in contrast to something like extreme programming, scrum has very little to do with software.  You can get scrum training and never even talk about software.  While it affects what order you do things in, things like software quality, design, and such really fall outside its purview, and there's still a lot of room for leadership in those areas, even if not formally acknowledged.


问:
Why are people so strongly opposed to #region tags in methods?
I hear a lot about keeping methods short and I've heard a lot of programmers say that using #region tags within a method is a sure sign that it is too long and should be refactored into multiple methods. However, it seems to me that there are many cases where separating code with #region tags within a method is the superior solution to refactoring into multiple methods.

Suppose we have a method whose computation can be separated into three rather distinct phases.  Furthermore, each of these stages is only relevant to the computation for this method, and so extracting them into new methods gains us no code reuse. What, then, are the benefits of extracting each phase into it's own method? As far as I can tell, all we gain is some readability and a separate variable scope for each phase (which will help prevent modifications of a particular phase from accidentally breaking another phase).

However, both of these can be achieved without extracting each phase into its own method. Region tags allow us to collapse the code into a form which is just as readable (with the added benefit that we no longer have to leave our place in this file should we decide to expand and examine the code), and simply wrapping each phase in {} creates its own scope to work with.

The benefit to doing it this way is that we don't pollute the class level scope with three methods which are actually only relevant to the inner workings of a fourth method. Immediately refactoring a long method into a series of short methods seems to me to be the code-reuse equivalent to premature optimization; you are introducing extra complexity in order to address a problem which in many cases never arises. You can always extract one of the phases into its own method later should the opportunity for code reuse arise.

Thoughts?

答:
It's not the regions in the methods that are the problem, but the case when there's a need (or even a use) to put regions in methods.

Having had to debug plenty of 200-300 line methods, I can tell you that I wouldn't wish it on anyone. If you're writing and looking after your own code that's fine - do whatever you want. But once someone else looks at it, it should be immediately clear what a method is doing.

"First it gets the things, and then it jigs them around, then if they need buzzing it does that, otherwise it checks whether they are blue and inverts their Copernicus value. Then, if the second thing is greater than the first thing, we need to get the juice box and insert it... "

No, that is not good enough. Break it up into regions all you want but I'm still shaking my head just thinking about it.

If you break into methods you get many benefits:

Clearer understanding of what's happening where, even if just through the name of the method. And you are wrong that a method can't be fully documented - add the documentation block (hit ///) and enter the description, parameters, return type, and also exception, example, remarks nodes to detail those scenarios. That's where it goes, that's what it's for!

There are no side effects or scoping problems. You may say that you declare all your variables in a sub-scope with {}, but do I have to check every method to make sure you didn't 'cheat'? Is this dodgyObject I'm using here only because used in this region, or did it come from somewhere else? If I were in my own method I'd be easily able to see whether it was passed to me or whether I created it myself (or rather, whether you created it).

My event log tells me which method an exception occurred in. Yes, I may be able to find the offending code with a line number, but knowing the method name (especially if I've named them properly) gives me a very good indication of what happened and what went wrong. "Oh, the TurnThingsUpsideDown method failed - it's probably failing while turning a bad thing" is a lot better than "Oh, the DoEverything method failed - it could have been 50 different things and I'll have to dig around for an hour to find it".

This is all before any reusability or improvability concerns. Properly separated methods obviously facilitate reuse, and also allow you to easily replace a method that's not performing (too slow, too buggy, changed dependency etc). Have you ever tried refactoring any of these huge methods? There's no way to know that what you're changing won't effect anything else.

Please properly encapsulate your logic into reasonably sized methods. I know that it's easy for them to get out of hand, and arguing that it's not worth redesigning once at that point is another issue. But you must accept the fact that there is no harm and at least potential benefit in having properly encapsulated, cleanly written and simply designed methods.


问:
what is the purpose of arrows?
I am learning functionnal programming with Haskell, and I try to grab concepts by first understanding why do I need them.

I would like to know the goal of arrows in functional programming languages. What problem do they solve? I checked http://en.wikibooks.org/wiki/Haskell/Understanding_arrows and http://www.cse.chalmers.se/~rjmh/afp-arrows.pdf. All I understand is that they are used to describe graphs for computations, and that they allow easier point free style coding.

The article assume that point free style is generally easier to understand and to write. This seems quite subjective to me. In another article (http://en.wikibooks.org/wiki/Haskell/StephensArrowTutorial#Hangman:_Main_program), a hangman game is implemented, but I cannot see how arrows makes this implementation natural.

I could find a lot of papers describing the concept, but nothing about the motivation.

What I am missing?

答:
I realize I'm coming late to the party, but you've had two theoretical answers here, and I wanted to provide a practical alternative to chew over. I'm coming at this as a relative Haskell noob who nonetheless has been recently force-marched through the subject of Arrows for a project I'm currently working on.

First, you can productively solve most problems in Haskell without reaching for Arrows. Some notable Haskellers genuinely do not like and do not use them (see here, here, and here for more on this). So if you're saying to yourself "Hey, I don't need these," understand that you may genuinely be correct.

What I found most frustrating about Arrows when I first learned them was how the tutorials on the subject inevitably reached for the analogy of circuitry. If you look at Arrow code -- the sugared variety, at least -- it resembles nothing so much as a Hardware Defnition Language. Your inputs line up on the right, your outputs on the left, and if you fail to wire them all up properly they simply fail to fire. I thought to myself: Really? Is this where we've ended up? Have we created a language so completely high-level that it once again consists of copper wires and solder?

The correct answer to this, as far as I've been able to determine, is: Actually, yes. The killer use case right now for Arrows is FRP (think Yampa, games, music, and reactive systems in general). The problem facing FRP is largely the same problem facing all other synchronous messaging systems: how to wire a continuous stream of inputs into a continuous stream of outputs without dropping relevant information or springing leaks. You can model the streams as lists -- several recent FRP systems use this approach -- but when you have a lot of inputs lists become almost impossible to manage. You need to insulate yourself from the current.

What Arrows allow in FRP systems is the composition of functions into a network while at the same time entirely abstracting away any reference at all to the underlying values being passed by those functions. If you're new to FP, this can be confusing at first, and then mind-blowing when you've absorbed the implications of it. You've only recently absorbed the idea that functions can be abstracted, and how to understand a list like [(*), (+), (-)] as being of type [(a -> a -> a)]. With Arrows, you can push the abstraction one layer further.

This additional ability to abstract carries with it its own dangers. For one thing, it can push GHC into corner cases where it doesn't know what to make of your type assumptions. You'll have to be prepared to think at the type level -- this is an excellent opportunity to learn about kinds and RankNTypes and other such topics.

There are also a number of examples of what I'd call "Stupid Arrow Stunts" where the coder reaches for some Arrow combinator just because he or she wants to show off a neat trick with tuples. (Here's my own trivial contribution to the madness.) Feel free to ignore such hot-dogging when you come across it in the wild.

NOTE: As I mentioned above, I'm a relative noob. If I've promulgated any misconceptions above, please feel free to correct me.

Title: what is the purpose of arrows?


答:
If you participate actively in codeing development then I would suggest "Scrum Master".

If you are more on the management side (ie don;t actively code) "Product Owner" may be more appropriate.

As the lead on my team I refused to let the manager take the scrum master position (he had no visited interest as he was not contributing code or design). We now rotate it (SM) through the developers (rotating once a quarter).

The PM side of the organization refused to give up the role of "Product Owner" as a result our manager does not play an active role in day to day agile processes, but he works with the "Produce Owner" to set priorities of the items in the product backlog.


答:
Here we go again ... There are plenty of other topics here on programmers which have ended up in the same discussion.

You point out some very interesting arguments relating to short functions. It is not a popular statement, but I am with you on this. After having discussed it oft times before, it is my impression the discussion usually boils down to whether you primarily focus on proper encapsulation, or take test driven development to the max. These are the two main contenders in what seems to be turning out yet another holy war, and I'm afraid we are on the under powered side.

However ...

The solution in my opinion definitely isn't wrapping the 'phases' in regions. Code folding is used to sweep code under the rug. Leave the code there as it is, it might remind you that you might want to refactor that at a later time! To relate it to an argument in your question: how will you be able to see an opportunity for code reuse if you don't see any code? Long segments of code should be exactly that, a thorn in the eye which makes you want to refactor it.

As an appropriate replacement for regions, I suggest using code paragraphs as Alex Papadimoulis names them in a comment. You might actually already be using a similar approach. It are simply blocks of code with a comment header, explaining what the entire block does. You have the readability of functions, but are able to use normally spaced english sentences, and you don't lose any encapsulation.


答:
Why not just pay the support devs 5 or 10k more than the build and forget devs?

By attaching an extra premium to support roles; in recognition of the additional challenges of "customer liasion" and "production code maintenance"; you'll not only provide extra motivation but more importantly the roles will be seen as having more prestige. After all a higher salary must mean a more important role and even if that's not the case it will be preceived that way.

Title: How to you "sell" support as an career option

Body:
We find it relatively easy to hire developers to work on various projects.

The problem arises when the project is finished but still needs to be supported.

We really battle to get people to join the support team. It's seen as dead-end, career-limiting, boring, second-class etc.

Currently, we get round this by getting the project team to assign some of their team to the support team for a while. Part of the assignment is to do a "brain dump" of the project so that the support team understands it. This works as long as the assignment is only for a fixed period.

Trying to hire people to work in support full-time is a problem. There are few applications and the calibre is not particularly high.

(The financial reality though is that support can be very lucrative for a company and once you get a reputation, you get approached by other companies to do their support even though you weren't involved in the original development.)


问:
Is DDD-Lite a pattern language for dependency injection?
I stumbled upon Greg Young's talk 7 Reasons why DDD Projects Fail where he mentions something he calls DDD-Lite at 7:20.

Summarizing, he basically says some use DDD as a pattern languages (entities, repositories, value objects, services, etc) without doing anything else related to DDD. He postulates 60% or more of domain models in .Net are DDD-Lite. He thinks DDD-Lite is basically building up a language around dependency injection, something you don't really need to do. He says either do DDD entirely or do something simpler. Otherwise he claims a person is putting forth all of this work in building good abstractions, but without any real benefits.

I must admit I don't know as much about DDD as I would like, and have not tried to use it yet. I also haven't read Eric Evan's book either. I am much more interested in Dependency Injection and many, many books and blogs on this subject use terms and reference concepts from Eric Evans' DDD book. This is where I've been exposed to DDD concepts. Books I've been reading that do this include:

Dependency Injection in .NET

Microsoft .Net: Architecting Applications for the Enterprise

Brownfield Application Development in .NET

If one wants to do Dependency Injection, what are simpler alternatives over doing "DDD-Lite?" It sounds like to me building good abstractions are quite useful regardless of if one is using concepts from DDD in a "DDD-Lite" way. (see Mark Seemann's blog posts: Interfaces are not abstractions, and Towards better abstractions). I have a hard time believing everyone doing Dependency Injection happens to also be doing (or needs to do) full fledged DDD. Did I somehow misunderstood Greg Young's argument about DDD-Lite?

答:
Dependency Injection and DDD are two disjoint concepts. Doing Dependency Injection does not require to do DDD nor does DDD require Dependency Injection.

A lot of DDD projects fail because they pick the patterns but neglect the process behind DDD. They do not take the time to extract business rules. They do not concentrate on the domain model and on careful abstractions. They don't establish an Ubiquitous Language.

In short: I guess that's a misunderstanding

OwnerDisplayName: Matt Spinelli

OwnerDisplayName: Saintedlama


问:
How can I test PHP skills in a interview?
My company needs to hire a PHP developer, but nobody has PHP knowledge in my company and we find difficult to test for PHP skills. If it were a C/Java developer I would ask him to write a quick implementation of the Game of Life, but PHP is a completely different language.

I saw this test with interest:

http://vladalexa.com/scripts/php/test/test_php_skill.html

Anyone else has more suggestions?

答:
Code

Ask the candidate to write code

Ask the candidate to read code

If you do ask the candidate to write code make sure that:

The code is non trivial but small

You allow access to the manual and the internet

If you do ask the candidate to read code make sure that:

The code has some trivial errors

The code has some non trivial errors

The code works fine, but it can be easily optimized

You can use three or more different pieces of code, start from the simpler one and only advance to the next if you see that the candidate copes with ease. Throw in some recursion, to spice things up.

Resources

Ask for a detailed list of PHP resources the candidate uses. Books, blogs, forums, magazines, etc. That's how my current employers found out about StackOverflow.

If the candidate mentions StackOverflow or Programmers, you should NOT ask or try to find out their username. If they wanted to advertise their reputation they would have included a Careers 2.0 link on their resume.

Frameworks

Every PHP developer should know of the most popular PHP frameworks:

Laravel

Zend Framework

CodeIgniter

Symfony

CakePHP

Yii

and be fluent in at least one of them. You can have a few code samples ready for each one and ask the candidate to read and explain them, after they tell you which one they are more familiar with.

Debugging & Profiling

I've always felt that PHP developers are lacking debugging and profiling skills (perhaps only the PHP developers I've worked with). If during the discussion you find out that the candidate actively uses xdebug, don't bother with the rest of the interview and just hire them. ;)

Input sanitization

This is important. You can start with a discussion on why it's important and then ask for the most common methods to achieve it. This discussion will help you on what to ask.

Some hints:

mysqli_real_escape_string is good

magic quotes are bad

PHP snafus

You can find a lot of PHP snafus in this excellent discussion. If you are interviewing for a senior position you should definetaly ask on some of those. Some examples:

PHP's handling of numeric values in strings:

```<code>"01a4" != "001a4" // true
"01e4" == "001e4" // also true
</code>```

Valid PHP code:

```<code>System.out.print("hello");
</code>```

In PHP, a string is as good as a function pointer:

```<code>$x = "foo";
function foo(){ echo "wtf"; }
$x(); # "wtf"
</code>```

Unit testing

Need I say more?

Conclusion

A good PHP developer should combine a variety of skills & talents:

A good understanding of HTTP

A good understanding of Apache configuration (Even if you use a different web server at your company)

At least a basic understanding of JavaScript

A great understanding of HTML / CSS

The list goes on and on. Make sure you tailor the interview to the specific needs of the job opening, you don't want to hire just a good developer but a good developer that's great at what you immediately need him / her to do.

Body:
Code

Ask the candidate to write code

Ask the candidate to read code

If you do ask the candidate to write code make sure that:

The code is non trivial but small

You allow access to the manual and the internet

If you do ask the candidate to read code make sure that:

The code has some trivial errors

The code has some non trivial errors

The code works fine, but it can be easily optimized

You can use three or more different pieces of code, start from the simpler one and only advance to the next if you see that the candidate copes with ease. Throw in some recursion, to spice things up.

Resources

Ask for a detailed list of PHP resources the candidate uses. Books, blogs, forums, magazines, etc. That's how my current employers found out about StackOverflow.

If the candidate mentions StackOverflow or Programmers, you should NOT ask or try to find out their username. If they wanted to advertise their reputation they would have included a Careers 2.0 link on their resume.

Frameworks

Every PHP developer should know of the most popular PHP frameworks:

Laravel

Zend Framework

CodeIgniter

Symfony

CakePHP

Yii

and be fluent in at least one of them. You can have a few code samples ready for each one and ask the candidate to read and explain them, after they tell you which one they are more familiar with.

Debugging & Profiling

I've always felt that PHP developers are lacking debugging and profiling skills (perhaps only the PHP developers I've worked with). If during the discussion you find out that the candidate actively uses xdebug, don't bother with the rest of the interview and just hire them. ;)

Input sanitization

This is important. You can start with a discussion on why it's important and then ask for the most common methods to achieve it. This discussion will help you on what to ask.

Some hints:

mysqli_real_escape_string is good

magic quotes are bad

PHP snafus

You can find a lot of PHP snafus in this excellent discussion. If you are interviewing for a senior position you should definetaly ask on some of those. Some examples:

PHP's handling of numeric values in strings:

"01a4" != "001a4" // true
"01e4" == "001e4" // also true

Valid PHP code:

System.out.print("hello");

In PHP, a string is as good as a function pointer:

$x = "foo";
function foo(){ echo "wtf"; }
$x(); # "wtf"

Unit testing

Need I say more?

Conclusion

A good PHP developer should combine a variety of skills & talents:

A good understanding of HTTP

A good understanding of Apache configuration (Even if you use a different web server at your company)

At least a basic understanding of JavaScript

A great understanding of HTML / CSS

The list goes on and on. Make sure you tailor the interview to the specific needs of the job opening, you don't want to hire just a good developer but a good developer that's great at what you immediately need him / her to do.


问:
How to protect source code from remote developers?
My company is going to hire an external developer to create some new modules and fix some bugs in our PHP software.

We have never hired an external developer by the hour before. How can we protect the source code? We are not comfortable giving out source code and were thinking that everything remained under a surveillance enabled VPN which external developer would log in to.

Has anyone solved this problem before? If so, how?

Edit: We want the developer to see/modify the code but under surveillance and on our machine remotely. Does anybody have a similar setup?

Edit 2: NDA is just a formality. IMO, even people who are in favor of NDAs know that it'll do nothing to protect their property.

Edit 3: Let me clarify that we aren't worried about the developer copying an algorithm or a solution from the code. Code is coming out of his brain, so naturally he is the creator and he can create that again. But our code is built over several years with tens of developers working on it. Let's say I hire an incompetent programmer by mistake, who steals our years of work and then sells it to the competitor. That can make us lose our cutting edge. I know this is rare, but such a threat has to be taken under consideration if you're in business. I'll make points of my comments so its easy for everyone to communicate:

Why NDA sucks? Take this scenario, if anyone is capable of suggesting a solution to this scenario I will consider the NDA effective. Ok, here goes:
We hire 2 external developers, one of them sells our code as it is to someone else after a year. You are no longer in touch with any of the developers, how are you supposed to find out who ripped you off? NDA does provide a purpose, but you can't rely completely on that. At least we cannot.

I did not meant to offend anyone while I was posting this question, even though unintentionally I did. But again to people answering/commenting like 'I will never ever work with you' or that Men-in-black-gadget thingy: It's not about you, it's a thread about how feasible a given technical solution would be. And if anyone in this community has worked under such an environment.

About 'Trust', of course we won't hire anyone we do not trust. But is that it? Can't someone be deceitful at first? We all trusted a lot of politicians to run our country, did they not fail us ever? So, I'm saying 'trust' is a complete other layer of protection like NDA, and my question was not directed to it. My question is rather directed towards technical measures we can take to avoid such a thing from happening.

答:
How does your company protect the source code from you and your fellow developers? What's the stop you and your coworkers from stealing the valuable source code and selling it to the competitor?

Whatever works for you should work for the remote developer.


问:
How many are too many interfaces on a class?
I would probably consider it a code smell or even an anti-pattern to have a class that implements 23 interfaces. If it is indeed an anti-pattern, what would you call it? Or is it simply just not following the Single responsibility principle?</p>

答: Its sounds as thought they have a "getter"/"setter" pair for each property, as is normal for a typical "bean" and promoted all these methods to the interface. So how about calling it a "has bean". Or the more Rabelaisian "Flatulence" after the well known affects of too many beans.


问:
Is there such thing as an example driven parser generator or ad-hoc DSL development?
I'm intrested to know if there exists a tool that lets you input examples of valid documents and lets you then generalize from that to a reusable parser.

I can imagine this, but everytime i start learning about parsers it gets to the granularity of something like lex and yacc and it seems more complicated than my instincts say it should be.

So I'm left wondering if

a) it's just fundamentally that complicated and I need to see it or

b) there's a way to build ad-hoc DSLs for relatively simple tasks that I could learn about

Update: a simple example of an "ad hoc" dsl i might like to make quickly.

Instead of the XML

```<code><foo>
  <item>bar</item>
  <item>bat</item>
</foo>
</code>```

I might want something like:

```<code>foo
  bar
  bat
</code>```

lines contain data items

indentation produces parent-child relations

My imaginary tool lets me convey the above information.

Then, in my imaginary tool, I might highlight "foo" above and right click, at which point it would prompt me to restrict the values to a choice list....

Then I might extend the first one to:

```<code>foo
  bar(5)
  bat
</code>```

in a line, '(' and ')' surround a sub item

The above might be qualified with a boolean value that specifies recursion or not, if set to true then bar(lala(4)) might work...

This is the kind of train of thought I generally have that led me to ask the question. It's possible that now I've qualified it, the answer changes - if so I apologize in advance.

答:
You cannot practically build a parser for a real computer language (or DSL) by just showing it examples.   Learning anything by just positive examples is pretty hard (as is well known by the machine learning community); you need at least some negative examples.  Pretty much you want parsers to be able to accept alternatives.  If you allow them, a simple disjunctive generalization that accepts just the set of positive examples and rejects everything else works just fine but isn't useful (e.g., a "parser" for the strings "QA" "BZQ1" and "RQ" would be just "QA" | "BZQ1" | "RQ").

This article talks about machine learning to induce grammars from data.   It doesn't say much about practicality.  No tool I have ever seen has been effective at doing this in a general way, and the differences between "legal" and "not legal" can be incredibly subtle.  Imagine trying to learn what were valid C++ programs according to the C++ standard, and rejecting the ones that MS allows that aren't legal.  Even the programmers pretty much can't do this, and the C++ standards committee argues endlessly about the tricky cases.

Frankly, if you have EBNF, writing down a grammar for a DSL is generally fairly easy... if you know what the DSL should allow.   Writing down a grammer that works for most parser generators is relatively hard, because they only accept limited versions of EBNF (eg., LL(k), LALR(1), ...).   You can make this a lot easier by using a full context-free parsing engine such as a GLR parser which doesn't have such restrictions.

Our DMS Software Reengineering Toolkit has such a GLR parser generator, and easily accepts context free grammars.  It seemingly does the impossible of parsing C++ with a straightforward BNF (the GNU folks had to build a terribly hacked LALR parser to do this for GCC); it is possible because there are context-free grammars for C++, just look in the standard!.

But parsing is just the easy part.  You shouldn't spend your energy there.  You need more machinery to process the DSL: building ASTs, inspecting for special cases, transforming to a target language, optimizing the code.

DMS is good for building DSLs not only because it can accept descriptions of DSLs relatively easily, but because it has most of that vast amount of machinery for processing (analyzing/transforming/...) that DSL that you will need, after you succeed in parsing.


答:
A number of points here.

Its highly unlikely that anyone except you and your company attaches any value to the source code.

If you expose you php on a public web site, unless your encoding DNA or something intrinsically complex then any competent developer could reverse engineer your algorithm in days or weeks.

Why would an external pose any more risk than an employee, the office cleaner or any other person who could access the code.

If the code is truly valuable then a standard freelance contract would give you all the legal protection you need.


答:
If I had to give it a name, I think I'd call it the Hydra:

In Greek mythology, the Lernaean Hydra (Greek:  Λερναία Ὕδρα) was an ancient nameless serpent-like chthonic water beast, with reptilian traits, (as its name evinces) that possessed many heads — the poets mention more heads than the vase-painters could paint, and for each head cut off it grew two more — and poisonous breath so virulent even her tracks were deadly.

Of particular relevance is the fact that it not only has many heads, but keeps growing more and more of them and is impossible to kill because of it. That's been my experience with these kinds of designs; developers just keep jamming more and more interfaces into it until it has too many to fit on the screen, and by then it's become so deeply entrenched in the program's design and assumptions that splitting it up is a hopeless prospect (if you try, you actually often end up needing more interfaces to bridge the gap).

One early sign of impending doom due to a "Hydra" is frequent casting of one interface to another, without much sanity checking, and often to a target that makes no sense, as in:

```<code>public void CreateWidget(IPartLocator locator, int widgetTypeId)
{
    var partsNeeded = locator.GetPartsForWidget(widgetTypeId);
    return ((IAssembler)locator).BuildWidget(partsNeeded);
}
</code>```

It's obvious when taken out of context that there's something fishy about this code, but the likelihood of this happening goes up with the more "heads" an object grows, because developers intuitively know that they're always dealing with the same creature.

Good luck ever doing any maintenance on an object that implements 23 interfaces. The chances of you not causing collateral damage in the process are slim to none.

Title: How many are too many interfaces on a class?

Body: I would probably consider it a code smell or even an anti-pattern to have a class that implements 23 interfaces. If it is indeed an anti-pattern, what would you call it? Or is it simply just not following the Single responsibility principle?</p>

Body:
If I had to give it a name, I think I'd call it the Hydra:

In Greek mythology, the Lernaean Hydra (Greek:  Λερναία Ὕδρα) was an ancient nameless serpent-like chthonic water beast, with reptilian traits, (as its name evinces) that possessed many heads — the poets mention more heads than the vase-painters could paint, and for each head cut off it grew two more — and poisonous breath so virulent even her tracks were deadly.

Of particular relevance is the fact that it not only has many heads, but keeps growing more and more of them and is impossible to kill because of it. That's been my experience with these kinds of designs; developers just keep jamming more and more interfaces into it until it has too many to fit on the screen, and by then it's become so deeply entrenched in the program's design and assumptions that splitting it up is a hopeless prospect (if you try, you actually often end up needing more interfaces to bridge the gap).

One early sign of impending doom due to a "Hydra" is frequent casting of one interface to another, without much sanity checking, and often to a target that makes no sense, as in:

public void CreateWidget(IPartLocator locator, int widgetTypeId)
{
    var partsNeeded = locator.GetPartsForWidget(widgetTypeId);
    return ((IAssembler)locator).BuildWidget(partsNeeded);
}

It's obvious when taken out of context that there's something fishy about this code, but the likelihood of this happening goes up with the more "heads" an object grows, because developers intuitively know that they're always dealing with the same creature.

Good luck ever doing any maintenance on an object that implements 23 interfaces. The chances of you not causing collateral damage in the process are slim to none.


问:
How important is the Acid3 Test anymore and what should replace it?
For a long while the default guide to latest standards support for browsers was the Acid 3 Test. I've just run this on Windows 7 (x64) for Chrome 15.0, Firefox 7.0, Safari 5.1 and IE 9.0 and they all score 100. Some of the animations could be smoother but on the whole there's not much to differentiate them.

I've then looked at the scores for html5test.com which show much wider variation:

343/450 : Chrome 15.0

298/450 : Firefox 7.0

293/450 : Safari 5.1

141/450 : IE 9.0

Are there other tests that are a useful measure for browser feature support? What minimum score on the HTML5 test is a 'good' score?

How important is the HTML5 test score and can it really test all the new features properly? Is it a good replacement for the Acid 3 test?

Are the modern browsers now compliant enough that the end user can remain ignorant of the level of standards support?

答:
The ACID 3 test isn't a definitive measure of a browser's capabilities. The test includes edge cases and handling of bad code, which are not as relevant as which standards are supported and how well. ACID 3 is just one benchmark, and not an especially useful one at that.

The obvious issue is Internet Explorer. v9 is rather good, and v10 looks even better; v9 will probably be the mainstream baseline for some years to come.

Also take a look at caniuse.com, which lists browser capabilities by technology and browser version.


答:
+1 for the answers you already have in your question!

Guided tour

10k lines of code is a lot, but I think it's still not impossible to have the other guy give you a 'guided tour'. You sit down together in front of the code and he takes you on a trip from the top to the bottom, working down the 'layers'. You'd need to do it in short bursts - all in one go would kill both of you.

Zoom-in, zoom-out

The advantage of doing this is that while he's explaining it to you, he will almost certainly have some "oh, yes, there's this as well" moments that he might not if he was just trying to document it on his own. And your questions will help to focus in on the obvious-to-him-but-not-to-anyone-else bits. This kind of zoom-in/zoom-out interaction is only possible one-on-one, trying to write or read something like that is unwieldy.

Documentation

I think you should both be independently documenting stuff - he should start at the bottom (in case you don't have time to get there together), and you should start at the top, on the basis of what you've understood of his guided tour and as if it was for someone else [in a previous job I inherited a load of 'legacy' code, and only just had the time to document it before leaving myself :)].

Where's what?

The aim of most of this is for you to be able to get a feel for where stuff happens. So that given a particular bug or modification, you can very quickly find the place in the code which you need to concentrate on. You could test yourself by taking the list of old bugs and seeing if you can accurately predict where the problem was.

Pump him dry

It doesn't matter if he ends up hating  you (smile), your job is to get as much information out of that guy's brain as you possibly can in the time available. Make sure that you get management on your side, and that they prioritise knowledge transfer over "just fixing those last few bugs before he leaves" (unless you're fixing them together...).

Title: Best Practices for Handing over Legacy Code

Body:
In a couple of months a colleague will be moving on to a new project and I will be inheriting one of his projects. To prepare, I have already ordered Michael Feathers' Working Effectively with Legacy Code.

But this books as well as most questions on legacy code I found so far are concerned with the case of inheriting code as-is. But in this case I actually have access to the original developer and we do have some time for an orderly hand-over.

Some background on the piece of code I will be inheriting:

It's functioning: There are no known bugs, but as performance requirements keep going up, some optimizations will become necessary in the not too distant future.

Undocumented: There is pretty much zero documentation at the method and class level. What the code is supposed to do at a higher level, though, is well-understood, because I have been writing against its API (as a black-box) for years.

Only higher-level integration tests: There are only integration tests testing proper interaction with other components via the API (again, black-box).

Very low-level, optimized for speed: Because this code is central to an entire system of applications, a lot of it has been optimized several times over the years and is extremely low-level (one part has its own memory manager for certain structs/records).

Concurrent and lock-free: While I am very familiar with concurrent and lock-free programming and have actually contributed a few pieces to this code, this adds another layer of complexity.

Large codebase: This particular project is more than ten thousand lines of code, so there is no way I will be able to have everything explained to me.

Written in Delphi: I'm just going to put this out there, although I don't believe the language to be germane to the question, as I believe this type of problem to be language-agnostic.

I was wondering how the time until his departure would best be spent. Here are a couple of ideas:

Get everything to build on my machine: Even though everything should be checked into source code control, who hasn't forgotten to check in a file once in a while, so this should probably be the first order of business.

More tests: While I would like more class-level unit tests so that when I will be making changes, any bugs I introduce can be caught early on, the code as it is now is not testable (huge classes, long methods, too many mutual dependencies).

What to document: I think for starters it would be best to focus documentation on those areas in the code that would otherwise be difficult to understand e.g. because of their low-level/highly optimized nature. I am afraid there are a couple of things in there that might look ugly and in need of refactoring/rewriting, but are actually optimizations that have been out in there for a good reason that I might miss (cf. Joel Spolsky, Things You Should Never Do, Part I)

How to document: I think some class diagrams of the architecture and sequence diagrams of critical functions accompanied by some prose would be best.

Who to document: I was wondering what would be better, to have him write the documentation or have him explain it to me, so I can write the documentation. I am afraid, that things that are obvious to him but not me would otherwise not be covered properly.

Refactoring using pair-programming: This might not be possible to do due to time constraints, but maybe I could refactor some of his code to make it more maintainable while he was still around to provide input on why things are the way they are.

Please comment on and add to this. Since there isn't enough time to do all of this, I am particularly interested in how you would prioritize.

Update: As the hand-over project is over I have expanded this list with my own experiences in this answer below.


问:
What non-programming books should a programmer read to help develop programming/thinking skills?
There are a lot of questions about what programming books should be on the programmer's bookshelf. How about non-programming related books that can help you become a better programmer or developer? It would also be interesting to know why they would help.

My first choice would be Sun Tzu's "Art of War" (however cliché), because it made it obvious that the success of any project depends on the strength of its weakest link (and warfare is a big project).

答:
Patterns of Home

An excellent reference on 10 patterns for the process of designing homes. Instead of being a catalog of patterns for elements of a home (such as living room, alcove, patio, etc.), it's a catalog of principles that should shape the design of homes; a guide to the factors that are critical to making a home livable for its habitants.

I've translated the 10 design process patterns they catalog to the design of software and it's remarkable how effective they are in helping you focus on the details relevant to big-picture thinking before you get bogged down on the specifics of designing and coding classes.


答:
If you want decent documentation reasonably painlessly buy a copy of Pascal Analyzer (PAL) I have used this on Delphi projects and it was great - they may now have split the documentation functionality off into a product I'm not familiar with (Pascal Browser) so you may have to buy both (< 300 USD) but PAL was a great tool for understanding where variables were being used where functions were being called from etc & picking up all sorts of potential issues with the code.

Use PAL to get an idea of how the code's structured plus probably a list of about 1000 suggested improvements if my experience was anything to go on.  Working through the list will improve the quality of the code, simplify it greatly & make your life easier for the future.  Delphi itself supports refactoring in recent versions (the last 5 years or so).  You did need to include everything in the dpr file for it to really work properly back when I was doing it so bear that in mind.

If you want unit tests, download DUnit & start creating some tests with the original coder - that's probably a constructive way to use at least some of their time.