答:
I handle this by using something like a Builder that contains various factories. The Builder is given hashes that contain the factories to make various types of objects, and it will look into the hash and retrieve the correct factory based on whatever criteria.

For example, I have multiple question types, and all of these can be made by some implementation of an IQuestionFactory. Most of the IQuestionFactory implementations are subclasses of BaseQuestionFactory, and they receive XML that represents one question and parse it according to the rules of the question, returning back some subclass of BaseQuestion.

Some questions need more information, such as if it is a form-filling question there might be a section of the XML that contains the questions that defines the fields that are used in the form. The Factories that make these questions implement IEnhancedQuestionFactory, and the builder will check the Factory that it retrieves from the QuestionFactoryRegistry and check to see if it implements this Interface. If it does, it passes the full XML of the file that contained the questions in addition to the individual XML that goes to the createQuestion method.

To show you how flexible this can get, some of the IQuestionFactory implementations are simply shells that contain multiple question factories, and they can look at the incoming XML and then call an internal factory and return whatever that makes. We use this when an XML file contains multiple question types.

However, it sounds like you need something more like the way we build Exercises (which are essentially Controllers wrapped around a collection of Questions), where the hash (ExerciseFactoryMap) is set up to return a default factory most of the time, but in cases where it has a specific Factory registered, it will return that. And we do have one specific Factory that will create an Exercise subclass that has an additional property, and it has the additionall capability to look at the XML and find the information that it needs to populate that property.

So, I'd agree with Killian Foth that the point of a factory is to hide the implementation details of how the object is being constructed, but there's nothing that says you can't combine multiple Factories in creative ways (for example, a Factory that contains other Factories that do the real work).

Title: Refactoring an existing abstract class and its parameters

Body:
I have an abstract class A which declares an abstract method doStuff.  Currently there are many classes that inherit from A and implement doStuff.

The class' instances are initialized at run-time via AFactory based on user input.
Originally all the classes had the same single parameter (the user input). But now I have an additional parameter that only a new class that inherits A needs.

So breaking it down I though of the following logic:

The interpreter class that generates instances based on user input(using AFactory of course) was not aware of this extra parameter.

Trying to push it into the class interpreter class would be really awkward because then I would have to know when to pass it to the factory which defeats the whole purpose of having a factory in the first place.

Sending it blindly into the Factory hoping it might do something with it seems quite ugly as well.

My current solution: Meanwhile I've decided to refactor A.doStuff(Param param) into A.doStuff(AParams params).

AParams can hold what ever parameters needed and doStuff can ignore then if they're not interested in them. This also seems a bit awkward to me , and remids me of sending structs in WIN32API that can hold a lot of ugly useless parameters and I'm not fond of it.

Is there a more elegant way to approach this problem ? Or some design pattern that I've overlooked and solves this?

Notes :

We're using Java 1.7

The class' names are silly in order to emphasize the theoretical design issue they do have normal indicative, meaningful names in reality :)

I did search quite a lot but having figured out that it's quite hard to search the web for specific abstract theoretical issues (as opposed to why is X throwing Exception in this code) I've decided to ask anyway so I'm sorry if this is a duplicate.

Edit 1:

Clarification: I need to pass a subclass-specific argument to the doStuff method.

EDIT 2:

I did not fully understand Kilian Foth's intention so I've written some Java-pseudo-code to help me better explain the problem/understand your solution. So:

This is a skeleton of my problem.

This is a skeleton of my solution.

This is what I think  might be Kilian Foth's solution, but I'm not sure.


问:
How do you keep track of what classes and functions your team has written?
When working on code, I face many of the same challenges that my teammates do, and I have written some helpful functions and classes, and so have they. If there is good communication, I'll hear about some great thing someone put together, and six months later when I need it I may remember it and call that function, saving myself time. If I don't remember it, or never knew about it, I will probably re-invent the wheel.

Is there a particular practice of documenting these kinds of things? How do you make them easy to find?

If your team has no such documentation, how do you find out if your wheel already exists?

EDIT:

All but one of the answers so far deals with an ideal situation, so let me sum up those solutions: documentation & communication; wikis, stand-up meetings, etc. Those are all great things, but they rely on programmers having the time (and skills) to write up the documentation and attend the meetings and take notes and remember everything.

The most popular answer so far (Caleb's) is the only one that could be used by a programmer who is incapable of documentation and meetings, and does only one thing: programming. Programming is what a programmer does, and yes, a great programmer can write up documentation, unit tests, etc., but let's face it - most of us prefer programming to documenting. His solution is one where the programmer recognizes re-usable code and pulls it out to its own class or repository or whatever, and by the fact that it is isolated, it becomes find-able and eases the learning curve for using it.... and this was accomplished by programming.

In a way I see it like this: I've just written three functions, and it occurs to me that someone else should know about them. I could document them, write them up, announce them at a meeting, etc. - which I can do, but it's not my strength - or .... I can extract them to a class, name it well, make them function like a black box, and stick it where other class files go. Then a short email announcing it is easy. Other developers can scan the code and understand it better than they could an isolated function used in code they don't fully understand - that context is removed.

I like this because it means having a set of well-named class files, with well-named methods, is a good solution that is accomplished by good programming. It does not require meetings, and it softens the need for detailed documentation.

Are there any more ideas in this vein ... for isolated and time-pressed developers?

答: Code review sessions can help. If your team meets regularly to discuss what was developed, then the person who came up with a solution can show the others how to use it. If someone brings up a point they're sticking on, other team members could propose an approach that increases reuse of existing components. </p>

ContentLicense: CC BY-SA 3.0


答:
Libraries. Frameworks. Version control.

If you've got reusable code, the very last thing you want is for different team members to copy the source code into their project. If they do that, chances are that they'll change a bit here and tweak a bit there, and soon you've got dozens of functions or methods that all have the same name but which each work a little bit differently. Or, perhaps more likely, the original author will continue to refine the code to fix bugs, make it more efficient, or add features, but the copied code will never get updated. The technical name for that is a huge freakin' mess.

The right solution is to pull that reusable stuff out of whatever project you built it for in the first place and put it into a library or framework in its own version control repository. That makes it easy to find, but also discourages making changes without consideration for all the other projects that might be using it. You might consider having several different libraries: one for well-tested code that's no longer likely to change, one for stuff that seems stable but which hasn't been thoroughly tested and reviewed, one for proposed additions.

Title: How do you keep track of what classes and functions your team has written?

Body:
When working on code, I face many of the same challenges that my teammates do, and I have written some helpful functions and classes, and so have they. If there is good communication, I'll hear about some great thing someone put together, and six months later when I need it I may remember it and call that function, saving myself time. If I don't remember it, or never knew about it, I will probably re-invent the wheel.

Is there a particular practice of documenting these kinds of things? How do you make them easy to find?

If your team has no such documentation, how do you find out if your wheel already exists?

EDIT:

All but one of the answers so far deals with an ideal situation, so let me sum up those solutions: documentation & communication; wikis, stand-up meetings, etc. Those are all great things, but they rely on programmers having the time (and skills) to write up the documentation and attend the meetings and take notes and remember everything.

The most popular answer so far (Caleb's) is the only one that could be used by a programmer who is incapable of documentation and meetings, and does only one thing: programming. Programming is what a programmer does, and yes, a great programmer can write up documentation, unit tests, etc., but let's face it - most of us prefer programming to documenting. His solution is one where the programmer recognizes re-usable code and pulls it out to its own class or repository or whatever, and by the fact that it is isolated, it becomes find-able and eases the learning curve for using it.... and this was accomplished by programming.

In a way I see it like this: I've just written three functions, and it occurs to me that someone else should know about them. I could document them, write them up, announce them at a meeting, etc. - which I can do, but it's not my strength - or .... I can extract them to a class, name it well, make them function like a black box, and stick it where other class files go. Then a short email announcing it is easy. Other developers can scan the code and understand it better than they could an isolated function used in code they don't fully understand - that context is removed.

I like this because it means having a set of well-named class files, with well-named methods, is a good solution that is accomplished by good programming. It does not require meetings, and it softens the need for detailed documentation.

Are there any more ideas in this vein ... for isolated and time-pressed developers?


答:
Well, it all comes down to communication.

Wiki's are great and you should definitely install and use one. A good internal programmers intranet is good if people read it and update it, so you're actually talking about a people problem there. You could suggest weekly "team update" meetings where everyone gets together and gives an overview of what work is going on. The tech leads (at least!) should be getting together and chatting about what each team is doing. "Brown Bag" informal sessions are great, schedule them at lunchtime and get people talking.

You also need a way of sharing code, packaging it, versioning it and distributing it. Things would be easier if you have a really well managed source code repository, arranged well into "common" and project folders.

If nothing like this is being done, bring it up with your boss, explain how it will benefit the company and suggest a way forward :)


答: The best way to handle something like that is to have a repository structure that has some simple conventions so that I know, as a programmer, if there is a function doXYZ, roughly where I should look for that function. Whether you're using namespaces, directories, modules, plugins, packages, whatever, your code should be modular so that functions that do the same thing or access the same data sources are in mostly the same spot.


答:
Being in a company with 700 employees, within teams varying between 2 and 20 people, here is my experience.

On the team level

We have "standup meetings" everyday for around 15-20 minutes. We can quickly share common knowledge like "I did this function yesterday, it rocks so hard".

We also have a wiki per project. Which means we can share (technical) information about what's done in the project, including custom classes/functions that were built-in.

On the agency level

On the agency level, we have 4 tools:

Another wiki. It's mainly there to give us information about hardware and stuff, but we sometimes use it to share technical information to be reviewed before putting it on the company level.

Weekly meetings. They're mostly to know the progress of each team/project, but since we're mostly tech enthusiasts, we can bring up cool stuff.

Mailing list. We have a mailing with everyone in the agency. Lots of cool stuff/fun stuff/useful stuff gets through there.

VCS repository. Each agency has its personal repository where we have small projects, mostly modules that we use in different projects.

On the company level

On the company level, it's more organized.

The "agency level" wiki is actually part of the company's wiki.

And the wiki is then split up based on technologies. Thus, anyone can improve it, search through it, and basically give a life to the wiki.

There are also available mailing lists to which we can subscribe. Anyone in the agency can subscribe, and most people follow at least one or two technologies, actually most people follow 5-10 of them.

And the VCS is of course the best code sharing system.

Conclusion

To sum up, there's no clear cut solution. Knowledge sharing has always been a big issue, and will probably remain. There are lot of solutions to create knowledge bases, and one could probably fit your bill. However, some people are trying to get even better KB since current solutions aren't always very smart.


问:
Building one way chat?
I'm implementing a Windows 8 app using C#, part of it is One Way Chat. It will be for multiple users such as teacher and student. We want to use a chat room for every course.

Teachers teach different courses that include many students and students study different courses, so when the teacher and student open the course page, they will find a chat page specific for this course.

How can I build such a thing?

答: One-way chat? Isn't that known as Email? Without the back and forth there's really no need for a real-time display of text. I could see a teacher using a standard policy of "if you have further questions, email me" being the digital equivalent of "If you have further questions, ask me after class". </p>

Title: Building one way chat?


问:
Where to put details about the acceptance criteria of a user story?
In this blog post about acceptance criteria the author explains that good acceptance criteria should:

State an intent not a solution (e.g. “The user can choose an account”
rather than “The user can select the account from a drop-down”)

Are independent of implementation (ideally the phrasing would be the
same regardless whether this feature/story would be implemented on
e.g. web, mobile or a voice activated system)

Are relatively high level (not every detail needs to be in writing)

And further details such as:

The column heading is “Balance”

The rolling balance format is 99,999,999,999.9 D/CR

We should use a dropdown rather than checkboxes

should be moved to either a Team internal documentation or Automated acceptance tests

However,
I often hear people frowning about using Cucumber or similar frameworks for doing GUI tests.
Moreover, using an internal documentation could generate lots of problems due to failure to update the documentation regularly.

I'm still struggling to find an effective way to capture such details during the conversation with the customer.

答:
I like to capture 'Constraints' as a 'P.S.' at the end of my story.

```<code>[user] [actions] so that [goal]

Constraints:
- No Touching
- Actions must be gluten free
</code>```

Those constraints are limitations that clients put on my design, that must be considered when weighing different solutions - I need to know about them up front, so I give them a lot of priority.

Body:
I like to capture 'Constraints' as a 'P.S.' at the end of my story.

[user] [actions] so that [goal]

Constraints:
- No Touching
- Actions must be gluten free

Those constraints are limitations that clients put on my design, that must be considered when weighing different solutions - I need to know about them up front, so I give them a lot of priority.


问:
How to ensure a project 100% tested?
I want to know how exactly, we can ensure that a project is 100% tested ?

In banking or financial applications not 1% also tolerable.

So being a developer, how can you say your code is 100% tested?

Explanation with example is highly appreciated.

答:
Short answer--you can't.  As soon as you expose an application over a network, you've introduced an infinite number of possible variations and conditions that you cannot possibly predict to 100% certainty.  What happens when a user does something incredibly stupid or unpredictable?  What happens when a malicious user works out your processes and comes up with a hack? What happens when networks or hardware fails?  You're never going to get all of it.

That said, you need to play to probabilities.  Your user base, customers, and business owners should be able to identify how they expect the application to be used.  That is, your requirements. Make sure each requirement has both positive and negative test cases based on a reasonable sample of test data and actions.  After that, it's really a case of coming up with ways that the application might be misused and developing test cases around them.  It is always possible to come up with another test, and thus my earlier statement that 100% is unattainable.

You CAN measure code coverage up to 100% (with the value of the last few percentage points being debatable).  This will make sure that if any of your code is reached and run, it will behave in an expected manner.  Code coverage makes no guarantees concerning the correctness of your application, just that you know that all of it will always work sometimes.

Title: How to ensure a project 100% tested?


问:
How much redundancy/robustness should complex software implement?
The focus of this question: Some software performs "extra work" in order to increase the chance of a "eventually successful/satisfactory" outcome, despite one or more internal errors in the software, which requires a longer execution time when those errors happen. All these happen without the user's knowledge if the outcome was successful.

Definition of complex software:

Contains code written by (contributed from) more than 10 developers over its lifetime, and not written in the same time frame

Depends on more than 10 external libraries, each with caveats

A typical software task (for generating a result wanted by the user) requires 10 or more input parameters, where most of them have default values but are configurable if the user needs control.

Most importantly, software that has the appropriate complexity relative to the task being performed, i.e. not unnecessarily complicated.

Edited: What is complex? Please see There is a big difference between Complex and Complicated. (direct link)

Definition of Redundancy/Robustness within this question:
(Added Robustness based on comments)

If a software task failed when the current set of parameters was used, try different parameters.

Obviously, there must be inside knowledge that those "different" parameters use a different code path, possibly resulting in a different (hopefully better) outcome.

Sometimes these different code path are chosen based on observations of the external libraries.

At the end, if the actual task performed is slightly different from the user's specification, the user will receive a report detailing the discrepancy.

Finally, like the 10-plus configurable parameters, the redundancy and reporting are also configurable.

Example of such software:

Database Migration

Business database

Source control database, etc.

Batch converting between a Word document and an OpenOffice document, PowerPoint and OpenOffice Draw, etc.

Automatic translation of an entire website

Automatic analysis of software package, such as Doxygen, but where the analysis needs to be more dependable (i.e. not just a documentation tool)

Network communication, where packets may be lost and a number of retries are expected

This question was originally inspired from How do you deal with intentionally bad code?
 but is now focused on just one of the causes of software bloat. This question does not address any other causes of software bloat, such as addition of new features.

Possibly related:

How to deal with complex codes in (huge) projects

How do people manage to write and maintain extremely complex and hard to read code?

答: Some operations probably warrant a "try-again" approach, especially if they depend on external resources like a database.  For example, if a database cannot be connected to or a query fails, the operation may be retried a certain number of times before giving up and throwing an error to a higher level.  However, in some logic, trying the same thing multiple times is often a symptom of bad code and magical thinking that hides real problems.</p>

ContentLicense: CC BY-SA 2.5


答:
I take a rather pragmatic approach -- if a technical detail is important for the acceptance of a story then it should be in the acceptance criteria, regardless of what some blog post says. If it really is critically important that the column name be "balance", that must be part of the acceptance criteria.

This may lead to overly long acceptance criteria. In such a case I think it's find to have one acceptance criteria be "must pass test suite X", and it is in "test suite X" where you put all of the nitty gritty details about the product.

Title: Where to put details about the acceptance criteria of a user story?

Body:
In this blog post about acceptance criteria the author explains that good acceptance criteria should:

State an intent not a solution (e.g. “The user can choose an account”
rather than “The user can select the account from a drop-down”)

Are independent of implementation (ideally the phrasing would be the
same regardless whether this feature/story would be implemented on
e.g. web, mobile or a voice activated system)

Are relatively high level (not every detail needs to be in writing)

And further details such as:

The column heading is “Balance”

The rolling balance format is 99,999,999,999.9 D/CR

We should use a dropdown rather than checkboxes

should be moved to either a Team internal documentation or Automated acceptance tests

However,
I often hear people frowning about using Cucumber or similar frameworks for doing GUI tests.
Moreover, using an internal documentation could generate lots of problems due to failure to update the documentation regularly.

I'm still struggling to find an effective way to capture such details during the conversation with the customer.


问:
How to integrate code reviews to a team
I work in a team that keeps growing. However, there are no code reviews and I see this as a problem every day. There are people with really limited skills committing code to our repository that I believe should not commit.

I'm not the team leader nor am I in a management position. I already proposed code reviews about 6 months ago and there was no feedback received.  Nor were there any code reviews.

I know code reviews would benefit everyone including the more experienced.  Has anyone had any experience trying to integrate code reviews in a team? What did you propose and how did you do it?

答:
As an end contributor, your options are limited.  The best you can do is try to figure out what's important to management and show how your solution (code reviews) impacts that.  See also “Too object-oriented” and What to do when your colleagues don't value code maintainability [duplicate].

You may want to consider looking around for another position.  Life is too short to waste in junk shops if you're not in a position to make things better.

Title: How to integrate code reviews to a team


答:
Lead by example, even if you aren't the leader. The first step might be for you to start asking other team members to review your own code. Even if there isn't an official team policy, just start doing it. If there are people who are equal or less in experience to you, offer to review their code for them. Even if the team as a whole doesn't adopt the practice, at least you'll personally reap the benefits of peer review. </p>

<p>You might also look at some off the shelf review tools, and try to configure and install one on your box or on a common server. Then, you could offer to demonstrate this to everyone over lunch. </p>

Title: How to integrate code reviews to a team

Body:
I work in a team that keeps growing. However, there are no code reviews and I see this as a problem every day. There are people with really limited skills committing code to our repository that I believe should not commit.

I'm not the team leader nor am I in a management position. I already proposed code reviews about 6 months ago and there was no feedback received.  Nor were there any code reviews.

I know code reviews would benefit everyone including the more experienced.  Has anyone had any experience trying to integrate code reviews in a team? What did you propose and how did you do it?

Body:
Lead by example, even if you aren't the leader. The first step might be for you to start asking other team members to review your own code. Even if there isn't an official team policy, just start doing it. If there are people who are equal or less in experience to you, offer to review their code for them. Even if the team as a whole doesn't adopt the practice, at least you'll personally reap the benefits of peer review.

You might also look at some off the shelf review tools, and try to configure and install one on your box or on a common server. Then, you could offer to demonstrate this to everyone over lunch.


问:
What should I do when waiting for a review?
Before asking my question, I must explain the situation.

I'm working for a company as a junior software engineer. One of the seniors always stops me when I have finished my development and want to commit.

He always wants me to wait for him to review it. This is ok, because usually he finds some bugs, and does some optimizations.

However I must commit my code before the deadline. When I finished, I call him and say it is finished. He usually comes late. So my code is late too.

My question is, what should I do? Should I wait him for a review?

EDIT: Addition to the question. I'm curious about one more issue.

I want to be free when coding. How could I gain the trust for freedom of development?

Some explanations:
I've talked with him about this. But it didn't help. We use an issue tracker already, but there isn't any task for reviews. There are just development and test tasks.

答:
One solution to this could be to get the senior developer involved much earlier by Pair Programming on your work.

Wikipedia page on Pair Programming

The most obvious advantage for you would be that the review happens much earlier in the process so you no longer have to wait for the senior developer.

As well as this you would be able to see the thought processes and techniques of the senior developer as he writes the code, and learn from this.

You might have the problem of the senior developer may not want to pair with you. That can be difficult, but my own experience is that both senior and junior developers gain a lot of experience from pair programming.

There is also often the concern that you will half productivity by having 2 developers work on the same piece of work. It's difficult to measure what the affect on productivity is with Pair Programming, the most common response I've heard is that productivity of teams that do pair and those that don't is about the same. (If anyone has knows any good research on this I would love to hear about it)


问:
Where did the convention of naming command line arguments as 'argv' come from?
It seems like Python, PHP, and Ruby all use the name "argv" to refer to the list of command line arguments. Where does the name "argv" come from? Why not something like "args"?

My guess is that it comes from C, where the v would stand for "vector". Wikipedia has a footnote that says:

the vector term in this variable's name is used in traditional sense
  to refer to strings.

However, there isn't any source for this info. Really, I'm curious if it has roots that trace even farther back. Did C use it because something before that used it?

答: argv comes from C, where the main() function takes an argv parameter that represents a vector of arguments to the program. You could also say that it comes from Unix, which is nearly the same as saying that it comes from C as most Unix development happened in C, and Unix and C have a long shared history.


答:
The problem with coding in finance is, at least in the market driven environments such as trading desks, that the codebase is built by non-professional programmers, mostly mathematicians or quants. These guys hack together matlab scripts and excel sheets in the worst possible way.

This issue has several sources:

These people are not programmers, but traders. Building bug-free software is not their job, making money is. They build scripts that help them identify trading opportunities, and are usually only used within very small teams, where everybody knows who understands which part of the code, and those are the only people that ever use the code. This leads to point 2.

End user and Programmer are the same person. Most code I've seen is Matlab or R, if something goes wrong, it is fixed ad-hoc. Errors emerge when preparing a presentation, and they have to be fixed quickly, which usually means dirty. If something else breaks in the process, it will be fixed when in becomes obvious (next presentation probably). That's why I tried to convince my old boss to enforce unit-testing, instead he decided to enforce 'double check the result', and I decided to quit.

There is a reason quants are called 'math wizards of wall street'. They deal with incredibly complex financial models that few people understand, where by 'few' I exclude most of the people in quant jobs as well. A huge portion of these models is garbage, and this has a far bigger impact than a small bug that is able to slip through unnoticed (after all, results are always subject to interpretation the end user - see 2).

Here is what I believe are good points to start with:

Introduce version control. If you are here, I do not need to tell you why. But quants don't come here.

Unit tests, at least on a per-script level. Have them setup a test environment and then run a test to check whether results are still good. Minimum requirement is to have a set of test-data and have scripts checked with that to see if the results are consistent with previous results to avoid flying blind. I've seen people modifying code and test it on a new set of data, without any clue whether those numbers make sense. Try to avoid that at all costs; at least have a basic idea where you stand.

Code reviews and a common code base. Instead of having everybody hacking together individual code pieces that have been pasted from Matlab tutorials, try to get everybody to use a common code base and discuss code they commit with others. This has several advantages:

Your code is understood by more team members. This is important, as code is often used interactively. Code is used more, and by more people, which not only saves time, but the next point as well.

The bugs are more likely to be found when the code produces results that are unexpected.

People will begin to add some comments, at least in my experience. People asking questions are just a waste of time, so give them a chance to figure it out themselves.

Get rid of Excel as much as possible. Try to use some kind of database (cvs is fine for starters) that holds data reliably and is not prone to outside modification. I've had situations where someone 'cleaned' data (correcting for stock splits etc), and modified the original data, while someone else built code to interpolate over missing data. Excel makes it too easy to screw things up, especially if users do not fully understand what the code does.

In this situation, your goal is not to be bug-free (if it ever is), it's to make as many people as possible understand what the code does. If they have a bit of an idea what's happening where, and where their numbers come from, they usually respect the code more and work more carefully. This leads to a lot less errors, and increases confidence in your results. Once you're there, you can start with the advenced software development techniques.

Obvious note: I'm talking about trading strategy related code here, not what's behind the accounting systems etc., because those back-end systems are usually built by professionals. Clearly, I'm not talking about professionals, and I ain't one either.

Title: How to ensure a project 100% tested?

Body:
I want to know how exactly, we can ensure that a project is 100% tested ?

In banking or financial applications not 1% also tolerable.

So being a developer, how can you say your code is 100% tested?

Explanation with example is highly appreciated.


问:
Are error codes wrong in SQL queries too?
I have an SQL query which does several things at once¹: it does multiple checks and then, if the checks pass, updates some data. Without entering in the domain-specific details, here's an imaginary example:

-- The user password should be updated only if the user account is not removed and
-- not locked, and the threshold was not exceeded.
if exists (select * from [People].[User] where [UserId] = @UserId)
begin
    if exists (select * from [People].[User] where [UserId] = @UserId and [IsLocked] = 0)
    begin
        if exists (select * from [People].[User]
                   where [UserId] = @UserId and [IsRemoved] = 0)
        begin
            update [People].[User] set [PasswordHash] = @Hash where [UserId] = @UserId
            select 0 -- Success.
        end
        else
        begin
            select 3 -- The account doesn't exist any longer.
        end
    end
    else
    begin
        select 2 -- The account is locked.
    end
end
else
begin
    select 1 -- The user cannot be found.
end
```

<p>The query is then used like this:</p>

<pre class="lang-cs prettyprint-override"><code>var errorCode = new SqlDataQuery(query, Program.ConnectionString)
    .With(new { UserId = this.Id, Hash = this.ComputeHash() })
    .ReadValue<int>();

// Error codes are used only between the database and code, and transformed into exceptions
// as soon as possible.
switch (errorCode)
{
    case 1: throw new UserNotFoundException();
    case 2: throw new AccountPermissionException();
    case 3: throw new AccountRemovedException();
}
</code>```

In general programming, error codes are considered bad and should be replaced by conventional error handling procedures, including exceptions.

Is it also bad to use them in SQL queries? If yes, how should I rewrite the query to follow best practices?

¹ Given the non-functional requirements related to the load and performance, there is no way to make several consecutive queries. All the checks and the update should be done in a single query.

答:
Instead of relying on the control-of-flow logic in your database, why not just get the data and handle it in your app code?

```<code>select userid, islocked, isremoved from [People].[User] where [UserId] = @UserId
</code>```

Based on whether or not a record is returned or the values for IsLocked and IsRemvoed, you can update the data or generate errors.

I don't know about other RDBS, but SQL Server has Try/Catch blocks that can also handle various types of errors.

Body:
Instead of relying on the control-of-flow logic in your database, why not just get the data and handle it in your app code?

select userid, islocked, isremoved from [People].[User] where [UserId] = @UserId

Based on whether or not a record is returned or the values for IsLocked and IsRemvoed, you can update the data or generate errors.

I don't know about other RDBS, but SQL Server has Try/Catch blocks that can also handle various types of errors.


答: In C the main() function can take two parameters: argc, which stands for "argument count", and argv, which stands for "argument vector".  In C you do not have fancy objects like vectors, which is why you have to pass in the number of items as argc.  In contrast, the languages you've mentioned have things like vectors or lists which know their own size, so argc is not needed.  But the name argv stuck.

Title: Where did the convention of naming command line arguments as 'argv' come from?

Body:
It seems like Python, PHP, and Ruby all use the name "argv" to refer to the list of command line arguments. Where does the name "argv" come from? Why not something like "args"?

My guess is that it comes from C, where the v would stand for "vector". Wikipedia has a footnote that says:

the vector term in this variable's name is used in traditional sense
  to refer to strings.

However, there isn't any source for this info. Really, I'm curious if it has roots that trace even farther back. Did C use it because something before that used it?


问:
ACID compliant Database that isn't NoSQL?
I'm not necessarily asking if a NoSQL database can be ACID compliant, which has been asked here:
Is there any NoSQL that is ACID compliant?

I'm wondering if we have a database either now or in the future that is wanting or is another option to a traditional RDBMS?

I know NoSQL was supposed to be the big thing and RDBMS were supposed to go by the wayside and so forth (I've read I dunno how many articles on it). But that never really solved the issue of data that was very strict and had to be kept consistent (like bank transactions... stuff like that). So when RDBMS was "supposedly" supposed to go to the wayside... what was supposed to replace this Data that had to be strict?

答: Although Nuodb is a RDBMS, I wouldn't consider it traditional. The approach is how to scale a database while still using the SQL language and being ACID. I guess it's the opposite of what you're suggesting, but getting the benefits of RDBMS and NoSQL.</p>


问:
AGPL License - does it apply in this scenario?
There is an AGPLv3 based software (Client) that makes web service calls (using SOAP) to another software (Server - commercial, cloud based). There is no common code or any connection whatsoever between these two except for the web service calls being made.

My questions -

Does the Server need to be AGPL too?  I guess not - but would like to confirm.

Let us say the end point URL for the Server can be configured on the Client side (by editing an XML file) to connect it to different Servers (again, there is no connection other than the webservice calls being made) does it require any of these Servers being AGPL?

Are there any issues in running the Client as a DLL that is loaded by other commercial applications on users' desktops? Does it require these other applications also to be AGPL?

答:
To answer your first two questions, the GPL FAQ says no, an AGPL-licensed client generally cannot affect the licensing requirements of a service it connects to:

If some network client software is released under AGPLv3, does it have to be able to provide source to the servers it interacts with?

This should not be required in any typical server-client relationship. AGPLv3 requires a program to offer source code to “all users interacting with it remotely through a computer network.” In most server-client architectures, it simply wouldn't be reasonable to argue that the server operator is a “user” interacting with the client in any meaningful sense.

Consider HTTP as an example. All HTTP clients expect servers to provide certain functionality: they should send specified responses to well-formed requests. The reverse is not true: servers cannot assume that the client will do anything in particular with the data they send. The client may be a web browser, an RSS reader, a spider, a network monitoring tool, or some special-purpose program. The server can make absolutely no assumptions about what the client will do—so there's no meaningful way for the server operator to be considered a user of that software.

To answer your third question (assuming by "commercial applications" you mean actually mean "GPL-incompatible applications"), the answer is the same as the normal GPL: no one is actually sure. The FSF believes that loading a (A)GPL-licensed library dynamically creates a derivative work, which would require the code using the library to be GPL-licensed. To be sure, not everyone shares this opinion, but that is the legal opinion and intent of the authors of the GPL.


答:
While the other answers note that argv comes from C, where did C get the idea to call an array a "vector"?

Directly, it came from BCPL. Though argv refers to the vector of (string) arguments, BCPL did have strings stored in vectors, but they were string literals and they worked like Pascal strings. The vector had two elements: the length at literal!0 and the characters at literal!1. According to Clive Feather, strings were manipulated by "unpacking" them into character arrays, transforming the array then "repacking" them into strings: compare this with C where strings are character arrays.

So yes, C used v for vector because something else had done so before. Now, did anything before BCPL use vector in this way? BCPL was itself a simplification of the "Cambridge[or Combined] Programming Language": this used vector as a synonym for a 1-dimensional array and matrix as a synonym for a 2-dimensional array. This is consistent with the notation in mathematics of vectors and matrices, though in CPL they're just handy mnemonics and don't have any of the properties associated with the mathematical structures.

Can we push back further in time regarding computing languages? One potential branch of our trail runs cold. CPL was heavily influenced by Algol 60 (the 1963 update). Now ALGOL 68 had types that were described as "packed vectors", such as bits and bytes: but these weren't in earlier releases of Algol which just had ARRAY referring to array. As BCPL comes from 1966, CPL must have been before that (but after 1963): ALGOL 68 (standardised in 1968 and 1973) cannot have been a direct influence.

On the other hand, Main Features of CPL also makes reference to McCarthy's LISP system. While this doesn't use vector to refer to a data structure in the system itself, those being S-expressions, M-expressions and L-expressions (L-expressions are strings, so any association between vector and string has disappeared), it does use vector in another sense to represent the "values of a number of variables" representing "the state of the machine at any time". So we have evidence for an assumption made in the comments: that use of the word 'vector' to mean 'array' in computing comes from application of the similar term in mathematics.


答:
Everybody agrees on their value, but it is hard to get consensus about how to bring them about.

If there aren't coding standards in place, you're left with either de facto standards or POV.

You might have one developer who is very hot on design patterns whilst another writes his new language in the style of an old one he used to develop with.

Also - whose code gets reviewed? If it is just junior staff they may feel aggrieved as may more senior staff who have to take time out to do it. The real value comes when it is 360. Junior developers get to avoid certain pitfalls whilst senior developers can offer their wealth of experience.

I realise none of the above directly answers "how to get started". But if you can't sell it or suggest a basic framework, you don't stand any chance of it being taken up.

Title: How to integrate code reviews to a team


问:
What are some good assignments for an introductory course, to reach today's students?
I periodically teach an introduction to programming course using Java. I want to give my students some exciting assignments that they can relate to or find interesting. At the very least, I want assignments that make sense and have an internal cohesion (for example, some very bad programming exercises seem contrived just so that you have to use the most recent programming construct covered).

To give you an idea of scope, here's what's being covered:

The assignments must be in Java, using some external library can be done, but it would need to be a simple API and not a full framework

Variables, Primitives and Strings

Console input and output

if, for, while

Arithmetic and logical operators

Simple graphics with line and shape drawing

Static methods

One-dimensional arrays

The students will not go into advanced topics (e.g., no recursion, no emphasis on inheritance). Thus, I'm not looking for complex projects: "Have them write a C compiler. I did it when I was 5 and it was the only way I learned!"

If you have ideas that are more advanced than the scope, please post them on the "Challenging" question linked below, and not this one.

Instead, what I'm looking for are interesting ideas that can be accomplished in a short program. For example:

Students can write a console version of the "Star Wars Name" Generator. This is effectively reading Strings and using substring, but I think it's fun. A similar variation would be a "Mad Libs" program. I used this one five years ago, and perhaps it's already "stale."

Using some trig supplied to them, students can draw regular polygons, and create interesting spiral shapes.

It's also not out of the question to use some simple animation class with most of the code supplied to them. And if you know a Twitter or Facebook service that can be accessed with a simple API, I would be very interested to know.

Please note that this question is different from the "Challenging Java questions for beginners" Question. I'm not looking for challenging per se, just interesting. I think if students work on something where they can easily answer "why would anyone ever want to program that?" then they will learn better.

Even simple problems like computing Miles per Gallon can be good. Although, if there's a way to update it to be more relevant, all the better. If you have an exercise from somewhere else (a book or a website), please cite the source.

To help you think about the typical freshman today, check out the Beloit Mindset list, for many examples that will surely make you feel old.

答:
I would iterate on a prime number generator.

Assignments

Print primes from 1 to 100.

Print primes from input1 to input2.

Record and print performance data of
prime generation.

Graph performance data of prime
generation.

Iterate on algorithm optimization of
the prime number generator.


问:
What problems are Java annotations well suited to?
I've been writing in Java and C# for a while, but I'm having a hard time identifying places where using a custom annotation would be advantageous.

I can see that JUnit uses annotations in test classes to identify the order it should run the methods in the test classes, which obviates the need for a configuration of some sort.

What are other examples of problems that annotations solve elegantly?

答:
I've been experimenting with using annotations to give executable specifications to code and generating unit tests for my algebra project.  For example, I have an interface with a method to add two objects together, and the properties you would expect from additions are marked as annotations:

```<code>interface Group<E> extends Set<E> {
  @Commutative @Associative @Identity("zero") @Inverse("neg")
  E plus (E, E);

  E zero ();

  E neg (E e);
}
</code>```

I have a (partially implemented) annotation processor that generates tests for these properties for any class that claims to implement this interface.

This is an example of "user" annotations: @Commutative, @Associative, etc. are implemented as part of the algebra library, not as part of the annotation processing tool; generating new properties with tests is a simple matter of adding a new annotation type with a special method that checks the property.

Annotations have been moderately well-suited to this task, although there are a number of shortcomings.  For example, java annotations do not have a notion of inheritance, so my processor has to explicitly search for annotations on all superinterfaces of a class.  Also, Java doesn't support marking a method with multiple copies of the same annotation, so I can't write @DistributesOver("foo") and @DistributesOver("bar") on the same method.

Body:
I've been experimenting with using annotations to give executable specifications to code and generating unit tests for my algebra project.  For example, I have an interface with a method to add two objects together, and the properties you would expect from additions are marked as annotations:

interface Group<E> extends Set<E> {
  @Commutative @Associative @Identity("zero") @Inverse("neg")
  E plus (E, E);

  E zero ();

  E neg (E e);
}

I have a (partially implemented) annotation processor that generates tests for these properties for any class that claims to implement this interface.

This is an example of "user" annotations: @Commutative, @Associative, etc. are implemented as part of the algebra library, not as part of the annotation processing tool; generating new properties with tests is a simple matter of adding a new annotation type with a special method that checks the property.

Annotations have been moderately well-suited to this task, although there are a number of shortcomings.  For example, java annotations do not have a notion of inheritance, so my processor has to explicitly search for annotations on all superinterfaces of a class.  Also, Java doesn't support marking a method with multiple copies of the same annotation, so I can't write @DistributesOver("foo") and @DistributesOver("bar") on the same method.


答:
Ideally, there should be at least one other person besides the author doing a code review on each checkin. The code review process can help mitigate the problem of many duplicate methods being checked in. Of course, you're constrained by the knowledge of the reviewers.

TL;DR: Code reviews for every checkin.


答:
Datomic looks promising

Datomic is a database of flexible, time-based facts, supporting queries and joins, with elastic scalability, and ACID transactions. Datomic can leverage highly-available, distributed storage services, and puts declarative power into the hands of application developers.

From the rationale :

Datomic is built upon the model of data consisting of immutable values. How can data be immutable? Don't facts change? They don't, in fact, when you incorporate time in the data. For instance, when Obama became president, it didn't mean that Bush was never president. As long as who is president isn't stored in a single (logical) place, there's no reason a database system couldn't retain both facts simultaneously.

Title: ACID compliant Database that isn't NoSQL?

Body:
I'm not necessarily asking if a NoSQL database can be ACID compliant, which has been asked here:
Is there any NoSQL that is ACID compliant?

I'm wondering if we have a database either now or in the future that is wanting or is another option to a traditional RDBMS?

I know NoSQL was supposed to be the big thing and RDBMS were supposed to go by the wayside and so forth (I've read I dunno how many articles on it). But that never really solved the issue of data that was very strict and had to be kept consistent (like bank transactions... stuff like that). So when RDBMS was "supposedly" supposed to go to the wayside... what was supposed to replace this Data that had to be strict?


问:
How to maintain standard quality of images uploaded by many users?
We're developing a site where individuals (store owners) will be able to take pictures and upload to the site. Our biggest concern is the variance in quality of pictures across the site.

The options we are considering are:

Minimum image cleaning scripts (including filters, resizing, sharpening, etc.)

Approval process for uploaded images

Having a team take the photos for them

I'd like to see if anyone has had any experience with 1 and 2 above. How effective is 1, and how efficient is 2?

答:
Depending on the scale of your operation (not specified) and the platform you're targeting (not specified) your range of options is very wide.

Assuming you're targeting a Unix/Linux platform, the default image processing library for #1 is ImageMagick - http://www.imagemagick.org/script/index.php  It's been around for ever and is widely supported on a broad range of platforms (it's even available for WinTel if you're going the IIS route).

If you can define the requirements for what makes up "standard quality" well enough, you can cover a good deal of your use cases programmatically.  There are bound to be some edge cases, so I'd recommend also implementing some version of #2 (workflow / approval system) in addition to the programmatic solution.

None of your options are going to solve all cases, and relying on only one option is likely to create bottlenecks in your process.

Your best bet is a combination of #1 & #2 if you want to keep complexity and costs down.


问:
Besides polymorphism, what's compelling about OOP?
When I first came to OOP (at first in Java, and then C++) after years of working in C and VB, it was amazing.  The idea of extending existing behaviour and operating generically over things of related types was very appealing, and I almost immidiately saw why it was that I wanted this.  That is, my motivation for OOP was subtyping polymorphism and inheritance.

Fast forward to today, and I regularly get to use ad-hoc polymorphism solutions (typeclasses and duck typing) which solve the problems subtyping originally appealed to me for in very elegant ways.  I have access to parametric polymorphism in most of my environments.  Programming generically with these different sorts of polymorphism gives me all the extensabiltiy and re-use inheritance ever did, and more.

So, my question is: why should I still care about OOP?  What uses of OOP have you found that are really great besides inheritance and subtyping?

Also, "because it's popular and you will have to use it" does not count.  I already am quite familiar with OOP, and use it in my day job because the code base uses it.  For a new project, or for myself, that's what I'm asking about.

答:
Without getting bogged down into a semantic discussion about precisely defining OOP, I'd say that if you are using polymorphism then (as you note) you are using the main benefit of OOP.

Using type classes or duck typing is really just another way to achieve the same goal. You aren't using the C++ / Java style of inherited object orientation, but you are still designing around the concept of typed objects. In my opinion this is either another style of OOP (distinct from the C++ inherited style), or is something so close to OOP that it is only nominally different.

Besides polymorphism, what's so compelling about C++ style OOP? Just the C++ style, if you like that.


答:
As someone who was never particularly enamored with OOP, I can think of a couple of reasons to use it.

One is, it's a good match for certain kinds of problems, such as GUI toolkits.  That's not to say that you can't use other facilities to solve the same problem, just that OOP is well-adapted to it.

Another reason is that, for all the long-standing hype, classic object-oriented languages do provide decent support for programming-in-the-large.  Sure, OOP hasn't got a monopoly on that kind of thing, and you could also look at this as a side effect of "it's popular".  Nonetheless, it's a well-tested way of solving that problem, as well.

I don't know if either of these are what you would call "compelling", but on the other hand, I'd also say that ad hoc polymorphism is almost as overhyped these days as OOP used to be.  Both sets of language features are toolsets which may or may not be particularly useful in a given context.  Also, they are frequently useful in combination;  there is no point in acting like it's a contest between them.

Title: Besides polymorphism, what's compelling about OOP?

Body:
When I first came to OOP (at first in Java, and then C++) after years of working in C and VB, it was amazing.  The idea of extending existing behaviour and operating generically over things of related types was very appealing, and I almost immidiately saw why it was that I wanted this.  That is, my motivation for OOP was subtyping polymorphism and inheritance.

Fast forward to today, and I regularly get to use ad-hoc polymorphism solutions (typeclasses and duck typing) which solve the problems subtyping originally appealed to me for in very elegant ways.  I have access to parametric polymorphism in most of my environments.  Programming generically with these different sorts of polymorphism gives me all the extensabiltiy and re-use inheritance ever did, and more.

So, my question is: why should I still care about OOP?  What uses of OOP have you found that are really great besides inheritance and subtyping?

Also, "because it's popular and you will have to use it" does not count.  I already am quite familiar with OOP, and use it in my day job because the code base uses it.  For a new project, or for myself, that's what I'm asking about.


答:
Besides the answers already given I would like to offer the following benefits:

It is a well known paradigm so by using OOP appropriately you will allow many other developers to work with your code more easily

There is a large body of knowledge built around OOP using such things as design patterns

Most frameworks also assume a certain knowledge of OOP in order to use them

I am sure there are a lot more reasons, but you will note these reasons do not vary much from what you already said as "because its popular."

Yes you will have to use it to some extent but what I seem to be reading is that it isn't exciting for you and that you don't feel compelled to work with OOP outside of your professional work or at least it isn't a driving force. So to answer your question with a question, why don't you find something that excites you again in programming?

I got the same way about OOP after being so excited when I started with C++ (waaay back when..) I felt kinda bored and was losing my gumption. I still use OOP daily in my professional work, but I have found great excitement in learning new things such as functional programming (Haskell) for instance. It is new for me and exciting and I get the feeling of learning things new again. Silly? Perhaps, but it has brought some enjoyment to what I do again. Maybe that is the answer you are looking for.


答:
This is a business question, not a technical one.

Sometimes I'm coding with researchers or on a prototype, so we'll build something with very low robustness. If it breaks, we fix it. There's no point in investing in extra magic if we're going to throw away the code soon.

But if the users of your system need it to be robust, you should build it that way. And you should make it robust specifically in the ways that you and they need to maximize long-term success, while ignoring the kinds of redundancy/robustness that they don't need.

Generally, I start rough and then add robustness over time. I frequently make questions like this part of the normal planning process. I generally work in the Extreme Programming style, where we make a long list of desired features, and I put robustness features in there, too. E.g., "System survives the failure of any single box," gets mixed in with things like "User can join using Facebook credentials." Whichever one comes up first, I build first.

Title: How much redundancy/robustness should complex software implement?

Body:
The focus of this question: Some software performs "extra work" in order to increase the chance of a "eventually successful/satisfactory" outcome, despite one or more internal errors in the software, which requires a longer execution time when those errors happen. All these happen without the user's knowledge if the outcome was successful.

Definition of complex software:

Contains code written by (contributed from) more than 10 developers over its lifetime, and not written in the same time frame

Depends on more than 10 external libraries, each with caveats

A typical software task (for generating a result wanted by the user) requires 10 or more input parameters, where most of them have default values but are configurable if the user needs control.

Most importantly, software that has the appropriate complexity relative to the task being performed, i.e. not unnecessarily complicated.

Edited: What is complex? Please see There is a big difference between Complex and Complicated. (direct link)

Definition of Redundancy/Robustness within this question:
(Added Robustness based on comments)

If a software task failed when the current set of parameters was used, try different parameters.

Obviously, there must be inside knowledge that those "different" parameters use a different code path, possibly resulting in a different (hopefully better) outcome.

Sometimes these different code path are chosen based on observations of the external libraries.

At the end, if the actual task performed is slightly different from the user's specification, the user will receive a report detailing the discrepancy.

Finally, like the 10-plus configurable parameters, the redundancy and reporting are also configurable.

Example of such software:

Database Migration

Business database

Source control database, etc.

Batch converting between a Word document and an OpenOffice document, PowerPoint and OpenOffice Draw, etc.

Automatic translation of an entire website

Automatic analysis of software package, such as Doxygen, but where the analysis needs to be more dependable (i.e. not just a documentation tool)

Network communication, where packets may be lost and a number of retries are expected

This question was originally inspired from How do you deal with intentionally bad code?
 but is now focused on just one of the causes of software bloat. This question does not address any other causes of software bloat, such as addition of new features.

Possibly related:

How to deal with complex codes in (huge) projects

How do people manage to write and maintain extremely complex and hard to read code?


答:
Besides inheritance and subtype polymorphism, here's a list with great things about object-oriented paradigm:

Encapsulation - keeping your data and internal structure hidden provides great flexibility in changing them

Modularization - Most object-oriented languages are class based which makes the modularization more natural; also each modules should communicate to other modules via well defined interfaces

Separation of concerns - Each module/class should do one thing; and is easier to identify what it does

Ease of modeling - domain entities can naturally be modeled into objects

Exception handling - although not really a feature of OOP, it is associated mainly with OO languages

Reusability - OO paradigm brought frameworks which is a great way of reusing code

Feasibility in building large projects - Basically, the object-oriented paradigm is the only feasible way in which we can build large system easily enough

The great advantage of OOP over the others is the idea of modularization; here you have many modules that communicate with each other by sending messages between them. This is a great improvement over the old way of programming were you had data and many subroutines changing the same data.


问:
Nested classes vs namespaces
Is it good to use nested classes or should I use namespaces instead?

In context:

I have a templated codec loader and a codec have In objects and Out objects

```<code>template<class TypeOfData>
class Codec
    {
    private:
        typename TypeOfData::In* reader;
        typename TypeOfData::Out* writer;
    };
</code>```

On the other hand, I cannot use

```<code>using TypeOfData;
</code>```

if i dont want to :: my way to a static method.

答:
Personally, I like this approach, because:

It is a way to standardize class type definitions. If you want you can see it as a kind of interface definition for types to be used for template instantiation, because you cannot instantiate this template with arbitrary types (for 'TypeOfData' type variable). Instead, a concrete 'TypeOfData' must define an inner 'In' and an 'Out' type definition.

You avoid writing a template which needs three type variables (in this concrete case) -- something like

```<code>template <class TypeOfData, class TypeOfIn, class TypeOfOut>
class Codec
{
private:
    TypeOfIn* reader;
    TypeOfOut* writer;
};
</code>```

which makes instantiating this template more complex. Also, you can pass any types for 'TypeOfIn' and 'TypeOfOut'. While this is more generic, it might not be the intention of the template's author. In this concrete case you can see, that there must be exactly one 'In' and one 'Out' type associated with a class 'TypeOfData', which is defined by 'TypeOfData' itself. Using a template with three type variables wouldn't tell you anything about these constraints. Furthermore, the template instantiator (client code) would have to know what 'TypeOfIn' and 'TypeOfOut' he had to use with a class 'TypeOfData'. And this will cause problems if, sometime in the future, the associated 'TypeOfIn' and 'TypeOfOut' types to be used with 'TypeOfData' change. Using the OP's version, client code would likely not have to change, because the template gets the correct types to use from 'TypeOfData' and not by client code.

So I think using this approach is good if these arguments match your requirements. BTW, in that case I wouldn't mind being forced "to :: my way to static method" (or type definitions). If they don't, however, you might be better off using another approach and profit from a possibly more generic (template) solution.

Title: Nested classes vs namespaces

Body:
Personally, I like this approach, because:

It is a way to standardize class type definitions. If you want you can see it as a kind of interface definition for types to be used for template instantiation, because you cannot instantiate this template with arbitrary types (for 'TypeOfData' type variable). Instead, a concrete 'TypeOfData' must define an inner 'In' and an 'Out' type definition.

You avoid writing a template which needs three type variables (in this concrete case) -- something like

template <class TypeOfData, class TypeOfIn, class TypeOfOut>
class Codec
{
private:
    TypeOfIn* reader;
    TypeOfOut* writer;
};

which makes instantiating this template more complex. Also, you can pass any types for 'TypeOfIn' and 'TypeOfOut'. While this is more generic, it might not be the intention of the template's author. In this concrete case you can see, that there must be exactly one 'In' and one 'Out' type associated with a class 'TypeOfData', which is defined by 'TypeOfData' itself. Using a template with three type variables wouldn't tell you anything about these constraints. Furthermore, the template instantiator (client code) would have to know what 'TypeOfIn' and 'TypeOfOut' he had to use with a class 'TypeOfData'. And this will cause problems if, sometime in the future, the associated 'TypeOfIn' and 'TypeOfOut' types to be used with 'TypeOfData' change. Using the OP's version, client code would likely not have to change, because the template gets the correct types to use from 'TypeOfData' and not by client code.

So I think using this approach is good if these arguments match your requirements. BTW, in that case I wouldn't mind being forced "to :: my way to static method" (or type definitions). If they don't, however, you might be better off using another approach and profit from a possibly more generic (template) solution.


问:
Coding style (do more, then simplify)
I'm a CS student and I have been coding for a few months shy of a year now, and I seem to have developed what I think may be a "bad" habit and I'm wondering if anyone does the same (or whether it's a bad habit at all). When I'm coding / solving a problem with code, I find that my initial implementation is lengthy and overly-complicated; in other words, there is a lot of extraneous code (variables, checks) that is simply not needed. When I finish the initial "draft," and make sure the code actually works, I simplify it and make it easier to understand/less verbose.

I think the reason I do this is that I have trouble foreseeing what I will need to complete a task and end up over-compensating and creating complexities that should not or need not exist. Anyone have any tips or advice on how to improve this facet of my coding style, or any input as to whether the habit is actually a bad one?

答:
The "Do more,  then simplify" approach has a major  downside: The big  and complex methods are very hard to test. And you want a test  that documents that  your refactored  code  produces the same results.

So you really need to start thinking about separation of concerns as early as possible, or else  you  will spend a lot of time  wrestling with really difficult unit  tests,  that could be prevented.  You need small pieces of code from the get go. For me, understanding the "Single Responsibility Principle" (SRP)  was very important in this context. Also, decency injection  plays a very big role here.

It is hard to do this in the beginning ( it still is for me a lot off times), but as you gain  experience, you will slowly learn identify patterns in the code,  and know how to break those patterns up into  simple and testable structures.

Title: Coding style (do more, then simplify)


问:
Database Facade to wrap our existing queries?
We have a very big application written in C++ using the MFC framework (millions of code lines). No need to say that it's a legacy system, but it's also heavily maintained and updated. This application lacks a lot of architecture. For example, we have a lot of classes that do queries directly to the database, which creates a lot of difficulty for unit testing.

I have read the book Working Effectively With Legacy Code, and one of the most important things to do first is to create some kind of architecture so we can separate the GUI from the logic and from the database.

My idea to go towards this is to create something like a database facade. There will be 2 goals for this:

Encapsulate all the calls to the database behind this facade.

Be able to test the facade in batch to detect errors in the SQL very fast.

The database facade itself will be implementing an IDatabaseXXXX interface so it could be easily mocked in the unit tests. The second goal will be to be able to run all the functions in the facade in batch to test if there are errors in the SQL queries. I don't count them as unit tests and would be running them only once per day.

My main concern about doing this is that I don't know if there is an existing framework or library to take care of this abstraction. As far as I know, there are some on other platforms like .NET, but it seems that for C++ or MFC, there are not a lot of options. Like I said, the application is very big and the change will be done slowly, mostly when new queries are added to the software.

I think it is a good thing to add that we also have a LOT of recordsets (one for almost each object). For the moment, I don't know how to deal with them, so I kept them on the side and decided to deal with the regular SQL queries. But if you have suggestions to deal with recordsets, I will be glad to hear them.

So my main question is: Is this whole idea of database facade worth trying? Is there any library of framework to help me in this adventure? If there are C++/MFC programmers out there, how do you deal with the abstraction of the query to the database?

Thanks!

EDIT

Some people on the chat suggest looking up at repository pattern which I knew from the world of MVC 3. Any suggestion or tutorial about the repository pattern in C++? Most of what I found is in the .NET world.

答:
I have read the book Working Effectively With Legacy Code, and one of the most important
  things to do first is to create some kind of architecture so we can separate the GUI from
  the logic and from the database.

That would be how to read the legacy code and then rewrite the system in a new platform.  But you can't honestly expect to actually do this in the legacy code itself.  Adding architecture to legacy code after the fact...that just doesn't sound feasible in the real world.


问:
What do small business people do with regards to 'legal' when selling software
For those who have sold software successfully over the Internet, after going to the effort of writing the software, creating a website, get a domain name, hosting the website, setting up a merchant facility, creating a trial version, etc - what do you do about the legal aspect of allowing the version downloaded from the Internet to be used only within the intended scope.  That is from the perspective of say:-

each workstation, or server, or CPU, etc counts as a CAL

Development Vs Evaluation Vs Production

support and upgrades

not allowing the user to on-sell

disallow modifying/extending

Is there a standard procedure / contract for this - i.e. are there documents in the public domain for this or can I take one from another software vendor, tailor it, etc.  Or, do I need to hand crank it - i.e. get an accountant/legal-person to write it up

答:
I tend to use FreeNetLaw for most of my small projects (esp. if I release them into the public domain). They have a good collection of templates that can be used for different purposes. The templates are licensed under the Creative Commons Attribution 2.0 UK: England & Wales License which requires attribution to the source website. Please read their terms carefully before reusing their content.

But you should also consider litigation while drafting your disclaimers and EULAs. And that is often the more worrisome aspect of software distribution (even for free/public domain software).


问:
Algorithm/Strategy or Data structure to capture priorities sub priorities in an app
I am working on a CMS that is starting to evolve a bit.

We started off with content that had the following priorities ( columnn in the db on the content table): HIGH MED LOW.  Data was fetched by priority HIGH being on top etc.

Now after a few months a need has risen to have sub priorities:  HIGH [ high, med , low ], MED [high, med, low ] etc.

I have a test branch with a sub-priority column in the db. So fetch by priority now brings back HIGH(high) HIGH(med) HIGH(low) first.   Wondering is there a better way to do this that I not seeing.

There is a rails app.

答:
If priority is not a small (3) set of values, and nuances between the priorities is necessary, then it is a larger enumerable set.

How large you make this set is up to you, but it is likely easier to make it very large (1 .. 1024 for example), but then you have to discipline the users to not put everything at max priority anyways. This is often a problem with bug trackers where the business sets the only priority (high, medium, low), everything is high.  Then they add critical, and everything is critical or high.

Consider trying to measure multiple metrics at once to determine the priority.  While bug tracker focused - Improving Bug Triage with User Pain takes multiple metrics that are orthogonal to each other:

Type of bug (crash - documentation)

Priority of bug (breaking build - nuisance)

Likelihood of hitting the bug (everyone hitting it - one person hitting it)

Score each of these on a 1 .. n scale, multiply them together and divide by the max.  This gives a number between 100 and 1.  And there is your priority.

For a CMS, one could consider such metrics as:

Importance of article (this is very important - just a notification)

Visibility of article (this goes on the front page - this goes to the back page)

etc...


问:
Refactoring an existing abstract class and its parameters
I have an abstract class A which declares an abstract method doStuff.  Currently there are many classes that inherit from A and implement doStuff.

The class' instances are initialized at run-time via AFactory based on user input.
Originally all the classes had the same single parameter (the user input). But now I have an additional parameter that only a new class that inherits A needs.

So breaking it down I though of the following logic:

The interpreter class that generates instances based on user input(using AFactory of course) was not aware of this extra parameter.

Trying to push it into the class interpreter class would be really awkward because then I would have to know when to pass it to the factory which defeats the whole purpose of having a factory in the first place.

Sending it blindly into the Factory hoping it might do something with it seems quite ugly as well.

My current solution: Meanwhile I've decided to refactor A.doStuff(Param param) into A.doStuff(AParams params).

AParams can hold what ever parameters needed and doStuff can ignore then if they're not interested in them. This also seems a bit awkward to me , and remids me of sending structs in WIN32API that can hold a lot of ugly useless parameters and I'm not fond of it.

Is there a more elegant way to approach this problem ? Or some design pattern that I've overlooked and solves this?

Notes :

We're using Java 1.7

The class' names are silly in order to emphasize the theoretical design issue they do have normal indicative, meaningful names in reality :)

I did search quite a lot but having figured out that it's quite hard to search the web for specific abstract theoretical issues (as opposed to why is X throwing Exception in this code) I've decided to ask anyway so I'm sorry if this is a duplicate.

Edit 1:

Clarification: I need to pass a subclass-specific argument to the doStuff method.

EDIT 2:

I did not fully understand Kilian Foth's intention so I've written some Java-pseudo-code to help me better explain the problem/understand your solution. So:

This is a skeleton of my problem.

This is a skeleton of my solution.

This is what I think  might be Kilian Foth's solution, but I'm not sure.

答:
The usual approach in cases like this (Command patternish) is passing additional parameters in the constructor. In your case, that means adding otherArgument to B during construction.

Turning the logic around might open up some options. For instance moving doStuff to AParams:

```<code>for (String arg : listOfArgs) {
    AParams p = AParams.create(arg, otherArgument));
    for (A a : listOfA) {
        p.doStuff(a); // Let AParams to the lifting depending on type of A
    }
}
</code>```

Alternatively you can swallow your pride and check with instanceof in the loop and set otherArgument manually before calling doStuff.

If the above is not possible, then you have no choice except doing what you're doing (broadening the parameter argument). Don't overanalyze this stuff.

Body:
The usual approach in cases like this (Command patternish) is passing additional parameters in the constructor. In your case, that means adding otherArgument to B during construction.

Turning the logic around might open up some options. For instance moving doStuff to AParams:

for (String arg : listOfArgs) {
    AParams p = AParams.create(arg, otherArgument));
    for (A a : listOfA) {
        p.doStuff(a); // Let AParams to the lifting depending on type of A
    }
}

Alternatively you can swallow your pride and check with instanceof in the loop and set otherArgument manually before calling doStuff.

If the above is not possible, then you have no choice except doing what you're doing (broadening the parameter argument). Don't overanalyze this stuff.


问:
Is it OK to split long functions and methods into smaller ones even though they won't be called by anything else?
Lately I've been trying to split long methods into several short ones.

For example: I have a process_url() function which splits URLs into components and then assigns them to some objects via their methods. Instead of implementing all this in one function, I only prepare the URL for splitting in process_url(), and then pass it over to process_components() function, which then passes the components to assign_components() function.

At first, this seemed to improve readability, because instead of huge 'God' methods and functions I had smaller ones with more descriptive names.
However, looking through some code I've written that way, I've found that I now have no idea whether these smaller functions are called by any other functions or methods.

Continuing previous example: someone looking at the code might think that process_components() functionality is abstracted into a function because it's called by various methods and functions, when in fact it's only called by process_url().

This seems somewhat wrong. The alternative is to still write long methods and functions, but indicate their sections with comments.

Is the function-splitting technique I described wrong? What is the preferred way of managing large functions and methods?

UPDATE: My main concern is that abstracting code into a function might imply that it could be called by multiple other functions.

SEE ALSO: discussions on reddit at /r/programming (provides a different perspective rather than most of the answers here) and /r/readablecode.

答:
If anyone is interested in some literature on this question: This is exactly what Joshua Kerievsky refers to as "Compose Method" in his "Refactoring to Patterns" (Addison-Wesley):

Transform the logic into a small number of intention-revealing steps at the same level of detail.

I believe the correct nesting of methods according to their "detail level" is important here.

See an excerpt on the publisher's site:

Much of the code we write doesn’t start out being simple. To make it simple, we must reflect on what isn’t simple about it and continually ask, “How could it be simpler?” We can often simplify code by considering a completely different solution. The refactorings in this chapter present different solutions for simplifying methods, state transitions, and tree structures.

Compose Method (123) is about producing methods that efficiently communicate what they do and how they do what they do. A Composed Method [Beck, SBPP] consists of calls to well-named methods that are all at the same level of detail. If you want to keep your system simple, endeavor to apply Compose Method (123) everywhere...

Addendum: Kent Beck ("Implementation Patterns") refers to it as "Composed Method". He advises you to:

[c]ompose methods out of calls to other methods, each of which is at roughly the
  same level of abstraction.
  One of the signs of a poorly composed method is a mixture of abstraction
  levels[.]

There, again, the warning not to mix different abstraction levels (emphasis mine).


答:
Remember that any advice you receive here is not to be fully trusted. Most people here aren't lawyers, and even if they are, they're not YOUR lawyer. The laws of software licensing and distribution tend to be sticky and different between different countries and states, so even if someone here is in exactly your situation but is three states away, his personal experience might not be applicable to you.

The best advice is get a lawyer. Get a lawyer that specializes in technology licenses. This is the best legal advice I can give. I know many lawyers who specialize in consulting for small software firms. Even a one man company needs a lawyer to draft paperwork make sure you're not making a mistake.

You wouldn't expect your customers to write their own software. That's what you're there for. Likewise, you should get a professional for your legal work.

Title: What do small business people do with regards to 'legal' when selling software

Body:
For those who have sold software successfully over the Internet, after going to the effort of writing the software, creating a website, get a domain name, hosting the website, setting up a merchant facility, creating a trial version, etc - what do you do about the legal aspect of allowing the version downloaded from the Internet to be used only within the intended scope.  That is from the perspective of say:-

each workstation, or server, or CPU, etc counts as a CAL

Development Vs Evaluation Vs Production

support and upgrades

not allowing the user to on-sell

disallow modifying/extending

Is there a standard procedure / contract for this - i.e. are there documents in the public domain for this or can I take one from another software vendor, tailor it, etc.  Or, do I need to hand crank it - i.e. get an accountant/legal-person to write it up


问:
What is the most appropriate testing method in this scenario?
I'm writing some Objective-C apps (for OS X/iOS) and I'm currently implementing a service to be shared across them. The service is intended to be fairly self-contained.

For the current functionality I'm envisioning there will be only one method that clients will call to do a fairly complicated series of steps both using private methods on the class, and passing data through a bunch of "data mangling classes" to arrive at an end result.

The gist of the code is to fetch a log of changes, stored in a service-internal data store, that has occurred since a particular time, simplify the log to only include the last applicable change for each object, attach the serialized values for the affected objects and return this all to the client.

My question then is, how do I unit-test this entry point method? Obviously, each class would have thorough unit tests to ensure that their functionality works as expected, but the entry point seems harder to "disconnect" from the rest of the world. I would rather not send in each of these internal classes IoC-style, because they're small and are only made classes to satisfy the single-responsibility principle.

I see a couple possibilities:

Create a "private" interface header for the tests with methods that call the internal classes and test each of these methods separately. Then, to test the entry point, make a partial mock of the service class with these private methods mocked out and just test that the methods are called with the right arguments.

Write a series of fatter tests for the entry point without mocking out anything, testing the entire functionality in one go. This looks, to me, more like "integration testing" and seems brittle, but it does satisfy the "only test via the public interface" principle.

Write a factory that returns these internal services and take that in the initializer, then write a factory that returns mocked versions of them to use in tests. This has the downside of making the construction of the service annoying, and leaks internal details to the client.

Write a "private" initializer that take these services as extra parameters, use that to provide mocked services, and have the public initializer back-end to this one. This would ensure that the client code still sees the easy/pretty initializer and no internals are leaked.

I'm sure there's more ways to solve this problem that I haven't thought of yet, but my question is: what's the most appropriate approach according to unit testing best practices? Especially considering I would prefer to write this test-first, meaning I should preferably only create these services as the code indicates a need for them.

答:
I would do something like your version 4 but make that initialiser public.

```<code>@interface Frobulator : NSObject

- (instancetype)init; //uses default collaborators
- (instancetype)initWithThingifier: (id <Thingifiying>)thingifier doohicker: (id <Doohicking>)doohicker; //designated initialiser

- (NSData *)frobulate: (NSData *)unfrobulatedData;

@property (nonatomic, readonly) id <Thingifying>thingifier;
@property (nonatomic, readonly) id <Doohicking>doohicker;

@end
</code>```

Now your unit tests:

test that -frobulate: interacts with the collaborators set via the initialiser. These can be mocks.

test that -init sets up the real collaborators.

You've then got the option in your app of either using the -init method to get the default collaborators, or supplying different collaborators should your needs change.

Body:
I would do something like your version 4 but make that initialiser public.

@interface Frobulator : NSObject

- (instancetype)init; //uses default collaborators
- (instancetype)initWithThingifier: (id <Thingifiying>)thingifier doohicker: (id <Doohicking>)doohicker; //designated initialiser

- (NSData *)frobulate: (NSData *)unfrobulatedData;

@property (nonatomic, readonly) id <Thingifying>thingifier;
@property (nonatomic, readonly) id <Doohicking>doohicker;

@end

Now your unit tests:

test that -frobulate: interacts with the collaborators set via the initialiser. These can be mocks.

test that -init sets up the real collaborators.

You've then got the option in your app of either using the -init method to get the default collaborators, or supplying different collaborators should your needs change.


问:
Distributed SVN via file transfer?
I work for a large bureaucratic (and security paranoid) organisation that provides SVN for its development teams to use.

I am working with a 3rd party vendor (at their site) and we currently share code via SVN export and patch files. The only way I have for transferring files is by a FTP drop box or email. I would like a better way to work.

I am currently lobbying to get some kind of DCVS system setup, ideally cloud hosted. Failing that I want a better way to manage keeping SVN repositories in sync.

In the meantime (or if I fail to get DCVS) how do I keep two SVN repositories in sync?
How do I best manage exporting the repository?
How do I manage incoming changes?

答:
The easiest way, if you have the money a bureaucratic and security paranoid org has, is to go to WanDisco and buy their product and time. SVN always had the ability to sync changes (its great for per-commit backups) but wandisco added the ability to do master-master syncs too, so you can have a fully distributed SVN setup.

Running a DVCS setup on the cloud will not get past your paranoid security team, not by a long chalk. Setting a DVCS up for them will probably be difficult too when they realise there is no central server to hold the definitive sources.

You may still have to manage the SVN system as it is - often, 3rd parties do not get direct access to the repo at all. This is for security reasons more than anything and shows you don't 100% trust the other team - which is common, often you won't even know who they are. SVN does have a lot of access controls you can apply to a repo, and I would recommend setting up a repo just for them to commit to, then merge their changes to the in-house repo, which should be a lot easier than ftp patchsets.

ContentLicense: CC BY-SA 4.0

Title: Distributed SVN via file transfer?


问:
Issue tracking system by function/method
I often feel that it would be more convenient if, within an issue tracking system, each issue were attributed to a certain function/method. Then, we can easily list all the issues related to a certain function/method. Many issues can be clearly attributed to a certain function/method. At times, we may want to look at issues sorted by the posted/edited time or by importance, be many other times, we want to look through only the issues related to a certain function/method.

Of course, the system can be designed to be able to also display them mixed. And there are some issues that do not belong to a particular function/method, but they can be grouped together in some generic group.

Is there such issue tracking system out there?

Is there any problem with such system. If so, what are the problems?

答:
To accomplish that we're using labels (also known as tags) in Jira. So we can also link one issue to multiple methods, search by methods and so on. We can already see which labels/tags are already used, how often they are used and send reports about specific peaks.

But that's not limited to Jira, you could use that way every issue tracker with a tag function.


问:
Creating a coding standards document
I work in a control systems company, where the primary work is SCADA and PLC, along with other control systems stuff.

Software development is not really something the company does, apart from little bits here and there, until there was a decision to create an internal project management and appraisal system.

This project has been taken on by people who came here as software people originally and we are mostly junior.

The project started off small, so we only documented stuff like design, database stuff etc, but we never really agreed upon a coding format/conventions.

We started using StyleCop to make sure we had well documented code, but I feel we need an official document for coding conventions/practices so we can continue a good standard and if there is any more major development work in the future, whomever works on it has a good baseplate.

Therein lies the problem, I have no idea how to draft up a document for coding conventions and standards, all I can think of is examples of good vs bad practice (for example camel case when naming variables, avoiding Hungarian notation etc) we are all competent enough programmers (apparently) but we just don't have a charter for this kind of stuff.

To put a point on it, my question is: What are the key aspects and contents of a good coding standards document?

答:
I was going through this process multiple times. And the most successful (although bumpy anyway) approach was to take a "Coding Standards" document from a well known company and modify it to fit your needs.

For example, I just found this one: http://www.tiobe.com/content/paperinfo/gemrcsharpcs.pdf

Anyway, keep your flame-thrower handy.

Cheers,

Title: Creating a coding standards document


答: The biggest problem is identifying the function or method in question.  Most bugs are entered by people not qualified to diagnose them to that level of detail.</p>

Title: Issue tracking system by function/method

Body:
I often feel that it would be more convenient if, within an issue tracking system, each issue were attributed to a certain function/method. Then, we can easily list all the issues related to a certain function/method. Many issues can be clearly attributed to a certain function/method. At times, we may want to look at issues sorted by the posted/edited time or by importance, be many other times, we want to look through only the issues related to a certain function/method.

Of course, the system can be designed to be able to also display them mixed. And there are some issues that do not belong to a particular function/method, but they can be grouped together in some generic group.

Is there such issue tracking system out there?

Is there any problem with such system. If so, what are the problems?