答:
The developers of that system are just trying to protect their job.

If the code is well-documented and understandable, then the developers are easily replaceable. Obviously, if the code is completely lacking in documentation and is indecipherable except to only those trained in the arcane COBOL arts, then it's not so easy for those developers to be removed and replaced.

As you said, those developers have been there for over a decade. They are probably making well over $100K, probably closer to $200K. I'm sure there is a temptation by managers to replace them with junior developers straight from college (or off-shore developers) who will make 1/2 to 1/3 the salary.

Title: Why should you document code?


问:
Why should you document code?

Possible Duplicate:

  “Comments are a code smell”

I am a graduate software developer for an insurance company that uses an old COBOL-like language/flat-file record storage system. The code is completely undocumented, both code comments and overall system design and there is no help on the web (unused outside the industry). The current developers have been working on the system for between 10 and 30 years and are adamant that documentation is unnecessary as you can just read the code to work out what's going on and that you can't trust comments.

Why should such a system be documented?

答:
I'm not sure I would agree that comments/documentation are unnecessary in general. I've observed, though, that over time as my team and I have become better at writing code we have been able to decrease the amount of comments. E.g. If a method is called ProcessFile() why would you want to add a comment that states "This function processes a file"?

There are, however, cases where comments can be extremely helpful. For example when the purpose of a particular statement is not obvious. To take an extremely simple (simplistic?) example: You may implement a division by two as a right shift of bits.

The amount of comments probably also depends on the programming language you use. For example compare assembler code with code written in a higher level language such as Java or C#. Again, I suspect there is a spectrum here.

I would agree, though, that comments cannot be trusted in general. The reason is that in particular with code that has a certain age, the code may have been modified while the comments are still the same. Code and comments are out of sync. Worst case this type of comment may lead a developer to wrong conclusions. My recommendation would be to always be cautious with using information contained in comments.

In summary I think good code requires less comments and in the extreme case could be self-explanatory. To move towards better code in my experience test-driven development (TDD), simple design and merciless refactoring are the best tools. None of these tools, however, replace proper thinking to make appropriate and reasonable choices.

ContentLicense: CC BY-SA 3.0

Title: Why should you document code?


答:
Why should such a system be documented?

In my opinion, any system that is used productively and is supposed to be maintained by people, should have documentation at reach of those people who are responsible for its support. The reason is, simply because:

Not all developers have the same IQ - You want every one to get it not only smart John.

Not all code is obvious, complex algorithms are not quite readable by all.

Business rules, while may be readable, may not alone show why they are there. Take for example this line in a reporting application:

```<code>if (lastname>="ZZ") then goto loop
</code>```

it is somewhat clear to the reader what is happening but not why this is the case?

Finding out details take long time, it is a waste of business money.

Dependency between pieces of the system may not always be obvious. Especially in batch processes where each job looks like an independent program but the execution sequence is a package that must be processed according to certain rules (like monthly runs, etc.).

Documentation should help you understand logs and whether the results are correct or not.

When you understand the function of each component you can answer business questions. Say Suzan calls from accounting and asks why are we missing 5 checks this month? Some programmers may respond, well, I ran the job and gave me no error - This can't help Suzan. If you know which part of the system does the data extraction for processing the checks and then know what are business rules applied to qualify a check to be printed you can provide an useful answer - Assuming there were no bugs.

Remember that documentation go way beyond the comments that are inserted in code. They include ERD, Business Requirements documents, Design documents, etc.

In short: good documentation gives the developers the necessary control to maintain a system.

Title: Why should you document code?

Body:
Possible Duplicate:

  “Comments are a code smell”

I am a graduate software developer for an insurance company that uses an old COBOL-like language/flat-file record storage system. The code is completely undocumented, both code comments and overall system design and there is no help on the web (unused outside the industry). The current developers have been working on the system for between 10 and 30 years and are adamant that documentation is unnecessary as you can just read the code to work out what's going on and that you can't trust comments.

Why should such a system be documented?

Body:
Why should such a system be documented?

In my opinion, any system that is used productively and is supposed to be maintained by people, should have documentation at reach of those people who are responsible for its support. The reason is, simply because:

Not all developers have the same IQ - You want every one to get it not only smart John.

Not all code is obvious, complex algorithms are not quite readable by all.

Business rules, while may be readable, may not alone show why they are there. Take for example this line in a reporting application:

if (lastname>="ZZ") then goto loop

it is somewhat clear to the reader what is happening but not why this is the case?

Finding out details take long time, it is a waste of business money.

Dependency between pieces of the system may not always be obvious. Especially in batch processes where each job looks like an independent program but the execution sequence is a package that must be processed according to certain rules (like monthly runs, etc.).

Documentation should help you understand logs and whether the results are correct or not.

When you understand the function of each component you can answer business questions. Say Suzan calls from accounting and asks why are we missing 5 checks this month? Some programmers may respond, well, I ran the job and gave me no error - This can't help Suzan. If you know which part of the system does the data extraction for processing the checks and then know what are business rules applied to qualify a check to be printed you can provide an useful answer - Assuming there were no bugs.

Remember that documentation go way beyond the comments that are inserted in code. They include ERD, Business Requirements documents, Design documents, etc.

In short: good documentation gives the developers the necessary control to maintain a system.


问:
Create my own database system
I need to learn how databases work in order to use them more efficiently, and my way of learning is by doing.

I want to create my own database system. I am not referring to creating a pseudo-database that would use query to parse files; this would simply be a filesystem interface with a query language. I am talking about the actual structure of a database engine. And since what I have in mind is neither relational nor document-oriented (it's "node-oriented", if that even exists), I would need any resource to be as abstract and high-level as possible.

So how would I go about creating that? What resources/tutorials/books can I read to understand?

The language does not matter in the slightest. Ideally, the code would be pseudo-code to illustrate the concept, not tied to a particular language, but anything would do. I was not able to find anything on the matter on google (since I am so illiterate on the subject, maybe I am just not entering the right search).

If such resources are not available, then I guess something about how to create a client would at least be a step in the right direction.

答:
Sounds like a great project. Apparently your goal is not to create a production software, but to learn about databases and the process of creating a database system.

I don't really think you need to do a lot of research. It seems like the purpose is to get the experience of what goes in to creating a node-based database system.

Here's how I would get started:

Choose your favorite language or a language that you want to improve.

Create the node object (or whatever is closest in your language). Figure out how to link them.

Make a short list of SQL statements that you will implement first.

Decide how to save the data. One obvious solution is to serialize all the nodes, load them when the program starts, and save them when the program ends.

After you get the basics working, you will have much more insight into what is difficult or problematic. Then you can do some research about it, find some improvements, and integrate them.

Title: Create my own database system


问:
Should developers do their own software releases (if there is a prod support team in place)?
I know there are going to always be differences depending on the particular size, staff etc, but i wanted to get feedback in general around:

In an environment where you have a production support team doing first line support and release management, is it better to simply have developers manage their own releases instead?  In this case, its internal software at an insurance company but the question should be valid at any company, size, etc I think.

Currently, we have our production team do releases but there is an argument that its inefficient and that if you allowed developers the ability to do it, they will focus more on making it simple and efficient and avoid basically passing on scripts, etc to run to another team.

The counter argument is that if you don't have a check and balance, you could get a software team (or an individual) that doesn't a very hacky job about getting their software out there (making on the fly changes, not documenting the process, etc) and that by forcing the prod support team to do the actual release, it enforces consistency and proper checks and balances.

I know this is not a black or white issue but I wanted to see what folks thought on this so the discipline and consistency is there but without the feeling that an inefficient process is in place.

答:
I'm currently working at a small company (it's just 4 of us) so we have to do all of the work (starting with the client interviews to fetch information about features, creating specification documents, and final product deployment).

It was chaos at first, but as we started getting used to doing multiple tasks, we realized that if you define workflows and kind of standarize them, everyone should be able to do some part of the process without knowing what the other did.

Another lesson we learned is: It's always good to know something about each part of the system. I don't mean how its implemented but rather what it does. It's really useful when creating releases (like the problem you mention) because the developer making the release, although he/she did not write that code, knows what is it for.

So, to sum up: Developers should develop to solve a problem. Releasers (I think I just made that up) should think about the best way to release a certain solution. If you think about releasing when developing, your code won't be as clean and may generate problems in the future.


答:
There are a number of reasons why developers should not do production releases.  This is even more important when you have a production support team who need to manage the code after release.

I have extensive experience in small organizations and teams without production support teams.  Even in these organizations releases were done as if we had a production support team.  My experiences supporting applications as well as developing them lead me to respect both roles and their different requirements.

Among the reasons for the handoff to production support:

Fixes may be done directly in production and lost when the next release comes out.  (I just violated this rule for a one-line configuration fix during a week-end production release.  But you can bet I made sure it got fixed in the codebase on Monday.  A larger fix went from developers to integration testing and then to production.)

Environment configuration may get baked into the code. This results in separate builds for development, integration testing, and production. Sometimes non-configuration or untested changes get included in the production build.

Production support gets builds they don't know how to run.  This seems great for the indispensable developer who needs to do all the restarts but is not good for the company.

Production and development code for a release can grow increasingly different.  (I once made the mistake of comparing a development code base that was supposed to be identical to the production code.  Some files were the same.)

Released code is packaged and configured in a manner more suitable for development than production.  The production team is likely to encourage or required appropriate packaging and configuration capabilities.

Code releases may not get tagged in version control.  Versions built for hand-off need to be tracked.  This may not necessarily happen, but less likely to be skipped or overlooked if the code is being "released" to integration testing or production.

Micro-releases are possible.  This makes support a nightmare.  (It was broken at 2:00 but it might have been fixed in the 2:15 or 3:05 release.)

The production support team is one of the stakeholders in the release.  It helps if the development team works with the production support team to make it successful.  Separate environment-specific configuration so that they can be maintained appropriately.  It is often appropriate for the production support team to maintain the environment configuration.

Title: Should developers do their own software releases (if there is a prod support team in place)?

Body:
I know there are going to always be differences depending on the particular size, staff etc, but i wanted to get feedback in general around:

In an environment where you have a production support team doing first line support and release management, is it better to simply have developers manage their own releases instead?  In this case, its internal software at an insurance company but the question should be valid at any company, size, etc I think.

Currently, we have our production team do releases but there is an argument that its inefficient and that if you allowed developers the ability to do it, they will focus more on making it simple and efficient and avoid basically passing on scripts, etc to run to another team.

The counter argument is that if you don't have a check and balance, you could get a software team (or an individual) that doesn't a very hacky job about getting their software out there (making on the fly changes, not documenting the process, etc) and that by forcing the prod support team to do the actual release, it enforces consistency and proper checks and balances.

I know this is not a black or white issue but I wanted to see what folks thought on this so the discipline and consistency is there but without the feeling that an inefficient process is in place.

ContentLicense: CC BY-SA 4.0


答:
I firmly believe that the developers should do all the things necessary to release their code. The biggest problem with delegation of responsibility is that it creates a lot of mistrust between teams that takes a lot hits and teams that do the work. This mistrust and friction causes both the teams focusing their effort and energy on fire fighting and finger pointing activities.

If the idea is that your team should develop valuable code that works well on a production environment then the biggest value comes from what the developer will learn from doing all the activities by himself. If he does not face the issue, he will view all firefighting from other teams as a hindrance rather than learning. When he views as hindrance  he will simply not learn but try to focus on how to do things undetected by the other teams.

If I were the company with money to afford specialist teams and demand zero failures. I would put in place a few loosely defined(non binding) expert teams and let the developer choose if he wants his work reviewed by them. If the release fails, the developer knows what he did wrong and how he can avoid it. As grows up in the technical ladder he might want to move into those expert teams.

Due to peer pressure people will get their work reviewed by the expert teams. And it will also create better relation between expert teams and developers, actually leading to better work.


问:
Getting in to smart card programming
I have a Compaq nw8440 with a smart card reader that is:

Compatible with ISO 7816 compliant Smart Cards. PC/SC interface support

I have been interested in smart cards and wanted to start playing around with them. If I wanted to get in to programming smart cards where can I find resources on how to do it, and would I need any additional hardware other than what my laptop provides (besides the cards to program)?

答:
Look into the Java Card platform to start. It's a subset of Java that allows one to write smart card applications. Also, you will need some blank cards to play with. A card reader and software should be enough to get you going.

Good luck!

Title: Getting in to smart card programming


问:
Why isn't protection against SQL injection a high priority?
On Stack Overflow, I see a lot of PHP code in questions and answers that have MySQL queries that are highly vulnerable to SQL injection attacks, despite basic workarounds being widely available for more than a decade.

Is there a reason why these types of code snippets are still in use today?

答: Don't confuse the purpose of a tutorial, which is to demonstrate something simply, with what should be done in a production environment. For example, most tutorial code I have written has little or no error/exception checking. I try to remind the reader that the code only demonstrates how to perform a specific task, not how to cover all the possible outcomes.</p>

OwnerDisplayName: Tomalak Geret'kal


问:
How can I make sure my evening project code is mine?
I'm a physicist with a CS degree and just started my PhD at a tech company (wanted to do applied research). It deals with large scale finite element simulations.

After reviewing their current approach, I think that a radically different method has to be applied (they are using a commercial tool which is very limited).

I'd rather base my research on an open source finite element solver and write a program which makes use of it. I'd like to develop this idea in the evenings, because that's the time that best suits me for programming (during the day I prefer reading and maths) and use it at a late stage of my PhD.

I'd like to have the option to release my program as open source on my website as a reference, for future personal or even commercial (e.g. consulting) use.

How can I make sure that my company doesn't claim the code ownership?

I thought that a version control system could help (check out only in the evening). This would document that I programmed not during regular office hours (documented elsewhere). But these data can be easily manufactured. Any other ideas?

I want to stress that I'm not interested in selling software and neither is my company.

Very interesting responses so far. This clearly helps me. Some remarks:

I'm not restrained by my work contract. National law says that the company owns anything I produce during working hours and no special agreement has been made (my employer is not selling software and may be a bit naive on this side). They mostly use software and non of my colleagues is a serious programmer.

Secondly, I need to rethink the point raised by @Mark about trade secrets. This is quite serious in the particular industry.

Thirdly, I care a lot about no to upset my supervisor/ boss. But, and this is the motivation for this question, I'd like to keep the innovative part of my work a bit separated so I can reuse it or at least demonstrate it as a reference work.

答:
You haven't listed your contract or where you live but I can tell you that here in the USA your company generally owns anything you do even outside of work if it's related to their business and given your description that you think you have a solution to something they are doing that is better than their current solution that sounds very much directly related to their business.

It would be up to the courts to decide if what you are doing is related but it seems pretty clear from your description it is.

The idea that stuff outside of work time that is related to your company's business belongs to them often sounds strange at first but there are plenty of logical reasons it has to be this way for many types of jobs.

Imagine the law was you owned everything done outside of work time regardless of if it was related. What would the consequences be? Some ideas to get you started.

You're in a meeting with some co-workers at 11am to 12pm and discuss some new product goals. 12pm to 1pm you take your lunch break. During lunch you have a brainstorm and think up an awesome solution. Do you own that solution? Can you reasonably and morally go back to the company and demand they must purchase this solution you just had because you thought of it not on company hours?

For knowledge workers, companies pay you not for 40 hours a week. They pay you to solve the problems they put in front of you regardless of when.

As others have pointed out there's also a conflict of interest. Imagine I work at a game company that has so far only made real time strategy games. I decide to, on my own time, make a platform game at home after hours. If I design a great AI algorithm at home don't I have a moral obligation to share that at work? If I withhold the ideas of game systems I develop at home from the solutions I put forward at work am I really holding up my end of the bargain with my employer? They are paying me for those solutions. Arguably, even though I came up with it on my own time it belongs to the employer. Again, they are paying me for solutions regardless of when they are thought up.

If you want to work on stuff outside of work you have basically a few options

1) Get written permission.

2) Do something unequivocally not related to your employees business.

3) Quit and do your the thing you felt so confident about.

For #2, again, it's going to be up to lawyers if it's remotely related. If you work at an IT company in the day and run a restaurant at night then there is probably no issue. If you work at a company that makes say net security software and you write a twitter app at night it's starting to get more ambiguous. Only you can decide how much risk to take. The best approaches are #1 or #3


问:
What is the economic rationale for focusing on free, open source projects?

Possible Duplicate:

  Why programming open source?

I'm having trouble understanding why people dedicate their time to an open source project that's free as in beer instead of focusing on a closed source, paid project.

Closed source projects seem to be more commercially viable, so why do programmers open source their code and make it free when there are commercial opportunities for it?

答:
This is probably best stated by the Public Domain Manifesto.

Beyond the theory and such, running a business is simply a pain in the butt.  Many developers want to build useful software that gets used by people.  Selling and supporting software takes an enormous amount of time, energry, and (most likely) skills that most developers simply do not have.


问:
Why do new programmers seem to ignore compiler error messages/runtime exception messages?
I think we’ve all seen this. Beginners ask questions on Stack Overflow that follow the basic outline...

I’m trying to do (very vague description of the goal) but it doesn’t work/I get an error/exception. Please help!

Isn’t it bizarre that so many of them seem to consider it unnecessary to paste the error message?

I wonder what the psychology of this is. What is it about error messages that makes people initially assume that they are useless and not worth paying any attention to?

The answer I’m looking for is not “they don’t understand the error message”. That doesn’t explain why they wouldn’t consider telling anyone else who might understand it.

答:
I think if it is a true beginner there's a good chance they don't know there is an error message at all.  They only know it doesn't run and that there is an error.  For example in Visual studio they may not see that part of the screen.  </p>

<p>Basically they don't know which part of the information they have available is useful to figure out what the problem is.  If they did there would be a better chance they could fix it themselves and not ask about it in the first place. </p>

Body:
I think if it is a true beginner there's a good chance they don't know there is an error message at all.  They only know it doesn't run and that there is an error.  For example in Visual studio they may not see that part of the screen.

Basically they don't know which part of the information they have available is useful to figure out what the problem is.  If they did there would be a better chance they could fix it themselves and not ask about it in the first place.

ContentLicense: CC BY-SA 2.5


问:
How do you structure your branches in TFS
My group at work has been trying to come up with a good process that we can use with TFS. I'm just wondering if some of you guys had some successful strategies with using TFS across multiple sites using multiple branches.

One specific issue that we have is probably our release engine. On the simple side, a developer should be able to check in his/her changes into the DEV Branch, and then ok certain date (say a freeze date) the DEV Branch will be "reverse integrated" into the Main Trunk (QA) in which then the changes will be pushed to the Production branch. The issue arose when a user check into the DEV Branch, but he doesn't want those changes to be moved into QA (because maybe other portion of the code is not done yet) ... any thoughts on that?

答:
I've been using it for about 4 years on a couple different teams. What I've found to work best for our group is managing branches by release/iteration. So all changes for the iteration are made on a development branch and when all of those are ready to go to QA then we merge.

This does become a little bit of a problem if you have something on the branch that isn't really ready to merge but then you can choose not to merge those change sets. That gets messy if the code that you aren't including changes some key piece or something but that has been rare in my experience. What we have done is manage the iterations so that everything really is complete by the end. If there is a piece that is risky you can do a branch off your DEV branch just for that so that you can manage it seperately.

I would keep to as few branches as possible so that you don't spend to much time merging.


答:
This has been discussed on lots of blogs by many people with different reasons.  Here are some of the reasons I can remember:

Building up experience

Enhancing resume (point to the open source project during interviews)

Enhance the free product with an additional monetary offering.

Not enough interest to polish it for full commercial release

"Moral" reasons as you suggest.

Title: What is the economic rationale for focusing on free, open source projects?

Body:
Possible Duplicate:

  Why programming open source?

I'm having trouble understanding why people dedicate their time to an open source project that's free as in beer instead of focusing on a closed source, paid project.

Closed source projects seem to be more commercially viable, so why do programmers open source their code and make it free when there are commercial opportunities for it?


答:
There are as many different reasons as there are programmers who make choices. Here are some:

You just need the software to get work done.

If you open source the software, other people will add features they need and you will likely get them for free.

Contributing to open source projects is fun, boosts your ego, and may improve your prospects for a job. (Your resume is verifiable, and companies may well find you.)

You hope to make money from donations, paid support, or getting paid to add needed features.

The base software that would make your job easier requires you to open source the resulting software. Making a version you could keep proprietary would take more effort.

You don't have the ability to support software, and if you are going to charge for it, you pretty much have to do that.

Money is just not a big motivator for you.

You want your efforts to have as great an effect as possible.

You have ulterior motives that will make you money. For example, Google's Android is open source, but promotes Google's search, voice, and location services which are highly profitable.

The last two jobs I've held, both with six-figure salaries, were both offered by companies that found me based on my contributions to open source or free projects.


问:
Understanding and developing web services
This question is in conjuction with How would you approach developing a Hotel Reservation System?

The solution to a system with different interfaces (or clients I should say) is to go with developing a Web service and have other systems interact with it.

I never had the requirement for developing a Web service so I am bit short on it. All I understand is that A web service is a system or application that performs some operations which may include modifying, sending or receiving data over a network using HTTP protocol. (Let me know if the understanding is wrong)

Now, from the other question it's clearly understood that I need to develop a web service but I have no idea as to how should I go about it. My language of choice is C# and .NET Framework.

Question: How do we develop a webservice and which tools, technology and framework should I use for the same using C# language?

Question: How can I interact with this from a desktop WPF application, website and mobile app.

答:
Web Services  is much good approach to make communication between windows and web application.

you can start and learn very easily from MSDN website. Here are few links that will help you to learn Web Services from start/ scratch.

MSDN - Web Service  - It have all information about various type of Web Service.

Simple Web Services

XML Web Services

WCF Web Services etc.

Create and Call Web Services - ASP.Net - Watch This Video to understand better that how to do all of this stuff.

A Step By Step Approach of Creating and Using an ASP.NET Web Service in Visual Web Developer will let you know that how to code for this.

Calling and consuming Web Services on .Net Platform is same for most the technologies. You have to add Web Service Reference in your project to consume them Either it is WPF application or Simple Windows Form Application.

Open your project in Visual Studio.
From the Project menu, click Add Web Reference.

In the dialog box, set the URL to the following: http://services.msdn.microsoft.com/contentservices/contentservice.asmx?wsdl

Press Go, then Add Reference, to create the web reference.

Check this Windows Presentation Foundation User Education - Binding to Web Services

For more information read O'really Programming .NET Web Services - Chapter 2 online.

Hope all of this will help to understand and implement Web Services in your application.
There are lots of Questions on Stackoverflow regarding Web Services. May be you will utilize them.


问:
GPLed Library (EXT JS) Licensing Issue
Good Day Everyone,

I am realy out of option for interpreting the GPL for EXTJS for my work/idea/personal project. I can see that this is an active forum I realy hope, I have a closure on this.

First let me explain my project, Iam creating this website which is like a webportal which is intented for End-User, now this webapps uses an EXTJS library which is GPL'ed as with my understanding on this GPL Any application uses GPL license libray should be released to as Open Source a a GPL compatible Linsence, this is when I or my application is a derivework or I have modified the Library and released it. or destribute it.

But EXTJS has this dual license which is typically giving me the rights to do what I want. without giving out my code.

If my application is intented for end user only, not a derive form of work, not a library, not a development tool, I will not distribute it because it is on the web. with this also the Libraries i will use will remain untouch as it is. and I will have list of library I use and thier respective license to credit them

Given this can I not close-source my application and not violate the GPL?
is it ok for me to use GPL library so long as the above is meet?

The question in short is can i used GPL'ed Library, do not released my code as OPensource compatible License
and still NOT violate the GPL'ed terms?

Thanks in Advance

Nick Ace

答:
Based on the letter of the GPL, you may be right in interpreting that it's possible to use Ext without releasing any code, depending on the circumstances.

However, there's also something as the intent of the people who make it. In your place, I would mail licensing@sencha.com and ask them this question. If you don't like their answer, use a different library. Dojo, YUI and a ton of other libraries are available under more permissive licenses, so you have a ton of options.

If you think that Ext JS is a step up from those other libraries, and the guys at Sencha want you to pay for it, then the honest thing to do is to pay for it. Good products deserve getting paid for if their authors want that.

Title: GPLed Library (EXT JS) Licensing Issue


问:
Should your client be able to view your project management board?
We're making a bespoke software for our client and use Codebase for our project management. Is it a good idea to let our client view our project management board?

The advantages that we thought of are that this would enhance the cooperation between the client and the dev team, following agile practices. He would essentially become part of our team. It would also reduce communication overhead and make sure we're on the same page. The client could track the progression of the system and make suggestions along the way on the user stories. In addition, he could submit bugs or feature requests.

The disadvantages that we though of are that some aspects of the board might be too technical to the client. He would suggest changes to the user stories too often and he might view some content that we normally wouldn't want our client to see. For example, when we compromise on technology or functionality, the client might question that and insist on doing things one way or the other.

答:
Client involvement in the project is important specially in requirements, prototyping, testing, close-down and operations stages (regardless of the methodology used). As you have pointed out, too much of an involvement could be harmful. This harm may be significant given certain client personality styles and backgrounds.

Having the requirements gathering task and prototyping tasks open with no limits or controls can cause the 'client creep' syndrome.

The project management should treat users as an other resource on the project and clearly define each client's role and what is required from them. They should be given information only on need-to-know basis and only the information relevant to their role.

Due to the iterative nature of software development, clients may loose trust in the development team if they are too close to their daily technical issues and observe their problems. Also, most clients are not qualified to participate in technical discussions. The result of their involvement will result in either dissatisfaction (Joe is wasting my time) or intrusion on the development team (I told you Excel is better...). In both cases, no one wins.

So the short answer is, involve clients with care.

The above is my own opinion from my own experience. It is not exact science.


答:
You could try to install a continuous integration process (see here http://en.wikipedia.org/wiki/Continuous_integration). That way, you have always and every day a new release candidate at hand. That does not mean that every of those releases are really delivered to the users, the decision is still up to the production team which version or milestone they deliver. The important part is that you get the responsibilties right between the developer team and the production team.

On the other hand, your development team will be forced to learn how to develop in smaller iterations, where each iteration is a fully documented, internally tested increment. Perhaps that will help you to work more efficient on both sides.


问:
What does your Lisp workflow look like?
I'm learning Lisp at the moment, coming from a language progression that is Locomotive BASIC -> Z80 Assembler -> Pascal -> C -> Perl -> C# -> Ruby.  My approach is to simultaneously:

write a simple web-scraper using SBCL, QuickLisp, closure-html, and drakma

watch the SICP lectures

I think this is working well; I'm developing good 'Lisp goggles', in that I can now read Lisp reasonably easily.  I'm also getting a feel for how the Lisp ecosystem works, e.g. Quicklisp for dependencies.

What I'm really missing, though, is a sense of how a seasoned Lisper actually works.

When I'm coding for .NET, I have Visual Studio set up with ReSharper and VisualSVN.  I write tests, I implement, I refactor, I commit.  Then when I'm done enough of that to complete a story, I write some AUATs.  Then I kick off a Release build on TeamCity to push the new functionality out to the customer for testing & hopefully approval.  If it's an app that needs an installer, I use either WiX or InnoSetup, obviously building the installer through the CI system.

So, my question is: as an experienced Lisper, what does your workflow look like?  Do you work mostly in the REPL, or in the editor?  How do you do unit tests?  Continuous integration?  Packaging & deployment?  When you sit down at your desk, steaming mug of coffee to one side and a framed photo of John McCarthy to the other, what is it that you do?

Currently, I feel like I am getting to grips with Lisp coding, but not Lisp development ...

答:
I work primarily with Clojure, and here's my setup:

Eclipse IDE (I use this as I also do a lot of Java work, sometimes in the same project as Clojure)

Counterclockwise plugin for Clojure (this includes a REPL)

Maven for dependency and build management

Egit for source code control

Workflow while coding is generally like this:

Open a REPL, loading all the current source files

Code and test in the REPL

When I'm happy with some code, copy / paste back into the source file

Occasionally reboot the REPL (either when I've messed up a namespace irrevocably, or just to check everything is still working in the source files)

Also write tests in the source files, which are run automatically by every Maven build. Sometimes the informal tests I've just done at the REPL get turned straight into unit tests.

Commit etc. at this point - pretty much a regular development workflow

Overall it's not too different from a regular Java/C# workflow apart from the more interactive use of the REPL during development.

Title: What does your Lisp workflow look like?


答:
In my case, I use lots of open-source software (OSS) at work.

When I need something a little better than what's available, then I evaluate commercial software. Sometimes, I find that developing what's missing from OSS packages is cheaper than the commercial offerings, especially when it demands a lot of customization, since these can be charged by man-days.

In that case, it makes sense to contribute to the OSS to benefit from the already-written base.


问:
Is duck typing a subset of polymorphism
From Polymorphism on WIkipedia

In computer science, polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface.

From duck typing on Wikipedia

In computer programming with object-oriented programming languages, duck typing is a style of dynamic typing in which an object's current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface.

My interpretation is that based on duck typing, the objects methods/properties determine the valid semantics. Meaning that the objects current shape determines the interface it upholds.

From polymorphism you can say a function is polymorphic if it accepts multiple different data types as long as they uphold an interface.

So if a function can duck type, it can accept multiple different data types and operate on them as long as those data types have the correct methods/properties and thus uphold the interface.

(Usage of the term interface is meant not as a code construct but more as a descriptive, documenting construct)

What is the correct relationship between ducktyping and polymorphism ?

If a language can duck type, does it mean it can do polymorphism ?

答:
I say that polymorphism is a generic trait, that can be implemented several ways:

class based inheritance.

prototype based objects (with or without inheritance)

duck typing

interface compliance (as done by Go's interfaces and implicitly on C++ templates)

each of them allows the programmer to use a single code with different types, so all embody the concept of polymorphism.

Title: Is duck typing a subset of polymorphism


答:
Here's one list:

Learning

You realize that the free stuff like linux didn't happen without hard work, and you want it happen again

complexity of software is just fun

it's just better alternative than anything else available

you already have a job, and another one is just not worth it, but keeping your skills up-to-date is still important

Ability to choose your own projects and techniques and conventions you use -- if money is involved, this choice is often taken away

no micromanaging managers

money makes it more difficult to distribute the end result, for no good reason

all distribution channels where money moves are closed and not available - and if they are available, they all limit the end user availability(which is more important) -- last time we tried the money distribution channels, the contracts made it impossible to use other distribution channels -- exclusive contracts.


问:
How to choose a good namespace name? (Linguistically)
English in not my native language, therefore it is a little more difficult to pick a good name for a namespace. One example to make you see my problem a bit better:

We have a set of classes that have to do with the way a company is organized (we can create organizational charts with it). Currently the namespace is CFW.CoreSystem.Organizational. Is this a good name?

What is linguistically the best way to name a namespace? (CFW.CoreSystem.Configuration is better than CFW.CoreSystem.Configurables).

[Moved it from StackOverflow]

答:
The name chosen for a namespace should indicate the functionality made
available by types in the namespace. For example, the
System.Net.Sockets namespace contains types that enable developers to
use sockets to communicate over networks.

The general format for a namespace name is as follows:

```<code><Company>.(<Product>|<Technology>)[.<Feature>][.<Subnamespace>]
</code>```

For example, Microsoft.WindowsMobile.DirectX.

Do use Pascal casing, and separate namespace components with periods (for example, Microsoft.Office.PowerPoint). If your brand employs nontraditional casing, you should follow the casing defined by your brand, even if it deviates from normal namespace casing.

Consider using plural namespace names where appropriate. For example, use System.Collections instead of System.Collection. Brand names and acronyms are exceptions to this rule, however. For example, use System.IO instead of System.IOs.

Do not use the same name for a namespace and a type in that namespace. For example, do not use Debug for a namespace name and also provide a class named Debug in the same namespace. Several compilers require such types to be fully qualified.

There are lots of Do or Do'not detail on MSDN regarding Naming of namespace, Assemblies etc.
Check this out for Namespaces

CFW.CoreSystem.Configuration is better.

The Namespace CFW.CoreSystem.Organizational is pretty good but
CFW.CoreSystem.Organization is much better to write.

Body:
The name chosen for a namespace should indicate the functionality made
available by types in the namespace. For example, the
System.Net.Sockets namespace contains types that enable developers to
use sockets to communicate over networks.

The general format for a namespace name is as follows:

<Company>.(<Product>|<Technology>)[.<Feature>][.<Subnamespace>]

For example, Microsoft.WindowsMobile.DirectX.

Do use Pascal casing, and separate namespace components with periods (for example, Microsoft.Office.PowerPoint). If your brand employs nontraditional casing, you should follow the casing defined by your brand, even if it deviates from normal namespace casing.

Consider using plural namespace names where appropriate. For example, use System.Collections instead of System.Collection. Brand names and acronyms are exceptions to this rule, however. For example, use System.IO instead of System.IOs.

Do not use the same name for a namespace and a type in that namespace. For example, do not use Debug for a namespace name and also provide a class named Debug in the same namespace. Several compilers require such types to be fully qualified.

There are lots of Do or Do'not detail on MSDN regarding Naming of namespace, Assemblies etc.
Check this out for Namespaces

CFW.CoreSystem.Configuration is better.

The Namespace CFW.CoreSystem.Organizational is pretty good but
CFW.CoreSystem.Organization is much better to write.


问:
What are the essential things one needs to know about UML?
I want my scribbles of a program's design and behaviour to become more streamlined and have a common language with other developers.

I looked at UML and in principle it seems to be what I'm looking for, but it seems to be overkill. The information I found online also seems very bloated and academic.

How can I understand UML in plain-English way, enough to be able to explain it to my colleagues? What are the canonical resources for understanding UML at a ground level?

答: The UML 2.0 Pocket Reference from O'Reilly is a bit more detailed than that but probably the best choice as it is small enough to quickly find what you need but still has explanations when you need them. And it's up-to-date, which is not the case for the "UML cheat sheets" or reference cards I've found on the web - those mostly describe UML 1.x</p>


问:
Role of "Refactoring" in good programming pratices?
I have learned in Agile Development that:

Refactoring is the process of clarifying and simplifying the design of
  existing code, without changing its behavior.

I have heard about some GUI refactoring tools like ReSharper and DevExpress Refactor Pro!

Here are my questions:

How does it takes place in the Software development process and how far it effects the system?

Does Refactoring using these tools really speed up the process of development/maintenance?

答:
First of all, depending upon the site of refactoring one can distinguish several types of it: code refactoring, database (schema) refactoring, refactoring of unit tests, refactoring of GUI etc.

There are several situations where you can meet refactoring during software development:

Refactoring is known to be a mandatory step in certain agile development techniques like test-driven development. It is supposed to perform refactoring step after every implementation step. In this case the refactoring targets just the last implementation and its goal is to integrate the new code into the existing code corpus in the most optimal way.

Refactoring can be done some internal problems in the working code are detected: this is called "code smell". This estimation is in many aspects rather subjective, despite the fact that it can be actually based upon certain code metrics (like number of lines of code per method, cyclomatic complexity of the code etc.). Here the goal of refactoring is to improve the code quality by changing it so that the metrics used for quality estimation return to the expected domain.

You often need to refactor the code to achieve certain principles of programming in your code, look for Clean Code development to learn more about such principles.

You may need to perform refactoring of your code and database schema to prepare it for coming changes, especially if those were not considered during the design phase of the project. For example data normalization and denormalization take often place during data-driven software development to prepare the database for possible extensions.

Refactoring tools available on the market basically support the developer in two ways:

While writing your code, you get suggestions how you can improve it "on-the-fly". Whereas many fallacies can be detected directly by your IDE, like Visual Studio or Eclipse (for example dead code, variables declared but not used etc.), the refactoring tools like Resharper can reveal problems which are far less evident, like re-writing the loops in LINQ queries etc.

These tools also support you with custom refactoring steps, like global renaming of your identifiers, splitting your class declarations into separate properly named files, extracting interfaces and base classes from your class implementation etc. They save a lot of work here, especially if your project has a large code base, but you must first know what you really want to refactor.

Actually using tools like ReSharper in everyday's development is so useful that it makes you almost dependent on them: they really accelerate the process of code writing, especially if you know how to use them appropriately!


问:
Is is possible to develop an application for both metro and classic style?
Is it possible to develop one application that can be be run in both: metro and classic style in Windows 8? I mean, application with the same core and two separate UIs, adjusted to currently used mode.</p>

答:
As @Murph said I am somewhat agree with their statements. Porting GUI Classic to Metro itself writing another library for just GUI change.

```<code>As I have explored about this, I got that it is possible with lots of efforts.
</code>```

When you convert UI code from a Silverlight or Windows Phone
  application, you can use many of the same UI types, but the types are
  now located in the Windows.UI.Xaml namespaces instead of the
  System.Windows namespaces. These new UI types are similar to the
  previous .NET Framework UI types but contain some different members.

Check about Library Changes/ NameSpace Changes over here.

and Check List of Problems with Metro that gives information about the problem that app face in such transformation.

Body:
As @Murph said I am somewhat agree with their statements. Porting GUI Classic to Metro itself writing another library for just GUI change.

As I have explored about this, I got that it is possible with lots of efforts.

When you convert UI code from a Silverlight or Windows Phone
  application, you can use many of the same UI types, but the types are
  now located in the Windows.UI.Xaml namespaces instead of the
  System.Windows namespaces. These new UI types are similar to the
  previous .NET Framework UI types but contain some different members.

Check about Library Changes/ NameSpace Changes over here.

and Check List of Problems with Metro that gives information about the problem that app face in such transformation.


问:
Avoiding coupling

It is also true that a system may become so coupled, where each class
is dependent on other classes that depend on other classes, that it is
no longer possible to make a change in one place without having a
ripple effect and having to make subsequent changes in many places.[1]
This is why using an interface or an abstract class can be valuable in
any object-oriented software project.

Quote from Wikipedia

Starting from scratch

I'm starting from scratch with a project that I recently finished because I found the code to be too tightly coupled and hard to refactor, even when using MVC. I will be using MVC on my new project aswell but want to try and avoid the pitfalls this time, hopefully with your help.

Project summary

My issue is that I really wish to keep the Controller as clean as possible, but it seems like I can't do this. The basic idea of the program is that the user picks wordlists which is sent to the game engine. It will pick random words from the lists until there are none left.

Problem at hand

My main problem is that the game will have 'modes', and need to check the input in different ways through a method called checkWord(), but exactly where to put this and how to abstract it properly is a challenge to me. I'm new to design patterns, so not sure whether there exist any might fit my problem.

My own attempt at abstraction

Here is what I've gotten so far after hours of 'refactoring' the design plans, and I know it's long, but it's the best I could do to try and give you an overview (Note: As this is the sketch, anything is subject to change, all help and advice is very welcome. Also note the marked coupling points):

Wordlist

```<code>class Wordlist {
    // Basic CRUD etc. here!
    // Other sample methods:
    public function wordlistCount($user_id) {} // Returns count of how many wordlists a user has
    public function getAll($user_id) {} // Returns all wordlists of a user
}
</code>```

Word

```<code>class Word {
    // Basic CRUD etc. here!
    // Other sample methods:
    public function wordCount($wordlist_id) {} // Returns count of words in a wordlist
    public function getAll($wordlist_id) {} // Returns all words from a wordlist
    public function getWordInfo($word_id) {} // Returns information about a word
}
</code>```

Wordpicker

```<code>class Wordpicker {

    // The class needs to know which words and wordlists to exclude
    protected $_used_words = array();
    protected $_used_wordlists = array();

    // Wordlists to pick words from
    protected $_wordlists = array();

    /* Public Methods */
    public function setWordlists($wordlists = array()) {}
    public function setUsedWords($used_words = array()) {}
    public function setUsedWordlists($used_wordlists = array()) {}

    public function getRandomWord() {} // COUPLING POINT! Will most likely need to communicate with both the Wordlist and Word classes

    /* Protected Methods */
    protected function _checkAvailableWordlists() {} // COUPLING POINT! Might need to check if wordlists are deleted etc.
    protected function _checkAvailableWords() {} // COUPLING POINT! Method needs to get all words in a wordlist from the Word class

}
</code>```

Game

```<code>class Game {

    protected $_session_id; // The ID of a game session which gets stored in the database along with game details
    protected $_game_info = array();

    // Game instantiation
    public function __construct($user_id) {
        if (! $this->_session_id = $this->_gameExists($user_id)) {
            // New game
        } else {
            // Resume game
        }
    }

    // This is the method I tried to make flexible by using abstract classes etc.
    // Does it even belong in this class at all?
    public function checkWord($answer, $native_word, $translation) {} // This method checks the answer against the native word / translation word, depending on game mode

    public function getGameInfo() {} // Returns information about a game session, or creates it if it does not exist
    public function deleteSession($session_id) {} // Deletes a game session from the database

    // Methods dealing with game session information
    protected function _gameExists($user_id) {}
    protected function _getProgress($session_id) {}
    protected function _updateProgress($game_info = array()) {}

}
</code>```

The Game

```<code>/* CONTROLLER */
/* "Guess the word" page */

// User input
$game_type = $_POST['game_type']; // Chosen with radio buttons etc.
$wordlists = $_POST['wordlists']; // Chosen with checkboxes etc.

// Starts a new game or resumes one from the database
$game = new Game($_SESSION['user_id']);
$game_info = $game->getGameInfo();

// Instantiates a new Wordpicker
$wordpicker = new Wordpicker();

$wordpicker->setWordlists((isset($game_info['wordlists'])) ? $game_info['wordlists'] : $wordlists);
$wordpicker->setUsedWordlists((isset($game_info['used_wordlists'])) ? $game_info['used_wordlists'] : NULL);
$wordpicker->setUsedWords((isset($game_info['used_words'])) ? $game_info['used_words'] : NULL);

// Fetches an available word
if (! $word_id = $wordpicker->getRandomWord()) {

    // No more words left - game over!
    $game->deleteSession($game_info['id']);
    redirect();

} else {

    // Presents word details to the user
    $word = new Word();
    $word_info = $word->getWordInfo($word_id);

}
</code>```

The Bit to Finish

```<code>/* CONTROLLER */
/* "Check the answer" page */

// ??????????????????
</code>```

( http://pastebin.com/cc6MtLTR )

Make sure you toggle the 'Layout Width' to the right for a better view. Thanks in advance.

Questions

To which extent should objects be loosely coupled? If object A needs info from object B, how is it supposed to get this without losing too much cohesion?

As suggested in the comments, models should hold all business logic. However, as objects should be independent, where to glue them together? Should the model contain some sort of "index" or "client" area which connects the dots?

Edit:
So basically what I should do for a start is to make a new model which I can more easily call with oneliners such as $model->doAction(); // Lots of code in here which uses classes!

How about the method for checking words? Should it be it's own object? I'm not sure where I should put it as it's pretty much part of the 'game'. But on another hand, I could just leave out the 'abstraction and OOPness' and make it a method of the 'client model' which will be encapsulated from the controller anyway. Very unsure about this.

答:
To which extent should objects be loosely coupled? If object A needs
  info from object B, how is it supposed to get this without losing too
  much cohesion?

Coupling and cohesion is an important aspect to keep in mind while writing software. However, ideally your code is comprised of high areas of cohesion, loosely coupled to other high areas of cohesion. It shouldn't be a goal to have everything as loosely coupled as possible. It only makes sense to loosely couple those parts of the software when they could be used independently of the other parts.

As suggested in the comments, models should hold all business logic.
  However, as objects should be independent, where to glue them
  together? Should the model contain some sort of "index" or "client"
  area which connects the dots?

Think of all the actions you can do on the model. 'start a game', 'end a game', 'join a game', 'throw dice', ... That are actions which should be exposed in the model. The controller binds the view, where e.g. a button is pressed to start a game, and calls the relevant action in the model.

Regarding your code

At first glance, I'm not sure you separated your entire business logic to your model, and see some of that going on in your controller.

Your model should be able to run on its own separately just by doing calls to it through the controller which simulate user interactions.

Title: Avoiding coupling


问:
Architecture Question
I am writing a rules/eligibility Module.
I have 2 sets of data, one is the customer data and the other is the customer products data.
Customer data to Customer products data is one to many.

Now I have to go through a set of Eligibility rules for each of this Customer product data.
For each customer products data, I can say the customer is eligible for that product or decline the eligibility and should move on to the next product record.

So in all the rules, I need to have access to customer and customer product data(the particular record that the rules are being executed against).
Since all the rules can either approve a product or decline a product, I created an interface with those 2 methods and is implementing the this interface for all the rules.
I am passing the Customer data and one product data for all the rules (because rules should be executed on each row of customer product data). An Ideal situation would be having the customer and customer product data available for the rule instead of passing them to each rule.

What is the best way of doing this in-terms of architecture?

Edit: Here is what I am doing

```<code>public class CustomerContract
{
    public DateTime StartDate { get; set; }
    public DateTime endDate { get; set; }
    //Other Contract related details

}
public class Customer
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string state { get; set; }
}

public class CustomerInfo
{
    public CustomerInfo(int CustomerID)
    {
        Customer = new Customer();// Get Customer from DB
        AppliedProducts = new List<CustomerProduct>();// Get the customer products by customerID
        CurrentContract = new CustomerContract();//Get the contract by CustomerID, State
        declineReasons = new List<int>();// just intailizing. the decline codes are added by rules.
    }

    public CustomerContract CurrentContract { get; set; }
    public IList<CustomerProduct> AppliedProducts { get; set; }
    public IList<int> declineReasons { get; set; }
    public Customer Customer { get; set; }
}

public class CustomerProduct
{
    public decimal AmountCharged { get; set; }
    public int DeclineReasonID { get; set; }
    public int Product { get; set; }
    public decimal DiscountApplicable { get; set; }
    public decimal AmountQuoted { get; set; }
    public decimal Tax { get; set; }
}

public interface IRule
{
    // Since we need to have access to contracts when deciding the eligibility
    CustomerProduct ExecuteRule(CustomerProduct currentproduct, CustomerInfo customerInfo);

    //when denied,
    CustomerProduct DenyProduct(CustomerProduct currentProduct);
}

public class EligibityEngine
{
    List<IRule>  rules = new List<IRule>();
    private CustomerInfo c;

    public EligibityEngine(int CustomerID)
    {
        c = new CustomerInfo(CustomerID);
        LoadRules();
        foreach (var customerProduct in c.AppliedProducts)
        {
            ExecuteRules(customerProduct);
        }
    }

    private void ExecuteRules(CustomerProduct currentProductItem)
    {
        foreach (var rule in rules)
        {
            currentProductItem = rule.ExecuteRule(currentProductItem, c);
        }
    }

    private void LoadRules()
    {
        // add all the IRule types here
        //rules.Add();
    }
}
</code>```

When I execute the rule, I have pass the customer Product data and customer data. I have to pass the result of one rule execution to the other. In the above pattern, if the rule changes data in customerInfo class, it is not save unless it is passes as ref.

My question is I want the all rules to have access to this data with out passing them in. So I need not worry about capturing the out put of the rule.

I want the executeRule method to void.

答:
As @ian31 pointed out, you need the Specification pattern. I once had a very similar need and the design I came up with is roughly as follows:

Each business rule (eligibility rules, in your case) was implemented as a logical predicate, or specification.

As in your case, there were chains of rules, that could be arranged in a conjunction (AND operation) or in a disjunction (OR operation). In a disjunction, the parameter had to be accepted by at least one of the rules and that rule should be reported by the rule engine. In a conjunction, the parameter should be accepted by all the rules, in which case the first rule in the chain should be reported.

There was an interface Rule that had three important implementations: one that delegated to a predicate, and the other two implemented the conjunction and disjunction requirements described above.

There was a RuleFactory that arranged the rules in the order specified by the customer (what is being done by the LoadRules() method in your example). This order could be easily changed without affecting any other part of the application.

It's important to note that none of these classes changed any state. They were pure functions that either accepted or rejected data.

Title: Architecture Question


问:
How can I share my python scripts with my less python-savvy business person partner?
I'm taking financial mathematics as an elective, and I'm working with real life finance industry worker type people. It's actually kind of fun. When I pulled out a macbook at one of our meetings, I had four lifelong windows users look at me like I had three heads.

Anyway, I'm helping with design and simulation of our trading strategy, and I wrote a little thing using matplotlib to visualize historical stock data. However, these guys don't know how to use git, or install python, or deal with path-related package management things. I need to be able to send my scripts to them to use, and I need to do it with absolutely minimal effort on their part.

I was thinking something on the lines of py2exe, but I'd like to hear some advice before I go ahead.

答: The best portable way is using web. You can use wsgi to make your script accessible from web. So they can access from all platforms.</p>


问:
What's the worst programming book you've ever read?
What's the worst programming-related or technical book you've ever read? This can be any book which one way or another can be connected to programming, as long as it's not fiction.</p>

答:
Anything and everything written by Herbert Schildt. Calling this one book is probably a bit of a stretch -- it's more like an eternal case of food poisoning committed to paper.

Fractal Programming in C, by Roger T. Stevens. As Leonard Plinth-Garnell would have said, "Exquisitely awful!"

Numeric Recipes in [C | C++]. Lots of "recipes", but 1) the code is really Fortran with C-family syntax, and 2) many (most?) of the algorithms is propounds are numerically unstable and generally best avoided.


问:
How to write manageable code with functional programming?
I just started with functional programming (with JavaScript and Node.js) and from the look of things it looks as if the code I am writing would grow to be one hell of a code base to manage, when compared to programming languages that have a sort of object oriented paradigm.

With OOP I am familiar with practices that would ensure your code is easily managed and extensible. But am nore sure of similar convention with functional programming.

答:
In practice, a large functional codebase will still need to be divvied up in some sort of structural system. If you are comfortable in OOP, classes remain the natural structuring element. You strive for "functional objects": conceptually related functions are placed together in a class. Of course, you avoid non-conversational state and reliance on instance variables.

Going beyond structure, there are certain techniques, such as partial function application, that are preferred in the functional world for extension, maintainability, and generalization. Learning to recognize these opportunities can be difficult when working in a hybrid functional/object mode, though. Personally, I think it is a good idea to work in a hybrid mode but to study and play in a more pure environment, such as that provided by Haskell.


答:
You have two problems:
* How do I get my program in the hands of others?
* How do I write programs that can run outside my own machine?

You can publicize the program using DropBox, which gives you a folder you can copy files to, and then are made available on a web page where you can email others the URL.  Very easy to use on a daily basis.

The "how can I make Python programs run outside my machine" depends on how much you can assume being available on the target computers, and it seems you cannot rely on anything else than stock Windows.  This mean you will need to let your users either have a very easy download/install of the runtime, or you will need to carry the runtime with you in your program.  This might prove to be quite troublesome - have you considered rewriting your program in e.g. .NET (using Mono) or Java, both which have portability in mind?

Title: How can I share my python scripts with my less python-savvy business person partner?

Body:
I'm taking financial mathematics as an elective, and I'm working with real life finance industry worker type people. It's actually kind of fun. When I pulled out a macbook at one of our meetings, I had four lifelong windows users look at me like I had three heads.

Anyway, I'm helping with design and simulation of our trading strategy, and I wrote a little thing using matplotlib to visualize historical stock data. However, these guys don't know how to use git, or install python, or deal with path-related package management things. I need to be able to send my scripts to them to use, and I need to do it with absolutely minimal effort on their part.

I was thinking something on the lines of py2exe, but I'd like to hear some advice before I go ahead.


答: I really liked Martin Fowler's UML Distilled.  Short and sweet, and more than adequate for whiteboard discussions.  Get a couple of copies and pass them around the team.

Title: What are the essential things one needs to know about UML?

Body:
I want my scribbles of a program's design and behaviour to become more streamlined and have a common language with other developers.

I looked at UML and in principle it seems to be what I'm looking for, but it seems to be overkill. The information I found online also seems very bloated and academic.

How can I understand UML in plain-English way, enough to be able to explain it to my colleagues? What are the canonical resources for understanding UML at a ground level?


问:
What is the most effective approach to learn an unfamiliar complex program?

Possible Duplicate:

  How do you dive into large code bases?

I have quite a bit of experience with different programming languages and writing small and functional programs for a variety of purposes.  My coding skills aren't what I have a problem with.  In fact, I've written a decent web application from scratch for my startup.

However, I have trouble jumping into unfamiliar applications.  What's the most effective way to approach learning a new program's structure and/or architecture so that I can start attacking the code effectively?  Are there useful tools for their respective languages (Python and Java are my two primary languages)?  Should I be starting with just looking at function names or documentation?  How do you veterans approach this problem?

I find this has to be with minimal help from coworkers or contributors who are already familiar with the application and have better things to do than help me.  I'd love to practice this skill in an open source project so any suggestions for starting points (maybe mildly complex) would be great too!

答:
Your best answer is to find and read the documentation. If there aren't any available and it is open-source project, it is probably not a good idea to use it.

Using a good IDE which allows you to jump to the implementation of the method is also very helpful to dig into the code.

If you want to work out how, where, when the codes are executed, it may be better to run it in debug mode. You can track back the stack call to see the behaviour or bookmark to pause the running application and view the variables.

OwnerDisplayName: bdroc

OwnerDisplayName: gigadot


答:
If you are satisfied with mere 10% of it then you shouldn't try to learn it from UML book. Rather, you better read a good book on object-oriented analysis or design patterns -- these books provide you with the 10% you are looking for.

If you are nonetheless looking for a tutorial for UML I would recommend this webpage, and especially this essay on UML diagrams (It's not an ad, I personally have no relation to this site whatsoever). Just browse through the diagrams and look at them: they are mostly self-explaining and you can easily understand what they are depicting as long as you are aware of OOP and generally program design and architecture.

Why would I recommend exactly this page? (asked in the comment)

There are several reasons why I liked it more than the others:

It presents you an overview table of UML diagrams on the very first page.

This table, apart from giving the short description of every UML2.0 digramm, also has a very useful column "Learning Priority" that can help a UML-beginner to identify the most often used UML diagrams.

Even though it contains machine-rendered diagrams as well, most diagrams look like being hand-drawn (probably they are hand-drawn). I take it as a sign that modelling can still be done using only your pencil and paper, no need to delve into UML visualisation software in the very beginning.


问:
What is the economic rationale for focusing on free, open source projects?

Possible Duplicate:

  Why programming open source?

I'm having trouble understanding why people dedicate their time to an open source project that's free as in beer instead of focusing on a closed source, paid project.

Closed source projects seem to be more commercially viable, so why do programmers open source their code and make it free when there are commercial opportunities for it?

答: Software is a medium of expression.  Some people post photos to the web where anyone can see them.  Some people, even professional writers, also write a blog.  Some people publish web comics.  Some people enjoy answering questions on a programming forum.  Some people like to write code.</p>


答:
I think there's no right answer, but here's my take. I've found the best way to learn a new town is to drive through it and do some shopping and dining. When you get lost, look at the map. So, to apply the analogy, I'd find a specific task to work on, and focus on that task. You'll learn things along the way, and even though it's just one slice through the code, it's a start. Doing more tasks means more slices, and you'll just naturally begin to get the bigger picture.

That's not to say that looking at high level architecture and code documentation isn't useful. It's just more useful when studying it with the context of your particular task.

Title: What is the most effective approach to learn an unfamiliar complex program?

Body:
Possible Duplicate:

  How do you dive into large code bases?

I have quite a bit of experience with different programming languages and writing small and functional programs for a variety of purposes.  My coding skills aren't what I have a problem with.  In fact, I've written a decent web application from scratch for my startup.

However, I have trouble jumping into unfamiliar applications.  What's the most effective way to approach learning a new program's structure and/or architecture so that I can start attacking the code effectively?  Are there useful tools for their respective languages (Python and Java are my two primary languages)?  Should I be starting with just looking at function names or documentation?  How do you veterans approach this problem?

I find this has to be with minimal help from coworkers or contributors who are already familiar with the application and have better things to do than help me.  I'd love to practice this skill in an open source project so any suggestions for starting points (maybe mildly complex) would be great too!


答: I think refactoring is like brushing your teeth. It's a chore that doesn't yield immediate benefits, but should be done routinely and quickly before the dentist ends up refactoring your teeth for you.</p>

Title: Role of "Refactoring" in good programming pratices?

Body:
I have learned in Agile Development that:

Refactoring is the process of clarifying and simplifying the design of
  existing code, without changing its behavior.

I have heard about some GUI refactoring tools like ReSharper and DevExpress Refactor Pro!

Here are my questions:

How does it takes place in the Software development process and how far it effects the system?

Does Refactoring using these tools really speed up the process of development/maintenance?


答:
The most important thing is to see what the program actually do when running.  This allows you to get a grasp on what concepts the program presents to the outside world, what data is expected to go in and out, and allow you to mentally model what should be happening inside.  If at all possible, have an experienced user demonstrate the program.

Next, you need to have it in buildable and runnable state inside your favorite IDE, so you can use all your familiar tools to investigate and debug code. From there you should be able to skim the source and correlate your current knowledge with the source code.  From there, your best bet for learning is to improve the current documentation of the source.  (This is not as silly as it sounds - it really helps).


答:
There is no tool, or a software or a pattern that can understand a complex project and then explain it to you { ;-) YET }.

See, for advanced system you will always need a good documentation to understand what's going under the hood. Or else you will need to sit and apply your time for understanding.

Let's take an example of Plone CMS. Suppose if this didnt offered a documentation, it would be hard for you, me or any experienced developer. You know why ?? Because no two people take the same solution route for a problem. X can develop a system in abc manner while Z can interpret it better in cba manner. So, the point is if you find it hard to understand other's written system, don't panic. It's happening to you and it has happened to everybody.

Solution to understanding complex systems :- This is just one way of doing it.

Track the result. If its a website, track the file that's rendering the output(HTML)

Check for the logic in this file and models it is accessing

Understand the Model and capture the database.

Therefore, always go from the endpoint to the start point. I take this road for complex system but still sometimes i am unable to figure why some did that and so on. But, at the end i understand what was in his mind and why things are developed this way.

NOTE:- One thing i would like to endorse which is just my opinion. Don't study someone else's system for just learning purpose. Have a real requirement or idea, then put that together. The best road to learning is driving your own car.


答:
Diagrams alone are not always helpful. For example, the use case diagram can't convey business rules in detail. The class diagram may be very useful since you may be able to generate class code and DLLs from it.

I find these diagrams the most useful:

Use Case Diagram

Class Diagrams

Activity Diagram

Sequence Diagram

There are so many useful resources, but check these:

UML End-to-End From Use Case to Sequence Diagram - Essential Software Tutorial on YouTube

"Practical UML: A Hands-On Introduction for Developers" by Randy Miller

Sparx System's UML Tutorial

OMG's UML.org

Edit-1 in response to Mark's comment.

While I don't use these resources day-to-day, they serve as quick reference for UML syntax.
The above resources are chosen since they provide quick and somewhat comprehensive representation of UML diagrams. It shows common diagrams and helps the new UML user quickly see the difference between them. The first resource, the video, gives details about the Use Case and how it relates to other diagrams.
The above resources are not expected to be enough for anyone who wants to learn UML or OOD, I realize that learning such topics was not intended in the original question.


答:
Algorithm how I usually approach foreign code (look down for a terse version of it in pseudo-code).

The best way to start exploring the foreign system is to read its documentation, especially if special developer documentation (developer manual etc.) is available here. Ask the previous developer to send you any documentation he or she has for the system and appoint a meeting with him/her (if this is feasible) in 1-2 weeks.

While preparing for the meeting study the documentation. If there is no documentation than you may have chances to get a copy of original specifications that were used to implement the system (in big companies these are usually prepared by Program/Project Managers and kept longer, than running documentation).

If your IDE (like VS2010 Ultimate or Eclipse with Plug-ins) support creating architecture diagrams, than try those to get an overview of your system. There is a bunch of special software, like JDepend/NDepend, depending upon your system, which can be useful here.

If you don't get any specification, look at unit tests -- this is in fact a part of the specification as well and already written in the form familiar to you.

During the meeting ask the developer to guide you through the system and ask questions to the parts you don't understand. I usually try to put myself in developer's shoes and see if something seems to be implemented in somewhat strange way: just ask, maybe there are implicit requirements or limitations you should be aware of.

And here is the promised succinct version of the text above.

```<code>if (Documentation.Exists()) ReadDocumentation();
else {
 AskDeveloperIfThereIsDocumentationLyingSomewhereAround();
 if (Documentation.Found()) ReadDocumentation();
}

If (Code.IsDocumentedProperly()) {
   ExtractCodeDocumentation();
   ReadCodeDocumentation();
}

If (IDEOfYourChoice.Supports(ArchitectureDiagramms)) ProduceDiagrammsAndStudyThem();

if (Specification.Exists()) ReadSpecification();
else AskPMIfThereIsDocumentationLyingSomewhereAround();

TryToRunTheSoftwareOnYourOwn();

if (Developer.IsAvailable()) AskToGuideYouShortlyThroughTheCode();
else if (User.Any( user => user.IsCompetent(ThisSystem))) AskUserToGuideYouThroughProgramm();

If (System.HasUnitTests()) {
  ReadUnitTests();
  RunUniTests();
}
</code>```

Body:
Algorithm how I usually approach foreign code (look down for a terse version of it in pseudo-code).

The best way to start exploring the foreign system is to read its documentation, especially if special developer documentation (developer manual etc.) is available here. Ask the previous developer to send you any documentation he or she has for the system and appoint a meeting with him/her (if this is feasible) in 1-2 weeks.

While preparing for the meeting study the documentation. If there is no documentation than you may have chances to get a copy of original specifications that were used to implement the system (in big companies these are usually prepared by Program/Project Managers and kept longer, than running documentation).

If your IDE (like VS2010 Ultimate or Eclipse with Plug-ins) support creating architecture diagrams, than try those to get an overview of your system. There is a bunch of special software, like JDepend/NDepend, depending upon your system, which can be useful here.

If you don't get any specification, look at unit tests -- this is in fact a part of the specification as well and already written in the form familiar to you.

During the meeting ask the developer to guide you through the system and ask questions to the parts you don't understand. I usually try to put myself in developer's shoes and see if something seems to be implemented in somewhat strange way: just ask, maybe there are implicit requirements or limitations you should be aware of.

And here is the promised succinct version of the text above.

if (Documentation.Exists()) ReadDocumentation();
else {
 AskDeveloperIfThereIsDocumentationLyingSomewhereAround();
 if (Documentation.Found()) ReadDocumentation();
}

If (Code.IsDocumentedProperly()) {
   ExtractCodeDocumentation();
   ReadCodeDocumentation();
}

If (IDEOfYourChoice.Supports(ArchitectureDiagramms)) ProduceDiagrammsAndStudyThem();

if (Specification.Exists()) ReadSpecification();
else AskPMIfThereIsDocumentationLyingSomewhereAround();

TryToRunTheSoftwareOnYourOwn();

if (Developer.IsAvailable()) AskToGuideYouShortlyThroughTheCode();
else if (User.Any( user => user.IsCompetent(ThisSystem))) AskUserToGuideYouThroughProgramm();

If (System.HasUnitTests()) {
  ReadUnitTests();
  RunUniTests();
}


答:
The answer is YES.

Duck Typing is a special case of dynamic typing, and even if dynamic typing per se cannot be directly considered as polymorphism (since it is just the property of the language to perform type check at runtime rather then at compile time), the techniques that usually underlie the dynamic typing, such late binding and dynamic dispatch are characteristic for polymorphism.

Title: Is duck typing a subset of polymorphism

Body:
From Polymorphism on WIkipedia

In computer science, polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface.

From duck typing on Wikipedia

In computer programming with object-oriented programming languages, duck typing is a style of dynamic typing in which an object's current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface.

My interpretation is that based on duck typing, the objects methods/properties determine the valid semantics. Meaning that the objects current shape determines the interface it upholds.

From polymorphism you can say a function is polymorphic if it accepts multiple different data types as long as they uphold an interface.

So if a function can duck type, it can accept multiple different data types and operate on them as long as those data types have the correct methods/properties and thus uphold the interface.

(Usage of the term interface is meant not as a code construct but more as a descriptive, documenting construct)

What is the correct relationship between ducktyping and polymorphism ?

If a language can duck type, does it mean it can do polymorphism ?


答:
Your game (Model) embodies the idea of behavioral modes. You know that behavior is in the Controller domain, so it seems like your Model drives your Controllers, which can't be right.

But it is in this case. The problem is that you're talking about two levels of abstraction. When your game is in one particular mode, you should have MVC triads -- the Controller gets the user interaction, forwards it to the Model, the View reflects the new Model state. At that level of abstraction, you certainly don't want your Model objects to influence your Controller.

But your problem has a higher-level, in which, at any one time, it is in a mode. The selection of a particular modal set of MVC triads should be under the control of a higher-level Model object (which, itself, is part of a higher-level MVC triad).

I have to admit I don't follow how your particular example, but let's take Soccer, where you have a normal mode and a penalty kicks mode. Conceptually, your higher-level design would go something like:

```<code>[PSEUDOCODE]

//High-level model of game
class SoccerModel {
   Controller activeController;

   Controller normalController;
   Controller penaltyKicksController;

   getActiveController()  { return activeController; }

   chooseGameMode(evt : GameEvent) : Controller {
         if ( evt == WHATEVER ) {
              activeController = normalController;
         } else if ( evt == SOMETHING_ELSE ) {
              activeController = penaltyKicksController;
         }
         return activeController;
   }
}

interface IController {
   //Returns an event in the Model domain
   eventForInput(input : SomeType) : GameEvent;
   //Deals with input, presumably by mapping it into a GameEvent and forwarding to Model
   handleInput(input : SomeType) : void;
}

class GameController : IController {

   SoccerModel highLevelModel; //Terrible name, but is responsible for modeling the game
   ...etc...

   handleInput(myInput) {
         var gameEvent = eventForInput(myInput);
         var modeController = highLevelModel.chooseGameMode(gameEvent);
         modeController.handleInput(myInput); //Maybe. Allows for more flexibility
   }

   eventForInput(myInput) {
         return model.getActiveController().eventForInput();
   }
}
</code>```

The high-level Model object (SoccerModel) holds Controllers, but at a lower-level. The Controllers it holds (penaltyKicksController normalController) do not have circular references back to the SoccerModel.

Title: Avoiding coupling

Body:
It is also true that a system may become so coupled, where each class
is dependent on other classes that depend on other classes, that it is
no longer possible to make a change in one place without having a
ripple effect and having to make subsequent changes in many places.[1]
This is why using an interface or an abstract class can be valuable in
any object-oriented software project.

Quote from Wikipedia

Starting from scratch

I'm starting from scratch with a project that I recently finished because I found the code to be too tightly coupled and hard to refactor, even when using MVC. I will be using MVC on my new project aswell but want to try and avoid the pitfalls this time, hopefully with your help.

Project summary

My issue is that I really wish to keep the Controller as clean as possible, but it seems like I can't do this. The basic idea of the program is that the user picks wordlists which is sent to the game engine. It will pick random words from the lists until there are none left.

Problem at hand

My main problem is that the game will have 'modes', and need to check the input in different ways through a method called checkWord(), but exactly where to put this and how to abstract it properly is a challenge to me. I'm new to design patterns, so not sure whether there exist any might fit my problem.

My own attempt at abstraction

Here is what I've gotten so far after hours of 'refactoring' the design plans, and I know it's long, but it's the best I could do to try and give you an overview (Note: As this is the sketch, anything is subject to change, all help and advice is very welcome. Also note the marked coupling points):

Wordlist

```<code>class Wordlist {
    // Basic CRUD etc. here!
    // Other sample methods:
    public function wordlistCount($user_id) {} // Returns count of how many wordlists a user has
    public function getAll($user_id) {} // Returns all wordlists of a user
}
</code>```

Word

```<code>class Word {
    // Basic CRUD etc. here!
    // Other sample methods:
    public function wordCount($wordlist_id) {} // Returns count of words in a wordlist
    public function getAll($wordlist_id) {} // Returns all words from a wordlist
    public function getWordInfo($word_id) {} // Returns information about a word
}
</code>```

Wordpicker

```<code>class Wordpicker {

    // The class needs to know which words and wordlists to exclude
    protected $_used_words = array();
    protected $_used_wordlists = array();

    // Wordlists to pick words from
    protected $_wordlists = array();

    /* Public Methods */
    public function setWordlists($wordlists = array()) {}
    public function setUsedWords($used_words = array()) {}
    public function setUsedWordlists($used_wordlists = array()) {}

    public function getRandomWord() {} // COUPLING POINT! Will most likely need to communicate with both the Wordlist and Word classes

    /* Protected Methods */
    protected function _checkAvailableWordlists() {} // COUPLING POINT! Might need to check if wordlists are deleted etc.
    protected function _checkAvailableWords() {} // COUPLING POINT! Method needs to get all words in a wordlist from the Word class

}
</code>```

Game

```<code>class Game {

    protected $_session_id; // The ID of a game session which gets stored in the database along with game details
    protected $_game_info = array();

    // Game instantiation
    public function __construct($user_id) {
        if (! $this->_session_id = $this->_gameExists($user_id)) {
            // New game
        } else {
            // Resume game
        }
    }

    // This is the method I tried to make flexible by using abstract classes etc.
    // Does it even belong in this class at all?
    public function checkWord($answer, $native_word, $translation) {} // This method checks the answer against the native word / translation word, depending on game mode

    public function getGameInfo() {} // Returns information about a game session, or creates it if it does not exist
    public function deleteSession($session_id) {} // Deletes a game session from the database

    // Methods dealing with game session information
    protected function _gameExists($user_id) {}
    protected function _getProgress($session_id) {}
    protected function _updateProgress($game_info = array()) {}

}
</code>```

The Game

```<code>/* CONTROLLER */
/* "Guess the word" page */

// User input
$game_type = $_POST['game_type']; // Chosen with radio buttons etc.
$wordlists = $_POST['wordlists']; // Chosen with checkboxes etc.

// Starts a new game or resumes one from the database
$game = new Game($_SESSION['user_id']);
$game_info = $game->getGameInfo();

// Instantiates a new Wordpicker
$wordpicker = new Wordpicker();

$wordpicker->setWordlists((isset($game_info['wordlists'])) ? $game_info['wordlists'] : $wordlists);
$wordpicker->setUsedWordlists((isset($game_info['used_wordlists'])) ? $game_info['used_wordlists'] : NULL);
$wordpicker->setUsedWords((isset($game_info['used_words'])) ? $game_info['used_words'] : NULL);

// Fetches an available word
if (! $word_id = $wordpicker->getRandomWord()) {

    // No more words left - game over!
    $game->deleteSession($game_info['id']);
    redirect();

} else {

    // Presents word details to the user
    $word = new Word();
    $word_info = $word->getWordInfo($word_id);

}
</code>```

The Bit to Finish

```<code>/* CONTROLLER */
/* "Check the answer" page */

// ??????????????????
</code>```

( http://pastebin.com/cc6MtLTR )

Make sure you toggle the 'Layout Width' to the right for a better view. Thanks in advance.

Questions

To which extent should objects be loosely coupled? If object A needs info from object B, how is it supposed to get this without losing too much cohesion?

As suggested in the comments, models should hold all business logic. However, as objects should be independent, where to glue them together? Should the model contain some sort of "index" or "client" area which connects the dots?

Edit:
So basically what I should do for a start is to make a new model which I can more easily call with oneliners such as $model->doAction(); // Lots of code in here which uses classes!

How about the method for checking words? Should it be it's own object? I'm not sure where I should put it as it's pretty much part of the 'game'. But on another hand, I could just leave out the 'abstraction and OOPness' and make it a method of the 'client model' which will be encapsulated from the controller anyway. Very unsure about this.

Body:
Your game (Model) embodies the idea of behavioral modes. You know that behavior is in the Controller domain, so it seems like your Model drives your Controllers, which can't be right.

But it is in this case. The problem is that you're talking about two levels of abstraction. When your game is in one particular mode, you should have MVC triads -- the Controller gets the user interaction, forwards it to the Model, the View reflects the new Model state. At that level of abstraction, you certainly don't want your Model objects to influence your Controller.

But your problem has a higher-level, in which, at any one time, it is in a mode. The selection of a particular modal set of MVC triads should be under the control of a higher-level Model object (which, itself, is part of a higher-level MVC triad).

I have to admit I don't follow how your particular example, but let's take Soccer, where you have a normal mode and a penalty kicks mode. Conceptually, your higher-level design would go something like:

[PSEUDOCODE]

//High-level model of game
class SoccerModel {
   Controller activeController;

   Controller normalController;
   Controller penaltyKicksController;

   getActiveController()  { return activeController; }

   chooseGameMode(evt : GameEvent) : Controller {
         if ( evt == WHATEVER ) {
              activeController = normalController;
         } else if ( evt == SOMETHING_ELSE ) {
              activeController = penaltyKicksController;
         }
         return activeController;
   }
}

interface IController {
   //Returns an event in the Model domain
   eventForInput(input : SomeType) : GameEvent;
   //Deals with input, presumably by mapping it into a GameEvent and forwarding to Model
   handleInput(input : SomeType) : void;
}

class GameController : IController {

   SoccerModel highLevelModel; //Terrible name, but is responsible for modeling the game
   ...etc...

   handleInput(myInput) {
         var gameEvent = eventForInput(myInput);
         var modeController = highLevelModel.chooseGameMode(gameEvent);
         modeController.handleInput(myInput); //Maybe. Allows for more flexibility
   }

   eventForInput(myInput) {
         return model.getActiveController().eventForInput();
   }
}

The high-level Model object (SoccerModel) holds Controllers, but at a lower-level. The Controllers it holds (penaltyKicksController normalController) do not have circular references back to the SoccerModel.