问:
What do you do to estimates for agile stories where developers are pair programming?
If it was a 2-point story for one person, would you double it if people are pairing?

Pairing isn't always necessarily done 100% of a dev task, so it seems that doubling the story points seems wrong.  And it might not be obvious how much of the task will require pairing until the end, so you wouldn't know what the points the story should be until you've finished - and it seems strange to change an estimate midway through a sprint.

However, if velocity is going to be an accurate representation of how much work we can get through during a sprint, it seems right to change the estimates if more than one person is working on a task.  But also, this seems like it adds a lot of admin overhead.

Thoughts?

答:
To follow up on this....

I met with a scrum consultant last week and asked this very question of him - his response was that it shouldn't change the way you estimate story points.  If you do pair programming on one story, the expectation is you are doing a level of pair programming on many/all stories, so any over/unders in manhours effort should even out over time, and shouldn't affect velocity.


问:
Is it common to run out of work towards the end of a sprint?
My current team operates under the Scrum approach to agile development. We do it properly, adhering to the guidelines and roles of a Scrum team, with a sprint length of 9 days and a team of 7.

We go through the backlog in the grooming and planning meetings, estimating what we need to, negotiating with the product owner etc and come up with a sprint of a point size meeting our velocity. However, the problem is this: towards the end of the sprint (up to 2 or 3 days prior to the finish) some (not all) team members find they have little work to be doing whilst others are finishing off/working on tasks which can't easily/reasonably be worked on by more than the current number of developers. The usual result of this is pulling extra work in - but  because we're nearing the end of the sprint, the work pulled in tends to be a series of bug fixes and small tasks which might usually occupy a single developer for a day.

My question is this: is running low on work toward the end of a sprint common? Is there anything which can be done to avoid it? Improve the situation?

答:
My team faces the same terrible problem: We always end up finishing our sprints ahead of schedule.

All joking aside it can be an indicator that something is wrong with estimation or expectations:

Are you consistently overestimating tasks and giving management a poor timeline of what to expect?

Do you have more developers than you need? (Shh, don't tell accounting.)

Or is your team really just that good that they consistently exceed expectations.

Deciding which of the above applies to you is up to you and your team and beyond the scope of the question, but the fact remains that if you are consistently getting done early, then your management is going to have an imperfect picture of what to expect from you. Either you can work on creating more accurate estimations, or management is going to just start expecting you to finish every sprint early. Finishing consistently early is almost as bad as finishing consistently late, but still not as good as getting it close every time.

As to what you should do is finish the sprint early and start on the next sprint right away. If you find that you're waiting to close the sprint up on a few tasks that only a couple people can do, then you're probably doing it wrong. Every person on the team should be able to do any task to a relative degree. If you have a Bus Factor of 1, something is wrong. Invest the time in your team to bring every member up to speed on the different aspects of the system, even if only for rare occurrences. You'll see that investment pay for itself when team members can talk about the project as a whole from top to bottom.

Try to break down these tasks that hold you back so that everyone can be working up until the tail end of the sprint. If you find that you can't break these tasks down, tackle them earlier so that everyone has something to work on, that way you can close the sprint early and start on the next one. Or, if your boss is cool with it you can always just take a few days off, but I'll let you figure out how to break that one to him.

ContentLicense: CC BY-SA 3.0


问:
ASP MVC Action parameters all strings vs explicit type
A colleague and I were developing an ASP.NET MVC project and during this we created a new action method to handle one of our views.  I initially started created the action like so:

```<code>public ActionResult Index(int id, int numberOfAssessments, int age)
{
    // do stuff
}
</code>```

However when I started writing we had a little discussion:

Him:"Why am I making these ints, they should all be strings"

Me: "Well they are ints so it makes more sense to make them strongly typed and so stop potential errors later in the code block".

Him: "Back what if we wanted to change the id to a alpha-numeric representation.  We know have to change this signature everywhere where if it was a string it would already handle this".

Me: "It's not a string now and we don't have any plans for making it a string at this moment though".

We didn't really decide explicitly what to do but it did get me thinking.

Question:

Should parameters to Action methods be all strings if that is going to make it more flexible in the future, or should they be specific to their type so that we can leverage MVC binding and error handling?  What is the best or accepted practice in these situations.

Are there too many considerations to take in for any definitive answer?

答:
I'd suggest that you only write the code to solve your current problem and your current problem only.

If taking advantage of the MVC binding, client-side validation, etc. makes solving your current problem easier, then by all means go with what addresses the current problem that you're trying to solve.

And just in case I wasn't clear before, only focus on your current problem.


问:
Is seniority/paygrade an important factor for effective QA members?
As a member of our company's QA team, I frequently get entirely unenthusiastic feedback from developers in their responses to test results in our agile, web-based software-as-a-service shop. Most of our testing is manual, since automated testing doesn't really make sense for us right now, and developers are usually reluctant to listen to any change suggestions beyond those that prevent javascript/500 errors. I understand that fixes/changes require work, and our developers are rarely short on work to do, but I don't think developers respect QAs input.

Unfortunately, our product owners are vacant: acceptance testing doesn't exist, and user stories usually are only one sentence long, and don't provide the developer with much to go off of. There is no other feedback mechanism to development other than from customers x-weeks later, who aren't designers/developers either, of course, and whose suggestions are all over the board.

I am technically competent, at worse, and am capable of simple development on our LAMP stack and feel confident that developers respect my knowledge. However, I have for the most part given up on feedback beyond that which prevents critical errors--which affect data integrity, or bottom-line functionality.

This has raised the question of whether seniority, or pay grade is a significant factor in how seriously developers value QAs input. In our case, where we don't do automated testing and QA members likely don't have as much technical expertise, it kind of makes sense that we make less than developers (between 60-70%, depending on time in grade). I don't believe in the argument that the opinion of the team member with the biggest pay check is the most important, however I can imagine how it's difficult to take feedback from team members who have a year or two less experience, are not as technically knowledgeable, and make noticeably less. In the end the best idea should win, but unfortunately that might be decided after the enhancement has been on production for several months, and users love it or hate it.

答:
As a member of our company's QA team, I frequently get entirely unenthusiastic feedback from developers in their responses to test results in our agile, web-based software-as-a-service shop.

That's because:

Our product owners are vacant: acceptance testing doesn't exist, and user stories usually are only one sentence long, and don't provide the developer with much to go off of. There is no other feedback mechanism to development other than from customers x-weeks later, who aren't designers/developers either, of course, and whose suggestions are all over the board.

QA feedback only has teeth when you have clear, measurable, actionable requirements that drive both the development and testing efforts, and developers that care about producing a quality product which meets those requirements.  You must have requirements that allow you to declare success.  You can't constantly move the goal posts and expect developers to be enthusiastic about scoring touchdowns.

See Also

Characteristics of Good Requirements


答:
It sounds to me like you have a dysfunctional team with a cowboy culture and you're trying to figure out what the root cause is. You are proposing a hypothesis that maybe developers don't respect test because of some sort of implicit hierarchy or length of service or some other factor, but you're not necessarily presenting evidence for the case, you're essentially asking "could this be what's wrong?"

In fact, it sounds like many things are wrong with the organization, and any issues driven by perceptions of status or power are merely symptomatic of poor leadership. You are not an agile shop if you are not practicing any of the enabling mechanisms of agile development. One line stories are not agile; those are mere bullet points on wishlists. A story contains a business motivation, a description of the customer's interaction with the product, and a definition of when the story is done. If you don't have those three things, you don't have enough information to decide what should happen or how you know you've done it right, so the story will never be "done". That's treading water, not making progress. Developers will never be short of work to do in such organizations, because they'll constantly be firefighting, aided only by tiny buckets of their own urine.

Some of the "definition of done" can be part of a general team agreement, but specific acceptance criteria for any story, even if terse, are essential.

There are very few cases in which "automated testing doesn't really make sense for us right now". It may be the case that the test team isn't the right organizational locus to deliver automated testing, especially early on, but it always makes sense to have automated testing. While it's ok in my book for developers to do a little bit of exploratory coding without formal automated tests (I'm not a TDD or even BDD purist), it seems horrifying to me as a developer that I'd consider releasing code to a test organization with no developer-written automated tests. Unit Tests and BDD tests, written by developers, and scenarios preferably written by Product Owners, are essential parts of agile delivery.

Figuring out the best use of a test organization in an agile team is a tricky problem for which there is no single formula for success. In an organization which has no definition of done, it will be highly difficult to demonstrate value, because there's no way of knowing if the test team has contributed to "done." I've worked in old school waterfall teams as well as agile teams with 1) no distinct test organization or 2) moderately integrated test teams, 3) partially integrated test teams with separate stories and work product, and 4) gated release models, where some QA involvement happened alongside ordinary development but there was a distinct "test pass" due to some legacy or regulatory reason.

The "right" model for the test team will actually depend on the level of technical sophistication of the test team members. I think having test team members with moderate or better technical sophistication pair with a developer while writing code, to suggest cases for automation, can be a great model. But a test team can be reasonably effective in validating that the stories have measurable acceptance criteria, doing some exploratory testing as developers check in code, and trying to augment developer unit testing with integration scenarios and fleshing out special cases. It's even sort of ok to have a throw-the-build-over-the wall approach in some circumstances, as long as there's a way of converting stories into test cases and there's some sort of feedback loop with the Product Owners and Developers.

But you won't really get there without active buyoff from your management and product owners on what the organizational priorities are and what test's role should be. I doubt there've been any serious conversations in your team other than "oh, I've worked on other software projects and that means I know we need to have some sort of test effort. Let's hire a test team." Most average and some above average developers will be tolerant of organizational inertia that doesn't demand they engage with the test team. In order for real progress to be made, some management or consensus driven initiative to drive "better" development practices needs to happen.

As a developer and as a former STE, STE Lead and SDET, I have nearly zero interest in how senior the test team members are or how much they are paid. What I care about is how they can help me ship better software. I personally like leveraging the skills of people who can work through tons of scenarios that I can't meaningfully explore given the team's desired organizational velocity; I'd be happy to walk through a test team member on how to start from existing unit tests or scenarios and build better coverage, or read test plans and provide feedback. But I might settle for focusing on "just good enough" coverage on my end and let the product owners and maybe just hope that the testers catch what I miss, if that's all the organization appears to value.

Somehow, either you are going to need to start selling to your management or to your most sympathetic developers on taking a more, dare I say it, agile approach to development and quality. I can't give you a formula for this, because I've not been that great at driving such things in organizations resistant to change, but the best you can hope for is a business value driven case (talking to the business side) or perhaps a craftsmanship/continuous improvement case on the technical side.

Title: Is seniority/paygrade an important factor for effective QA members?

Body:
As a member of our company's QA team, I frequently get entirely unenthusiastic feedback from developers in their responses to test results in our agile, web-based software-as-a-service shop. Most of our testing is manual, since automated testing doesn't really make sense for us right now, and developers are usually reluctant to listen to any change suggestions beyond those that prevent javascript/500 errors. I understand that fixes/changes require work, and our developers are rarely short on work to do, but I don't think developers respect QAs input.

Unfortunately, our product owners are vacant: acceptance testing doesn't exist, and user stories usually are only one sentence long, and don't provide the developer with much to go off of. There is no other feedback mechanism to development other than from customers x-weeks later, who aren't designers/developers either, of course, and whose suggestions are all over the board.

I am technically competent, at worse, and am capable of simple development on our LAMP stack and feel confident that developers respect my knowledge. However, I have for the most part given up on feedback beyond that which prevents critical errors--which affect data integrity, or bottom-line functionality.

This has raised the question of whether seniority, or pay grade is a significant factor in how seriously developers value QAs input. In our case, where we don't do automated testing and QA members likely don't have as much technical expertise, it kind of makes sense that we make less than developers (between 60-70%, depending on time in grade). I don't believe in the argument that the opinion of the team member with the biggest pay check is the most important, however I can imagine how it's difficult to take feedback from team members who have a year or two less experience, are not as technically knowledgeable, and make noticeably less. In the end the best idea should win, but unfortunately that might be decided after the enhancement has been on production for several months, and users love it or hate it.


问:
How would you evaluate object oriented design skills?
what kind of insights or questions would lead you to determine a person's OOAD skills.</p>

答:
I tend to pick a real world scenario, something well known to anyone† and ask them to identify the entities; the actors involved; what interactions there are between them; where common features could be abstracted; what properties need be considered.

Yes, you could ask them to sit down and draw UML, yes you could ask them searching questions on some OOP implementation specifics to see if they can "hit the ground running".

But what an employer really needs within their team is a mind that understands the concepts involved and can apply them to whatever turns up.  Specifics can be learnt quickly, when concepts are embedded.

† Deep familiarity and an absence of a connection with code help: A family's use of a bathroom in the morning; cooking dinner; a bus route to work; the assembly of a car.

ContentLicense: CC BY-SA 2.5


答:
Should parameters to Action methods be all strings if that is going to make it more flexible in the future, or should they be specific to their type so that we can leverage MVC binding and error handling?

In short: No, each parameter should represent the type that your method expect. Otherwise, you would need check each parameter and cast them to specific types within the method.

As an example, take the DateTime type. If you pass it as a string then you would need to have casting to get the actual DateTime value, while MVC model binding provides that out of the box.

Currently, our team is working on a large asp.net mvc application, and we follow several good practice in the project. One of them is to allow nullable types for parameters that may have null values, when the requested or posted. This approach helps a lot with optional search parameters that end user may/may not provide.

Title: ASP MVC Action parameters all strings vs explicit type

Body:
A colleague and I were developing an ASP.NET MVC project and during this we created a new action method to handle one of our views.  I initially started created the action like so:

```<code>public ActionResult Index(int id, int numberOfAssessments, int age)
{
    // do stuff
}
</code>```

However when I started writing we had a little discussion:

Him:"Why am I making these ints, they should all be strings"

Me: "Well they are ints so it makes more sense to make them strongly typed and so stop potential errors later in the code block".

Him: "Back what if we wanted to change the id to a alpha-numeric representation.  We know have to change this signature everywhere where if it was a string it would already handle this".

Me: "It's not a string now and we don't have any plans for making it a string at this moment though".

We didn't really decide explicitly what to do but it did get me thinking.

Question:

Should parameters to Action methods be all strings if that is going to make it more flexible in the future, or should they be specific to their type so that we can leverage MVC binding and error handling?  What is the best or accepted practice in these situations.

Are there too many considerations to take in for any definitive answer?


问:
How can designing for inheritance cause extra cost?
So I wanted to inherit from a sealed class in csharp and got burned. There is just no way to unseal it unless you have access to the source.

Then it got me thinking "why sealed even exists?". 4 months ago. I couldn't figure it out, despite reading many things about it, such as:

Jon Skeet's wishes "classes were sealed by default in .NET."

Prefer composition over inheritance?

"You should not seal all classes (...)"

How do you mock a Sealed class?

I've tried to digest all that since then, but it's just too much for me. Eventually, yesterday I tried it again. I've scanned over all of them again, plus few more:

Why should a class be anything other than "abstract" or "final/sealed"?

In over 15 years programming, first time I've heard of SOLID, out of an answer from a question already linked and I obviously didn't read it all 4 months ago

Finally, after lots of pondering, I decided to heavily edit the original question based on the new title.

The old question were too broad and subjective. It was basically asking:

In the old title: One good reason to use sealed

In the body: How to properly modify a sealed class? Forget about inheritance? Use composition?

But now, understanding (which I didn't yesterday) that all sealed does is preventing inheritance, and we can and should indeed use composition over inheritance, I realized what I needed was practical examples.

I guess my question here is (and in fact have always been) exactly what Mr.Mindor suggested me in a chat: How can designing for inheritance cause extra cost?

答:
First of all, you should read Eric Lippert's post on why Microsoft seal their classes.

Link

Secondly, the sealed keyword exists to do exactly what it does - prevent inheritance.  There are many situations where you want to prevent inheritance.  Consider a class that you have a collection of.  If your code depends on that class working in a particular fashion you don't want someone overriding one of the methods or properties in that class and causing your application to fail.

Thirdly, using sealed encourages composition over inheritance, which is a good habit to get into.  Using composition over inheritance means that you can't break Liskov's substitution principle and you're following the Open/Closed principle.  sealed is therefore a keyword that assists you in following two of the five most important principles of o-o programming.  I'd say that makes it a very valuable feature.

ContentLicense: CC BY-SA 4.0


答:
Is seniority/paygrade an important factor for effective QA members?

In short: No, it is not. The effective QA member is the one who provides Quality Assurance of deliverable (for ex: module functionality) by verifying them against the requirements. They are valuable team members who spot out requirement gaps, wrong implementation of business rules in the application and in the database system.

As a developer, we do respect and value a well versed QA, who has good understanding of software development process, open to lean/understand new things, and posses scripting skills to check correctness of data entries in the database with good humor and attitude toward the team members.


答:
You're actually asking two different questions here.

Should MVC parameters all be strings?

Of course they shouldn't. The fact that you may want to change the type later is an absurd argument; somewhere, somehow, some component is going to be depending on that ID being a specific type, and it's not going to be any easier or less risky in the future to change a bunch of casts and type checks than it is going to be to change the type of a parameter.

If the designers of ASP.NET MVC didn't want you to use strong-typed parameters (or the more sophisticated equivalent, model binding with strong-typed properties) then they wouldn't have written a ton of code to support exactly that scenario. Strong typing is one of the main reasons to use a framework like MVC, instead of legacy frameworks where you had to screw with Request.QueryString and so on.

If you miss the good old days of Request.Form and Request.QueryString and don't think you'll ever need to overload any of your action methods, then by all means turn all your parameters into strings for nostalgia. If you still have some measure of sanity left, you'll leverage the extensive validation that's built into MVC for your convenience and use the correct types.

Should IDs be strings?

This is a much more difficult question to answer because very often it depends on the ID.

A lot of the time you may have different developers and/or different teams working on the same product or feature. Often there will be domain model code and/or APIs written before anyone has any clue about how or where it's going to be stored. Other times you'll be working in a DDD/BDD style and want to express the fact that it really doesn't matter what type it is because there's no validation associated with it.

You see, web APIs lend themselves very well to the string-as-ID model, because no matter what the underlying type turns out to be, the error handling is trivially simple: Try to convert to the expected type, and if conversion fails, then return a 404. An invalid ID is functionally the same as a missing resource.

The above doesn't work if you allow the client to specify its own IDs for new resources, but then again, if you're going to allow the client to specify its own IDs, you really should make the ID a string instead of imposing arbitrary and probably undocumented restrictions on the client. Non-string IDs are usually non-strings specifically because they need to be auto-generated, e.g. an integer sequence, a GUID, a BSON Object ID, etc. If your ID isn't auto-generated, a string is typically the best choice for your underlying data model because it allows for the most human-readable IDs.

I prefer to use string IDs in my API and/or view models because it saves me having to worry about what the database guys are doing and/or potentially have to face a type change. But that is merely personal preference from my own experience and certainly not a hard and fast rule about MVC; there are certain frameworks/products that have real trouble with string IDs (RavenDB, I'm lookin' at you) so it's not a decision you should make lightly, not unless you can understand and predict the consequences.

So there is some merit to the argument about making the ID a string - but not to making all of the parameters strings for no real reason. That's just weird and I'd take a hot steaming dump on it if I ever saw it in a code review.


问:
How can I stop myself overwriting member variables with 'new' ones?
The bulk of my programming experience has been with C++ and (shudder) FORTRAN (I'm a scientist not a programmer as such, but I do my best). I've recently started using python extensively and find it great. However, I just spent a frustrating few hours tracking down a bug that turned out to be caused by me creating a new object member in a function, i.e.

```<code>def some_func(self):
    self.some_info = list()
</code>```

but, I had already created elsewhere the member some_info for this object for a different purpose, so bad things obviously happened later on, but it was tricky to track back to here.

Now obviously in a language like C++ this is impossible to do, since you can't just create object members on the fly. Because I'm used to the language taking care of this, I don't have a well developed procedural discipline to prevent me abusing the freedom that python (and other dynamically typed languages) provides.

So what is the best way to prevent this kind of mistake when using languages like python?

答:
This may be a somewhat trivial advice, but try not to create attributes outside of __init__ method (especially not outside the class's methods), unless you really need to. pylint catches this, among many other things.

Of course, there is still a possibility of reassigning an existing attribute to something else entirely, but at least you will have a single place where you can see all the attributes at once. Also this will ensure that right after the construction your object is valid and does not require calls to any other internal state-changing methods.


答:
In a nutshell, you make your classes smaller, small enough that such conflicts are easy to spot.  Usually when you can't find a way to create a member in __init__ that's a good sign you might want to split it into its own class.  Also, avoid using a member when a local variable will do.

When a programming language doesn't impose practices, you have to impose them yourself.

Title: How can I stop myself overwriting member variables with 'new' ones?

Body:
The bulk of my programming experience has been with C++ and (shudder) FORTRAN (I'm a scientist not a programmer as such, but I do my best). I've recently started using python extensively and find it great. However, I just spent a frustrating few hours tracking down a bug that turned out to be caused by me creating a new object member in a function, i.e.

```<code>def some_func(self):
    self.some_info = list()
</code>```

but, I had already created elsewhere the member some_info for this object for a different purpose, so bad things obviously happened later on, but it was tricky to track back to here.

Now obviously in a language like C++ this is impossible to do, since you can't just create object members on the fly. Because I'm used to the language taking care of this, I don't have a well developed procedural discipline to prevent me abusing the freedom that python (and other dynamically typed languages) provides.

So what is the best way to prevent this kind of mistake when using languages like python?


问:
Can we reduce confusion in line-based diff tools by annotating the code with some unique tokens?
Let's say I have

```<code>procedure1() {
    --body of first procedure--
}
</code>```

Then I rename it into procedure2 and create a procedure1 above it:

```<code>procedure1() {
    --body of second procedure--
}

procedure2() {
    --body of first procedure--
}
</code>```

Not once a line-based diff tool has highlighted the code from --body of second procedure
all the way to procedure2() { as new code inside procedure1.

This is bound to happen, since most diff tools are oblivious of the underlying structure of the source code. AST-based diff tools can't work very well either, because of several reasons and I know what people really want is a semantic diff tool, but that's not going to happen.

I haven't seen a discussion though, about whether or not it would be practical to annotate the code in such a way that a line-based diff tool would understand the underlying structure of the source code.

For example, I could throw in some UUIDs in the code, like this:

```<code>//BeginBlock{E999A3BF-626E-428F-A2C1-6AFF0CD22BF2}
procedure1() {
    --body of first procedure--
}
//EndBlock
</code>```

And the modified code would look like this:

```<code>//BeginBlock{7C734F0A-92F4-45EB-B653-DBB9A0F18354}
procedure1() {
    --body of second procedure--
}
//EndBlock

//BeginBlock{E999A3BF-626E-428F-A2C1-6AFF0CD22BF2}
procedure2() {
    --body of first procedure--
}
//EndBlock
</code>```

The point is to assign some tokens (unique within a file or project) to some marks that would reflect part of the structure of the source code.

An IDE could update those annotations automatically and they could help a diff tool better detect structural changes. The tool would scan the code once to identify the sections of the program (and how they've been moved around) and then compare those blocks having the same ID.

Do you think this approach is practical?

答:
The Patience Diff algorithm is designed to address this, insofar as it is possible to do so with unannotated text. From that article:

[Patience Diff] only considers lines that are (a) common to both files, and (b) appear only once in each file. This means that most lines containing a single brace or a new line are ignored, but distinctive lines like a function declaration are retained. Computing the longest common subsequence of the unique elements of both documents leads to a skeleton of common points that almost definitely correspond to each other. The algorithm then sweeps up all contiguous blocks of common lines found in this way, and recurses on those parts that were left out, in the hopes that in this smaller context, some of the lines that were ignored earlier for being non-unique are found to be unique. Once this process is finished, we are left with a common subsequence that more closely corresponds to what humans would identify.

It is available in Git (as of 1.8.2) using a command-line flag:

```<code>git diff --patience
</code>```

Or a configuration option:

```<code>git config diff.algorithm patience
</code>```

This algorithm will still suffer when unique lines don’t offer enough information to reconstruct the history. In your example:

I rename it into procedure2 and create a procedure1 above it

The fact that you say and is already going to mess with any diff algorithm, because you’re making multiple semantic changes in one patch. The number of changes you make is the number of changes that a diff algorithm needs to infer that you made.

Tagging lexical blocks with extra metadata is not a real solution. You might as well get perfect versioning by adding an ID to every character in the document—it is an improvement, but doesn’t scale. I would much rather see an editor automatically stash, commit, and unstash around an automated refactoring such as a rename. Then at least I know that the changes are semantically isolated, and a post facto diff algorithm will have an easier time of it.

Body:
The Patience Diff algorithm is designed to address this, insofar as it is possible to do so with unannotated text. From that article:

[Patience Diff] only considers lines that are (a) common to both files, and (b) appear only once in each file. This means that most lines containing a single brace or a new line are ignored, but distinctive lines like a function declaration are retained. Computing the longest common subsequence of the unique elements of both documents leads to a skeleton of common points that almost definitely correspond to each other. The algorithm then sweeps up all contiguous blocks of common lines found in this way, and recurses on those parts that were left out, in the hopes that in this smaller context, some of the lines that were ignored earlier for being non-unique are found to be unique. Once this process is finished, we are left with a common subsequence that more closely corresponds to what humans would identify.

It is available in Git (as of 1.8.2) using a command-line flag:

git diff --patience

Or a configuration option:

git config diff.algorithm patience

This algorithm will still suffer when unique lines don’t offer enough information to reconstruct the history. In your example:

I rename it into procedure2 and create a procedure1 above it

The fact that you say and is already going to mess with any diff algorithm, because you’re making multiple semantic changes in one patch. The number of changes you make is the number of changes that a diff algorithm needs to infer that you made.

Tagging lexical blocks with extra metadata is not a real solution. You might as well get perfect versioning by adding an ID to every character in the document—it is an improvement, but doesn’t scale. I would much rather see an editor automatically stash, commit, and unstash around an automated refactoring such as a rename. Then at least I know that the changes are semantically isolated, and a post facto diff algorithm will have an easier time of it.


问:
Is big-O really that relevant when working in industry?
In every interview I have been in, I have been quizzed on mathematical analysis of complexity, including big-O notation.

How relevant is big-O analysis to development in industry? How often do you really use it, and how necessary is it to have a honed mindset for the problem?

答:
I'd say it's very frequent. We don't generally prove something has a particular big-O, but we have internalized the idea, and memorized/become familiar with the big-O guarantees for particular data structures and algorithms, and we pick the fastest ones for a particular use. It helps to have a library that's full of all of the options, like the Java collections library, or the C++ STL. You implicitly and naturally use big-O every day when you choose to use a java.util.HashMap (O(1) lookup) instead of a java.util.TreeMap (O(lg n) lookup)  and certainly choosing not to run a linear search across a java.util.LinkedList (O(n) lookup) for something where you don't need sorted access.

When someone chooses a suboptimal implementation and someone who knows better comes along and sees their code, it's a part of our vocabulary to correct them "your implementation takes quadratic time, but we can get this down to n-log-n time by doing it this way instead" as naturally and automatically as we would use the English language to order a pizza.


答:
I had already created elsewhere the member some_info for this object for a different purpose

Well, you did not post the real names of your class and members, but such things can happen more easily when some_info has an ambigous name, not making clear it's real purpose. So besides the other good answers here, try to avoid that, choose names which document the purpose of a variable more clearly,  especially for member variables.


问:
Finding an object on an infinite line

Question:

There is an infinite line. You are standing at a particular point you can either move 1 step forward or 1 step backward. You have to search for an object in that infinite line. Your object can be in any direction. Give an optimal solution

My approach:

```<code>       Go 1 step forward, 2 step back ward
       Go 2 step forward, 4 step back ward and so on
</code>```

Complexity:

Lets say the required object is at point n.

Total number of steps:

```<code> 3 + 6 + 9 + .... n
 = 3(1 + 2 + 3 ... n)
 = O(n^2)
</code>```

Is there a way to improve the efficiency?

答:
What do you mean by 'optimal solution' ?

Make as few steps as possible?

I would not increase the distance from the start point by 1 every time, because after some time you nearly always visit a position you already visited and the ratio of new visited points converges to 0. I would use a pattern that guarantees that we always visit a fixed ratio of new points.

E.g

r: right step

l: left step

```<code>                x
                 r              new: 1   old: 0
               ll               new: 2   old: 1
                rrrr            new: 4   old: 3
           llllllll             new: 8   old: 7
            rrrrrrrrrrrrrrrr    new:16   old:15
</code>```

This way the ratio of already visited positions to new visited positions id always about 1:1.

Title: Finding an object on an infinite line

Body:
What do you mean by 'optimal solution' ?

Make as few steps as possible?

I would not increase the distance from the start point by 1 every time, because after some time you nearly always visit a position you already visited and the ratio of new visited points converges to 0. I would use a pattern that guarantees that we always visit a fixed ratio of new points.

E.g

r: right step

l: left step

                x
                 r              new: 1   old: 0
               ll               new: 2   old: 1
                rrrr            new: 4   old: 3
           llllllll             new: 8   old: 7
            rrrrrrrrrrrrrrrr    new:16   old:15

This way the ratio of already visited positions to new visited positions id always about 1:1.


问:
In MVC is it considered good practice to have private, non-action, functions in a controller class?
Sometimes action functions in the controller class can become huge and nasty, with many-many lines of code to simply control the flow of data from the Model to the View. At some point these huge functions completely lose track of the basic principles of good code, i.e. only doing one thing, being small, readable and manageable etc.

Would it be considered good practice to break these huge action functions into smaller private functions in the controller class or should the need of such optimization mean we should rather add them in the model?

I would vote for having the smaller functions as private in the controller so that they are relative to the action, but I have heard arguments that the controller should preferably be simple while the model can get huge and clumpy; and was just wondering which one would be the most preferred method.

答:
In MVC I try and ensure that my controller is as "thin" as possible and also that my models are as dumb as possible.

The logic and helper functions that are needed get put into separate stand alone helper classes. It makes my testing a lot easier as well (you are testing.. right?? :D) Testing controllers is notoriously difficult, any time you try and create an instance of a controller to test you have to think about the HTTP Context and faking http this and that, and its a pain, but its a pain on purpose. You need all that stuff because a controller is so closely linked to HTTP and the web. Its the entry point to your web app.

Logic and helper functions have nothing to do with the web. They're entirely environment agnostic (or they should be). That alone should tell you they don't belong together in the same place. Plus, if you tie all of your applications logic so closely to the web, or a particular web implementation, you can never take it with you.

We developed our MVC site with all of our database entities (not our mvc models, our actual db entities), our storage, our helper classes and our logic in seperate stand alone dll's. We have only every had one web site, but we did it like this anyway.

A few months ago we were asked to create a few desktop apps that are related to a few of our fringe systems. This was easily done as all of our tested code could easily be re-used. If we'd shoved our code into our web project, or put in in our controllers, we would never have been able to do this.


问:
What are the alternatives to resx file
I am developing a Windows application and I want to store all the text for labels, radio buttons, buttons, check boxes and column headers of grids at one place. I have tried using a class file, an xml file, a database table and a resource file.

I found that a class file is the best way to store all these texts, but I want to know is there any alternative way? If I am using a class file then I will have to recompile the project if any text changes.

Will a resource file work properly for large amounts data? What about a dictionary or storing data in variables?

答:
I think you pretty much mentioned it all.

If you want something flexible, where you don't need to recompile, then the DB might be your best option.

But otherwise I would go with .resx, as this is the standard.

Saving text inside class files is a rather bad idea.

Title: What are the alternatives to resx file

OwnerDisplayName: Remy


答:
I have just done something similar following this CodeProject walkthrough: link

It is for making multiple easily updateable text files into resource files which you can add to your project in order to have different languages (in my case, a combo box allows me to change between as many languages as I create resource files for)

The advantage of this over .resx files is that you can have only 1 per language per project, instead of having to have 1 per language per form

Just something else to think about

Title: What are the alternatives to resx file

Body:
I am developing a Windows application and I want to store all the text for labels, radio buttons, buttons, check boxes and column headers of grids at one place. I have tried using a class file, an xml file, a database table and a resource file.

I found that a class file is the best way to store all these texts, but I want to know is there any alternative way? If I am using a class file then I will have to recompile the project if any text changes.

Will a resource file work properly for large amounts data? What about a dictionary or storing data in variables?

OwnerDisplayName: iabbott


答:
Besides the .resx format, you can also use .txt or .restext files, which are in a simpler (and easier to read and edit) format.

Creating Resource Files for Desktop Apps (see the "Resources in Text Files" section)

The format is essentially name = value, with the ability to have comments and conditional compilation.

Another option is to use whatever source or text file you want, and build the binary .resources file either manually or as part of a build step. (see "Resources in .resrouces Files" from the link above).

Either way, there is a little more work to get these into your project and compiling, but they both have the benefit of having support for multiple languages, just like the .resx file.

Title: What are the alternatives to resx file

OwnerDisplayName: crashmstr


答:
My instinct is that the issue here is really a combination of your expectations and the respect shown to you by the team management.

QA's main goals are to document a combination of product deviations from the spec, usability issues and performance issues.  The key word is document.

The product manager role is responsible for deciding priorities on where developers spend their effort, and it may mean that at the current moment they have decided that the priority is to implement features, and to address defects later (The infinite bug strategy). Whilst this is known to be a poor long term strategy, there are often situations where short term it is the politically correct thing to do. (e.g show progress to a customer at next weeks meeting).

As long as you are documenting the defects, you are doing your job, and the product manager has to justify making the decision to ship with known defects.

That said, the secondary issue is about the respect shown to you by the team managers.  If they are seeing you as a problem, because you keep finding bugs, and all they want to do is to get the product out, earning money, then the solution is the same. Keep identifying the bugs, but respect that the choices (and then the blame) are the managers' in the decisions to ship /apply development resources, and your role is to provide them accurate and timely information to make decisions.

If my instincts are right, I'd start looking for a more successful organisation to work for, because this project is likely to end badly.


问:
How can I effectively manage long-term feature development and short-term bug fixing at the same time?
We have a huge C, and C++ code base. There is a plan to add a new feature into the existing system, but, this should happen only after 3 to 4 months.

So, we are looking for best possible options.

Branching off is one option, but, this involves porting the bug fixes to the feature branch from the trunk.

Staying on the trunk itself, have ifdef to differentiate the new feature compilation

Split the source/header files that involve the new feature, edit the makefiles to pick the right file.

I understand this question is pretty vague, and only people working on it can well decide the way forward. But, I'm looking for generalized opinions on a case like this.

答:
This is what I would do:

tag the current source

start developing on the trunk

if you have to modify the source that you have tagged, you will create a branch from that tag

About refactoring, the best way to be sure not to break existing functionalities is to write tets: unit tests, performance tests and integration tests. Run tests on a daily basis. Also continous integration is a good idea.


答:
An exponential growth strategy runs O(n) time, average and worst case. This is optimal if you disregard constant factors. If you want to optimize the constant factor as well, you need to make some assumption about the probability distribution.

For example if you use a doubling strategy, the maximal cost is 7*n

```<code>dist = 1
loop
    MoveTo(dist)
    MoveTo(-dist)
    dist = dist * 2
</code>```

Title: Finding an object on an infinite line

Body:
Question:

There is an infinite line. You are standing at a particular point you can either move 1 step forward or 1 step backward. You have to search for an object in that infinite line. Your object can be in any direction. Give an optimal solution

My approach:

```<code>       Go 1 step forward, 2 step back ward
       Go 2 step forward, 4 step back ward and so on
</code>```

Complexity:

Lets say the required object is at point n.

Total number of steps:

```<code> 3 + 6 + 9 + .... n
 = 3(1 + 2 + 3 ... n)
 = O(n^2)
</code>```

Is there a way to improve the efficiency?

Body:
An exponential growth strategy runs O(n) time, average and worst case. This is optimal if you disregard constant factors. If you want to optimize the constant factor as well, you need to make some assumption about the probability distribution.

For example if you use a doubling strategy, the maximal cost is 7*n

dist = 1
loop
    MoveTo(dist)
    MoveTo(-dist)
    dist = dist * 2


问:
8 bit and 1 byte, is this a valid question to be asked?
I saw these question in our school's past paper, and I'm wondering if this is a valid question.

How big is bool in C and C++?

A) 1 bit

B) 4 bit

C) 8 bit

D) 1 byte

What is the smallest unit of memory C or C++ use?

A) 1 bit

B) 4 bit

C) 8 bit

D) 1 byte

The answer to both are D, but I am thinking if this is inappropriate.

EDIT: 1 byte is not necessarily 8 bits on some systems. See this StackOverflow post.

答:
I'd say the answers are both D) but the questions do leave a bit to be desired, for the first as AProgrammer points out, a bool could be bigger than 1 byte, for the second question it should clarify the smallest unit of addressable memory (bitfields allow a structure of multiple smaller memory units but they aren't addressable)

to clarify why C) is not the answer, there may not be 8 bits in a byte in C || C++

hopefully its obvious why A) and B) are not correct


答: AFAIK, no answers presented here are correct.  The size of bool and _Bool is not constrained to be 1 byte (I seem to remember that there is a constraint in C which forces sizeof(_Bool)<=sizeof(short) which hasn't an equivalent in C++)

Title: 8 bit and 1 byte, is this a valid question to be asked?

Body:
I saw these question in our school's past paper, and I'm wondering if this is a valid question.

How big is bool in C and C++?

A) 1 bit

B) 4 bit

C) 8 bit

D) 1 byte

What is the smallest unit of memory C or C++ use?

A) 1 bit

B) 4 bit

C) 8 bit

D) 1 byte

The answer to both are D, but I am thinking if this is inappropriate.

EDIT: 1 byte is not necessarily 8 bits on some systems. See this StackOverflow post.


答:
The size of bool in std::vector is 1 bit.

Vector of bool

This is a specialized version of vector, which is used for elements of type bool and optimizes for space.

It behaves like the unspecialized version of vector, with the following changes:

The storage is not necessarily an array of bool values, but the library implementation may optimize storage so that each value is stored in a single bit.

Elements are not constructed using the allocator object, but their value is directly set on the proper bit in the internal storage.

Member function flip and a new signature for member swap.

A special member type, reference, a class that accesses individual bits in the container's internal storage with an interface that emulates a bool reference. Conversely, member type const_reference is a plain bool.

The pointer and iterator types used by the container are not necessarily neither pointers nor conforming iterators, although they shall simulate most of their expected behavior.

These changes provide a quirky interface to this specialization and favor memory optimization over processing (which may or may not suit your needs). In any case, it is not possible to instantiate the unspecialized template of vector for bool directly. Workarounds to avoid this range from using a different type (char, unsigned char) or container (like deque) to use wrapper types or further specialize for specific allocator types...


答: You can't.  If this is a problem you encounter on a regular enough basis, Python (and probably other dynamically typed languages are a bad choice for you.


问:
Are there any real-world cases for C++ without exceptions?
In When to use C over C++, and C++ over C? there is a statement wrt. to code size / C++ exceptions:

Jerry answers (among other points):

(...) it tends to be more difficult to produce truly tiny executables with C++. For really small systems, you're rarely writing a lot of code anyway, and the extra (...)

to which I asked why that would be, to which Jerry responded:

the main thing is that C++ includes exception handling, which (at least usually) adds some minimum to the executable size. Most compilers will let you disable exception handling, but when you do the result isn't quite C++ anymore. (...)

which I do not really doubt on a technical real world level.

Therefore I'm interested (purely out of curiosity) to hear from real world examples where a project chose C++ as a language and then chose to disable exceptions. (Not just merely "not use" exceptions in user code, but disable them in the compiler, so that you can't throw or catch exceptions.) Why does a project chose to do so (still using C++ and not C, but no exceptions) - what are/were the (technical) reasons?

Addendum: For those wishing to elaborate on their answers, it would be nice to detail how the implications of no-exceptions are handled:

STL collections (vector, ...) do not work properly (allocation failure cannot be reported)

new can't throw

Constructors cannot fail

答:
A good example is kernel mode programming.

You can use C++ there for cleaner code but without exceptions. There is no runtime library for them and exception handling use too much stack memory that is very limited in the kernel (I experimented with C++ exceptions in Windows NT kernel and exception throwing and unwinding eats a half of available stack - very easy to get stack overflow and crash the whole system).

Typically you define your own new and delete operators. Also I found pretty handy a placement new and c++11 rvalue references. No STL or other C++ user-mode libraries which rely on exceptions can be used.


问:
Is a NoSQL database suitable for me?
I'm developing a WPF application whose core functionality involves creating a large object graph (often tens of thousands of entities) which the user can modify certain parts of, then save to a database. A graph can also be subsequently retrieved, modified and saved again. It's feasible that a user can create dozens of these graphs per day.

The app also provides the user with different ways to search the entities in the database (predominantly text searches on various fields), presenting the search results to the user and allowing the user to select one, which will result in the relevant entity graph being retrieved in full and presented for the user to view and modify as above.

Currently I'm using Entity Framework and SQL Express, but I'm uneasy about certain aspects of the architecture and design, and the client isn't keen on having to install SS. I've only recently come across the concept of NoSql databases, and sounds like they might be a good fit for what I'm doing, but I have a couple of questions.

First, I'm assuming performance wouldn't be any worse than EF when reading or writing one of these object graphs?

What about my app's search functionality? Will a NoSql db support this sort of thing, and what would the performance be like, bearing in mind the size and quantity of "documents" that I'm likely to have.

What about lookup (reference) data? Would I duplicate such data in each NoSQL document, or would I keep it all in a single NoSql document and store their IDs in the main documents?

Finally, any recommendations for a product? MongoDb and RavenDb seem to be the main OSS contenders for Windows.

答:
Its quite likely that a NoSQL database will meet your needs better than an SQL database, but all that does is increase your choice options.

Pretty much every type of database can store your data set, but what really matters is what kind of searches you need to do.  The different database types have very different abilities in this area, and that is what will help you identify the suitable types of database to use.

This link contains a good list of different NoSQL products grouped into their loose behaviours.

What I would say though, is that most of these products are not targeted to the windows environment. This means that you would need a linux database server and that you have a seperate application server hosting the windows application.

Title: Is a NoSQL database suitable for me?


答:
Beside of Dmitri Zaitsev and spaceman great answers i don't know if the following is also  valid for PHP:
You should try to avoid private methods due the lack of automated test possibilities.

Yes, you can use metaprogramming or dependency injection to test private methods as well but you shouldn't do it as it has a huge impact at the readability of your code.

Always remember the KISS principle: Keep it simple, stupid.

Title: In MVC is it considered good practice to have private, non-action, functions in a controller class?

Body:
Sometimes action functions in the controller class can become huge and nasty, with many-many lines of code to simply control the flow of data from the Model to the View. At some point these huge functions completely lose track of the basic principles of good code, i.e. only doing one thing, being small, readable and manageable etc.

Would it be considered good practice to break these huge action functions into smaller private functions in the controller class or should the need of such optimization mean we should rather add them in the model?

I would vote for having the smaller functions as private in the controller so that they are relative to the action, but I have heard arguments that the controller should preferably be simple while the model can get huge and clumpy; and was just wondering which one would be the most preferred method.


答:
If you are depending on the order and structure of the text file containing the source to code help you manage your change sets, you're just never gonna get it quite right.  A better diff tool may help you, some.

Some ideas.

By radically changing the intent and names of functions, you are basically demanding that the whole subset of source, a least in this file, be reviewed again for consistency,logical errors, integration boo boos, etc.  You just can't change the intent of the code,and expect a line or character based automated diff tool to try and infer the equivalent changes in meaning.

If you find this happening a lot, you have two options as I see.  You can either rely less on automated diff tools and once a file is changed beyond comparability, you simply must review it as new.  Read the functions.  Figure out whether they work.  It's tedious.  But you've changed the meaning.  So there are no shortcuts to ensuring correctness.  So....furthermore,if you want to have more Automated QA, you should split these functions into two files, based on their semantics.   The next time you change things.  It's a lot of files sometimes, but what you doing, is more clearly defining in textual or filing structure, what each thing does instead of relying on uniqueness of function names or relative positioning within a single file to define the intended semantic structure of the functions that comprise your project.

So,split things into files.

If procedure2 is now doing the job of procedure1 , that's a big change in intent.

The only way to propagate this cleanly is to actually program to an interface.  ANd effective use of smaller files should facilitate this.

I also note, look at something like the GAC manifest binding in .Net.  How it tries to enable library consumers to specify that they need a 1.x version ,but that it also enables,producers of libraries to specify,that this 2.1 versions is function for function backward compatible with all 1.x requirements.  This is kinda what you are after with the GUID idea.  A stable interface.

Title: Can we reduce confusion in line-based diff tools by annotating the code with some unique tokens?

Body:
Let's say I have

```<code>procedure1() {
    --body of first procedure--
}
</code>```

Then I rename it into procedure2 and create a procedure1 above it:

```<code>procedure1() {
    --body of second procedure--
}

procedure2() {
    --body of first procedure--
}
</code>```

Not once a line-based diff tool has highlighted the code from --body of second procedure
all the way to procedure2() { as new code inside procedure1.

This is bound to happen, since most diff tools are oblivious of the underlying structure of the source code. AST-based diff tools can't work very well either, because of several reasons and I know what people really want is a semantic diff tool, but that's not going to happen.

I haven't seen a discussion though, about whether or not it would be practical to annotate the code in such a way that a line-based diff tool would understand the underlying structure of the source code.

For example, I could throw in some UUIDs in the code, like this:

```<code>//BeginBlock{E999A3BF-626E-428F-A2C1-6AFF0CD22BF2}
procedure1() {
    --body of first procedure--
}
//EndBlock
</code>```

And the modified code would look like this:

```<code>//BeginBlock{7C734F0A-92F4-45EB-B653-DBB9A0F18354}
procedure1() {
    --body of second procedure--
}
//EndBlock

//BeginBlock{E999A3BF-626E-428F-A2C1-6AFF0CD22BF2}
procedure2() {
    --body of first procedure--
}
//EndBlock
</code>```

The point is to assign some tokens (unique within a file or project) to some marks that would reflect part of the structure of the source code.

An IDE could update those annotations automatically and they could help a diff tool better detect structural changes. The tool would scan the code once to identify the sections of the program (and how they've been moved around) and then compare those blocks having the same ID.

Do you think this approach is practical?


答:
Option 2 is called "Feature Toggle". IMHO that is the option to prefer as long as the "feature entry point" is small, ideally just one #ifdef, not dozens. Even better is a feature toggle you can switch at run time, so you don't need a separate build run to test the current status of your new feature. This way, you can easier bring "intermediate releases" of your software into production, giving you earlier feedback if one of the changes accidentally broke an existing feature.

Option 1 is IMHO the second best option. It works better if you don't have a small entry point. It has the advantage that you have a lower risk of introducing any bugs into the current production version, but the drawback that typically the merging effort may be higher. Additionally, you will have to build and maintain two branches in parallel.

I don't know how well Option 3 is possible in your case, it is just a different form of Option 1, but it seems to me that this may cause some code duplication (within the same version of your software) - if that's the case, don't do it.

Title: How can I effectively manage long-term feature development and short-term bug fixing at the same time?

Body:
We have a huge C, and C++ code base. There is a plan to add a new feature into the existing system, but, this should happen only after 3 to 4 months.

So, we are looking for best possible options.

Branching off is one option, but, this involves porting the bug fixes to the feature branch from the trunk.

Staying on the trunk itself, have ifdef to differentiate the new feature compilation

Split the source/header files that involve the new feature, edit the makefiles to pick the right file.

I understand this question is pretty vague, and only people working on it can well decide the way forward. But, I'm looking for generalized opinions on a case like this.


问:
How do programming languages define functions?
How do programming languages define and save functions/methods? I am creating an interpreted programming language in Ruby, and I am trying to figure out how to implement function declaration.

My first idea is to save the content of the declaration in a map. For example, if I did something like

```<code>def a() {
    callSomething();
    x += 5;
}
</code>```

Then I would add an entry into my map:

```<code>{
    'a' => 'callSomething(); x += 5;'
}
</code>```

The problem with this is that it would become recursive, because I would have to call my parse method on the string, which would then call parse again when it encountered doSomething, and then I would run out of stack space eventually.

So, how do interpreted languages handle this?

答:
Reading your post, I noticed two questions in your question. The most important one is how to parse. There are many kinds of parsers (e.g. Recursive descent parser, LR Parsers, Packrat Parsers) and parser generators (e.g. GNU bison, ANTLR) you can use to traverse a textual program "recursively" given a (explicit or implicit) grammar.

The second question is about storage format for functions. When you are not doing syntax-directed translation, you create an intermediate representation of your program, which can be an abstract syntax tree, or some custom intermediate language, in order to do further processing with it (compile, transform, execute, write on a file, etc).


答:
You shouldn't be calling parse upon seeing callSomething() (I presume you meant callSomething rather than doSomething).  The difference between a and callSomething is that one is a method definition while the other is a method call.

When you see a new definition, you'll want to do checks related to ensuring you can add that definition, so:

Check if function doesn't already exist with same signature

Ensure that method declaration is being performed in the proper scope (i.e. can methods be declared inside other method declarations?)

Assuming these checks pass, you can add it to your map and begin checking the contents of that method.

When you find a method call like callSomething(), you should perform the following checks:

Does callSomething exist in your map?

Is it being called properly (number of arguments matches signature that you have found)?

Are arguments valid (if variable names are used, are they declared?  can they be accessed at this scope?)?

Can callSomething be called from where you are (is it private, public, protected?)?

If you find that callSomething() is okay, then at this point what you would want to do really depends on how you wish to approach it.  Strictly speaking, once you know that such a call is okay at this point, you could only save the name of the method and the arguments without going into further details.  When you run your program, you will invoke the method with the arguments you should have at runtime.

If you want to go further, you could save not just the string but a link to the actual method.  This would be more efficient, but if you have to manage memory, it can get confusing.  I would recommend you simply hold onto the string at first.  Later you can try to optimize.

Note that this is all assuming that you've lexxed your program, which means you have recognized all tokens in your program and know what they are.  That isn't to say you know if they make sense together yet, which is the parsing phase.  If you don't yet know what the tokens are, I suggest you first focus on getting that information first.

I hope that helps!  Welcome to Programmers SE!

Title: How do programming languages define functions?

Body:
How do programming languages define and save functions/methods? I am creating an interpreted programming language in Ruby, and I am trying to figure out how to implement function declaration.

My first idea is to save the content of the declaration in a map. For example, if I did something like

```<code>def a() {
    callSomething();
    x += 5;
}
</code>```

Then I would add an entry into my map:

```<code>{
    'a' => 'callSomething(); x += 5;'
}
</code>```

The problem with this is that it would become recursive, because I would have to call my parse method on the string, which would then call parse again when it encountered doSomething, and then I would run out of stack space eventually.

So, how do interpreted languages handle this?


答:
Would I be correct in assuming that your "parse" function not only parses the code but also executes it at the same time?  If you wanted to do it that way, instead of storing the contents of a function in your map, store the location of the function.

But there's a better way.  It takes a bit more effort up-front, but it yields much better results as complexity increases: use an Abstract Syntax Tree.

The basic idea is that you only parse the code once, ever.  Then you have a set of data types representing operations and values, and you make a tree of them, like so:

```<code>def a() {
    callSomething();
    x += 5;
}
</code>```

becomes:

```<code>Function Definition: [
   Name: a
   ParamList: []
   Code:[
      Call Operation: [
         Routine: callSomething
         ParamList: []
      ]
      Increment Operation: [
         Operand: x
         Value: 5
      ]
   ]
]
</code>```

(This is just a text representation of the structure of a hypothetical AST.  The actual tree would probably not be in text form.)  Anyway, you parse your code out into an AST, and then you either run your interpreter over the AST directly, or use a second ("code generation") pass to turn the AST into some output form.

In the case of your language, what you would probably do is have a map that maps function names to function ASTs, instead of function names to function strings.

Body:
Would I be correct in assuming that your "parse" function not only parses the code but also executes it at the same time?  If you wanted to do it that way, instead of storing the contents of a function in your map, store the location of the function.

But there's a better way.  It takes a bit more effort up-front, but it yields much better results as complexity increases: use an Abstract Syntax Tree.

The basic idea is that you only parse the code once, ever.  Then you have a set of data types representing operations and values, and you make a tree of them, like so:

def a() {
    callSomething();
    x += 5;
}

becomes:

Function Definition: [
   Name: a
   ParamList: []
   Code:[
      Call Operation: [
         Routine: callSomething
         ParamList: []
      ]
      Increment Operation: [
         Operand: x
         Value: 5
      ]
   ]
]

(This is just a text representation of the structure of a hypothetical AST.  The actual tree would probably not be in text form.)  Anyway, you parse your code out into an AST, and then you either run your interpreter over the AST directly, or use a second ("code generation") pass to turn the AST into some output form.

In the case of your language, what you would probably do is have a map that maps function names to function ASTs, instead of function names to function strings.


答:
I'll try to post some helpful hints, but with all due respect, this is Release Management 101, and if you really have a huge code base and a need for parallel work streams in the organization, you would do well to either read a book on it or hire somebody with more experience in this area.

Assuming this situation:

The business needs new functionality that will take a long time to complete.

The business needs various bugs fixed now.

You have multiple developers who can work on different areas simultaneously.

You cannot defer the development of the feature until after the bugs are fixed.

Make absolutely sure that point #4 is true, because if you can invalidate that assumption, your job suddenly gets a whole lot easier. I can't tell you much time I've saved in the past by simply not doing bug-fixing and feature-development at the same time. That said, it is sometimes an unfortunate necessity.

Formally, your options are:

Feature Branches: You create a branch where all of the new feature development will take place. Not recommended because they inherently break Continuous Integration. You can of course clone your "CI build" for the feature branch, but that's not actually CI because the code hasn't actually been integrated, it's just being built and maybe tested in isolation.

Feature Toggles: This is typically not done with an ifdef but rather a configuration option. The ability to set this at runtime, not build time, is important because it makes testing and deployment a lot easier. Compile-time toggles require you to maintain two separate builds and two separate artifacts, but you can only promote one, a situation which tends to introduce ambiguity and process short-cutting.

Runtime feature toggles are partially recommended with some caveats:

It is important to minimize the surface area of the toggle. Ideally you would want the check to happen in only one place. Feature toggles that get too big for their britches are evil for the same reason that Singletons and other global state are. Try to check it just once, at application startup.

Too many feature toggles can become a spaghetti mess of their own over time, essentially creating a program-within-a-program. Feature Z depends on Feature Y which depends on Feature X but not Feature Q which is deprecated and breaks feature AB... etc. So in addition to minimizing the scope of individual toggles, you need to take steps to minimize the number of toggles and properly manage the dependencies between them. Even if there are no dependencies, you still need to run all end-to-end tests with each state that could plausibly be used in production, which quickly becomes a combinatorial explosion for the testers and release managers.

Parameterized Build or simply Multiple Targets: This is an incredibly useful tool/technique but I've never seen it used to build different feature sets and can't recommend that as an option here. You would normally use it to build for different platforms and/or perform certain one-off-tasks like running integration tests, generating documentation, etc. Using it as a poor-man's feature toggle has all of the potential drawbacks of a feature toggle and hides all of the complexity in your build scripts, which are generally the least flexible and most difficult to test of all your code.

Feature Abstraction, AKA Branch By Abstraction (a dangerous misnomer since it does not involve any actual branching): This means you encapsulate all of the interesting functionality of the new feature in a single class and use refactoring techniques (particularly Extract Interface) to encapsulate all of the existing functionality in the same interface. Then when you're ready to launch the feature, you just change the implementation.

This combines the advantages of (a) being in your trunk or mainline, (b) being fully covered by unit tests and possibly integration tests, and (c) not introducing any new global state to the application. This is much easier to do if your application uses dependency injection but not impossible if it doesn't. This is always the best choice if and when you are able to do it - it introduces the least overhead and the lowest risk, and can be combined very easily with options 2 or 3 above if you need to make the feature available on-demand to your testers.

Note that when using this option, once the feature has actually been launched, you should reevaluate whether the abstraction is still necessary and remove it if the overhead of maintaining it outweighs whatever benefits you're still getting.

You should choose options 4, 2, and 1 in descending order of preference. This is coming from someone with a whole lot of experience with all of the above options.

Final note: Fixing a bug or adding a new feature is not refactoring. Refactor does not mean "change", it refers to preserving the existing functionality exactly during some code change. So please don't use it to refer to your situation; what you're doing is the opposite of refactoring.


问:
Developer thinks they do not have to follow standard development process
How do you deal with a senior developer who does not think that the company standard way of developing software applies to them ?

For instance:

Will ask other developers to do work by email, rather than assign
bugs to them.

Will keep copies of documentation and code in their own local area,
rather than keeping them in the common area under source control. (and overwrite others changes with theirs)

NOTE: This has been flagged to QA people before.

答:
I document their activities, give them multiple written warnings, work with HR to create and implement an improvement plan, then I fire them.

edit

Since you're not the manager, the best you can do is document what you see (stick to facts) and forward to your manager once in a while.  If any of your peers complain to you about this person, encourage them to also document & forward to the boss.

Having a stack of documented events from multiple peers is very helpful to the manager when it's time to take action.


答:
On an infinite line you will never find the object.  Infinity is a weird thing. i.e. pick a point on a finite line, as the length of the line approaches infinity the probability that the point you picked is the object approaches zero.

Some things that might make this problem meaningful

The line is finite (some number N)

The object can only be at discrete points.

I would image that in these cases the optimal (fewest number of steps) solution would be to walk in one direction until you find the object or reach the end.  If you reach the end you would turn around.

Title: Finding an object on an infinite line


答:
Obviously, firing them or reporting them to management is an option; whether or not it would be my first choice as an option would depend on whether or not they're also a good developer.

It seems wrong-headed to send a very smart person packing just because they don't follow the process. Especially if you don't fully understand why they don't follow the process. I would suggest that instead of simply labeling this person as a renegade and looking for ways to deal with the person, you address each of the problematic behaviours one by one and look for ways to deal with those specific behaviours.

For instance:

Not committing things to source control is infuriating (as a lead, I've occasionally had to politely grill others about this) but sometimes it's hard to find alternatives, especially if you're using old-school centralized VCS where you only get one chance to fix merge conflicts and commit.

When dealing with TFS or even SVN, before the git-tfs or git-svn plugins were stable, I would frequently have to make backups of my working copy just in case I messed up a merge. In companies where merge conflicts are difficult to resolve or broken builds aren't handled properly, delayed commits or no commits can be a defensive behaviour that points to higher-level organizational problems that need to be resolved.

Not saying any of that applies to you or your teammate or your organization, the point is we don't know, and I assume you don't know either, otherwise you would probably have included that information in your question. (right?)

For problem #1 (using email for work assignment), the solution is blindingly obvious: Ignore them. I think the vast majority of developers have had to deal with this problem at one point, although the more common incarnation of the problem is business users making requests by email, as opposed to other developers/managers.

It's basically the same situation, though. You ignore the email requests, and if pressed, you politely explain that your email comes in too fast and too frequently to be able to keep track of any issues or requests buried in there, and that you need it in the bug database in order to track your own time. Mention this to the Project Manager, assuming you have one; they will definitely take your side on it.

I've found myself at the business end of this, too, when dealing with sysadmins; sometimes there's a blurry line between just asking a question on IM and requesting an investigation of some issue, and I'll get told to submit a ticket by emailing their tracking address. It's a minor inconvenience but it's really no big deal, I understand how their time is both highly compressed and under intense scrutiny, and they can't afford to be doing random stuff for random people without a priority attached.

In most cases, if there is a good reason for a process to exist, then it should be a simple matter for you to either register a formal complaint, or to simply follow the correct process yourself and let others deal with the consequences of not following it.

But, as I mentioned before, make sure that what you're complaining about is the specific process not being followed, don't word it as a general complaint about the person otherwise you'll almost certainly come out looking like the bad guy.

Title: Developer thinks they do not have to follow standard development process

Body:
How do you deal with a senior developer who does not think that the company standard way of developing software applies to them ?

For instance:

Will ask other developers to do work by email, rather than assign
bugs to them.

Will keep copies of documentation and code in their own local area,
rather than keeping them in the common area under source control. (and overwrite others changes with theirs)

NOTE: This has been flagged to QA people before.


答:
To encourage the usage of a bug tracking system instead of e-mails, you can use the same technique I've used with my customers. Create an automated e-mail explaining how to submit a bug or request a feature on a bug tracking system. Send this automated e-mail each time you receive a bug/feature request by mail.

Few days later, the person would be so annoyed that either he will confront you (beware of angry people), or start using the bug tracking system.

Similarly, ignore documents which are not stored in the official repository. If the person asks you why haven't you followed a specific document, ask which one, and tell that you never read it, since it's not in the repository.


答:
From a generic point of view, the definition of a function is little more than a label, or bookmark, in the code. Most other loop, scope and conditional operators are similar; they're stand-ins for a basic "jump" or "goto" command in the lower levels of abstraction. A function call basically boils down to the following low-level computer commands:

Concatenate the data of all parameters, plus a pointer to the next instruction of the current function, into a structure known as a "call stack frame".

Push this frame onto the call stack.

Jump to the memory offset of the first line of the function's code.

A "return" statement or similar will then do the following:

Load the value to be returned into a register.

Load the pointer to the caller into a register.

Pop the current stack frame.

Jump to the caller's pointer.

Functions, therefore, are simply abstractions in a higher-level language specification, which allow humans to organize code in a more maintainable and intuitive way. When compiled into an assembly or intermediate language (JIL, MSIL, ILX), and definitely when rendered as machine code, almost all such abstractions go away.


问:
What are the most crucial categories of content to organize into an internal developer portal in a large company?
I have been tasked with organizing all of the company's internal content currently spread around sharepoint, a markdown reference manual and confluence into a single cohesive and usable portal in confluence. I want the home page to be the "dev center" and for it to be where we point new devs and where everyone goes for reference and to see what is going on at the company. Here are some general categories I imagine might be important:

news... what's going on in the company, promotions, new hires, project updates

best practices... coding standards, solutions to common problems, etc...

on-boarding... docs describing how to set up a dev environment on your workstation

company culture... org chart, roles and responsibilities, the functions of different groups, processes

training... courses coming up, recommended and required training

events... events coming up, slides and materials from previous events

Anything else you think is important to include? My goal is to have this portal be something devs actually want to look at multiple times per day for help doing their jobs.

Expected user base is around 500 devs, testers, ops, etc... across over a dozen teams. Both .Net and Java are in use in this Enterprise. The page will be in Confluence, so I believe we can let everyone contribute in some way, or should we lock it down and appoint content managers? Good point about analytics. I will include that in my proposal.

Thanks for the input!!

答:
A few other things to include:

Calendar - What are the key dates coming up for the dev team?  Are there milestones to be aware?  Are there code freezes or other things that may be worth noting here.

Links to various other systems - Bug tracking, incident management, feature tracking and other stuff may be useful to have as links here so that a developer can easily click to them from this page as new hires and others may not always be aware of all the systems.  Links to the project sites could also be included in here.

The company culture could be split into a few pieces: 1) Corporate values that may be stated in the side as a short message, 2) Links to HR policies for things like time off, performance reviews, etc. 3) A team's "who's who" that may be different than the formal org chart and could include cell numbers to contact people if there is a problem after hours.

The best practices could be split into what is done within your company and what other resources are out there.  For example, your company may have its own naming convention for variables that is different than what some best practices may say.  Similarly, the dev process you use may be different.  Just consider the idea of having what is within the company in one part of the page and recommendations from others as another part of the page.

It may be worth having some "Quote of the day" or other daily updated feature that could be useful as a way to entice people to go to the portal regularly.


问:
Do you encourage to keep login credential in keystore?
When developing login module for a web application, do you suggest to keep the username and password in a keystore? Lets assume the keystore was kept in a very safe place in web server.</p>

答:
It's never a good idea to store passwords on the server anywhere, keystore or otherwise. It doesn't matter how safe you intend to keep the passwords -- you are still storing them somewhere, which introduces a set of possible vulnerabilities which are completely avoidable.

You should either be offloading the login process to an external provider (for exmaple, OpenID) or you should only be storing is password hashes (and associated salts). That way even if your server is compromised, the passwords would not be available without some brute force password cracking software (which still won't get strong passwords -- and won't get many weaker ones if you use a good password hashing algorithm like BCrypt).

As for where to store the password hashes, it doesn't really matter as long as it's meets your specifications for permanence and performance. Most people use a typical database to store these, but a simple key-value store (with permanence) would be fine for most applications.


问:
Who does test-driven development?
I've been working in the enterprise space for the past 4½ years and have noticed that generally speaking, enterprises are not conducive environments for the test-first style of development. Projects are usually fixed-cost, fixed-timeline and waterfall style. Any unit testing, if done at all, usually comes after development in the QA phase and done by another team.

Prior to working for an enterprise, I consulted for many small to medium sized companies, and none of them were willing to pay for a test-first style of development project. They usually wanted development started immediately, or after a short design stint: i.e., something more akin to Agile, though some clients wanted everything mapped out similar to waterfall.

With what types of shops, companies, and clients does test-driven development work
best? What types of projects tend to be conducive to TDD?

答: Every line of code I write is using test driven development.  If management isn't on board with writing tests first then I don't tell management about it.  I feel that strongly that test driven development is a better process.</p>

Title: Who does test-driven development?


问:
What is the value of workflow tools?
I'm new to Workflow developement, and I don't think I'm really getting the "big picture". Or perhaps to put it differently, these tools don't currently "click" in my head.

So it seems that companies like to create business drawings to describe processes, and at some point someone decided that they could use a state machine like program to actually control processes from a line and boxes like diagram. Ten years later, these tools are huge, extremely complicated (my company is currently playing around with WebSphere, and I've attended some of the training, its a monster, even the so called "minimalist" versions of these workflow tools like Activiti are huge and complicated although not nearly as complicated as the beast that is WebSphere afaict).

What is the great benefit in doing it this way? I can kind of understand the simple lines and boxes diagrams being useful, but these things, as far as I can tell, are visual programming languages at this point, complete with conditionals and loops. Programmers here appear to be doing a significant amount of work in the lines and boxes layer, which to me just looks like a really crappy, really basic visual programming language.

If you're going to go that far, why not just use some sort of scripting language? Have people thrown the baby out with the bathwater on this? Has the lines and boxes thing been taken to an absurd level, or am I just not understanding the value in all this?

I'd really like to see arguments in defense of this by people that have worked with this technology and understand why its useful. I don't see the value in it, but I recognize that I'm new to this as well and may not quite get it yet.

答:
Years ago, before most of us were born, software developers had to write their own code to store data. If you needed to save program state, well, that was seen as part of the function of the code, so many software developers ended up writing code to organize data and save and read it and so forth.

And then someone realized that this was something that happened a lot -- that, the logic to save, organize, read and search data was actually a component that was so commonly used that it should be it's own component. And we got databases.

In the last 10 to 15 years, IT departments have been realizing that the logic to choreograph and/or orchestrate business processes is so common that it should also be it's own component, which has lead to all sorts of different workflow tools.

There are 3 primary benefits of a workflow tool:

Time needed to make and deploy changes: you can develop and change the logic of a workflow without the same technical risks that you have with changing a piece of code.

Transparency: the business logic in a BPM based system is immediately available to and readable by the business analyst, whereas only developers will be able to read the business logic in "code-based" systems.

Reuse of technical components: BPM tools are often used in conjunction with systems that have a Service Oriented Architecture. By separating the business logic from the technical components -- especially for enterprise systems which must implement hundreds or thousands of different business processes -- you're able to reuse the technical components while spending relatively little time on developing the business logic (with a workflow tool).

However, one of the most common problem that I run into with workflow and BPM tool usage, is that developers still try to "bury" business logic in non-transparent code.

What I see, all the time, is developers still trying to add the business logic in the most technical ways possible, instead of the most transparent way possible. This is natural, because developers are, by their very nature, much more comfortable with code than with a workflow tool. Furthermore, the more logic you keep in a technical way, the more you'll be needed as a developer. Unfortunately, this is the worst thing a developer can do to a BPM system because he or she is undercutting the primary benefits of using BPM.

Lastly, most BPM tools aren't far enough that business analysts can develop the workflows themselves: however, that's what the goal is. Ideally, business analysts would develop the workflows/business process diagrams and developers would only work on the technical components that are called by the workflow engine.

Title: What is the value of workflow tools?


问:
Is there an advantage for a C programmer to have read K&R?
This question has been haunting me because I'm now reading Kernighan & Ritchie's: The C Programming Language (K&R) but I meet a lot, and I mean A LOT, of C programmers that have never read it.

So, my question is: Is there an advantage to reading K&R? Should be a necessity?

答: Helpful yes, necessary no. K&R is not the definition of the C language. It's simply one of many introductory texts. I found it particularly clear and concise, but other readers may prefer other texts. Simply having read it doesn't set you apart from other programmers in any way.</p>


问:
Liskov substitution principle when implementing two unrelated interfaces
Suppose I have two unrelated interfaces with the same method:

```<code>interface Table {
    /**
     * @param width (0 < width <= 100)
     */
    void setWidth(int width);
}

interface Square {
    /**
     * @param width (50 <= width <= 10000)
     */
    void setWidth(int width);
}
</code>```

Then I create a class which implements both of these interfaces:

```<code>class SquareTable implements Square, Table {
    void setWidth(int width) {
        precondition = ...
        if (!precondition)
            throw new PreconditionFailedException("Precondition failed: ...");
    }
}
</code>```

How precondition expressions should be combined to satisfy Liskov substitution principle? Should they and'ed or or'ed? I.e. what should be written instead of ...:

```<code>width > 0 && width <= 10000 // using OR
width >= 50 && width <= 100 // using AND
</code>```

And which rule should be used for postconditions?

```<code>interface Table {
    /**
     * @return width (0 < width <= 100)
     */
    int getWidth();
}

interface Square {
    /**
     * @return width (50 <= width <= 10000)
     */
    int getWidth();
}

class SquareTable implements Square, Table {
    int getWidth() {
        postcondition = ...
        if (!postcondition)
            throw new PostconditionFailedException("Postcondition failed: ...");
    }
}

width > 0 && width <= 10000 // using OR
width >= 50 && width <= 100 // using AND
</code>```

答:
The simplest case is that the precondition should be ORed (if you meet the conditions for either interface, then your method can be called) and the postcondition should be ANDed (the return must satisfy all constraints that apply, no matter which interface you had).

You can loosen the postcondition slightly depending on the preconditions satisfied.  You only need to meet the postconditions for the interface that you met the preconditions for.  Because if you don't meet the precondition for one interface, then you shouldn't be being called for that interface.


答:
I’m not sure you’d learn anything different from K&R than from other C books, but I tend to believe that you can learn quite a bit about people from seeing what books they prefer to read about a subject.

K&R is a well written and concise book, but a bit clichéd as a recommendation.

My personal favorite was Harbison & Steele, just as well written as K&R, but considerably more detailed.

If somebody prefers a book in the  “…for Dummies” series, I would suspect their dedication to their craft, not because those books are all that bad, but because they don’t go very deeply into details.

If somebody swears by books written by Herbert Schildt, they have the will to go into details, but I would suspect their judgment in the books they picked.

In general, I don’t think the time spent reading a quality technical book (and K&R is definitely one, and not a very long one) is never wasted.

Title: Is there an advantage for a C programmer to have read K&R?

Body:
This question has been haunting me because I'm now reading Kernighan & Ritchie's: The C Programming Language (K&R) but I meet a lot, and I mean A LOT, of C programmers that have never read it.

So, my question is: Is there an advantage to reading K&R? Should be a necessity?


答:
I'd agree with Charles E. Grant: it's not necessary, but it's worth the read, and here's why I think so:

The Bad Stuff

It's dated and thus could be confusing.

If you already know C well you won't learn much.

If you're not a fan of the K&R code style, your eyes might burn.

The 3rd point being insignificant, and the 2 first points being relatively painless, at least you know reading it won't hurt.

The Good Stuff

It's a good introduction for novice programmers, both for C and programming in general.

It's a nice read (as in: it reads easily and is well written).

It's not only about the technical value, but also about the historical value. If you aim at being an expert, it's good to know how the language evolved, so it's good to have a look at a book that was around not that long after its genesis, and one of the language's most famous books at that. C has changed. Not knowing the old bits may not be useful if you don't have to use them but it may help a great deal if you run into older code, or if you wonder why some things were done one way or another.

Again, it's about the history. Reading "Hackers" from Steven Levy or "Dealers of Lightning" from Hitzlick doesn't teach me anything of technical value, but it's anecdotical. Somehow, I find K&R to be of great value in this regard as well.

It's not a waste of time, so I'd say grab a copy at a local library and leave it on your desk. Pick it up at some point, and you may be surprised that there was a small hole in the space-time continuum when you raise your head again.