答:
I'm just watching the recorded videos and I think he said something along these lines as criteria for not unit testing:

Needs a lot of mocking.

Can't figure out a better design.

Need to deliver/ship.

In my experience there are at least a few situations where unit testing should be carefully evaluated:

The code is trivial.  E.g. getters/setters.

The code is glue code between multiple external components.  This is where you'd have to resort to some extreme mocking to simulate those external components to the extent that your test is meaningless and is a barrier to refactoring.  Code that interacts with hardware, databases, network services etc. can be example of this.

There is already very good coverage in other tests that hits what is your candidate for unit testing.

You can reason about the correctness through some other means.

There is no time or business value to write the code + unit tests, e.g. having poor quality code with no tests means your startup will survive to next month because you can demo your product to a VC vs. having nothing and your startup is dead.

Examples of good situations for (unit) testing would be:

Shortest path in a graph algorithm (where you would have some sample input graphs where you know the shortest path)

AES encrypt/decrypt where you'd use standard test vectors to verify your algorithm is a compliant implementation.

h.264 video encoder.

I think they were also pretty clear that what's important is feedback and unit testing is one tool in the tool-box for getting that feedback.  They were also very clear that TDD is one particular style of getting feedback and that the style you use also depends on your personality and how you approach problem solving.

Title: What kind of code would Kent Beck avoid unit testing?

Body:
I've been watching a few of the Is TDD Dead? talks on youtube, and one of the things that surprised me is Kent Beck seems to acknowledge that there are just some kinds of programs that aren't worth unit testing.  For example, right here DHH says that Kent Beck is

... very happy to say "Well, TDD doesn't fit in this case, I'm just going to bail"

It's frustrating to me that Kent Beck seems to acknowledge this, but nobody asks him to elaborate on it or give concrete examples.  I'd like to know the situations where Kent Beck thinks TDD is a bad fit.  Nobody can read his mind or speak for him, but I'm hoping he's been transparent enough through his books/tweets/whatever for someone to be able to answer.

I'm not necessarily going to take what he says as gospel, but it would be useful to know that the times I've tried TDD and it just felt impossible/useless are situations that he would have bailed on it himself.  Or, if it turned out he would have tested that code it'd suggest to me that I was approaching the process very wrong.  I also think it would be enlightening to understand why he would bail on such projects.

My opinion on why this is not a duplicate of "When is it appropriate to not unit test?"

After skimming those answers I'm not satisfied.  For example, look at UncleBob's answer.  He doesn't even acknowledge that such a situation exists.  I really think there's value in understanding Kent Beck's position, not just a general, "What's your opinion?" type of question.  After all, he's the father of TDD.


问:
In C++ Good reasons for NOT using symmetrical memory management (i.e. new and delete)
I try to learn C++ and programming in general. Currently I am studying
open source with help of UML. Learning is my hobby and great one too.

My understanding of memory allocation in C++ is that it should be
symmetrical. A class is responsible for its resources. If memory is
allocated using new it should be returned using delete in the same
class. It is like in a library you, the class, are responsibility for
the books you have borrowed and you return them then you are done.

This, in my mind, makes sense. It makes memory management more
manageable so to speak.

So far so good. The problem is that this is not how it works in the
real world.

In Qt for instance, you create QtObjects with new and then hand over
the ownership of the object to Qt. In other words you create QtObjects
and Qt destroys them for you. Thus unsymmetrical memory management.
Obviously the people behind Qt must have a good reason for doing this.
It must be beneficial in some kind of way,

My questions is:

What is the problem with Bjarne Stroustrups idea about a symmetrical
memory management contained within a class?

What do you gain by splitting new and delete so you create an
object and destroy it in different classes like you do in Qt.

Is it common to split new and delete and why in such case, in other
projects not involving Qt?

Thanks for any help shedding light on this mystery!

答:
What is the problem with Bjarne Stroustrups idea about a symmetrical memory management contained within a class?

In most cases, there is no problem at all with doing symmetrical memory management. This is also what the principle of RAII is based upon.

There are, however, always situations where the class that allocated some memory isn't the last one to need to reference that memory. Sometimes this can be resolved by passing the ownership (and thus the responsibility for deletion) on to another class. Sometimes it is not even clear who will be the last to reference a piece of memory. In those cases, garbage collection techniques like reference counting come in handy.

What do you gain by splitting new and delete so you create an object and destroy it in different classes like you do in Qt.

You gain additional design possibilities. For example, if you have a polymorphic container, the class that puts items in it isn't required to outlive the container itself and the classes that read from it. This can be useful in implementing GUIs.

Is it common to split new and delete and why in such case, in other projects not involving Qt?

Given the popularity of boost::shared_ptr<> and the introduction of std::shared_ptr<> in the recent C++ update, there must be some demand for a-symmetric memory management. Both classes implement shared memory ownership based on reference counting.

ContentLicense: CC BY-SA 3.0


问:
Breaking up classes and methods into smaller units
During code reviews a couple devs have recommended I break up my methods into smaller methods.

Their justification was (1) increased readability and (2) the back trace that comes back from production showing the method name is more specific to the line of code that failed. There may have also been some colorful words about functional programming.

Additionally I think I may have failed an interview a while back because I didn't give an acceptable answer about when to break things up.

My inclination is that when I see a bunch of methods in a class or across a bunch of files, it isn't clear to me how they flow together, and how many times each one gets called. I don't really have a good feel for the linearity of it as quickly just by eye-balling it.

The other thing is a lot of people seem to place a premium of organization over content (e.g. 'Look at how organized my sock drawer is!' Me: 'Overall, I think I can get to my socks faster if you count the time it took to organize them').

Our business requirements are not very stable. I'm afraid that if the classes/methods are very granular it will take longer to refactor to requirement changes. I'm not sure how much of a factor this should be.

Anyway, computer science is part art / part science, but I'm not sure how much this applies to this issue.

EDIT:

Check out: What is the ideal length of a method for you?

答: Besides the other good answers above, I'd suggest you check into several studies of software development that demonstrate that highly cohesive functions are easier to understand and reason about.  The more ideas that are jammed into one function/class/module the lower the cohesion. Lower cohesion (among other things) leads to lower rates of comprehension.  </p>


问:
Is my work on a developer test being taken advantage of?
I am looking for a job and have applied to a number of positions. One employer responded. I had a pretty lengthy phone interview (perhaps an hour +) and they then set me up with a developer test. I was told that the test was estimated to take between 6 and 8 hours and that, provided the results met with their approval, I would be paid for my work.

That gave me some pause, but I endeavored. The developer test took place on a VM accessed via RDP. The task was to implement a search page in a web project that requests data from the server, displays it on the screen in a table, has a pretty complicated search filtering scheme (there are about 15 statuses and when sending the search to the server you can search by these statuses) in addition to the string/field search. Additionally, they want SVG icons to change color on certain data values, and some data represented differently than how it's structured in the database.

Loooong story short, this took a heck of a lot longer than 6-8 hours. Much of it was due to the very poor VM that I was running on (Visual Studio 2013 took 10 minutes to load, and another 15 minutes to open the 3 GB ginormous solution).

I was told that after completing the test I should commit my changes to source control...  Hmm, OK. I followed directions. And after committing the changes, I was emailed a response. The SVGs weren't colored right, there was a bug in this edge-case, there was an occasional problem with this other thing that I never experienced, etc. So I am 13-14 hours into this thing now, and I have to do bug fixes. I do them, and the employer comes back with more bug fix requests.

All my work is apparently going into a production application. I noticed a few anomalies in the code where it looked like others had coded all of one functionality but hadn't touched anything else.

Am I just being used for cheap labor? Even if they pay me the promised 50 dollars an hour for 6 hours, I have committed about 18 hours to this thing now. If I bug fix all of the stuff they keep coming up with, I will have worked at least 16 hours for free.

I have taken a number of developer tests, but I have never taken one during which I worked on code destined for production. I have never taken a test where I implemented a feature that was in the pipeline for development, and I have never taken one that took 4 rounds and a total of 20+ hours. I get the impression they are using their developer test to field some of the functionality on the cheap.

Do I have the wrong impression? And is this testing protocol appropriate?

答:
Just for comparison: The interview for my current job was around 1 hour talking about what I did so far and what the company is planning to do and how I would fit in. After that we worked together a week on a small project they had lying around, I guess just to see how we get along with each other. They paid me for this as freelancer the same amount I get now as their employee, so there was never a full day of unpaid work, let alone 3 days.

If the code is really used in production, I would send them the bill for the 24 hours you have spent, not your fault if their estimations are wrong. Assuming they didn't let you estimate how long it will take.


答:
It's closely tied with the idea behind unit testing ... where "unit" is a hotly contested and poorly defined term. Basically, if you start chunking your code up, at what point do you hit nice little bundles that behave in unsurprising ways? It's nice to exercise your conceptual units before they get blended into the whole.

In OO, it's also guided by the Single Responsibility Principle, which bascially says that each class should do one thing and one thing well. That is, you should be able to think about each thing in your system easily without having to resort to using your fingers and toes to count.

At the core, I look at my code and try to identify distinct ideas. Usually these ideas have some properties, and a set of operations that make sense on them. If the idea really is just an idea, then the odds of it being useful in more than one place go up.

When you've defined code around the data and operations related to core ideas, you can start putting your clean, sharply-defined ideas together in a way that turns into a big messy program.

Let's say you're writing a Sock Drawer app. Some of the ideas that you'll need to model are: a dresser, a drawer, a sock, a pair of socks. Each of those is pretty easy to define in terms of their attributes and operations you can perform on them. Once you have those things defined, written, and tested, then you can start putting them together to make a whole system.

Let's say that version 2.0 of your Sock Drawer requires a rocket-assisted conveyer belt and a black-box AI module which selects socks for you based on the weather, from all over the world. If you have your core ideas in place, then you can start wrapping them in AI logic and extended functionality. Your system can grow by adding richness in the interaction of core ideas, without fussing with the core ideas themselves too much.

...

A couple of practical exercises that will help break things up are: 1) limit the size of your coding units, 2) limit the amount of indentation you allow yourself (no more than 3 nested levels!!!!!! but try no more than 2 as an exercise) 3) follow "don't repeat yourself" religiously.

All of these are fairly objective criteria that will force you to think harder about how to find patterns and consolidate like code into cohesive bundles.

Title: Breaking up classes and methods into smaller units

Body:
During code reviews a couple devs have recommended I break up my methods into smaller methods.

Their justification was (1) increased readability and (2) the back trace that comes back from production showing the method name is more specific to the line of code that failed. There may have also been some colorful words about functional programming.

Additionally I think I may have failed an interview a while back because I didn't give an acceptable answer about when to break things up.

My inclination is that when I see a bunch of methods in a class or across a bunch of files, it isn't clear to me how they flow together, and how many times each one gets called. I don't really have a good feel for the linearity of it as quickly just by eye-balling it.

The other thing is a lot of people seem to place a premium of organization over content (e.g. 'Look at how organized my sock drawer is!' Me: 'Overall, I think I can get to my socks faster if you count the time it took to organize them').

Our business requirements are not very stable. I'm afraid that if the classes/methods are very granular it will take longer to refactor to requirement changes. I'm not sure how much of a factor this should be.

Anyway, computer science is part art / part science, but I'm not sure how much this applies to this issue.

EDIT:

Check out: What is the ideal length of a method for you?


问:
What methods exist for assessing an organisation's development capability?
I have a bit of a challenge at work at the moment.  Presently (and in fact, for some time now), we have been experiencing the following problems with some in-house maintained applications:

Defects (sometimes quite serious) being released into production;

The Customer (that is, the relevant business unit) perpetually changing their minds (or appearing to do so) about what issue to work on next;

A situation where everyone seems to be in a "fire-fighting" mode a lot of the time;

Development staff responding to operational requests from business users; ("operational" here means something that needs to be done in order to continue with business, or perhaps just to make a business user's life a little less painful, as opposed to fixing a bug in the application, or enhancing the application);

Now I'm sure this doesn't sound particularly new or surprising to most of the participants on this Q&A site and no prizes for identifying the "usual suspects" when it comes to root causes.  My challenge is that I have to persuade the higher-ups to do uncomfortable things in order to address all of this.

The folk I need to persuade come from a mixture of the following two cultures:

Accounting;

IT Infrastructure.

I have therefore opted for a strategy that draws from things with-which folk from such a culture would be most comfortable (at least, in my estimation), namely: numbers and tangibles.  Of course modern development practitioners know all too well that this sort of thing isn't easily solved using an analytical mindset (some would argue that that mindset is, in fact, entirely inappropriate).  Never-the-less, this is the dichotomy with-which I am faced, so that's the stake that I've put in the ground.

I would like to be able to do research and use the outputs to present findings in the form of metrics and measures.  I am finding it quite difficult, though, to find an agreed-upon methodology and set of templates for assessing an organisations development capability--the only thing that seems applicable is the Software Engineering Institute's Capability Maturity Model.  The latter, however, seems dated and even then rather vague.

So, the question is: How do I go about assessing our organisation's software engineering capability such that I can present the findings in a way that is concrete and references a generally accepted industry standard?

UPDATE:

Doing a little more research, I came across this little oasis - a CMMI FAQ worded in laymans terms--just the sort of useful resource that one needs in this area ... and free.

答:
May I recommend the Joel Test: 12 Steps to Better Code. Quoting from the blog post:

```<code>1. Do you use source control?
2. Can you make a build in one step?
3. Do you make daily builds?
4. Do you have a bug database?
5. Do you fix bugs before writing new code?
6. Do you have an up-to-date schedule?
7. Do you have a spec?
8. Do programmers have quiet working conditions?
9. Do you use the best tools money can buy?
10. Do you have testers?
11. Do new candidates write code during their interview?
12. Do you do hallway usability testing?
</code>```

These questions were written by Joel Spolsky in 2000, but still have not lost their relevancy to this day (2014). However, I would add a few additions to some of the questions:

```<code>1. Specifically, do you use a source-control system with built-in code
   review capability? (e.g. something like git's pull-requests)
2. Do you have a continuous build system in place that
   kicks in automatically on every commit?
3. Do you have a continuous delivery system in place that (at least)
   installs every build automatically in a test environment?
...
6. Do you actually work by Scrum or Kanban?
7. Do you write and estimate user stories on a regular basis?
...
11. Do you find useful tasks for coding that relate to what the
    job is actually about? (as opposed to asking for the 1e6th
    incarnation of the Fibonacci algorithm, or to solve the TSP
    when the job is about writing your next JavaScript UI)
12. Do you use A/B testing to determine what people actually prefer?
    (as opposed to their stated opinion)
</code>```

Body:
May I recommend the Joel Test: 12 Steps to Better Code. Quoting from the blog post:

1. Do you use source control?
2. Can you make a build in one step?
3. Do you make daily builds?
4. Do you have a bug database?
5. Do you fix bugs before writing new code?
6. Do you have an up-to-date schedule?
7. Do you have a spec?
8. Do programmers have quiet working conditions?
9. Do you use the best tools money can buy?
10. Do you have testers?
11. Do new candidates write code during their interview?
12. Do you do hallway usability testing?

These questions were written by Joel Spolsky in 2000, but still have not lost their relevancy to this day (2014). However, I would add a few additions to some of the questions:

1. Specifically, do you use a source-control system with built-in code
   review capability? (e.g. something like git's pull-requests)
2. Do you have a continuous build system in place that
   kicks in automatically on every commit?
3. Do you have a continuous delivery system in place that (at least)
   installs every build automatically in a test environment?
...
6. Do you actually work by Scrum or Kanban?
7. Do you write and estimate user stories on a regular basis?
...
11. Do you find useful tasks for coding that relate to what the
    job is actually about? (as opposed to asking for the 1e6th
    incarnation of the Fibonacci algorithm, or to solve the TSP
    when the job is about writing your next JavaScript UI)
12. Do you use A/B testing to determine what people actually prefer?
    (as opposed to their stated opinion)


问:
How to name a method that both performs a task and returns a boolean as a status?
If there is a method

```<code>bool DoStuff() {
    try {
        // doing stuff...
        return true;
    }
    catch (SomeSpecificException ex) {
        return false;
    }
}
</code>```

should it rather be called IsStuffDone()?

Both names could be misinterpreted by the user:
If the name is DoStuff() why does it return a boolean?
If the name is IsStuffDone() it is not clear whether the method performs a task or only checks its result.

Is there a convention for this case? Or an alternative approach, as this one is considered flawed? For example in languages that have output parameters, like C#, a boolean status variable could be passed to the method as one and the method's return type would be void.

EDIT: In my particular problem exception handling cannot be directly delegated to the caller, because the method is a part of an interface implementation. Therefore, the caller can't be charged with dealing with all the exceptions of different implementations. It is not familiar with those exceptions. However, the caller can deal with a custom exception like StuffHasNotBeenDoneForSomeReasonException as was suggested in npinti's answer and comment.

答:
Might fail for different reasons, Exception, normal conditions, so would use this:

```<code>boolean doStuff() - returns true when successful
</code>```

Important is to document what the boolean means.

Body:
Might fail for different reasons, Exception, normal conditions, so would use this:

boolean doStuff() - returns true when successful

Important is to document what the boolean means.


问:
Best Practices: Database app programming patterns
I have written many database (MySQL) web apps so far but I always think my structure is kinda clumsy. I want to improve the programming/design pattern I use, hoping for some advice here. Particularly, I cannot find a structure that complements an OOP approach that encapsulates the implementation of the database (schema). I

Think my question can be best explained by example. There are 2 approaches I use now say I have an Invoice object/class:

first is to use static member functions

```<code>class Invoice
{
   int id;
   string ref;
   int customer_id;
   date created;
   date due;

   static id create();
   static bool update(id, field1, field2, ...);
   static bool delete(id);
   static bool get(id);
};
</code>```

The second approach is to put every thing in a database object:

```<code>class Database extends ProprietaryDBConnecter, Singleton
{
   id createInvoice();
   bool updateInvoice(id, field1, field2, ...);
   bool deleteInvoice(id);
   bool getInvoice(id);

   id createCustomer();
   bool updateCustomer(id, field1, field2, ...);
   bool deleteCustomer(id);
   bool getCustomer(id);

   // etc...
}
</code>```

I find that both ways the (SQL) member functions are very much unseparable from the "view", in that the "view" determines what the classes needs to have and hence seems to break the document/view architecture.

Also, it seems kind of inefficient for example a SELECT statement should only select what is needed, but the presence of member variables in Invoice seems to imply "guaranteed data".

Don't know if I explained the question clearly, What are some other best approaches to this architecture/design pattern/what-it-is-known-as?

Thanks for advices

答:
Well I suppose that you could use an ORM.

But really, database design should NOT follow OOP priciples, it should follow database design priciples such as normalization.  And it should be designed at the database not in the application. And the data integrity rules should be enforced at the database level not by the application.

I would suggest you read some database design books and, then, read about performance tuning the database of your choice.

ContentLicense: CC BY-SA 2.5


答:
You are missing three big points.  First, using well-named and well-designed smaller functions means you usually don't have to understand how all the functions flow together and how often they are called.  You look at the level of abstraction you need, and don't try to hold the entire call stack in your head at once.

For example, if I'm reading an algorithm and come across number.isPrime, I have a pretty good idea what that does.  I can debug perfectly fine at that layer of abstraction and only have to delve a layer deeper if I discover it is returning incorrect results.  Admittedly, it's a little extra work if I do have to go there, but usually I don't.

On the other hand, if the original author didn't break out isPrime into its own function, I have no choice but to slog through that extra layer of abstraction every single time.

Second, smaller functions are easier to test and debug, because they only do one thing, and therefore are more likely to be correct.  isPrime is pretty easy to test with some sample data at boundary conditions, then you can trust it after that point.  If it's buried inline deep inside another function, it's difficult to isolate where any problems are.

Finally, smaller functions are more likely to be reusable.  When you use smaller functions, you will naturally find places to avoid duplication, and it will be easy to consolidate.  Also, the reused functions are already tested and debugged, saving you time.

It's not so much the difference between an organized or unorganized sock drawer as between a sock drawer and a knitting machine.  Even if a knitting machine can spit out 10 socks per minute, that's still not the abstraction level you want when you're getting dressed in the morning.


问:
Should Maven generate JAXB java code or just use Java code from source control?
We're trying to plan how to mash together a build server for our shiny new Java backend.  We use a lot of JAXB XSD code generation and I was getting into a heated argument with whoever cared that the build server should:

Delete JAXB created structures that were checked in.

Generate the code from XSD's.

Use code generated from those XSD's.

Everyone else thought that it made more sense to just use the code they checked in (we check in the code generated from the XSD because Eclipse pretty much forces you to do this as far as I can tell).

My only stale argument is in my reading of the Joel test is that making the build in one step means generating from the source code and the source code is not the Java source, but the XSD's because if you're messing around with the generated code you're gonna get pinched eventually.

So, given that we all agree (you may not agree) we should probably be checking in our generate Java files, should we use them to generate our code or should we generate it using the XSD's?

答:
Generated files shouldn't be checked into source code control (related: P.SE: Do I check generated code in to source control or not? SO Should I store generated code in source control).  The code generated by jaxb certainly falls into this category.

The logic falls much the same reason you don't check in object files into source code control or the final build itself.  They are the programatic output of some other process.

The contents of source code control should be enough to do a build from any given point in time.  This may include the .xsd as part of the contract you are given for the API (just as one would check in .h files for a library in the C world).

Having generated source in source code control leads to the temptation to tweak it and it becomes something that you can't generate again.  Someone else can't take jaxb and generate the same thing.

Generated source also runs up against the DRY principle.  The necessary information to build it is in the .xsd and the build step.  Adding the class files that are generated is another copy of this information with no added value.

From the two above points, realize that changing the generated source means (while necessary sometimes) means that the source code no longer matches the definition - it doesn't match the .xsd (or if dealing with a grammar, the source doesn't match the language definition anymore).  Consider the nightmare when the application is ported from one language to another and you generate the source from the .xsd and the functionality of the generated code doesn't match that of the generated (and tweaked) code.

Sometimes, the generated source can be very large to the point of something prohibitively expensive to put into source code control.  Anecdote: Apache Axis once generated a 4 megabyte .java file for me (yes, 4 megabytes of text) - I really didn't want to have that be something sitting in the source tree (most IDEs freaked out about something that massive).

So no, don't check in generated source.  You should only have what you need to do a build and the steps to do that build.


问:
Can I save & store a user's submission in a way that proves that the data has not been altered, and that the timestamp is accurate?
There are many situations where the validity of the timestamp attached to a certain post (submission of information) might be invaluable for the post owner's legal usage. I'm not looking for a service to achieve this, as requested in this great question, but rather a method for the achievement of such a service.

For the legal (in most any law system) authentication of text content and its submission time, the owner of the content would need to prove:

that the timestamp itself has not been altered and was accurate to begin with.

that the text content linked to the timestamp had not been altered

I'd like to know how to achieve this via programming (not a language-specific solution, but rather the methodology behind the solution).

Can a timestamp be validated to being accurate to the time that the content was really submitted?

Can data be stored in a form that it can be read, but not written to, in a proven way?

In other words, can I save & store a user's submission in a way that proves that the data has not been altered, and that the timestamp is accurate?

I can't think of any programming method that would make this possible, but I am not the most experienced programmer out there. Based on MidnightLightning's answer to the question I cited, this sort of thing is being done.

Clarification: I'm looking for a method (hashing, encryption, etc) that would allow an average guy like me to achieve the desired effect through programming.

I'm interested in this subject for the purpose of Defensive Publication.

I'd like to learn a method that allows an every-day programmer to pick up his computer, write a program, pass information through it, and say:

I created this text at this moment in time, and I can prove it.

This means the information should be protected from the programmer who writes the code as well. Perhaps a 3rd party API would be required. I'm ok with that.

答:
Sure.

You can take the content, append the textual representation of the timestamp), and then generate a cryptographically secure hash to the result which you store along with the data.  In the future, you can take the content that you've stored, the timestamp that you've stored, and repeat the process.  If the hash comes out the same, you can say with high confidence the content is unchanged.

Of course, this is only as secure as the hash algorithm that you choose.  Any hash will have some risk of collisions but a secure hash will make this risk incredibly small.  Ideally, if a hash produces a 32-bit number, you'd expect the odds of a collision to be 1/2^32.  A less secure hash will create the possibility that an attacker could change the timestamp and make a subtle change to the content that would produce the same hash when the two were concatenated together.  Even that, though, would generally require a pretty sophisticated attacker-- generating non-obvious hash collisions for even relatively weak hashes like MD4 (i.e. that don't require that the text is completely garbled) is rather challenging.

Assuming a perfect hash algorithm, any given string is converted deterministically into a hash but every hash is equally likely given the universe of inputs and which has no recoverable information about the original input string.  In a perfect world, if I have a 32-bit hash algorithm, knowing nothing about the string that I input, any of the 2^32 possible outputs would be equally likely.  Changing 1 character of the input string would also make any of the 2^32 possible outputs equally likely.  That makes it impractical, short of brute-force generating and trying 2^32 inputs, to find another input that produces a collision with any particular hash.  Of course, real hash algorithms likely aren't perfect (just like real encryption algorithms likely aren't perfect) so even the best algorithms probably aren't as tough to break as their raw bit-length would predict.  But they're likely good enough that no attacker is going to be able to produce a collision over the lifetime that you care about the information.


答:
I worked at a shop that stored images of legal documents in a database. In order to achieve security, all user documents were stored this way:

take a hashcode of the document

encrypt the document & store it

encrypt the hashcode & store it

take a hashcode of the encrypted document & store it

take a hashcode of the encrypted hashcode & store it

Now, it's still possible for someone who has all the encryption keys to change everything, but if any one of those get out of sync, they could detect the tampering.

(Full disclosure: to this day, I'm unsure if that process was brilliant or just a convincing way to sound brilliant without actually accomplishing anything.)

I'm not certain that's a sufficient, or even good, solution, but essentially the answer to your question boils down to hashcodes, encryption, and saving different pieces in different places.

In your case, it might be sufficient to save the text and the hash of the text in separate data stores. On any retrieval, check to make sure they still match. However, someone with root access could still defeat that if they knew what they needed to do.

Title: Can I save & store a user's submission in a way that proves that the data has not been altered, and that the timestamp is accurate?

Body:
There are many situations where the validity of the timestamp attached to a certain post (submission of information) might be invaluable for the post owner's legal usage. I'm not looking for a service to achieve this, as requested in this great question, but rather a method for the achievement of such a service.

For the legal (in most any law system) authentication of text content and its submission time, the owner of the content would need to prove:

that the timestamp itself has not been altered and was accurate to begin with.

that the text content linked to the timestamp had not been altered

I'd like to know how to achieve this via programming (not a language-specific solution, but rather the methodology behind the solution).

Can a timestamp be validated to being accurate to the time that the content was really submitted?

Can data be stored in a form that it can be read, but not written to, in a proven way?

In other words, can I save & store a user's submission in a way that proves that the data has not been altered, and that the timestamp is accurate?

I can't think of any programming method that would make this possible, but I am not the most experienced programmer out there. Based on MidnightLightning's answer to the question I cited, this sort of thing is being done.

Clarification: I'm looking for a method (hashing, encryption, etc) that would allow an average guy like me to achieve the desired effect through programming.

I'm interested in this subject for the purpose of Defensive Publication.

I'd like to learn a method that allows an every-day programmer to pick up his computer, write a program, pass information through it, and say:

I created this text at this moment in time, and I can prove it.

This means the information should be protected from the programmer who writes the code as well. Perhaps a 3rd party API would be required. I'm ok with that.


答:
Traditionally, you would use timestamping services for this sort of thing. A timestamp service is a well-known service that performs the following tasks:

You send a small bit of data to the service (such as a hash).

The service combines this data with the current timestamp.

The combined data is signed with the service's private key.

The service sends the combined data and signature back to the client.

This allows anybody to validate that the given hash was signed at the given time, by validating the signature using the service's public key.

In answer to your questions:

Can a timestamp be validated to being accurate to the time that the content was really submitted?

Yes, if everybody trusts the timestamp service (the timestamp service can be neutral and can sign timestamp submitted by friends and enemies alike). Consider for example a timestamp service offered by a national government (if you only care about transactions within a particular country), or by an entity such as a Swiss bank.

Can data be stored in a form that it can be read, but not written to, in a proven way?

Yes, because the signature of the timestamp service can be verified at any time using the service's public key.

NOTE: Both "Yes" above come with the usual caveats of properly implemented services. If the timestamp service is compromised in any way, signed timestamps may become suspect.

There are other solutions to this problem as well. The Wikipedia article on Trusted timestamping gives a good overview.


答:
I would like to suggest to use the 'Try' prefix. This is a well known pattern for situations that the method may succeed or not. This naming pattern has been used by Microsoft in .NET Framework (for example, TryParseInt).

But, maybe this is not about naming. It is about how you design your method's input/output parameters.

My idea is that if a method has a return value, then the purpose of calling that method should be to get that return value. So, you should avoid using return type to indicate the status of an operation.

In C#, I prefer to use an out parameter. Using an out I am marking the parameter as a side parameter. Specially that C# 6 will support inline variable declaration.

```<code>DoStuff(out var isStuffDone); // The out parameter name clearly states its purpose.
DoStuff(out var _); // I use _ for naming parameters that I am ignoring.
</code>```

Title: How to name a method that both performs a task and returns a boolean as a status?

Body:
If there is a method

```<code>bool DoStuff() {
    try {
        // doing stuff...
        return true;
    }
    catch (SomeSpecificException ex) {
        return false;
    }
}
</code>```

should it rather be called IsStuffDone()?

Both names could be misinterpreted by the user:
If the name is DoStuff() why does it return a boolean?
If the name is IsStuffDone() it is not clear whether the method performs a task or only checks its result.

Is there a convention for this case? Or an alternative approach, as this one is considered flawed? For example in languages that have output parameters, like C#, a boolean status variable could be passed to the method as one and the method's return type would be void.

EDIT: In my particular problem exception handling cannot be directly delegated to the caller, because the method is a part of an interface implementation. Therefore, the caller can't be charged with dealing with all the exceptions of different implementations. It is not familiar with those exceptions. However, the caller can deal with a custom exception like StuffHasNotBeenDoneForSomeReasonException as was suggested in npinti's answer and comment.

Body:
I would like to suggest to use the 'Try' prefix. This is a well known pattern for situations that the method may succeed or not. This naming pattern has been used by Microsoft in .NET Framework (for example, TryParseInt).

But, maybe this is not about naming. It is about how you design your method's input/output parameters.

My idea is that if a method has a return value, then the purpose of calling that method should be to get that return value. So, you should avoid using return type to indicate the status of an operation.

In C#, I prefer to use an out parameter. Using an out I am marking the parameter as a side parameter. Specially that C# 6 will support inline variable declaration.

DoStuff(out var isStuffDone); // The out parameter name clearly states its purpose.
DoStuff(out var _); // I use _ for naming parameters that I am ignoring.


问:
Programmer VS Commercial Systems (ERP)
My question here is relative to jobs for programmers.

Why does employer still contract programmers if today we have a lot of good commercial system avaliable on the market?

I want to be very clear at this point, this question is relative only to a system, more specially to ERP systems.  Maybe this question looks a little bit useless, but right now I'm working and this doubt arose to me and my boss.

I have a few answers to my own question, but I really would like to speculate this subject a bit more.

Also I know, every good company needs a customized system, but ... the question is here. :-)

Any answer will make me feel better. Thanks.

答:
I work with the team that develops Microsoft Dynamics AX. Actually, I'm in the team that makes the development tools that allow programmers to extend Dynamics AX.

We provide this tools because is impossible to offer solutions that cover all our customers' needs. Depending on how much customization is needed the customer might want to hire a programmer (or a team).

In AX we have a programming language called X++ that requires real programming knowledge if quality code is expected or if a lot of customization is required. I assume that SAP and Oracle have similar features.

So, unless the out-of-the-box solution fits the customers needs - which doesn't happen for big companies -, a team of programmers is needed to customize it.

Title: Programmer VS Commercial Systems (ERP)


问:
Best strategy to discover a web service in a local network?
I am currently doing some research for a project. The setup is simple, I have a computer running a service in my home network and any device connected to that same network should be able to discover the service automatically and use it. I have no specific technology requirement whether it is on the server or client side. The client knows about the service definition.

Other than that I have no idea what strategy to use, what technology to look at or whether I should go for a SOAP or a HTTP based service. I think going HTTP with REST API is the best for targeting all devices but I am opened to any suggestions.

Thanks.

答:
One of the simplest ways to achieve this is to use UDP broadcast. Essentially:

The server listens for UDP packets on a certain port.

When a client wants to connect to the server, it sends a broadcast UDP packet to the certain port.

When the server sees a broadcast packet, it replies to that client with information about what the actual address/URL of the server is.

There are established standards that build upon this idea, for example mDNS.


答:
Not going to write a long answer, but I am seriously confused, why is nobody bringing up the issue of copyright?

As far as my experience goes I have never heard about an agreement being made to transfer copyright ownership of code written during a developer test to the other party. If this is the case you can actually sue them for copyright infringement and the damages awarded for this can be quite nice, especially so in the US from the stories I have heard. And if they want to settle (do propose this) you can ask any exorbitant fee for the infringement (after which they would in principle still not be allowed to use your work and you could still sell your work to them if they would still be interested).

Title: Is my work on a developer test being taken advantage of?

Body:
I am looking for a job and have applied to a number of positions. One employer responded. I had a pretty lengthy phone interview (perhaps an hour +) and they then set me up with a developer test. I was told that the test was estimated to take between 6 and 8 hours and that, provided the results met with their approval, I would be paid for my work.

That gave me some pause, but I endeavored. The developer test took place on a VM accessed via RDP. The task was to implement a search page in a web project that requests data from the server, displays it on the screen in a table, has a pretty complicated search filtering scheme (there are about 15 statuses and when sending the search to the server you can search by these statuses) in addition to the string/field search. Additionally, they want SVG icons to change color on certain data values, and some data represented differently than how it's structured in the database.

Loooong story short, this took a heck of a lot longer than 6-8 hours. Much of it was due to the very poor VM that I was running on (Visual Studio 2013 took 10 minutes to load, and another 15 minutes to open the 3 GB ginormous solution).

I was told that after completing the test I should commit my changes to source control...  Hmm, OK. I followed directions. And after committing the changes, I was emailed a response. The SVGs weren't colored right, there was a bug in this edge-case, there was an occasional problem with this other thing that I never experienced, etc. So I am 13-14 hours into this thing now, and I have to do bug fixes. I do them, and the employer comes back with more bug fix requests.

All my work is apparently going into a production application. I noticed a few anomalies in the code where it looked like others had coded all of one functionality but hadn't touched anything else.

Am I just being used for cheap labor? Even if they pay me the promised 50 dollars an hour for 6 hours, I have committed about 18 hours to this thing now. If I bug fix all of the stuff they keep coming up with, I will have worked at least 16 hours for free.

I have taken a number of developer tests, but I have never taken one during which I worked on code destined for production. I have never taken a test where I implemented a feature that was in the pipeline for development, and I have never taken one that took 4 rounds and a total of 20+ hours. I get the impression they are using their developer test to field some of the functionality on the cheap.

Do I have the wrong impression? And is this testing protocol appropriate?


答:
There is no way to do what you want with pure digital information theory.  However, there is a way to use a trusted assistant to help you.  The classic version of this involves posting information in a classified column on a particular day in a particular newspaper.  It is exceedingly difficult to forge such a post after the fact, so it is generally treated as trustworthy.

Now the real challenge is deciding what information to post.  Obviously posting all of your timestamped data to the classifieds would get old after a while.  However, posting a hash of all of the timestamped data you collected (including hashing the timestamps themselves), and posting that to the newspaper daily would be reasonable.  Then, if you have to prove the timestamp in a court of law, you merely reveal all timestamps in that block.  Anyone verifying you simply needs to hash the data, then go look in the newspaper for that hash.

This of course, only provides one bound - you can't have possibly generated the timestamped data after the newspaper received the hash, but it could have been generated any time before hand and delayed until you "needed it."  For many legal situations, just an upper bound is sufficient.  For others, more careful bounds are needed.  A common solution, which happens to be used by bitcoin, is to chain the data.  Store your timestamped data, and hash it.  You then create a chain of hashes combining this hash of timestamped data with the last entry in the chain.  This does not prevent you from falsifying a time, but it does make it dramatically more difficult because now you have to falsify every entry that follows the injected data.

There are hundreds of variants of these verification schemes using tools like this, but they all fall into two steps:

Create a "proof" document which is small enough to be easy to manage (such as a hash)

Provide this "proof" document to a trusted third party who can reasonably vouch that it received the proof

Remember that legal requirements are usually to some level of doubt.  This gives flexibility.  For example, if you need to prove a log message's time to a minute, you might use a 2 step process.  Daily, you post the hash of your entire log to a newspaper or other trusted entity.  Every minute, you publish the hash of the logs on a public website. If nobody downloads those minute logs, they may try to discredit them, but they cannot discredit the newspaper data, and the mere fact that you constantly publish verifiable data may be sufficient to assuage doubt by demonstrating that you had a desire to be held to a strong standard.


答:
I would approach it from the opposite direction: why is Bjarne's position a good idea?  Then we can see when it falls apart.

The primary reason for Bjarne's position of symmetrical memory management is that C++ can cause memory leaks if memory ownership is not handled properly.  Bjanrne's position is based on the idea that symmetric memory management increases the likelyhood of developers managing memory properly, and minimizing leaks.

It does this by keeping memory management out of the interactions between classes.  Generally speaking, function calls don't explicitly notate memory management behaviors.  Those tend to be relegated to comments.  Comments can be overlooked.

In the real world, it is not always convenient to do symetric memory management.  For example, any data required to properly manage the memory must have a lifespan as long as the data itself (otherwise it would be invalid when it was needed).  In real life code, developers will cut corners in order to improve readability of their API.

Modern development has seen the introduction of shared_ptr.  shared_ptr solves these issues by putting the memory management rules directly into the function definition, and does so in a way which is so popular amongst developers, that people find few reasons to roll their own.

Shared_ptr meets Bjarne's rule by putting memory management all in one place: shared_ptr, and meets real life needs by allowing ownership of the memory to be passed from place to place.

Title: In C++ Good reasons for NOT using symmetrical memory management (i.e. new and delete)

Body:
I try to learn C++ and programming in general. Currently I am studying
open source with help of UML. Learning is my hobby and great one too.

My understanding of memory allocation in C++ is that it should be
symmetrical. A class is responsible for its resources. If memory is
allocated using new it should be returned using delete in the same
class. It is like in a library you, the class, are responsibility for
the books you have borrowed and you return them then you are done.

This, in my mind, makes sense. It makes memory management more
manageable so to speak.

So far so good. The problem is that this is not how it works in the
real world.

In Qt for instance, you create QtObjects with new and then hand over
the ownership of the object to Qt. In other words you create QtObjects
and Qt destroys them for you. Thus unsymmetrical memory management.
Obviously the people behind Qt must have a good reason for doing this.
It must be beneficial in some kind of way,

My questions is:

What is the problem with Bjarne Stroustrups idea about a symmetrical
memory management contained within a class?

What do you gain by splitting new and delete so you create an
object and destroy it in different classes like you do in Qt.

Is it common to split new and delete and why in such case, in other
projects not involving Qt?

Thanks for any help shedding light on this mystery!


问:
Algorithm to measure how "diffused" 5,000 pennies are in an economy?
Please allow me to use this example/metaphor to describe an algorithm I need.

Objects

There are 5 thousand pennies.

There are 50 cups.

There is a tracking history (Passport "stamp" etc) that is associated with each penny as it moves between cups.

Definition

I'll define a "highly diffused" penny as one that passes through many cups.

A "poorly diffused" penny is one that either passes back and forth between 2 cups

Question

How can I objectively measure the diffusion of a penny as:

The number of moves the penny has gone through

The number of cups the penny has been in

A unit of time (day, week, month)

Why am I doing this? I want to detect if a cup is hoarding pennies.

Resistance from bad actors

Since hoarding is bad, the "bad cup" may simply solicit a partner and simply move pennies between each other.  This will reduce the amount of time a coin isn't in transit, and would skew hoarding detection.

A solution might be to detect if a cup (or set of cups) are common "partners" with each other, though I'm not sure how to think though this problem.

Broad applicability

Any assistance would be helpful, since I would think that this algorithm is common to

Economics

The study of migration patterns of animals, citizens of a country

Other natural occurring phenomena

... and probably exists as a term or concept I'm unfamiliar with.

答:
Simplest is often the best. Or at least a really good start.

You already have the history of which cups each penny has visited, hence you know the number of cups visited by each penny. We might expect to see a normal distribution of the number of cups visited vs the number of visits per penny.

A similar approach can be used to observe the distribution of pennies in each cup.

A penny that is poorly diffused has visited few cups, but one that is being hoarded (in your definition) is one that also has had many visits. Patterns of hoarding would skew the distributions.

So I would suggest looking for pennies where

```<code>number-of-visits / number-of-cups-visited
</code>```

is greater than one, as a starting point.

This analysis can be performed for each time period you are interested in.

The cutoffs you choose (I suggested one, above) should be able to be adjusted; the warnings posted by @Cort Ammon should be taken seriously.

Body:
Simplest is often the best. Or at least a really good start.

You already have the history of which cups each penny has visited, hence you know the number of cups visited by each penny. We might expect to see a normal distribution of the number of cups visited vs the number of visits per penny.

A similar approach can be used to observe the distribution of pennies in each cup.

A penny that is poorly diffused has visited few cups, but one that is being hoarded (in your definition) is one that also has had many visits. Patterns of hoarding would skew the distributions.

So I would suggest looking for pennies where

number-of-visits / number-of-cups-visited

is greater than one, as a starting point.

This analysis can be performed for each time period you are interested in.

The cutoffs you choose (I suggested one, above) should be able to be adjusted; the warnings posted by @Cort Ammon should be taken seriously.


问:
Do you have your own 'misc utils' library? What part are you most proud of?
I know that many of us maintain our own little personal library with tools and utilities that we use often.

I've had mine since I was 16 years old so it has grown to quite a considerable size. Some of the stuff I've written has since been added to the framework. I wrote my own little implementation of expression trees for use with genetic algorithms long before LINQ, which I quite like and was proud of at the time - of course its pretty useless now. But recently I have been going through it and upgrading to .NET 4.0 and re-kindled an interest.

So I'm curious as to what you use your library for. Maybe we could get some cool ideas going for useful little snippets and share them amongst ourselves.

So my questions are:

Do you have a miscellaneous utility library?

Which part are you most proud of and why?

Give an example of code if you like :-)

答:
No.

I've seen some nightmarish effects of a dozen developers all adding their own little "util.h" style libraries to projects, and have it turn into a giant mess of inconsistent function naming and behaviors. Much like PHP. So for that reason I avoid doing it.

I avoid needing to do that by using programming environments that give me nearly all the tools and libraries I need up front whenever possible, such as C# and python.


问:
How can I rank teams based off of head to head wins/losses
I'm trying to write an algorithm (specifically in Ruby) that will rank teams based on their record against each other. If a team A and team B have won the same amount of games against each other, then it goes down to point differentials.

Here's an example:

```<code>A beat B two times
B beats C one time
A beats D three times
C bests D two times
D beats C one time
B beats A one time
</code>```

Which sort of reduces to

```<code>A[B] = 2
B[C] = 1
A[D] = 3
C[D] = 2
D[C] = 1
B[A] = 1
</code>```

Which sort of reduces to

```<code>A[B] = 1
B[C] = 1
A[D] = 3
C[D] = 1
D[C] = -1
B[A] = -1
</code>```

Which is about how far I've got

I think the results of this specific algorithm would be:

```<code>A, B, C, D
</code>```

But I'm stuck on how to transition from my nested hash-like structure to the results.

My psuedo-code is as follows (I can post my ruby code too if someone wants):

```<code>For each game(g):
  hash[g.winner][g.loser] += 1
</code>```

That leaves hash as the first reduction above

```<code>hash2 = clone of hash
For each key(winner), value(losers hash) in hash:
  For each key(loser), value(losses against winner):
    hash2[loser][winner] -= losses
</code>```

Which leaves hash2 as the second reduction

Feel free to as me question or edit this to be more clear, I'm not sure of how to put it in a very eloquent way. Thanks!

答: You appear to be dealing with a feedback arc set. Because each team plays more than once, you're looking at a more complex situation than the minimum case though you could conceivably do the number of wins as a weight and still wind up with a restricted case that has a valid approximate solution in O(log|V|loglog|V|) time.


问:
Tournament bracket method to put distance between teammates
I am using a proper binary tree to simulate a tournament bracket. It's preferred any competitors in the bracket that are teammates don't meet each other until the later rounds.  What is an efficient method in which I can ensure that teammates in the bracket have as much distance as possible from each other?  Are there any other data structures besides a tree that would be better for this purpose?

EDIT: There can be more than 2 teams represented in a bracket and there is no requirement to have an equal number of people from each team in a bracket.  I intend to use this for individual sports where a person still has an affiliation with a team and we want to delay teammates facing each other until as late as possible.

答:
Let's suppose that the leaf nodes of your tree are numbered 0..n-1 where n is the total number of players. These numbers would be assigned via depth-first search. That would result in nodes 0 and 1 having a common parent, and 2 and 3 having a common parent. Parents of these parents will have a common parent and so on.

Now, let's also assume that you have m teams, each with n/m players, you could assign players numbers in round-robin fashion such that the players from team i are numbered i, n/m+i, n/m*2+i, n/m*3+i, ...

Once that happens, you distribute them across the leaf nodes of your tree and that should maximize the distance between them.

```<code>Example:
If no. of players = 16, no. of teams = 4.
Team 0 players = 0, 4,  8, 12
Team 1 players = 1, 5,  9, 13
Team 2 players = 2, 6, 10, 14
Team 3 players = 3, 7, 11, 15
</code>```

All of the players are equally distributed with as much distance as possible without sacrificing any other team's players' distances.

If the number of players are not the same on every team, then please do let know, I will take another attempt at it.

Body:
Let's suppose that the leaf nodes of your tree are numbered 0..n-1 where n is the total number of players. These numbers would be assigned via depth-first search. That would result in nodes 0 and 1 having a common parent, and 2 and 3 having a common parent. Parents of these parents will have a common parent and so on.

Now, let's also assume that you have m teams, each with n/m players, you could assign players numbers in round-robin fashion such that the players from team i are numbered i, n/m+i, n/m*2+i, n/m*3+i, ...

Once that happens, you distribute them across the leaf nodes of your tree and that should maximize the distance between them.

Example:
If no. of players = 16, no. of teams = 4.
Team 0 players = 0, 4,  8, 12
Team 1 players = 1, 5,  9, 13
Team 2 players = 2, 6, 10, 14
Team 3 players = 3, 7, 11, 15

All of the players are equally distributed with as much distance as possible without sacrificing any other team's players' distances.

If the number of players are not the same on every team, then please do let know, I will take another attempt at it.


问:
Face Recognition(OpenCV) with MySQL and PHP
First of all I have asked this question on stackoverflow and got down vote for question being not belonging to the site. I am trying my luck se now(more suitable to se I guess) and I hope I will not get down vote from here too

I want to develop a face recognition app that searches the database for an image. I looked at opencv a little. I really liked it and I want to use it but the problem is I am planning to use PHP for server backend and OpenCV is in C++. My app will require lots of communication between PHP and C++ and also I will have to connect to the database and fetch images from them. Basically what I am planning to do is :

PHP will get the request which includes the desired image file

PHP will pass this image to my C++ code

C++ will search the database to find the person

C++ will pass the result to PHP

PHP will return the result to client

However this approach makes me really scared because there are lots of gray areas for me to how to do it. Should I use sockets to do the communication or IPC (POSIX Messages etc if possible) or should I use entirely C++ for my project(C++ server could be very difficult) or should I use PHP extensions(I know almost nothing about it). How can I use OpenCV with a Database and how can I perform a fast search(Hash values for grayscale cropped images maybe?). I also have to detect faces to train some images for a user which also requires the steps above. What are the suggestions you can make? Which way would be easiest for me to implement this application? Excuse me for the language and disorganized structure question but I am really worried about almost everything about the project and I really want to do it. Any guidance will be appreciated

答:
There do seem to be PHP wrappers for OpenCV, such as OpenCV For PHP.

Now, for the recognition part, I think that the best way to go is to use Artificial Neural Networks. ANN's can be trained to identify people within images and are more suited because they can handle relatively inconsistent inputs and produce relatively stable results. There does seem to be ANN implementations in PHP, such as FANN. The implementation of an ANN's should also be quite fast (once trained, that is) and will remove the need for a database, unless you will be using it for other things and/or persist the neural network itself.

This would mean that you can write your solution entirely in PHP.

That being said, my experience with wrappers is that you do not always get all the goodies provided by the original library, so with that in mind, you could also opt to have PHP handle your front end and then, use C++ as back end, which should allow you to exploit all the power of OpenCV (which could come in handy for future add-ons).

As for communication between the two layers, I think using standard SOAP web service communication (for PHP and C/C++) will provide you with a robust solution.


问:
What happens if you're unable to solve a problem?
I'm a year away from graduating from university, and I'm really looking forward to solving practical problems. Especially non-trivial ones which require a bit of research and a lot of thinking.

But at the same time, that is also my greatest fear - being faced with a problem that I'm unable to solve, no matter how hard I try. And with pressure to deliver code on impending deadlines just around the corner, it does look a bit scary when viewing it from the safe playgrounds on uni (where the worst thing that can happen is that you have to redo a course or exam).

So for those who have been in industry for any longer length of time, what would happen if you were told to solve a problem that you couldn't? Has it happened, and if so, what did happen? Did they just drop it and said "Oh well, guess we can make do with something else"? Were there consequences? Were you reprimanded, or even fired?

答: Usually, I get someone smarter than me to fix it.  He does and he's my boss.  I feel stupid.  We move on.</p>


问:
How can my team avoid frequent errors after refactoring?
To give you a little background: I work for a company with roughly twelve Ruby on Rails developers (+/- interns). Remote work is common. Our product is made out of two parts: a rather fat core, and thin up to big customer projects built upon it. Customer projects usually expand the core. Overwriting of key features does not happen. I might add that the core has some rather bad parts that are in urgent need of refactorings. There are specs, but mostly for the customer projects. The worst part of the core are untested (not as it should be...).

The developers are split into two teams, working with one or two PO for each sprint. Usually, one customer project is strictly associated with one of the teams and POs.

Now our problem: Rather frequently, we break each other's stuff. Someone from Team A expands or refactors the core feature Y, causing unexpected errors for one of Team B's customer projects. Mostly, the changes are not announced over the teams, so the bugs hit almost always unexpected.  Team B, including the PO, thought about feature Y to be stable and did not test it before releasing, unaware of the changes.

How to get rid of those problems? What kind of 'announcement technique' can you recommend me?

答:
We worst part of the core are untested (as it should be...).

This is the problem. Efficient refactoring depends heavily on suite of automated test. If you don't have those, the problems you are describing begin to appear. This is especially important if you use dynamic language like Ruby, where there is no compiler to catch basic errors related to passing parameters to methods.


问:
How does Telnet work?
Is telnet just a simple socket connection?

I usually have a difficult time in the networking area so I use some code from the internet to help me out, but I can't seem to find a library for Telnet in Objective-C.

The closest thing I've found is CocoaAsyncSocket

I was wondering, Is telnet just plain socket connections?

Do I just create a socket to the server and send the commands?

答:
Telnet is a bit more than just plain socket connections, but in many cases, just opening a socket to the server and sending the commands will do the trick anyway.

See the wikipedia page for more details and links to the RFCs.

Title: How does Telnet work?


答:
I would recommend reading Working Effectively with Legacy Code by Michael C. Feathers. It explains that you really need automated tests, how you can easily add them, if you don't already have them, and what "code smells" to refactor in what way.

Besides that, another core problem in your situation seems a lack of communication between the two teams. How big are these teams? Are they working on different backlogs?

It's almost always bad practice to split up teams according to your architecture. E.g. a core team and a non-core team. Instead, I would create teams on functional domain, but cross-component.

Title: How can my team avoid frequent errors after refactoring?

Body:
To give you a little background: I work for a company with roughly twelve Ruby on Rails developers (+/- interns). Remote work is common. Our product is made out of two parts: a rather fat core, and thin up to big customer projects built upon it. Customer projects usually expand the core. Overwriting of key features does not happen. I might add that the core has some rather bad parts that are in urgent need of refactorings. There are specs, but mostly for the customer projects. The worst part of the core are untested (not as it should be...).

The developers are split into two teams, working with one or two PO for each sprint. Usually, one customer project is strictly associated with one of the teams and POs.

Now our problem: Rather frequently, we break each other's stuff. Someone from Team A expands or refactors the core feature Y, causing unexpected errors for one of Team B's customer projects. Mostly, the changes are not announced over the teams, so the bugs hit almost always unexpected.  Team B, including the PO, thought about feature Y to be stable and did not test it before releasing, unaware of the changes.

How to get rid of those problems? What kind of 'announcement technique' can you recommend me?


答:
I think if you get 80% of the functionality you need off the shelf, you're doing well. So why not stop there?

A large corporation spending millions on staffing can save a lot of money if they can get the other 20%. I worked at a firm where the billing manager interrupted the IT staff during lunch because of a billing template error. I was a little put off at first, but learned the monthly bill was for over a million dollars (Typical for this client).

Many companies have too many people sitting around figuring out ways to spend other peoples money. "We must have a program that dynamically changes the company logo used for internal memorandum as a new holiday approaches." And somebody builds it because that's what they want. Too bad the time wasn't spent on the billing template.

Some department decides to buy the application/data silo that they see fit and then everyone wants all the data consolidated for reporting.

Title: Programmer VS Commercial Systems (ERP)

Body:
My question here is relative to jobs for programmers.

Why does employer still contract programmers if today we have a lot of good commercial system avaliable on the market?

I want to be very clear at this point, this question is relative only to a system, more specially to ERP systems.  Maybe this question looks a little bit useless, but right now I'm working and this doubt arose to me and my boss.

I have a few answers to my own question, but I really would like to speculate this subject a bit more.

Also I know, every good company needs a customized system, but ... the question is here. :-)

Any answer will make me feel better. Thanks.


问:
Failed to allocate memory - What is it trying to say?
In my early days of programming I often used to get memory related fatal errors in the following format:

```<code>Fatal error: Allowed memory size of <some big number> bytes exhausted
(tried to allocate <some small number> bytes) in /path/to/filename.php
on line <some line number>
</code>```

I'm a little embarrassed to state that even though I have figured out how to solve them and take steps to avoid them altogether, I'm still not quite sure what exactly does the message translate to in simple words.

For example, if I get a message such as:

```<code>Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 4000 bytes)
in ........ on line 34
</code>```

As things stand at the moment, I assume it to be stating that the script consumes 67108864 bytes of data, but only 4000 bytes are available during runtime.

Am I right in my assumption?

If not, what's the correct interpretation?

答:
Your program has 67108864 bytes (~67MB) available to it at runtime, all of which it has filled. The specific allocation which took the total memory usage from <67MB to >67MB was an allocation of 4000 bytes, which happened within the expression on line 34.

Basically, you're using too much memory, and all the interpreter can give you to help is the specific allocation which broke the camel's back. It could have been a one byte allocation, all that matters is that it took you over your memory limit.


问:
Maintaining Two Separate Software Versions From the Same Codebase in Version Control
Let's say that I am writing two different versions of the same software/program/app/script and storing them under version control. The first version is a free "Basic" version, while the second is a paid "Premium" version that takes the codebase of the free version and expands upon it with a few extra value-added features. Any new patches, fixes, or features need to find their way into both versions.

I am currently considering using master and develop branches for the main codebase (free version) along side master-premium and develop-premium branches for the paid version. When a change is made to the free version and merged to the master branch (after thorough testing on develop of course), it gets copied over to the develop-premium branch via the cherry-pick command for more testing and then merged into master-premium.

Is this the best workflow to handle this situation? Are there any potential problems, caveats, or pitfalls to be aware of? Is there a better branching strategy than what I have already come up with?

Your feedback is highly appreciated!

P.S. This is for a PHP script stored in Git, but the answers should apply to any language or VCS.

答:
In “hardware” this is done often, they are systems sold to control the mess, sorry I can’t remember what they are called.

Once the “mid range” washing machine ships, it’s code is not change other than for a very important bug fix, even when the same code gets changed in the “low end” washing machine that ships  a few months later.

Customers don't expect to get upgrades to a washing machine they have already brought, a new model is also not shipped every few months.

Most of us don’t live in that world, so do what Greg says unless you are writing software for washing machines.


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

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

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

答:
Strangely no one mentions this:

To make things a priority, make them easy: Get a good refactoring tool.

There are excellent refactoring tools out there (at least for .NET afaik). Oh, and don't forget to write unit tests beforehand (as others already pointed out).

Good luck!


答:
While most current answers are in favour of conditional compilation instead of branches, there is one scenario where there is a clear benefit to using branches: if you (now or later) decide to make the source code of the basic version available, including all the version history but excluding all the premium features, then you can do so with the branches approach but not with a single branch and conditional compilation.

I'd advise against cherry picking, and instead merge all changes from the basic version into the premium version. There should be no feature or bug fix included in the basic but missing in the premium version. To make things as painless as possible, you should make sure that the premium branch modifies the common files as little as possible. So the premium branch should mostly contain additional files, and perhaps some slight modifications to build instructions. That way, changes from the basic version will merge automatically without causing conflicts.

Greg's answer suggested that you “consider branches for things that will be (or might be) merged back together again later”. With the approach I just described this is the case, except that the final branch for all commits will be master-premium not master (which is actually master-basic).

Sub-modules would of course be an option as well. It depends on your build process, but if you can make the premium version into a project which uses the basic version as a module, that would be just fine. You might however have a harder time if at some point you decide to cherry-pick features from the premium branch into the basic branch. With sub-modules such a change would be represented as two distinct commits, whereas with branches this would be a single commit to the basic version, and the next merge into the premium version would know that these changes are already included and don't have to be merged again.

Title: Maintaining Two Separate Software Versions From the Same Codebase in Version Control

Body:
Let's say that I am writing two different versions of the same software/program/app/script and storing them under version control. The first version is a free "Basic" version, while the second is a paid "Premium" version that takes the codebase of the free version and expands upon it with a few extra value-added features. Any new patches, fixes, or features need to find their way into both versions.

I am currently considering using master and develop branches for the main codebase (free version) along side master-premium and develop-premium branches for the paid version. When a change is made to the free version and merged to the master branch (after thorough testing on develop of course), it gets copied over to the develop-premium branch via the cherry-pick command for more testing and then merged into master-premium.

Is this the best workflow to handle this situation? Are there any potential problems, caveats, or pitfalls to be aware of? Is there a better branching strategy than what I have already come up with?

Your feedback is highly appreciated!

P.S. This is for a PHP script stored in Git, but the answers should apply to any language or VCS.


答:
67108864 bytes are also known as 64 MiB (Mebibyte).
Many softwares like PHP still identifies 64 MB as 64 MiB, this is an historically grown issue.

Nowaday we define 64 000 000 bytes as 64 MB (Megabyte, 64 * 1000 ^ 2)
and 67108864 bytes as 64 MiB (Mebibyte, 64 * 1024 ^ 2).

Title: Failed to allocate memory - What is it trying to say?

Body:
In my early days of programming I often used to get memory related fatal errors in the following format:

```<code>Fatal error: Allowed memory size of <some big number> bytes exhausted
(tried to allocate <some small number> bytes) in /path/to/filename.php
on line <some line number>
</code>```

I'm a little embarrassed to state that even though I have figured out how to solve them and take steps to avoid them altogether, I'm still not quite sure what exactly does the message translate to in simple words.

For example, if I get a message such as:

```<code>Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 4000 bytes)
in ........ on line 34
</code>```

As things stand at the moment, I assume it to be stating that the script consumes 67108864 bytes of data, but only 4000 bytes are available during runtime.

Am I right in my assumption?

If not, what's the correct interpretation?


答:
Of the misc code I've written, most of the good stuff is in CCAN now, while the rest I tend to find better versions of in existing open source projects.  I find myself writing less and less general-purpose "misc" code these days, in favor of writing application-specific variants of such code, or of writing general-purpose modules that I can release by themselves.

C

Here's a function and typedef I've used more than once.  For applications that need timing, it's hard to beat milliseconds in terms of simplicity:

```<code>#include <stdint.h>
#include <sys/time.h>

typedef int64_t msec_t;

static msec_t time_ms(void)
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return (msec_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
}
</code>```

And more miscellaneous C functions that I tend to use over and over (and over):

```<code>/* Remove a trailing newline, if present. */
void chomp(char *buffer)
{
    if (!*buffer)
        return;

    while (*buffer)
        buffer++;

    if (buffer[-1] == '\n')
        buffer[-1] = 0;
}

/*
 * Skip whitespace, update the pointer, and return it.
 * Example:
 *
 * switch (*skipSpace(&s)) {
 *     case '\0':
 *         ...
 *     case '(':
 *         ...
 */
const char *skipSpace(const char **sptr)
{
    const char *s = *sptr;
    while (isspace(*s))
        s++;
    *sptr = s;
    return s;
}

/* Scramble an array of items uniformly. */
void scramble(void *base, size_t nmemb, size_t size)
{
    char *i = base;
    char *o;
    size_t sd;
    for (;nmemb>1;nmemb--) {
        o = i + size*(rand()%nmemb);
        for (sd=size;sd--;) {
            char tmp = *o;
            *o++ = *i;
            *i++ = tmp;
        }
    }
}
</code>```

Haskell

Haskell's nub :: (Eq a) => [a] -> [a] function is O(n²) because, by its type signature, it's only allowed to test if two elements are equal.  A simple O(n log n) alternative is map head . group . sort, but it requires forcing the entire input list before producing output, whereas nub can start producing output right away.  The following is an O(n log n) alternative to nub that collects already-seen items in a Data.Set:

```<code>module Nub (nub') where

import Prelude
import Data.Set (empty, member, insert)

nub' :: Ord a => [a] -> [a]
nub' xs = loop xs empty where
    loop [] _ = []
    loop (x:xs) set =
        if x `member` set
            then loop xs set
            else x : loop xs (insert x set)
</code>```

In Haskell, I use alternatives to sequence, mapM, forM, replicateM, and filterM.  These  actions each generate a list, but the list can't be used until the action completes in its entirety (if you're using a strict monad like IO).  The alternatives build the list in reverse rather than forming a tower of thunks, which I found through benchmarking to be faster, at least with GHC.

```<code>sequence' :: Monad m => [m a] -> m [a]
sequence' ms = loop ms [] >>= return . reverse where
    loop []     xs = return xs
    loop (m:ms) xs = do
        x <- m
        loop ms (x:xs)

mapM' :: Monad m => (a -> m b) -> [a] -> m [b]
mapM' f xs = sequence' $ map f xs

forM' :: Monad m => [a] -> (a -> m b) -> m [b]
forM' = flip mapM'

replicateM' :: Monad m => Int -> m a -> m [a]
replicateM' n x = sequence' (replicate n x)

filterM' :: Monad m => (a -> m Bool) -> [a] -> m [a]
filterM' pred xs = loop xs [] >>= return . reverse where
    loop []     xs' = return xs'
    loop (x:xs) xs' = do
        keep <- pred x
        loop xs (if keep then (x:xs') else xs')
</code>```

Note: sequence_, mapM_, forM_, and replicateM_ functions are still a better choice if you aren't interested in the result list.

Title: Do you have your own 'misc utils' library? What part are you most proud of?

Body:
I know that many of us maintain our own little personal library with tools and utilities that we use often.

I've had mine since I was 16 years old so it has grown to quite a considerable size. Some of the stuff I've written has since been added to the framework. I wrote my own little implementation of expression trees for use with genetic algorithms long before LINQ, which I quite like and was proud of at the time - of course its pretty useless now. But recently I have been going through it and upgrading to .NET 4.0 and re-kindled an interest.

So I'm curious as to what you use your library for. Maybe we could get some cool ideas going for useful little snippets and share them amongst ourselves.

So my questions are:

Do you have a miscellaneous utility library?

Which part are you most proud of and why?

Give an example of code if you like :-)

Body:
Of the misc code I've written, most of the good stuff is in CCAN now, while the rest I tend to find better versions of in existing open source projects.  I find myself writing less and less general-purpose "misc" code these days, in favor of writing application-specific variants of such code, or of writing general-purpose modules that I can release by themselves.

C

Here's a function and typedef I've used more than once.  For applications that need timing, it's hard to beat milliseconds in terms of simplicity:

#include <stdint.h>
#include <sys/time.h>

typedef int64_t msec_t;

static msec_t time_ms(void)
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return (msec_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
}

And more miscellaneous C functions that I tend to use over and over (and over):

/* Remove a trailing newline, if present. */
void chomp(char *buffer)
{
    if (!*buffer)
        return;

    while (*buffer)
        buffer++;

    if (buffer[-1] == '\n')
        buffer[-1] = 0;
}

/*
 * Skip whitespace, update the pointer, and return it.
 * Example:
 *
 * switch (*skipSpace(&s)) {
 *     case '\0':
 *         ...
 *     case '(':
 *         ...
 */
const char *skipSpace(const char **sptr)
{
    const char *s = *sptr;
    while (isspace(*s))
        s++;
    *sptr = s;
    return s;
}

/* Scramble an array of items uniformly. */
void scramble(void *base, size_t nmemb, size_t size)
{
    char *i = base;
    char *o;
    size_t sd;
    for (;nmemb>1;nmemb--) {
        o = i + size*(rand()%nmemb);
        for (sd=size;sd--;) {
            char tmp = *o;
            *o++ = *i;
            *i++ = tmp;
        }
    }
}

Haskell

Haskell's nub :: (Eq a) => [a] -> [a] function is O(n²) because, by its type signature, it's only allowed to test if two elements are equal.  A simple O(n log n) alternative is map head . group . sort, but it requires forcing the entire input list before producing output, whereas nub can start producing output right away.  The following is an O(n log n) alternative to nub that collects already-seen items in a Data.Set:

module Nub (nub') where

import Prelude
import Data.Set (empty, member, insert)

nub' :: Ord a => [a] -> [a]
nub' xs = loop xs empty where
    loop [] _ = []
    loop (x:xs) set =
        if x `member` set
            then loop xs set
            else x : loop xs (insert x set)

In Haskell, I use alternatives to sequence, mapM, forM, replicateM, and filterM.  These  actions each generate a list, but the list can't be used until the action completes in its entirety (if you're using a strict monad like IO).  The alternatives build the list in reverse rather than forming a tower of thunks, which I found through benchmarking to be faster, at least with GHC.

sequence' :: Monad m => [m a] -> m [a]
sequence' ms = loop ms [] >>= return . reverse where
    loop []     xs = return xs
    loop (m:ms) xs = do
        x <- m
        loop ms (x:xs)

mapM' :: Monad m => (a -> m b) -> [a] -> m [b]
mapM' f xs = sequence' $ map f xs

forM' :: Monad m => [a] -> (a -> m b) -> m [b]
forM' = flip mapM'

replicateM' :: Monad m => Int -> m a -> m [a]
replicateM' n x = sequence' (replicate n x)

filterM' :: Monad m => (a -> m Bool) -> [a] -> m [a]
filterM' pred xs = loop xs [] >>= return . reverse where
    loop []     xs' = return xs'
    loop (x:xs) xs' = do
        keep <- pred x
        loop xs (if keep then (x:xs') else xs')

Note: sequence_, mapM_, forM_, and replicateM_ functions are still a better choice if you aren't interested in the result list.


问:
Is method overriding always a violation of Liskov Substitution Principle?
Overriding a method originally defined in the super class, by definition means this method will do different things when invoked on an object of the base class or an object of the subclass.

So does this mean that overriding methods always means violating LSP? Or are there cases when it doesn't?

答:
By definition different things? Whaddayoumean?

Liskov says you should not "go against" your ancestor's behavior. Doesn't mean that you cannot extend or augment it by doing stuff in addition to that base behavior.

In your overridden method you call inherited to execute the ancestor's behavior (honoring Liskov) and then can do stuff in addition to that.

Not calling inherited at all (*) would be a Liskov violation (unless you re-code the base's implementation, which I'd strongly advice against). Update @Ratchetfreak actually has a pretty neat example where a descendant would only call inherited if it hadn't already cached a result for an otherwise "expensive" calculation.

(*) please note that I am used to a language where you can call inherited regardless of whether the ancestor or the ancestor method is marked abstract. The compiler takes out the call.


问:
How to name a method that both performs a task and returns a boolean as a status?
If there is a method

```<code>bool DoStuff() {
    try {
        // doing stuff...
        return true;
    }
    catch (SomeSpecificException ex) {
        return false;
    }
}
</code>```

should it rather be called IsStuffDone()?

Both names could be misinterpreted by the user:
If the name is DoStuff() why does it return a boolean?
If the name is IsStuffDone() it is not clear whether the method performs a task or only checks its result.

Is there a convention for this case? Or an alternative approach, as this one is considered flawed? For example in languages that have output parameters, like C#, a boolean status variable could be passed to the method as one and the method's return type would be void.

EDIT: In my particular problem exception handling cannot be directly delegated to the caller, because the method is a part of an interface implementation. Therefore, the caller can't be charged with dealing with all the exceptions of different implementations. It is not familiar with those exceptions. However, the caller can deal with a custom exception like StuffHasNotBeenDoneForSomeReasonException as was suggested in npinti's answer and comment.

答:
I would pick a name based on the primary role of the method. The fact, that method returns boolean value doesn't mandate 'Is' prefix. Let's have some Java code, which uses 'Is' prefix quite extensivelly. Take look at java.io.File.delete(). It returns boolean, but it isn't called isFileDeleted(). The reason is that the primary role of the metod is to delete a file. Someone calls this method with the intention to delete a file.

The boolean is there just to comunicate back the result of the work. On the other hand let's see java.util.Map.isEmpty(). Obviously, you call such a method to find out if the collection is empty. You do not want any stuff done. You just want to find out what the current state is.

So personally, I would definitelly stick with DoStuff().

This is somewhat a very important issue for me. Many times when I maintain legacy code, I do stumble upon something I call personally "lying method". Name suggests action A, but the body does action B. The most bizzare example beeing a getter method changing data in the database.


问:
Best Practices: Database app programming patterns
I have written many database (MySQL) web apps so far but I always think my structure is kinda clumsy. I want to improve the programming/design pattern I use, hoping for some advice here. Particularly, I cannot find a structure that complements an OOP approach that encapsulates the implementation of the database (schema). I

Think my question can be best explained by example. There are 2 approaches I use now say I have an Invoice object/class:

first is to use static member functions

```<code>class Invoice
{
   int id;
   string ref;
   int customer_id;
   date created;
   date due;

   static id create();
   static bool update(id, field1, field2, ...);
   static bool delete(id);
   static bool get(id);
};
</code>```

The second approach is to put every thing in a database object:

```<code>class Database extends ProprietaryDBConnecter, Singleton
{
   id createInvoice();
   bool updateInvoice(id, field1, field2, ...);
   bool deleteInvoice(id);
   bool getInvoice(id);

   id createCustomer();
   bool updateCustomer(id, field1, field2, ...);
   bool deleteCustomer(id);
   bool getCustomer(id);

   // etc...
}
</code>```

I find that both ways the (SQL) member functions are very much unseparable from the "view", in that the "view" determines what the classes needs to have and hence seems to break the document/view architecture.

Also, it seems kind of inefficient for example a SELECT statement should only select what is needed, but the presence of member variables in Invoice seems to imply "guaranteed data".

Don't know if I explained the question clearly, What are some other best approaches to this architecture/design pattern/what-it-is-known-as?

Thanks for advices

答:
I cannot find a structure that
  complements an OOP approach that
  encapsulates the implementation of the
  database

Seems like you're describing the Object-relational impedance mismatch.

There are number of things that are supposed to solve this OODBMS, ORM tools, a host of data access tools.

I think the fact that there's so many solutions leads me to believe that One True Solution™ doesn't exist.

So you can pick any direction you like secure in the knowledge that some people will hate it and some will love it.


答:
First simple case: adding caching to an expensive operation. there is no functional difference between the original and the new function.

Also the original function could be documented to do something and as long as the overriding function still fits within that documentation then there is no problem (the core of the substitution principle). Remember you should code against the API not the implementation.

Title: Is method overriding always a violation of Liskov Substitution Principle?

Body:
Overriding a method originally defined in the super class, by definition means this method will do different things when invoked on an object of the base class or an object of the subclass.

So does this mean that overriding methods always means violating LSP? Or are there cases when it doesn't?


答:
The previous answers that point you to better unit tests are good, but I feel that there might be more fundamental issues to adress.
You need clear interfaces for accessing core code from the code for the customer projects.
This way if you refactor the core code without altering the behaviour as observed through the interfaces, the other team's code will not break. This will make it much easier to know what can be "safely" refactored, and what needs a, possibly interface breaking, redesign.


答:
LSP forbids to violate the contracts of a supertype in a subtype, it does not forbid to change the behaviour of any method (within the bounds of that contract).

For example, lets assume you have a superclass Report, associated with a certain object Foo, with a method ToString(), and subtypes HTMLReport, XMLReport and TextReport. Lets further assume Report is not abstract and the default implementation of ToString() is to return the empty string. Now you define a contract in the following manner:

ToString() shall deliver a string with a textual representation of Foo in a certain text format (and the empty string if the format is not defined so far).

ToString() shall not mutate the Report object

ToString() shall never throw an Exception

So the subclasses can easily override the ToString method, each one implementing a different behaviour, but all perfectly following the LSP.

On the other hand, if your contract would be

ToString() shall always return the empty string

then overriding it and return something different would violate the LSP - but such a contract would obviously make not much sense for any real world scenario.


问:
Fixing a spelling mistake in a method name
One of the methods that I commonly use in our codebase is misspelled (and it predated me).

This really irritates me not simply because it is mispelled but more importantly it makes me ALWAYS get the name wrong the first time I type it (and then I have to remember "Oh, right, it should be mispelled to this...")

I'm making a few changes around the original method. Should I take the opportunity to just rename the freaking method?

答:
I've done this a few months ago (for different reasons). The steps I took (the language was Perl):

Rename the method. Alias the old name to the new name (this should not break any code, as the method can be called by either name).

Inform the rest of the developers about the name change and why, telling them to use the new name from now on.

Grep the code base for the old name, fix any occurrences.

Log any uses of the old name (using the old name should still work at this time). Fix those cases.

Wait (while doing 4.), until no more entries appear in the log.

Break the alias. Make a method using the old name that throws a fatal exception with a message about the name change.

After some time, remove the method with the old name.

Of course, your mileage will vary.