答:
In Python this is fairly descriptive:</p>

```<code>if a in range(14, some_number, 8):
    do something
</code>```

Title: Ifology - how to write this statement better?

Body:
I'm wondering how to write the if statement in the following block in a better way. It's supposed to operate when $a is 14, 22, 30 and for all following values at intervals of 8, up to some limit. The current way is obviously not good since the action must be performed each time that periodic pattern is fulfilled, and this would require many, many OR operators.

```<code>if($a == 14 || $a == 22 || $a == 30 || $a == 38 || $a == 46... until some number){
    do something...
}
</code>```

Body:
In Python this is fairly descriptive:

if a in range(14, some_number, 8):
    do something


问:
How message acknowledge deadlock problem is being solved in real world applications?
To my understanding message acknowledge deadlock problem is this:

In order to sync value X between A and B

A sends X to B

A waits for B to send acknowledgment to A so it makes sure B has latest X

B waits for A to send acknowledgment of acknowledgment that B received their acknowledgment.

and so on ...

How in real world applications we solve such problem? Do we just assume the infrastructure work and stop checking for acks?

答:
Do you really need to verify that A knows that B knows that A knows that B knows that A knows that B knows that A changed the value of X?

B needs to know that A changed the value of X. This is obvious.

A needs to know that B knows that A changed the value of X, because if B didn't get the message A needs to resend it. This one can not be avoided unless you assume the entire messaging pipe is perfect and can not loose messages.

But does B need to know that A knows that B knows that A changed the value of X? One can say that B needs to know when to stop sending ACKs, but is that really necessary? I say not! This is where the ACK chain stops!

B does not need to verify that A got the ACK. If A did not get the ACK, it will simply assume that B did not get the original message and resend it. B will receive the resent message, and will either recognize it already got it and do nothing or - if no such duplicate message recognition was implemented - will simply set the value of X again. No harm done. But in any case - B will send an ACK on the resent message.

A is the one responsible to make sure B get the new value of X. A needs to resend again and again - but B only needs to send one ACK for each message of A.

ContentLicense: CC BY-SA 3.0


答:
In practice you solve it like this:

A sends X to B.

B sends an acknowledgement to A verifying that it received what was sent.  (For simple protocols like TCP it sends back a checksum, more complex ones like rsync might send back an MD5 hash.)

If A fails to receive the acknowledgement in a timely fashion, it sends X again.  In careful world protocols (eg TCP) it usually does do with a variable delay in case the problem is network congestion.

This continues until either A receives an acknowledgment, or gives up on sending the message.

In theory you could do much more complex and reliable stuff.  However research into this area is likely to induce depression.  See http://research.microsoft.com/en-us/people/mickens/thesaddestmoment.pdf to get the joke.

Title: How message acknowledge deadlock problem is being solved in real world applications?

Body:
To my understanding message acknowledge deadlock problem is this:

In order to sync value X between A and B

A sends X to B

A waits for B to send acknowledgment to A so it makes sure B has latest X

B waits for A to send acknowledgment of acknowledgment that B received their acknowledgment.

and so on ...

How in real world applications we solve such problem? Do we just assume the infrastructure work and stop checking for acks?


问:
Is "friendly fire" session replay a valid concern?
I've been reading a lot about sessions and security, trying to learn as much as possible before writing too much code. I've read about limiting session replay by including a timestamp within the cookie or data sent by the server:

{timeStamp, sessionID, HMAC({timeStamp, sessionID}, Key)}

limiting the valid time with the timestamp and keeping everything over a TLS connection will minimize replay. But what happens if the user who authenticates and receives this cookie (or data) is complicit in an attack whereby he immediately sends this cookie out to others (who now have perhaps a half hour according to the timestamp). Of course, the credentials would remain limited to whatever the initial user is privileged to do.

Is this a real concern in the wild? Is there a name for it?

Is it realistic, since this is TLS, to assume the client's IP won't change, and thus use that IP as a check to make sure this cookie is always played from the IP it was originally sent to?

答:
The situation that you are referring to would happen if the client is compromised.  This is a real concern, but in that case any protection that you implement is trivially bypassable by having the compromised client do whatever needs to be done.  So you can do an IP address check, but it won't actually help much.

That said, the data structure that you have proposed has a red flag.  Why are you sending a timestamp to the client?  Are you going to trust what the client says?  The session ID should map to a data structure that you control which will, among other things, know when the timestamp expires.  There is therefore no need to pass that information to the client.


问:
How to measure his own skill in a programming language?

Possible Duplicate:

  How Can I Know Whether I Am a Good Programmer?

As many programmers I have worked in several languages. While of course there are some that I am more at ease than other, I do not have a real way to precisely measure my skill in a specific language.

So I thought of a system which allows me to help me with that. I am looking for 5 common criteria in programming languages, to which I will have a value from 1 (junior) to 4 ( Senior) to represent my skill.

I however have no real idea of the criteria I should choose for that.

Does anybody have suggestion ?

Thanks.

答: Take a look at the Programmer's competency matrix. It's a good all-around measure of skill, more or less.</p>

ContentLicense: CC BY-SA 2.5


问:
Ifology - how to write this statement better?
I'm wondering how to write the if statement in the following block in a better way. It's supposed to operate when $a is 14, 22, 30 and for all following values at intervals of 8, up to some limit. The current way is obviously not good since the action must be performed each time that periodic pattern is fulfilled, and this would require many, many OR operators.

```<code>if($a == 14 || $a == 22 || $a == 30 || $a == 38 || $a == 46... until some number){
    do something...
}
</code>```

答:
If your test values are not in any specific sequence (are not powers or two, not all even, not all odd, etc) you can use a lookup table to avoid the long if chains:

```<code>int test_values[] = { 14, 22, 30, 38, 46, ... };

for (i = 0; i < test_values.length; i++)
{
    if (input == test_values[i])
    {
        do something...
    }
}
</code>```

This way it is also very easy to add more values by just expanding the array. The array of cases can also be initialized from an external config file.

Body:
If your test values are not in any specific sequence (are not powers or two, not all even, not all odd, etc) you can use a lookup table to avoid the long if chains:

int test_values[] = { 14, 22, 30, 38, 46, ... };

for (i = 0; i < test_values.length; i++)
{
    if (input == test_values[i])
    {
        do something...
    }
}

This way it is also very easy to add more values by just expanding the array. The array of cases can also be initialized from an external config file.


问:
Is Testing a necessary part of Agile methodology?
I have been on numerous teams that try to practice Agile methodologies and often these teams are test centric. Is testing a necessary part of practicing the Agile methodology or is it just a XP practice that has been latched on over the years?</p>

答:
If you do not have tests, how do you know your code works?

Edit: the assertion that tests cannot prove that the code works fails to define one crucial term, namely works. What does it mean for a program to work? If you keep this term vague, then there is no way at all to prove or be sure that any program works. Ever.

On the other hand, you can define works as "behaves according to a specification". Now you can not only use tests to show that code works, but the tests themselves can serve as an executable specification of your code's behavior. In other words, a well written test suite defines what works means.

This way of thinking also forces you to re-examine the meaning of a bug. If your code passes all the tests, then there are no bugs in the code. If, despite that, the system does not behave as it should, then its behavior is not correctly specified. I. e. the bug is in the spec, defined by tests.

This approach to software development decouples the functional specification of a system from its implementation, which, according to every software engineering book in the world, is a very good thing. At the same time, this approach ensures that your implementation always corresponds to the functional spec.


答:
In theory, this problem is not solvable for single messages, and A and B cannot know for certain that a message has been received and acknowledged. See the Two Generals' Dilemma.

If you are sending a string of messages, this changes somewhat. It is possible for both sender and receiver to know that some messages have been successfully sent and received. For instance, TCP/IP uses a strategy that includes the use of sequence numbers. Each segment contains a sequence number which is sent back in the acknowledgement. This arrangement seems to be sufficient for running a large, world-wide data network.


问:
How to check in website/url have been updated or not?
I am trying to make a Android application which will take your URL and if there is new update on that website then it will show the user that this link have been updated.

I am working on the project which will check for the website if they have been updated or not.
I know that there are RSS on most of websites, but I am talking about those websites which don't have but are important for us. Like the websites where result will be posted but for that I will have to check that website again and again.

How can I check that website is updated or not?

答:
You can use the If-Modified-Since HTTP header. If the server tells you that the page has been modified since the given date, then you can download the new content.

http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.29


答: You are probably talking about automated testing, unit tests, integration tests etc. These are more important to agile than manual testing (with testers and such) because they are too slow, thus its not possible to test every small change that you make. Since agile is about fast small iterations, having tests that verify correctness in seconds or minutes, rather than hours or days, is very useful.</p>

Title: Is Testing a necessary part of Agile methodology?

Body: I have been on numerous teams that try to practice Agile methodologies and often these teams are test centric. Is testing a necessary part of practicing the Agile methodology or is it just a XP practice that has been latched on over the years?</p>


问:
Should a developer refuse to access production server?
There are already questions on SE that ask if a developer should have access to the production server(s).

But, given the fact that I already have a root access on the production server, should I say that, as a developer, using that access is beyond my responsibilities? Should I argue that I'm not a sysadmin and I am afraid to break things?

Or, should changing things on the production server be considered bad practice but just a part of our poor release/debug/development /whatever process?

Thank you.

答:
It depends.  Here is the meta principle.  If you are in a small company, and there is a problem, and you're refusing to solve it, then your behavior just became a problem.

Now the question is what problem you have.

Is the problem that production changes need to be made and you're the one available?

Is the problem that you really don't know how to do the task?

Or is the problem that someone is trying to use you as a back door to get things done that someone else thinks shouldn't happen?

Decide fast.

If it is the first, then what you should do is perform the task, carefully document as you go what you did, and then send that to whoever ideally should have done that job, possibly along with your comment that you feel out of your depth and this is risky.  Feel free to CC that to any and all who you think are qualified to have an opinion on what you did.  There is a chance that you'll get feedback that helps you do it better next time.

If it is the second, then measure twice, cut once.  This is a learning opportunity, treat it like one.  And send an email like the one described above looking for feedback and advice for how to do it next time.

If it is the last, then you should say, "So and so is responsible for this, and I don't want to create a problem because I don't know what else I'd be stepping on."  And then stand firm on passing the buck.

If you are in doubt, err on the side of getting the immediate thing done after delivering any warnings you need.  Usually you won't screw up (too badly), and that addresses an obvious immediate problem.  If your action turned out to be wrong, blame tends to be easy to deflect.  (Unless you're in a toxic organization, in which case the only choice that will work in the long run is getting a better job.)


答:
Avoid interaction only if...

Completely avoiding the production server is only practical if:

You provide the client with a painless way of updating the software, and you are willing to provide training to show them how to go about it.

Updates are such that the client can perform them at their leisure.  If you require them to perform an update for security loopholes in your software, they may not actually want to / be able to do so, and you must account for that.

You reject the possibility of having access in any way.  One of the legal implications of being able to access the production server is that you could be blamed for literally any type of problem that you have access to.  Removing that possibility is paramount to removing legal responsibility.

However, the advantages of completely avoiding the production server only apply if the entire company is in agreement.  If you, the programmer, decides this is the best approach and Bob, the intern programmer disagrees and ignores your heed, you've accomplished nothing ultimately except potentially some cigarette ashes in your morning coffee in the office.  In other words, if this is not company policy, this is what must change, not you personally.  You can mention these points to your boss, however, if your company isn't onboard, you must ultimately interact with the production server.

Some helpful advice if you must

Should you have to interact with the production server, I have enough experience to mention a few pointers:

DO perform backup before doing anything that would manipulate the database.  The more recent, the better.  Should something happen and you have a day-old backup, you'll still be in the sh*t, but at least you won't get fired over it.  Have a copy from half an hour ago, and you may even get out of it unscathed.

DO provide notice prior to performing any activity on the production server.  Should this be a legal issue, while this isn't rock solid evidence that you don't touch the server without a notice, it is a good argument in your favor.  If you send an e-mail, be sure to get back an indicator that your customer has read it.

DO contact your client when would be convenient to perform updates / checks.  You only really need to do this once, to get a general idea of hours (lunchtime or whatnot).  Make sure you send a confirmation of the hours communicated by phone in writing in an e-mail, and make sure that e-mail is received by your client (e-mails do still fail sometimes).

DO NOT perform changes on the database that you cannot reverse.  Yes, you have a backup, it's true, though how would your client react if you were forced to tell them that the only way to return to a previous state was to wipe out all data for that day?  More importantly, how would your boss react to you telling him that you should wipe out the client's production data for that day?  If there is no other way, you can always choose NOT to do it.  You can always port the data to your local databases to replicate problems (assuming of course that you have approval).  There should be no excuses here.

DO NOT leave junk data on the database.  This is a corollary to the above statement.  If you created a new record to test something, though it may not impact the functioning of the program, the client can still see this.  It is completely unprofessional as a programmer and it makes your company seem like you sell chocolate, and also software on the side.

You probably already know this points or you wouldn't be asking if it is such a good idea to modify the production server, though maybe this answer could help you formulate some sort of company policy for what concerns interaction with the production server.

Hope that helps!

Title: Should a developer refuse to access production server?

Body:
There are already questions on SE that ask if a developer should have access to the production server(s).

But, given the fact that I already have a root access on the production server, should I say that, as a developer, using that access is beyond my responsibilities? Should I argue that I'm not a sysadmin and I am afraid to break things?

Or, should changing things on the production server be considered bad practice but just a part of our poor release/debug/development /whatever process?

Thank you.


答:
Both Agile and XP try to avoid Big Design Up Front. In BDUF, requirements are gathered, a formal specification is created, then coding is done, then testing is done. This makes sense for well-defined, mission- and life-critical systems like medical equipment, space probes, etc.

Agile avoids this flow because it doesn't work well for problems which aren't well-defined, for example "whatever changes the client asks for this week". We still need a formal specification, so we know what to do and when we're done, but rather than some kind of written document we use code in the form of automated tests.

Automated unit tests are quick to write, quick to run and very modular/decoupled. This makes them a fast way to formally specify and check the requirements.


问:
Google Summer of Code Experience
I was a Google Summer of Code student this year and successfully completed my project. It was an awesome learning experience.

Just wondering, from an industry point of view - how is or how well is a Summer of Code experience viewed? I mean, if you were going to hire me, would it mean anything to you? I am just asking this since doing SoC != an internship. As a SoC student, I was a independent contractor for Google. Sure, there was proper development, but I am interested in looking at it from the experience you guys have here. Would you prefer me?

Sorry for not revealing my name; I'd hope you understand.

答:
I've done both GSoC and internships, and I don't think they are easily comparable from this angle.

An internship teaches shows you how companies function, lets you work in close proximity with your team, be part of a process, and learn. You get to interact with seasoned veterans that can mentor you along the way and show you how to get better, which is invaluable. It can be a good or a bad experience, but you'll learn something either way. I found it helpful to start out doing internships, because there's more guidance provided, people acknowledge the fact you are pretty new to programming. It's a two-way experience that you might not be able to obtain, purely, from GSoC.

On the other hand, you can't succeed in GSoC without self-discipline and self-motivation. This shows what kind of control you have over yourself, whether working remotely means you slack off, and how passionate you are about programming. It's important to companies because it reflects your work ethic. Additionally, the code is in the open, and it can serve as a testament of your skills at a certain point in time. The mentorship/guidance you receive is of a different nature, but the emphasis is on you. I appreciated the considerable freedom I had in terms of certain decisions during my GSoC project. I think it's a great way to prove yourself (to yourself, firstly).

There's a general opinion that open source contributions help with potential jobs; Google themselves mention that participation in GSoC helps if you apply to work for them. I think the consensus is that, by contributing to open-source, you show dedication as a programmer. (It probably helps even more if you kept contributing to whatever project you were on during GSoC, after the summer ended. I'm not in that position, but I would certainly ask a potential hire about why they did or did not continue working on their project.) You show an interest in your skill that goes beyond a paycheque, and all things considered companies prefer that. I certainly enjoy working with someone that codes it because they like to much more than I do with someone that is just trying to get rich.

In conclusion, I think GSoC is valuable, not because Google sponsors it, but rather because it's an open-source endeavour that reflects well on your interests as a programmer. I think internships can help you become a better programmer and a much better team player, and they offer a different kind of learning experience: you learn how FOSS development works in one, and how companies do in the other. Practice a balanced diet.

Title: Google Summer of Code Experience


答:
Are you in any way shape or form Responsible for any action that must be run "as root" on the Production server?

If so, then you're lumbered.

Get hold of a shell add-in that records everything you type into a file - that way, at least you'll have a record of how things got broken,

Get someone else to look over your shoulder before you press anything circular and vaguely red (especially if its flashing to any degree),

Notify whoever looks after your corporate Security arrangements that you have this level of access (and let them ask why) - that may well stir up a hornets' nest for your Boss,

Investigate ways of minimising the risk of your causing any damage - can what you need to do be done any other way (or by somebody/ something else)?

Automation - doing things reliably, the same way, every time, is a Wonderful thing.

Brace yourself for the worst when it happens.

If you don't actually need this level of access, then somebody needs to take it away from you.

The Principle of Least Privilege doesn't just apply to application code; it applies equally well to people.  Does you Boss really want you in a position to see their salary?  Letting that "slip" in conversation might very well get things rolling.


问:
Why are there no PUT and DELETE methods on HTML forms?
HTML4 / XHTML1 allows only GET and POST in forms, now it seems like HTML5 will do the same. There is a proposal to add these two but it doesn't seem to be gaining traction.

What were the technical or political reasons for not including PUT and DELETE in HTML5 specification draft?

答:
History

I think it's worth mentioning the first appearance of HTML forms in RFC1866 (Section 8.1).
Here the method attribute is defined as the following:

```<code>     METHOD
            selects a method of accessing the action URI. The set of
            applicable methods is a function of the scheme of the
            action URI of the form. See 8.2.2, "Query Forms:
            METHOD=GET" and 8.2.3, "Forms with Side-Effects:
            METHOD=POST".
</code>```

Further explanations are located in Section 8.2.2 - GET and Section 8.2.3 - POST

Keep in mind, that HTML 2.0 (Nov. 1995) was specified before HTTP 1.0 (May 1996). So everybody used HTTP only with GET (as of HTTP 0.9) or with the extension POST. But only a few web servers supported PUT and DELETE (like stated in the HTTP 1.0 Appendix).

Speculation

If you think about how Berners-Lee's development of the semantic web could have evolved it seems clear that it went from actual problems to a general concept

First he wanted to share documents. Therefore he needed markup.

Then he wanted to query databases for content, so he needed forms.

Then he wanted to put new data into the database. So he used forms with GET and POST.

After that he may have realized that you could do every CRUD operation on data from remote, so HTTP was extended but never HTML because it was too late (only a few servers supported the new CRUD operations in 1996).

ContentLicense: CC BY-SA 4.0

Body:
History

I think it's worth mentioning the first appearance of HTML forms in RFC1866 (Section 8.1).
Here the method attribute is defined as the following:

     METHOD
            selects a method of accessing the action URI. The set of
            applicable methods is a function of the scheme of the
            action URI of the form. See 8.2.2, "Query Forms:
            METHOD=GET" and 8.2.3, "Forms with Side-Effects:
            METHOD=POST".

Further explanations are located in Section 8.2.2 - GET and Section 8.2.3 - POST

Keep in mind, that HTML 2.0 (Nov. 1995) was specified before HTTP 1.0 (May 1996). So everybody used HTTP only with GET (as of HTTP 0.9) or with the extension POST. But only a few web servers supported PUT and DELETE (like stated in the HTTP 1.0 Appendix).

Speculation

If you think about how Berners-Lee's development of the semantic web could have evolved it seems clear that it went from actual problems to a general concept

First he wanted to share documents. Therefore he needed markup.

Then he wanted to query databases for content, so he needed forms.

Then he wanted to put new data into the database. So he used forms with GET and POST.

After that he may have realized that you could do every CRUD operation on data from remote, so HTTP was extended but never HTML because it was too late (only a few servers supported the new CRUD operations in 1996).


问:
How to validate a given domain is owned by the user?
I'm writing a software which will be used mostly by companies.

I then had the idea to give companies a way to register their email domain so that every user which registers with an email of the given domain will be automatically put in the company group.

I know Slack does something like this and it works, but there are some problems... for example I've just registered "live.it" (the live.com italian version by Microsoft).

I can't just assume that if an user has validated an email with a specific domain then it's safe to put every user with the same domain_mail in the same group.

For example, if I register with me@gmail.com I don't want to let user register "gmail.com" has its own domain.

I'd like to avoid use of methods like "put an html file in the root of the domain" or "set a TXT record" so I was wondering how should I do.

答:
File in root directory

Don't discard the possibility of putting a file in a root directory of the corporate website. It works well and is widely used: Google Webmaster Tools is one example of such technique. This makes this approach attractive: since most users already know it, they won't be lost. Also, it doesn't require any technical knowledge, unlike modifying MX records (most small companies won't even know what an MX record is).

In order to avoid polluting the root directory, you should ask to put a file only when doing your checks. Once you've found the file, the user may be able to remove it.

Note that users who don't have any corporate website won't be able to access your service, but I don't think there are many customers in this case.

Note that:

You should check for both http://example.com/file and http://www.example.com/file, because some websites are configured in a way they don't support http://example.com/ form.

You may support HTTPS as well, given that I don't think there are a lot of companies with no redirection from HTTP to HTTPS.

You should not accept any other third-level domains such as http://mysite.example.com/, because this will make it possible for someone who bought an third-level domains to claim that he's the owner of the second-level domain example.com.

Sending an e-mail

Sending an e-mail with secret link is rather problematic. You can't do it to firstname.lastname@example.com, because a given person may not have a corporate e-mail address (this is often the case of startups, where people prefer using their personal address).

Using e-mails such as admin@example.com will not work in some cases.

First, there are always companies not having postmaster@example.com, admin@example.com etc., but having their particular "system" e-mail addresses you haven't whitelisted. Consider specifically foreign companies; for example, in France, it is not unusual to use "Administrateur" instead of "Administrator", including for e-mail addresses and account names.

Second, many small companies don't access and don't know how to access their system e-mails. They pay not even know they have abuse@example.com with hundreds of urgent e-mails waiting for their reply.

For the same reason, you can't base yourself on WHOIS records for e-mail address.


问:
Is the KISS principle more important than utilizing OOP to solve a problem?
I'm a PHP developer coding in the Yii 1.x framework. I was looking for a way to encode unescaped JSON in Yii 1.x, and found the CJSON framework class for this purpose (so OOP).

Since it does not support unescaped JSON though, I had to revert back to the pure PHP, procedural, non-OOP approach of using json_encode($results, JSON_UNESCAPED_SLASHES);. However, I asked how to achieve the same with the Yii framework.

As an answer I received information that, while it does what I want, is not possible with the base framework and requires that I extend a base class. This proposed solution requires 12 lines of code and involves creation of a separate file, while my solution requires just 1 new line of code.

Just to feed my curiosity - what is more important in situations like this? Should I follow KISS and make my code as simple as possible, even reverting to procedural code, or should I stick to OOP solutions and always extend classes if I can't do what I need with existing framework code?

答:
Comparing procedural code and OOP is like comparing apples and oranges. Sometimes, one leads to a better design, sometimes the other and sometimes neither.

In languages that support a mixture of OO and procedural code (which is the large majority of OO languages), it can make sense to sub-class an existing class if

the base class is open for extension (not sealed, final, whatever it is called in your language of choice), and

your extension must be used by another class, that takes (a reference to) the base class as dependency, or

your extension is applicable only in some situations, but it must also seamlessly handle the situations that the base class caters for, or

your extension needs access to parts of the base class, or

the code using the extension will mostly use it in conjunction with the base class.

If none of that holds, then you should go for whatever leads to the simplest code, be it a class, extension or procedure (or just a procedure call in this case).


答:
Would a random (adequately skilled) programmer, tasked with making changes to your code readily identify what you were doing one way or the other?  Would potential future changes be easier or harder one way or the other?

Using your example above, I would prefer to find an extended class.  This would indicate to me that the logic related to the unescaped JSON was there and not somewhere else.  It would also allow for easier re-use of the same bit of logic somewhere else.

Title: Is the KISS principle more important than utilizing OOP to solve a problem?

Body:
I'm a PHP developer coding in the Yii 1.x framework. I was looking for a way to encode unescaped JSON in Yii 1.x, and found the CJSON framework class for this purpose (so OOP).

Since it does not support unescaped JSON though, I had to revert back to the pure PHP, procedural, non-OOP approach of using json_encode($results, JSON_UNESCAPED_SLASHES);. However, I asked how to achieve the same with the Yii framework.

As an answer I received information that, while it does what I want, is not possible with the base framework and requires that I extend a base class. This proposed solution requires 12 lines of code and involves creation of a separate file, while my solution requires just 1 new line of code.

Just to feed my curiosity - what is more important in situations like this? Should I follow KISS and make my code as simple as possible, even reverting to procedural code, or should I stick to OOP solutions and always extend classes if I can't do what I need with existing framework code?


问:
What is the most robust, extensible way to represent a contract in code?
I would like to find or create a syntax to express business contracts programmatically, and I am looking for a robust, flexible, future-resistant way to do this.

A client should be able to add a negotiation points of varying types to the contract.

An example of a boolean negotiation point:

"There is a pre-payment penalty?" (yes/no)

While the above is certainly doable, it seems more difficult to describe the relationships between the negotiation points in an abstract way.

Some examples:

$600 is paid by "Client A" for inspection.

The above amount is paid by "Client B" if condition Y (information that should have been disclosed before the inspection was not disclosed).

Some other possible functionality:

Virtual fields are calculated based on the numeric values of other fields.

Notes:

It certainly seems like XML or possibly JSON-schema are possible candidates for describing the above.  But I am open to other options.

http://en.wikipedia.org/wiki/List_of_XML_markup_languages

Many thanks,

答:
The biggest problem is the huge set of assumptions that you so easily skip.

Just take your example: "$600 is paid by Client A for inspection"

USD or other dollar?

Paid when?

To whom?

What counts as an inspection?

Is this a mandatory payment, or only incurred if A opts to do the inspection?

Are multiple inspections allowed, If so, is this per inspection?

Your DSL will need to deal with all this complexity. For contracts in English, lawyers have already developed ways to resolve such issues, and even prevent them by reviewing draft contracts.


答:
The question is in effect: "What does it mean to own an email domain?".

Owning a website is defined by the ability to put a file in the root. Ordinary users may be able to put a file on http://example.com/~user42/validation.txt but not on http://example.com/validation.txt.

For email, there's no such hierarchy. However, the postmaster address is special. (Reserved per RFC2142) You won't be able to create postmaster@gmail.com. Thus, the ability to create and/or access postmaster@ is the proof you need for email domain ownership.

Title: How to validate a given domain is owned by the user?

Body:
I'm writing a software which will be used mostly by companies.

I then had the idea to give companies a way to register their email domain so that every user which registers with an email of the given domain will be automatically put in the company group.

I know Slack does something like this and it works, but there are some problems... for example I've just registered "live.it" (the live.com italian version by Microsoft).

I can't just assume that if an user has validated an email with a specific domain then it's safe to put every user with the same domain_mail in the same group.

For example, if I register with me@gmail.com I don't want to let user register "gmail.com" has its own domain.

I'd like to avoid use of methods like "put an html file in the root of the domain" or "set a TXT record" so I was wondering how should I do.


答:
Just to feed my curiosity, I'd like to ask, what is more important in situations like that? Should I follow KISS and make my code as simple as possible, even reverting sometimes to procedural code, or should I bound myself to OOP and always use extended classes, if I can't get, what I want, out of base code?

As Tim Peters said "Practicality beats purity".

Unless you have strict requirements one way or another (e.g. an obsessive-compulsive code reviewer with a gun, that knows where you live) you should optimize your code for maintenance. In other words, choose the one that is easier to figure/maintain/extend/reuse/fix.

That said, this is not a KISS vs. OOP issue as much as it is a "practicality vs. purity" issue (the best OOP code is simple, not in opposition to KISS).


问:
Are there any serialization schemes for OOP that include methods or operations in the contract in addition to data structure?
So typically we create schemas, mime-types, etc for our objects when we're communicating to another system about objects.

The document usually defines data structure of the objects for serialization purposes with no recording of the object's methods.  All I am left with on the client are effectively structs with no methods.

So for example let's say I have multiple classes and let's say those included an Account and an Order.  Let's also specify that orders are tied to an account.  Now let's say I have a client who wants to fetch a certain order that's related to an account from a distributed service that provides this information.  I could code all of the searching, scanning and other types of logic into the distributed server and make the client rely on it for everything it could want to do (extreme RPC).  I could just write code to scan through object graphs on the client, forcing each client with type of interest to replicate the code.  I could create a library that contains common functions.   But what I'd really like, is the ability to replicate methods on the object to the client as part of the contract.  The client would not only know the data structure of the distributed object, but could also call and execute operations on the object that was distributed with it.

Is there any system out there that serializes operations\code along with data structure for objects?  Ideally it shouldn't just be an RPC client stub that invokes operations on a server.

答:
I think the reason this isn't done more often is because you're sending code along with your data, and therefore you no longer have total control over the code.  Maintaining security over your operations would be a real challenge.  This is not true of data, because you can sanitize, validate and authorize data, using code that you can control and secure.

Code is also not homogeneous, in the same way data is.  Many different programming languages and techniques are used to create data processing systems, but the data remains in essentially the same form.  This is especially true of XML data.  XML data is specifically designed to be systems-agnostic; you can process it on any system with and XML reader.

If you want to look for a live example of code as data, you need look no farther than Lisp. Lisp has a deep philosophy of "code as data." In "The Nature of Lisp," the author explained this distinction by pointing out that you can translate any programming language to XML, transmit it over the wire, and execute it:

```<code><define-function return-type="int" name="add">
    <arguments>
        <argument type="int">arg1</argument>
        <argument type="int">arg2</argument>
    </arguments>
    <body>
        <return>
            <add value1="arg1" value2="arg2" />
        </return>
    </body>
</define>
</code>```

So all you have to do is send the source code in your transmitted object, compile it at the target, and execute it against your encapsulated data. :)

Your "serialization of code" then boils down to "include the necessary source code to process this object with every packet of data you send."  I think you can see how this can quickly become very unwieldy.  If you're going to transmit programs to a remote system that will operate on data you send it, it makes more sense to transmit those programs to the remote system ahead of time, install them, execute them, and then send your data.

Body:
I think the reason this isn't done more often is because you're sending code along with your data, and therefore you no longer have total control over the code.  Maintaining security over your operations would be a real challenge.  This is not true of data, because you can sanitize, validate and authorize data, using code that you can control and secure.

Code is also not homogeneous, in the same way data is.  Many different programming languages and techniques are used to create data processing systems, but the data remains in essentially the same form.  This is especially true of XML data.  XML data is specifically designed to be systems-agnostic; you can process it on any system with and XML reader.

If you want to look for a live example of code as data, you need look no farther than Lisp. Lisp has a deep philosophy of "code as data." In "The Nature of Lisp," the author explained this distinction by pointing out that you can translate any programming language to XML, transmit it over the wire, and execute it:

<define-function return-type="int" name="add">
    <arguments>
        <argument type="int">arg1</argument>
        <argument type="int">arg2</argument>
    </arguments>
    <body>
        <return>
            <add value1="arg1" value2="arg2" />
        </return>
    </body>
</define>

So all you have to do is send the source code in your transmitted object, compile it at the target, and execute it against your encapsulated data. :)

Your "serialization of code" then boils down to "include the necessary source code to process this object with every packet of data you send."  I think you can see how this can quickly become very unwieldy.  If you're going to transmit programs to a remote system that will operate on data you send it, it makes more sense to transmit those programs to the remote system ahead of time, install them, execute them, and then send your data.


答:
Could you afford avoiding the use of free webmails for registration?

That's what Brium does: you can't sign-in with an @gmail.com, @live.com, etc e-mail - you have to use your own.

And it clusters you by this.

If you are targeting businesses, that should be a good way to go.

You could still have the problem of knowing who the boss is (say, the admin of that group), but it may not be that important - the boss should probably have the tools for telling any employee to transfer the ownership to him, provided someone registered before the boss.


问:
Email service or simply abstract email out and call from?
Got a fairly large web application in asp.net using C#.  Also have a mobile setup using a common api that we wrote to basically share data across both of our apps using web methods and common classes.

Email was initially thrown together in maybe two days using a simple email class and some basic properties.

For instance, once a record is created we send an email.  Imagine a crm type system such that when an account or a customer is created an email is sent.  The thing I dislike the most is we're calling it right from within for instance the presentation layer:

```<code>MyAPI.SaveCompany(company object);
Email.SendMail(...);
</code>```

For the mobile application we've got a web service to for instance save a company just like above.  Then just as shown above after saving a company we do the same thing Email.SendMail right within the web method.

Its time to fix this as to me it just feels wrong.  What do you guys recommend I do?

Should this be a standalone service that sends emails based on events in a database table that keeps track of all these events,

Or should I just create an email class like I already have and just call it somewhere else?

I thought about just calling it right when I call SaveCompany (inside this method) and then I wouldn't have to worry about my web UI or my mobile since its inside SaveCompany it would call it automatically.  But then this feels wrong as it ties up my manager class (my API) to some physical email implementation.

Can someone please give me some hints or how they accomplish this possibly a look at their design or thought process.

As mentioned this is ASP.NET Web Forms, C#, a lot of jQuery, and SQL Server 2008.

答:
Basically, you have two issues here:

E-mails are dispatched from presentation layer,

The API is tied up to physical e-mail implementation.

The first issue is solved by the first step of moving the code where it belongs: in business layer. You shouldn't save companies from presentation layer, and you shouldn't send e-mails from there: move all this code where it belongs to, and focus presentation layer on presentation, i.e. generation of HTML code or JSON or XML from a model.

Business layer:

public class Example
{
    public void ProcessSamplePage(...)
    {
        CustomerManagement.Create(...);
        SmtpService.NotifyCustomerRegistered(...);
        var model = ...
        Presentation.GenerateHtml(model);
    }
}
```

<p>Moving from ASP.NET to ASP.NET MVC may help avoiding such errors in future.</p>

<p>The next step is Dependency Injection, which also solves the second problem. Instead of using a specific class provided by .NET Framework to send e-mails directly from your business layer, you can create an interface which will have a specific method for <em>dispatching messages</em>, and then using whatever implementation you want. Dispatching message can mean sending an actual e-mail through .NET Framework, sending an e-mail through a third-party library, sending an e-mail by manually connecting to SMTP server, storing a text file in a directory where the SMTP service will pick it or... storing the message in the database.</p>

<p>Business layer:</p>

<pre class="lang-cs prettyprint-override"><code>public class Example
{
    public Example(IMessagesDispatcher dispatcher) { ... }

    public void ProcessSamplePage(...)
    {
        CustomerManagement.Create(...);
        this.dispatcher.NotifyCustomerRegistered(...);
        var model = ...
        Presentation.GenerateHtml(model);
    }
}
</code>```

Now that you can store messages in the database instead of just sending them through e-mails, you can imagine more complex scenarios, such as a Windows Service which checks regularly the database and sends pending e-mails. This also allows to control the load of SMTP server: if you have to send hundreds of e-mails per second between 2 PM and 3 PM, but only a few dozen e-mails per minute at night, you can reschedule low-priority e-mails to be actually dispatched at night.

Body:
Basically, you have two issues here:

E-mails are dispatched from presentation layer,

The API is tied up to physical e-mail implementation.

The first issue is solved by the first step of moving the code where it belongs: in business layer. You shouldn't save companies from presentation layer, and you shouldn't send e-mails from there: move all this code where it belongs to, and focus presentation layer on presentation, i.e. generation of HTML code or JSON or XML from a model.

Business layer:

public class Example
{
    public void ProcessSamplePage(...)
    {
        CustomerManagement.Create(...);
        SmtpService.NotifyCustomerRegistered(...);
        var model = ...
        Presentation.GenerateHtml(model);
    }
}

Moving from ASP.NET to ASP.NET MVC may help avoiding such errors in future.

The next step is Dependency Injection, which also solves the second problem. Instead of using a specific class provided by .NET Framework to send e-mails directly from your business layer, you can create an interface which will have a specific method for dispatching messages, and then using whatever implementation you want. Dispatching message can mean sending an actual e-mail through .NET Framework, sending an e-mail through a third-party library, sending an e-mail by manually connecting to SMTP server, storing a text file in a directory where the SMTP service will pick it or... storing the message in the database.

Business layer:

public class Example
{
    public Example(IMessagesDispatcher dispatcher) { ... }

    public void ProcessSamplePage(...)
    {
        CustomerManagement.Create(...);
        this.dispatcher.NotifyCustomerRegistered(...);
        var model = ...
        Presentation.GenerateHtml(model);
    }
}

Now that you can store messages in the database instead of just sending them through e-mails, you can imagine more complex scenarios, such as a Windows Service which checks regularly the database and sends pending e-mails. This also allows to control the load of SMTP server: if you have to send hundreds of e-mails per second between 2 PM and 3 PM, but only a few dozen e-mails per minute at night, you can reschedule low-priority e-mails to be actually dispatched at night.


答:
Depending on your setup, email can occasionally take an unreasonable quantity of time to respond, and it can fail ambiguously and need retries.  So I would suggest that this is one of the times when a service is in order.  Either in the form of a service of your own, or of an SMTP server you have control over.

The local SMTP server presents a better-known interface, which mediates the other issues, but I generally favor the situation where the status of the database is what causes the sending of messages asynchronously.

The best solution I have seen is for email to be integrated into a workflow service that keeps track of who has done what and whom that enables to do what next.  Then you can send email with effective links in them, but know when those links are no longer applicable.

Title: Email service or simply abstract email out and call from?

Body:
Got a fairly large web application in asp.net using C#.  Also have a mobile setup using a common api that we wrote to basically share data across both of our apps using web methods and common classes.

Email was initially thrown together in maybe two days using a simple email class and some basic properties.

For instance, once a record is created we send an email.  Imagine a crm type system such that when an account or a customer is created an email is sent.  The thing I dislike the most is we're calling it right from within for instance the presentation layer:

```<code>MyAPI.SaveCompany(company object);
Email.SendMail(...);
</code>```

For the mobile application we've got a web service to for instance save a company just like above.  Then just as shown above after saving a company we do the same thing Email.SendMail right within the web method.

Its time to fix this as to me it just feels wrong.  What do you guys recommend I do?

Should this be a standalone service that sends emails based on events in a database table that keeps track of all these events,

Or should I just create an email class like I already have and just call it somewhere else?

I thought about just calling it right when I call SaveCompany (inside this method) and then I wouldn't have to worry about my web UI or my mobile since its inside SaveCompany it would call it automatically.  But then this feels wrong as it ties up my manager class (my API) to some physical email implementation.

Can someone please give me some hints or how they accomplish this possibly a look at their design or thought process.

As mentioned this is ASP.NET Web Forms, C#, a lot of jQuery, and SQL Server 2008.


问:
Is there ever a reason to do all an object's work in a constructor?
Let me preface this by saying this is not my code nor my coworkers' code. Years ago when our company was smaller, we had some projects we needed done that we did not have the capacity for, so they were outsourced. Now, I have nothing against outsourcing or contractors in general, but the codebase they produced is a mass of WTFs. That being said, it does (mostly) work, so I suppose it's in the top 10% of outsourced projects I've seen.

As our company has grown, we've tried to take more of our development in house. This particular project landed in my lap so I've been going over it, cleaning it up, adding tests, etc etc.

There's one pattern I see repeated a lot and it seems so mindblowingly awful that I wondered if maybe there is a reason and I just don't see it. The pattern is an object with no public methods or members, just a public constructor that does all the work of the object.

For example, (the code is in Java, if that matters, but I hope this to be a more general question):

public class Foo {
  private int bar;
  private String baz;

  public Foo(File f) {
    execute(f);
  }

  private void execute(File f) {
     // FTP the file to some hardcoded location,
     // or parse the file and commit to the database, or whatever
  }
}
```
<p>If you're wondering, this type of code is often called in the following manner:</p>
<pre class="lang-java prettyprint-override"><code>for(File f : someListOfFiles) {
   new Foo(f);
}
</code>```

Now, I was taught long ago that instantiated objects in a loop is generally a bad idea, and that constructors should do a minimum of work. Looking at this code it looks like it would be better to drop the constructor and make execute a public static method.

I did ask the contractor why it was done this way, and the response I got was "We can change it if you want". Which was not really helpful.

Anyway, is there ever a reason to do something like this, in any programming language, or is this just another submission to the Daily WTF?

答:
There are patterns common in languages where functions and classes are much more the same thing, like Python, where one uses an object basically to be function with too many side-effects or with multiple named objects returned.

In this case, the bulk, if not all of the work may be done in the constructor, as the object itself is just a wrapper around a single bundle of work, and there is no good reason to stuff it into a separate function.  Something like

```<code>var parser = XMLParser()
var x = parser.parse(string)
string a = x.LookupTag(s)
</code>```

is really no better than

```<code> var x = ParsedXML(string)
 string a = x.LookupTag(s)
</code>```

Instead of directly having the side effects outright, you can call the object to enforce the side-effect on cue, which gives you better visibility.  If I am going to have a bad side effect on an object, I can do all my work and then get passed the object I will badly effect and do my damage to it.  Identifying the object and isolating the call this way is clearer than passing multiple such objects into a function at once.

```<code>x.UpdateView(v)
</code>```

You can make the multiple return values through accessors on the object.  All the work is done, but I want the stuff all in context, and I don't really want to pass multiple references into my function.

```<code>var x = new ComputeStatistics(inputFile)
int max = x.MaxOptions;
int mean = x.AverageOption;
int sd = x.StandardDeviation;
int k = x.Kurtosis;
...
</code>```

So as a joint Python/C# programmer, this does not seem all that weird to me.

Body:
There are patterns common in languages where functions and classes are much more the same thing, like Python, where one uses an object basically to be function with too many side-effects or with multiple named objects returned.

In this case, the bulk, if not all of the work may be done in the constructor, as the object itself is just a wrapper around a single bundle of work, and there is no good reason to stuff it into a separate function.  Something like

var parser = XMLParser()
var x = parser.parse(string)
string a = x.LookupTag(s)

is really no better than

 var x = ParsedXML(string)
 string a = x.LookupTag(s)

Instead of directly having the side effects outright, you can call the object to enforce the side-effect on cue, which gives you better visibility.  If I am going to have a bad side effect on an object, I can do all my work and then get passed the object I will badly effect and do my damage to it.  Identifying the object and isolating the call this way is clearer than passing multiple such objects into a function at once.

x.UpdateView(v)

You can make the multiple return values through accessors on the object.  All the work is done, but I want the stuff all in context, and I don't really want to pass multiple references into my function.

var x = new ComputeStatistics(inputFile)
int max = x.MaxOptions;
int mean = x.AverageOption;
int sd = x.StandardDeviation;
int k = x.Kurtosis;
...

So as a joint Python/C# programmer, this does not seem all that weird to me.


问:
Question about requirements
I know that functional requirements are requirements that tell the system what to do while non-functional requirements are about quality and constraints. For below requirements, which of these will fall under non-functional or functional?

UI must be graphical in nature. I would put this under non-functional requirements because it talks about the quality of the system. I am not too sure.

Users must be able to view information instantly. This could be functional but at the same time, the adverb 'instantly' could be related to performance. So that could also fall under non-functional requirements

Every user should run on a separate client process. This tells the system to run a process for each user. This could be functional, although I am not too sure, as this could be related how the system is implemented.

答:
This isn't a requirement, it's an implementation detail. Requirements say what needs to happen, not how.

Amusingly impossible, this is a requirement that you need to push back on to see what people really want.

Again, not a requirement.

In short, it doesn't matter how you label your requirements - it matters that they're good requirements.

Title: Question about requirements


答:
Seeing in your comments that you might not prefer to use the file-in-root-of-website method, an alternative which might work is to

Verify ownership using WHOIS

You would need to get the domain being requested (for example stackexchange.com), and one of the emails listed in the WHOIS output for that domain. (Note that this won't work for secret/private registrations, but if your audience is corporations this usually isn't a problem)

For example:

```<code>WHOIS information for stackexchange.com:**
...
Domain Name: STACKEXCHANGE.COM
Registrar WHOIS Server: whois.name.com
Registrar URL: http://www.name.com
Updated Date: 2014-05-14T16:49:02-06:00

Registrant Name: Sysadmin Team
...
Registrant Email: sysadmin-team@stackoverflow.com
Admin Name: Sysadmin Team
Admin Organization: Stack Exchange, Inc.
...
Admin Email: sysadmin-team@stackoverflow.com
Tech Name: Sysadmin Team
...
Tech Email: sysadmin-team@stackoverflow.com
Name Server: cf-dns02.stackexchange.com
Name Server: cf-dns01.stackexchange.com
DNSSEC: NotApplicable
</code>```

You could even do the whois lookup interactively and provide a dropdown list of the valid emails (in this case, just sysadmin-team@stackoverflow.com). You would then send a verification code/link to the chosen email.

Body:
Seeing in your comments that you might not prefer to use the file-in-root-of-website method, an alternative which might work is to

Verify ownership using WHOIS

You would need to get the domain being requested (for example stackexchange.com), and one of the emails listed in the WHOIS output for that domain. (Note that this won't work for secret/private registrations, but if your audience is corporations this usually isn't a problem)

For example:

WHOIS information for stackexchange.com:**
...
Domain Name: STACKEXCHANGE.COM
Registrar WHOIS Server: whois.name.com
Registrar URL: http://www.name.com
Updated Date: 2014-05-14T16:49:02-06:00

Registrant Name: Sysadmin Team
...
Registrant Email: sysadmin-team@stackoverflow.com
Admin Name: Sysadmin Team
Admin Organization: Stack Exchange, Inc.
...
Admin Email: sysadmin-team@stackoverflow.com
Tech Name: Sysadmin Team
...
Tech Email: sysadmin-team@stackoverflow.com
Name Server: cf-dns02.stackexchange.com
Name Server: cf-dns01.stackexchange.com
DNSSEC: NotApplicable

You could even do the whois lookup interactively and provide a dropdown list of the valid emails (in this case, just sysadmin-team@stackoverflow.com). You would then send a verification code/link to the chosen email.


问:
Value Object: static factory or assisted injection?
First let assume that everybody agree that there is nothing wrong with injecting some value object into injectable object such as service. Indeed, a service can get another service injected, but could along the way get some configuration information as well. Configuration information that would be represented as Value object.

Now let's talk about using DI framework, on value object directly.
(I intentionally do not say, let's apply dependency injection on value object, because i see the critics coming about what is a dependency and etc...)

Here is what can be red everywhere:

Using DI for Value object is wrong or useless. They are newable. They
  do not have real dependency.

In general i would first disagree with the idea of "newable".

I think it is a good practice to use Factories anyway. It leaves you
  some control over how exactly the object is created and what strategy,
  you may use behind and etc...

The factory itself could be configured and etc...One could even think about changing the implementation instantiated for the given interface of a value object, based on the operating system constraint or whatever condition you may think of....

Let us now assume that we all agree to use factories for value object creation. Building on that, I would like to develop the following point:  Can a DI be used as a simple factory tool, when it comes to value objects?

Why I'm asking this:

Because i want to use factories as exposed above. I don't want to
  scattered around my value object creation. (Is that legitimate ?)

This means that i will definitely use assisted-injection all the time to create my value object (The other way would be to use static factories in my code).

In essence using a DI as factory container for you value object, means that you will be likely to pass factories as parameter of your services, to allow them to create those value objects.

Which one do you use? why ? Why would you be against one or the other ?

Do you prefer to use a static (Singleton / anti-pattern ?) in the middle of your service code, or you would rather inject your factory, weather it via a DI or a factories that non static ?

答:
I reject the premise of your question. Value objects, by definition, are immutable data classes that only use other value objects or primitives. I'll say that again: value objects have no dependencies, so there is no need to use an IoC-style pattern such as Abstract Factory*. A value object with dependencies is not a value object.

So, in the interest of simple design and understandable code, you should just new up your value object(s) unless you have a really compelling reason not to. Anything more complicated is overengineering.

The only use case I can think of for not using the constructor directly is if you need to choose between a number of subclasses of your value object based on some condition. (I am skeptical about how often this really happens.) In that case I would use a static factory method, not dependency injection.

* I don't think it's a good idea to use IoC for anything that is not a dependency. In particular, you should avoid using a container for classes in your domain model.

OwnerDisplayName: MaatDeamon


问:
How to handle a large amount of authenticated clients
I currently have made a multithreaded server in c++ for windows, where each connected client gets a thread to themselves which stays running until the client's socket is closed.

When a client connects, they can run commands (fetch motd, get current version of the client) or can login to get access to other commands (fetch user information, download files, etc).

So far this basic approach has worked well, but I have noticed that there have been an increasing amount of clients using my service and I'm starting to worry about how efficient this approach is.  I've read online that a process in windows can only handle somewhere around 1500-2000 threads, and I think I might soon hit that amount of simultaneous users, and I think it's about time I changed my design around.

What would be the best way to handle this amount of users?

答:
You don't mention how many users you think this thing is going to scale to, and if that number is unlimited or unknown (but growing) this isn't going to scale very well in the long run.

One way to do this is that you keep a pool of authenticated user IDs with some sort of expiry value of 15 minutes or something. If a user makes a request, your logic should check to see if they are logged in and within the expiry limit (also reset this limit) if they are outside the expiry limit, ask them to log in again.

It seems that you're going to also run into trouble if you keep it this way but expand your server horizontally and do load balancing. Race conditions may or may not affect you in this instance.

Just some naive thoughts, but it seems like the goal would be to push multiple users using a single thread and keep a ratio of n users to 1 thread based on load and blocking.


答:
No, it's not "necessary"

The principles of Agile say nothing directly about testing.

But It's Highly Advisable

Given Agile's commitment to a sustainable process, continuous/incremental delivery, and software quality, automated testing is the best solution currently available for most projects

Exceptions (as noted by Jörg W Mittag) include provably-correct development tools, meta-programming systems that generate code, et al. But these kinds of systems are rare.


答:
Ask your users to add a TXT record to their domain with a reference to their user account on your site (their username, ID, or an arbitrary token generated when asking the user to verify their domain).

I remember adding a record called adn_verification=<my user name> on a social network to display my domain as verified, and I thought that's pretty neat and doesn't require you to have the domain pointing to a web server.


问:
Converting cron schedule to time intervals
I have, on the server, many jobs defined by users and some of those jobs are scheduled using cron expressions. I need to check (I can execute Groovy/Java on the server) if those jobs take longer than they are scheduled (I mean job is taking 10 minutes, but scheduled to run every 5 minutes).

I have been trying to find something that converts cron expression to time interval(s). This seems to be doing pretty good job converting cron expressions to human-readable strings, but what about getting the shortest time interval?

Is the solution to recursively loop from years to seconds and add every time found to list, calculate each time interval and find the smallest from there? Or does a better way exist?

Example, say we have a cron expression: 0 0 11,16,19,21 * * *
This translates to: Every year every month every day at 11:00, 16:00, 19:00 and 21:00. That gives us intervals: 5h, 3h, 2h and 14h. I am interested in the shortest interval - 2h.

I do understand that this can quickly get very complex and result in gazillion intervals, but I was randomly looking thru the expressions that I would need to calculate and they are rather easy. While waiting here for an answer, I discovered Quartz library. I can give it a cron expression and simply ask it "when is next, when is next etc".  So if I'd ask.. say 5 times, I probably have most of my cases covered. I have to check how it performs. If anybody has a better solution, I warmly welcome it.

答:
If you need to consider multiple crontab entries for the same task, you will have to iterate through a full 400-year Gregorian cycle.  For example:

```<code>59 23 29 2 * me /home/me/mytask # 11:59 Feb 29
01 00  1 3 * me /home/me/mytask # 00:01 Mar 1
</code>```

These events will occur two minutes apart every leap year

Worse:

```<code>59 23 29 2 * me /home/me/mytask # 11:59 Feb 29
01 00  * * 0 me /home/me/mytask # 00:01 Sunday
</code>```

These events will occur two minutes apart when Feb 29 falls on Saturday.

Another difficult case for systems where the cron daemon uses local time:

```<code>0 1,3 * * * me /home/me/mytask # 01:00 and 03:00
</code>```

These jobs will run two hours apart except on the morning when DST begins.  On that morning they will run one hour apart.

Body:
If you need to consider multiple crontab entries for the same task, you will have to iterate through a full 400-year Gregorian cycle.  For example:

59 23 29 2 * me /home/me/mytask # 11:59 Feb 29
01 00  1 3 * me /home/me/mytask # 00:01 Mar 1

These events will occur two minutes apart every leap year

Worse:

59 23 29 2 * me /home/me/mytask # 11:59 Feb 29
01 00  * * 0 me /home/me/mytask # 00:01 Sunday

These events will occur two minutes apart when Feb 29 falls on Saturday.

Another difficult case for systems where the cron daemon uses local time:

0 1,3 * * * me /home/me/mytask # 01:00 and 03:00

These jobs will run two hours apart except on the morning when DST begins.  On that morning they will run one hour apart.


答:
One case comes to mind where the constructor/destructor does all the work:

Locks.  You normally never interact with a lock during it's lifetime.  C#'s using architecture is good for handling such cases without explicitly referring to the destructor.  Not all locks are implemented this way, though.

I have also written what amounted to a constructor-only bit of code to patch a runtime library bug.  (Actually fixing the code would have caused other problems.)  There was no destructor because there was no need to undo the patch.

Title: Is there ever a reason to do all an object's work in a constructor?

Body:
Let me preface this by saying this is not my code nor my coworkers' code. Years ago when our company was smaller, we had some projects we needed done that we did not have the capacity for, so they were outsourced. Now, I have nothing against outsourcing or contractors in general, but the codebase they produced is a mass of WTFs. That being said, it does (mostly) work, so I suppose it's in the top 10% of outsourced projects I've seen.

As our company has grown, we've tried to take more of our development in house. This particular project landed in my lap so I've been going over it, cleaning it up, adding tests, etc etc.

There's one pattern I see repeated a lot and it seems so mindblowingly awful that I wondered if maybe there is a reason and I just don't see it. The pattern is an object with no public methods or members, just a public constructor that does all the work of the object.

For example, (the code is in Java, if that matters, but I hope this to be a more general question):

public class Foo {
  private int bar;
  private String baz;

  public Foo(File f) {
    execute(f);
  }

  private void execute(File f) {
     // FTP the file to some hardcoded location,
     // or parse the file and commit to the database, or whatever
  }
}
```
<p>If you're wondering, this type of code is often called in the following manner:</p>
<pre class="lang-java prettyprint-override"><code>for(File f : someListOfFiles) {
   new Foo(f);
}
</code>```

Now, I was taught long ago that instantiated objects in a loop is generally a bad idea, and that constructors should do a minimum of work. Looking at this code it looks like it would be better to drop the constructor and make execute a public static method.

I did ask the contractor why it was done this way, and the response I got was "We can change it if you want". Which was not really helpful.

Anyway, is there ever a reason to do something like this, in any programming language, or is this just another submission to the Daily WTF?


问:
@SuppressWarnings in generic array declaration
While doing a coding test, I ran into a problem where I need to initialize an array of generic type in Java. While trying to figure out how to do that, I looked at this Stack Overflow question and it requires that I suppress a warning which doesn't seem like a good practice, and might have other type safety issues. For clarity, here is the code:

```<code>public class GenSet<E> {
  private E[] a;

  public GenSet(Class<E> c, int s) {
    // Use Array native method to create array
    // of a type only known at run time
    @SuppressWarnings("unchecked")
    final E[] a = (E[]) Array.newInstance(c, s);
    this.a = a;
  }

  E get(int i) {
    return a[i];
  }
}
</code>```

Does this mean I am going about the problem wrong? Is it ok to have the @SuppressWarnings("unchecked") in this case?

Should I just use an ArrayList?

答:
@SuppressWarnings("unchecked") is sometimes correct and unavoidable in well-written code. Creating an array of generic types is one case. If you can work around it by using a Collection<T> or List<T> of generics then I'd suggest that, but if only an array will do, then there's nothing you can do.

Casting to a generic type is another similar case. Generic casts can't be verified at runtime, so you will get a warning if you do, say

```<code>List<Integer> numbers = (List<Integer>) object;
</code>```

That doesn't make it bad style to have generic casts. It simply reflects a limitation of the way generics were designed in Java.

To acknowledge that I'm intentionally writing code with warnings, I've made it a rule to add a comment to any such lines. This makes the choice stand out. It also makes it easy to spot these lines, since @SuppressWarnings can't always be used directly on the target lines. If it's at the top of the method it might not be obvious which line or lines generate warnings.

```<code>((List<Integer>) object).add(1);   // warning: [unchecked] unchecked cast
</code>```

Also, to be clear, you should not work around this with a raw type (List instead of List<T>). That is a bad idea. It will also produce warnings if you enable -Xlint, so wouldn't really make the situation any better, anyways.

Body:
@SuppressWarnings("unchecked") is sometimes correct and unavoidable in well-written code. Creating an array of generic types is one case. If you can work around it by using a Collection<T> or List<T> of generics then I'd suggest that, but if only an array will do, then there's nothing you can do.

Casting to a generic type is another similar case. Generic casts can't be verified at runtime, so you will get a warning if you do, say

List<Integer> numbers = (List<Integer>) object;

That doesn't make it bad style to have generic casts. It simply reflects a limitation of the way generics were designed in Java.

To acknowledge that I'm intentionally writing code with warnings, I've made it a rule to add a comment to any such lines. This makes the choice stand out. It also makes it easy to spot these lines, since @SuppressWarnings can't always be used directly on the target lines. If it's at the top of the method it might not be obvious which line or lines generate warnings.

((List<Integer>) object).add(1);   // warning: [unchecked] unchecked cast

Also, to be clear, you should not work around this with a raw type (List instead of List<T>). That is a bad idea. It will also produce warnings if you enable -Xlint, so wouldn't really make the situation any better, anyways.


答:
The question of 'should' finds its way into a number of other situations.  In the world of devops where programmers take what is seen as traditionally IT roles, the line gets very blurry. In other worlds such as banks or anything that handles money (or health care and hipaa), the question is a resounding 'no' with no further elaboration necessary.

Lets look at how one of those money handling areas handles it.  The PCI DSS (Payment Card Industry (i.e.: Visa, Mastercard and the like) Data Security Standard) has some rather specific points on this subject.

There are specific requirements in the DSS such as 3.5.1:

Restrict access to cryptographic keys to the fewest number of custodians necessary.

or 6.4.2:

Separation of duties between development/test and production environments

This last one specifically speaks to what you are asking and in the guidance section reads:

Reducing the number of personnel with access to the production environment and cardholder data minimizes risk and helps ensure that access is limited to those individuals with a business need to know.

The intent of this requirement is to separate development and test functions from production functions. For example, a developer may use an administrator-level account with elevated privileges in the development environment, and have a separate account with user-level access to the production environment.

This means that if you are wearing a developer hat, you shouldn't have administrative access on the production environment.  One can argue that you can switch hats (and all associated environments - here's the "you are on call and have admin access laptop that you don't do development on - and don't do admin things from your development machine."), but that gets into how management wants to claim they are meeting the requirements.

So, should devs have access to production?  Sure - reading logs and the like is very helpful and a pain to have to go through IT and/or Operations organizations to get access to.  Should devs have admin access to production? Depends on what they are doing and what the various regulations say.

If you are at a small shop that doesn't have the personnel, or infrastructure, or requirement that you don't have access you are likely to find yourself with admin access no mater if you like it or not and be asked to do admin things on it from time to time.

It really depends on where you are and how much red tape there is to protect production from the devs (because there are few things as fun as accidentally pushing code or editing live code on production).

The life of someone who has access to production is always 'interesting'.


答:
Based on the fact you are asking if you should use ArrayList instead, I assume the use of an array is not a requirement. I would use the ArrayList or other collection and rely on interfaces, not implementations, to reference it:

```<code>List<Integer> myInts = new ArrayList<Integer>();
myInts.add(4);
</code>```

Java generics are in a tough position. On one hand, Java has the self-imposed (but good) goal of being backwards compatible. Since generics are essentially incompatible with pre-1.5 bytecode, this results in type erasure. Essentially, the generic type is removed at compile time and generic method calls and accesses are reinforced with type casts instead. On the other hand, this limitation makes generic references really messy sometimes to the point that you must use @SuppressWarnings for unchecked and raw types at times.

What this means is that collections that rely on method calls to insulate users of a collection from the storage work fine, but arrays are reified which means that per the language, array types must be available at runtime. This runs counter to collections which as I mentioned have the generic type erased. Example:

```<code>String[] array1 = new String[1];
Object[] array2 = array1;
</code>```

Despite the reference array2 being declared as Object[], the JVM knows the array it targets can only hold strings. Because these types are reifable, they are essentially incompatible with generics.

StackOverflow has many questions on the topic of Java generics and arrays, here are a few good ones I found:

How to: generic array creation

Generic arrays in Java

Title: @SuppressWarnings in generic array declaration

Body:
While doing a coding test, I ran into a problem where I need to initialize an array of generic type in Java. While trying to figure out how to do that, I looked at this Stack Overflow question and it requires that I suppress a warning which doesn't seem like a good practice, and might have other type safety issues. For clarity, here is the code:

```<code>public class GenSet<E> {
  private E[] a;

  public GenSet(Class<E> c, int s) {
    // Use Array native method to create array
    // of a type only known at run time
    @SuppressWarnings("unchecked")
    final E[] a = (E[]) Array.newInstance(c, s);
    this.a = a;
  }

  E get(int i) {
    return a[i];
  }
}
</code>```

Does this mean I am going about the problem wrong? Is it ok to have the @SuppressWarnings("unchecked") in this case?

Should I just use an ArrayList?

Body:
Based on the fact you are asking if you should use ArrayList instead, I assume the use of an array is not a requirement. I would use the ArrayList or other collection and rely on interfaces, not implementations, to reference it:

List<Integer> myInts = new ArrayList<Integer>();
myInts.add(4);

Java generics are in a tough position. On one hand, Java has the self-imposed (but good) goal of being backwards compatible. Since generics are essentially incompatible with pre-1.5 bytecode, this results in type erasure. Essentially, the generic type is removed at compile time and generic method calls and accesses are reinforced with type casts instead. On the other hand, this limitation makes generic references really messy sometimes to the point that you must use @SuppressWarnings for unchecked and raw types at times.

What this means is that collections that rely on method calls to insulate users of a collection from the storage work fine, but arrays are reified which means that per the language, array types must be available at runtime. This runs counter to collections which as I mentioned have the generic type erased. Example:

String[] array1 = new String[1];
Object[] array2 = array1;

Despite the reference array2 being declared as Object[], the JVM knows the array it targets can only hold strings. Because these types are reifable, they are essentially incompatible with generics.

StackOverflow has many questions on the topic of Java generics and arrays, here are a few good ones I found:

How to: generic array creation

Generic arrays in Java


答:
To add to the suggestions already on the page: I recommend to give the user options in how he validates his domain. The other suggestions on the page are all perfectly usable, but sometimes you are in the situation where someone who wants to verify their domain only has limited access to their server or even their website. For example, your user might not be able to add domain records or files in the domain root.

For example, Troy Hunt allows users to search for an entire domain in his database of compromised accounts, but you need to verify first. He gives the user the choice of 4 methods:

Via email;

through a meta tag;

A file upload;

a TXT record.

In all 4 of these cases, he requires the user to enter a specific value somewhere which he verifies against.

The explanation is at http://www.troyhunt.com/2014/01/im-pwned-youre-pwned-were-all-pwned.html.


问:
C++: Metaprogramming with a compiler API rather than with C++ features
This started out as a SO question but I realized that it is quite unconventional and based on the actual description on the websites, it might be better suited to programmers.se since the question has a lot of conceptual weight.

I have been learning clang LibTooling and it is a very powerful tool capable of exposing the entire "nitty gritty" of the code in a friendly way, that is, in a semantic way, and not by guessing either. If clang can compile your code, then clang is certain about the semantics of every single character inside that code.

Now allow me to step back for a moment.

There are many practical problems that arise when one engages in C++ template metaprogramming (and especially when venturing beyond templates into the territory of clever albeit terrifying macros). To be honest, to many programmers, myself included, many of the ordinary uses of templates are also somewhat terrifying.

I guess a good example would be compile-time strings. This is a question that is over a year old now, but it is clear that C++ as of right now does not make this easy for mere mortals. While looking at these options isn't quite enough to induce nausea for me, it nevertheless leaves me unconfident about being able to produce magical, maximally efficient machine code to suit whatever fancy application I have for my software.

I mean, let's face it, folks, strings are pretty simple and basic. Some of us just want a convenient way to emit machine code that has certain strings "baked in" significantly more than we do get when coding it the straightforward way. In our C++ code.

Enter clang and LibTooling, which exposes the abstract syntax tree (AST) of the source code and allows a simple custom C++ application to correctly and reliably manipulate raw source code (using Rewriter) alongside a rich semantic object-oriented model of everything in the AST. It handles a lot of things. It knows about the macro expansions, and lets you follow those chains. Yes, I am talking about source-to-source code transformation or translation.

My fundamental thesis here is that clang now enables us to create executables which themselves can function as the ideal custom preprocessor stages to our C++ software, and we can implement these metaprogramming stages with C++. We are simply constrained by the fact that this stage must take input which is valid C++ code and produce as output more valid C++ code. Plus whatever other constraints your build system applies.

The input has to be at least very close to valid C++ code because, after all, clang is the compiler front-end and we are just poking around and being creative with its API. I do not know if there is any provision for being able to define new syntax to use, but clearly we have to develop the ways to properly parse it and add it to the clang project in order to do this. To expect any more is to have something in the clang project that is out of scope.

Not a problem. I would imagine that some no-op macro functions can handle this task.

Another way to look at what I'm describing is to implement metaprogramming constructs using runtime C++ by manipulating the AST of our source code (thanks to clang and its API) instead of implementing them using the more limited tools available in the language itself. This has clear compilation performance benefits as well (template-heavy headers slow compilation proportionally to how often you use them. Lots of compiled stuff then gets carefully matched up and thrown away by the linker).

This does, however, come at the cost of introducing an additional step or two in the build process and also in the requirement of writing some (admittedly) somewhat more verbose software (but at least it is straightforward runtime C++) as part of our tool.

That isn't the whole picture. I am pretty certain that there is a much larger space of functionality that can be had from generating code that is extremely difficult or impossible with core language features. In C++ you can write a template or a macro or a crazy combination of both, but in a clang tool you can modify classes and functions in ANY way that you can achieve with C++, at runtime, while having full access to the semantic content, in addition to template and macros and everything else.

So, I'm wondering about why everybody isn't already doing this. Is it that this functionality from clang is so new and nobody is familiar with the huge class hierarchy of clang's AST? That can't be it.

Perhaps I am just underestimating the difficulty of this a little bit, but doing "compile-time string manipulation" with a clang tool is nearly criminally simple. It's verbose, but it's insanely straightforward. All that's needed are a bunch of no-op macro functions that map to actual real std::string operations. The clang plugin implements this by fetching all the relevant no-op macro calls, and performs the operations with strings. This tool is then inserted as a part of the build process. During build, these no-op macro function calls are automatically evaluated into their results, and then inserted back as plain old compile-time strings in the program. The program can then be compiled as usual. In fact this resulting program is also much more portable as a result, not requiring a fancy new compiler supporting C++11.

答:
Several C++ compilers have some more or less documented and stable API, in particular most free software compilers.

Clang/LLVM is mostly a big set of libraries, and you could use them.

Recent GCC is accepting plugins. In particular, you could extend it using MELT (which is itself a meta-plugin, providing your with a higher-level domain specific language to extend GCC).

Notice that the syntax of C++ is not easily extensible in GCC (and probably neither in Clang), but you could add your own pragmas, builtins, attributes, and compiler passes to do what you want (perhaps also providing some preprocessor macros invoking these things to give a user-friendly syntax).

You might be interested in multi-stage languages and compilers, see e.g the Implementing Multi-stage Languages Using
ASTs, Gensym, and Reflection paper by C.Calcagno et al. and work around MetaOcaml. You certainly should look inside the macro facilities of Common Lisp. And you could be interested by JIT libraries like libjit, GNU lightning, even LLVM, or simply -at run-time!- generate some C++ code, fork a compilation of it into a shared object dynamic library, then dlopen(3) that shared object. J.Pitrat's blog is also related to such reflective approaches. And also RefPerSys.


答:
These aren't very good requirements at all but unfortunately in real world it is quite common to get "requirements analysis" which contains "requirements" like those.

I would recommend to go trough available documentation and convert all the "requirements" to user stories. When converting, you will find out which really are requirements and which are something else. Only requirements can be written as user stories which make sense from the end user point of view. E.g. requirement 3: "As a user I want that the system runs a separate client process for me" does not really make sense. So it is not a requirement but implementation details. There however might exist a requirement that is trying to be meet with this detail and it should be written on requirements analysis.

After "requirement analysis" is converted to requirement analysis, the best thing to do is to discuss with the customer (if that's possible) to make sure that you have understood everything correctly. Understanding what is really needed and why is crucial to create great software. Classification to functional and non-functional requirements is minor details.

And the answer to your question:

None of those three "requirements" are functional. Requirement 2 will become quality (performance) requirement when time constraint is specified (e.g. 2 seconds).

Title: Question about requirements

Body:
I know that functional requirements are requirements that tell the system what to do while non-functional requirements are about quality and constraints. For below requirements, which of these will fall under non-functional or functional?

UI must be graphical in nature. I would put this under non-functional requirements because it talks about the quality of the system. I am not too sure.

Users must be able to view information instantly. This could be functional but at the same time, the adverb 'instantly' could be related to performance. So that could also fall under non-functional requirements

Every user should run on a separate client process. This tells the system to run a process for each user. This could be functional, although I am not too sure, as this could be related how the system is implemented.


答:
Metaprogramming in C++ with compilers' API (instead of using templates) is indeed interesting and practically possible. Since metaprogramming is not (yet) standardized, you will be tied to a specific compiler, which is not the case with templates.

So, I'm wondering about why everybody isn't already doing this. Is it
  that this functionality from clang is so new and nobody is familiar
  with the huge class hierarchy of clang's AST? That can't be it.

Many people do this, but in other languages.
My opinion is that most C++ (or Java, or C) developers don't see the need for it (maybe rightfully), or are not accustomized to metaprogramming approaches; I also think that they are happy with the refactoring/code-generating features of their IDE, and that anything fancier might be seen too complex/hard to maintain/hard to debug. Without proper tools, it might be true. You should also take into account inertia and other non-technical problems, like hiring and/or training people.

By the way, since we are mentionning Common Lisp and its macro system (see Basile's answer), I must say that just yesterday, Clasp was released (I am not affiliated):

Announcing Clasp

Using Common Lisp to refactor C++ [video]

Clasp intends to be a conforming Common Lisp implementation that compiles to LLVM IR.
Moreover, it exposes Clang libraries (AST, Matcher) to the developer.

First, that means that you could write in CL and not use C++ anymore, except when using its libraries (and if you need macros, use CL macros).

Secondly, you can write tools in CL for your existing C++ code (analysis, refactoring, ...).

Title: C++: Metaprogramming with a compiler API rather than with C++ features

Body:
This started out as a SO question but I realized that it is quite unconventional and based on the actual description on the websites, it might be better suited to programmers.se since the question has a lot of conceptual weight.

I have been learning clang LibTooling and it is a very powerful tool capable of exposing the entire "nitty gritty" of the code in a friendly way, that is, in a semantic way, and not by guessing either. If clang can compile your code, then clang is certain about the semantics of every single character inside that code.

Now allow me to step back for a moment.

There are many practical problems that arise when one engages in C++ template metaprogramming (and especially when venturing beyond templates into the territory of clever albeit terrifying macros). To be honest, to many programmers, myself included, many of the ordinary uses of templates are also somewhat terrifying.

I guess a good example would be compile-time strings. This is a question that is over a year old now, but it is clear that C++ as of right now does not make this easy for mere mortals. While looking at these options isn't quite enough to induce nausea for me, it nevertheless leaves me unconfident about being able to produce magical, maximally efficient machine code to suit whatever fancy application I have for my software.

I mean, let's face it, folks, strings are pretty simple and basic. Some of us just want a convenient way to emit machine code that has certain strings "baked in" significantly more than we do get when coding it the straightforward way. In our C++ code.

Enter clang and LibTooling, which exposes the abstract syntax tree (AST) of the source code and allows a simple custom C++ application to correctly and reliably manipulate raw source code (using Rewriter) alongside a rich semantic object-oriented model of everything in the AST. It handles a lot of things. It knows about the macro expansions, and lets you follow those chains. Yes, I am talking about source-to-source code transformation or translation.

My fundamental thesis here is that clang now enables us to create executables which themselves can function as the ideal custom preprocessor stages to our C++ software, and we can implement these metaprogramming stages with C++. We are simply constrained by the fact that this stage must take input which is valid C++ code and produce as output more valid C++ code. Plus whatever other constraints your build system applies.

The input has to be at least very close to valid C++ code because, after all, clang is the compiler front-end and we are just poking around and being creative with its API. I do not know if there is any provision for being able to define new syntax to use, but clearly we have to develop the ways to properly parse it and add it to the clang project in order to do this. To expect any more is to have something in the clang project that is out of scope.

Not a problem. I would imagine that some no-op macro functions can handle this task.

Another way to look at what I'm describing is to implement metaprogramming constructs using runtime C++ by manipulating the AST of our source code (thanks to clang and its API) instead of implementing them using the more limited tools available in the language itself. This has clear compilation performance benefits as well (template-heavy headers slow compilation proportionally to how often you use them. Lots of compiled stuff then gets carefully matched up and thrown away by the linker).

This does, however, come at the cost of introducing an additional step or two in the build process and also in the requirement of writing some (admittedly) somewhat more verbose software (but at least it is straightforward runtime C++) as part of our tool.

That isn't the whole picture. I am pretty certain that there is a much larger space of functionality that can be had from generating code that is extremely difficult or impossible with core language features. In C++ you can write a template or a macro or a crazy combination of both, but in a clang tool you can modify classes and functions in ANY way that you can achieve with C++, at runtime, while having full access to the semantic content, in addition to template and macros and everything else.

So, I'm wondering about why everybody isn't already doing this. Is it that this functionality from clang is so new and nobody is familiar with the huge class hierarchy of clang's AST? That can't be it.

Perhaps I am just underestimating the difficulty of this a little bit, but doing "compile-time string manipulation" with a clang tool is nearly criminally simple. It's verbose, but it's insanely straightforward. All that's needed are a bunch of no-op macro functions that map to actual real std::string operations. The clang plugin implements this by fetching all the relevant no-op macro calls, and performs the operations with strings. This tool is then inserted as a part of the build process. During build, these no-op macro function calls are automatically evaluated into their results, and then inserted back as plain old compile-time strings in the program. The program can then be compiled as usual. In fact this resulting program is also much more portable as a result, not requiring a fancy new compiler supporting C++11.