问:
What are the practical uses of Windows Services?
I am new to working with Windows Services. Although I have learnt to create  Windows Services in VS2010  I would like to know some practical ways in which windows services could be used?

I tried Googling with the current context in mind only to find more tutorials on how to create Windows Services.

EDIT on Bounty Offer:

All the answers are great but I was looking for more practical examples on windows services and their implications? This will help developers know when it is appropriate to use them with the case study.

答:
Services on Windows are basically programs that run without a GUI.  Web servers (such as apache), database servers (such as mysql & sql server), anti-virus engines, and application/'middleware' servers are all practical examples of applications that often run as services.  There may be GUI client to allow you to interact with the service, but the service itself doesn't have one.  It just runs 'in the background', doing its thing.  In addition, since services run with the user rights assigned to them, they can run as their assigned user whether or not a user is actually logged into the machine.  So a database server would have the same access rights regardless of the person logged into the machine at the time, if any.  So you can see why that'd be important - you dont want to have to keep a user logged in to keep a web server running, for example.

They are the Windows equivalent (in most practical ways) to Daemons on *nix.


答:
Service

A program, routine, or process that performs a specific system function to support other programs, particularly at a low (close to the hardware) level. When services are provided over a network they can be published in Active Directory, facilitating service-centric administration and usage.

I would like to know some practical ways in which windows services
  could be used?

As per the service defination, Window Service and others type of services do lots of functionality. In this context search engines are your friend.

Windows services are normally used when an application needs to continuously run. You should create a Windows Service to run code in the background, without user interaction.

A Windows Service will run even if no-one is logged on. Windows service can start running as soon as the machine is powered up, which makes ideal for running as a server, http server for example. No one is required to login.

For example if they need to:

Wait for incoming requests. (Like through remoting or wcf)

Monitor a queue, file system etc.If a program just needs to run periodically, like once a day. It is normally easier to create a scheduled task..

Any server that accepts connections (such as a mail, web, or FTP server) should usually be a Windows Service.

I would use a service for the following reasons:

You don't need to have a session running. This is good for security, and also reduces overhead on the server.

You get some of the management commands built in for free

o   Start

o   Stop

o   Pause

o   Continue

You can handle server events such as shutdown.

Links with additional information about these services:

At Asp.net - //TODONT: Use a Windows Service just to run a scheduled process

What is use of WIndows Service

ContentLicense: CC BY-SA 3.0

Title: What are the practical uses of Windows Services?

Body:
I am new to working with Windows Services. Although I have learnt to create  Windows Services in VS2010  I would like to know some practical ways in which windows services could be used?

I tried Googling with the current context in mind only to find more tutorials on how to create Windows Services.

EDIT on Bounty Offer:

All the answers are great but I was looking for more practical examples on windows services and their implications? This will help developers know when it is appropriate to use them with the case study.


答:
A service runs in the background, even if no-one is signed on to the machine. Anything you can imagine wanting to do without relying on a person to start an app and click a button is a good candidate for a service. For example, monitoring a folder and whenever a file is written to it, process it in some way. Any "server" you can think of - web server, ftp server, mail server - is a service, and so are many background processes you may not often think of.

Some things that were once written as services (backup files at 2am, send reminder emails at 3am etc) are probably better done today as scheduled tasks, which have tremendous flexibility on Windows 7 and up, but if the developer never learned them, or the system must support XP, you will also find services doing those sorts of tasks.


问:
Source Control: Roles and Responsibilities - Best Practices
I'm looking for "Best Practices" concerning roles and responsibilities, specifically who is responsible for merges from development branches to trunk (or main). Basically I'm looking for ammunition to help my cause.

Let me describe what I'm facing. I am the lead developer (owner) of a particular application. Our company recently moved from VSS (where I was the administrator of the VSS database in which my application was stored) to TFS (where I only have permissions on development branches created by our "operations" team). In previous jobs, I was a TFS Admin, so I know my way around TFS and MSBuild.

I don't have an issue with the branching and merging strategy being used (main branch, with bug/project development branches created as needed, merged back to main then promoted to a release branch). The issues I have are:

I cannot create my own branches. I must create a TFS task to have an "operations" team member create the branch for me.

I cannot merge from Main to my development branch. I must create a TFS task to have an "operations" team member perform the merge, and then hope he doesn't "step on" any of my teams changes since the "ops guy" may or may not be a developer and certainly has little to no knowledge of the code he is merging.

I cannot merge from development to Main. Again I must create a TFS task to have the "ops guy" perform the merge, hoping that he does it correctly. Then I have to create another TFS task to merge back to my branch so that I can resolve any issues which have occured by having a non-developer merge to Main.

I cannot create or edit MSBuild scripts. Again I have to work with the "ops" team which is new to MSBuild so only the most basic build tasks can be performed. (Forget about anything complex, or heaven-forbid a custom task).

I cannot execute an MSBuild script. Again only the "ops" team can do this.

To top all of this off, typically it is an "off-shore" resource which performs the requested tasks, so even if I create the task to (branch/merge/build) in the early morning, it probably won't be completed until that evening.

Now I have no issue with the "operations" team maintaining the release branches. As all they are doing is (basically) taking the latest version from Main and promoting it to the release branch; so as long as "Main" is stable and ready, the release branch will be good.

My opinion is that technical leads (such as I) should be responsible for maintaining the trunk ("Main") and any merging to/from the development branches. The team lead should also have the ability to generate MS Build scripts to build and deploy to the Integration test environment.

Can anyone direct me to a Best Practices document that'll help me prove my case? All my searching has turned up only Best Practices concerning the techniques of branching and merging, and no mention of WHO should be performing said branching/merging.

答:
Practices I've seen are:

Anybody can create work branches to their heart's content. A developer must be able to create a feature branch in the second they find there is a point in storing their current work in progress. Because they want/should back it up at the end of the day, want to share it with another team member, need to be shielded from changes in main or whatever.

Anybody can do absolutely anything to development branches. Developer must be able to merge from main the minute another developer tells them something they need has been integrated in main.

For merge to main (integration), there are three options:

Developers do this themselves. They just discuss the risks with the lead developer and test the features appropriately. That implies anybody has the permissions; if somebody breaks the rules, they just get scolded and the wrong change is reverted.

Another developer does it after reviewing the changes. It still requires everybody has permissions to do it; rules are still enforced by the lead developer.

There is designated integrator who reviews and merges into main. But the integrator is part of the team and needs to understand the code. On smaller team it would be the same person as architect, on larger they would be separate, but would need to cooperate closely.

Whoever prepares a feature should adapt the build script. But I am not sure how it works with TFS; in the systems I used the build script was always just a versioned file, so developers edited it just like any other and it was integrated along with everything else.

If there is a designated integrator, they usually take care of defining (which script to run) and starting the builds. Otherwise either the team lead does it, designated team member does it or anybody has permissions and the team lead delegates setting up and starting particular builds on a case-by-case basis.

In no case should above operations require operator outside the team. Operator is only needed for setting up the permissions, creating replicas and such.


问:
How do I format negative user stories?
Following the formal user story style:

As <user>, I want <goal> so that <benefit>.

Our team has found difficulties in expressing things where there is a desire by the system's owners to do something which negatively affects the user.

As an arbitrary example, let's say owner wants to have the system charge customers every time they check their email.

Following the formal style of user stories, you might write this as follows:

As a customer, I want to be charged every time I check my email so that the system owner can increase their revenue.

Obviously the customer has no desire to be charged; the story becomes jarring to read and the language is getting in the way of the facts.

How could the requirement be written differently?

答:
The <user> does not have to be the end user - it can easily be the business owner/system owner:

```<code>As a system owner
I want to charge customers
So that the business can pay my programmers
</code>```

Title: How do I format negative user stories?

Body:
The <user> does not have to be the end user - it can easily be the business owner/system owner:

As a system owner
I want to charge customers
So that the business can pay my programmers


答:
If paying money affected customers negatively, they wouldn't be using that service. Don't worry about this. Also, users don't (usually) pay money because they want to help out system owners, but because they want some service in exchange, so your example should really be like this:

As a customer, I want to be charged every time I check my email so
  that I can get service X in exchange.

Also, user stories are written from the perspective of all user roles, not just end  customers. Consider writing this one from the perspective of the system owner as another user role:

As a system owner, I want customers to be charged every time they
  check their email so that I increase my revenue.

A general advice: Focus on the positive part of the user story and don't overthink it. They should be simple. If the user story is very negative, without a way to avoid it, then the problem is with the conception of the system, and in that case it doesn't really matter what you write on your cards.

Title: How do I format negative user stories?

Body:
Following the formal user story style:

As <user>, I want <goal> so that <benefit>.

Our team has found difficulties in expressing things where there is a desire by the system's owners to do something which negatively affects the user.

As an arbitrary example, let's say owner wants to have the system charge customers every time they check their email.

Following the formal style of user stories, you might write this as follows:

As a customer, I want to be charged every time I check my email so that the system owner can increase their revenue.

Obviously the customer has no desire to be charged; the story becomes jarring to read and the language is getting in the way of the facts.

How could the requirement be written differently?


问:
User Stories about Automated tasks, who is the user?
Following the formal user story style:

As <user>, I want <goal> so that <benefit>.

How can stories be written when there isn't an obvious user-interaction taking place, as in the case of automated processes like nightly invoicing?

答:
What's wrong with e.g.:

As a sales assistant, I want the system to generate my invoices raised during the day, that night without my interaction so that time is saved.

Think of who will use the results of the process.


答:
Just give the thing a name as "AutomaticInvoicer". See it as a robot that acts as a person. No big difference there. Maybe use "it" instead of "I" to make the distinction clear.

```<code>As <AutomaticInvoicer>, it wants to search for open invoices so that
it can initiate booking.
</code>```

Title: User Stories about Automated tasks, who is the user?

Body:
Following the formal user story style:

As <user>, I want <goal> so that <benefit>.

How can stories be written when there isn't an obvious user-interaction taking place, as in the case of automated processes like nightly invoicing?

Body:
Just give the thing a name as "AutomaticInvoicer". See it as a robot that acts as a person. No big difference there. Maybe use "it" instead of "I" to make the distinction clear.

As <AutomaticInvoicer>, it wants to search for open invoices so that
it can initiate booking.


问:
Is Android a language or a framework/platform?
I know that Android uses the Java language with a limited Java SDK and that Google claims it isn't Java. But is it right to say that Android is a Programming language?
Or is it more right to say that Android is a framework in Java? Or is both true?</p>

答: Android is a free open source platform available for anyone to use. The Android operating system is a multi-user Linux system in which each application is a different user. And Android relies on Linux version 2.6 for core system services such as security, memory management, process management, network stack, and driver model.</p>

ContentLicense: CC BY-SA 2.5


问:
Who's the author/creator of the Repository Pattern?
I´m pretty sure it´s not the gang of four. I have a feeling this is a newer pattern. Where was it first published/mentioned?</p>

答:
I saw it first published in Martin Fowler's Patterns of Enterprise Application Architecture (2002).

Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects.

For a full description see P of EAA page 322

A system with a complex domain model often benefits from a layer, such as the one provided by Data Mapper (165), that isolates domain objects from details of the database access code. In such systems it can be worthwhile to build another layer of abstraction over the mapping layer where query construction code is concentrated. This becomes more important when there are a large number of domain classes or heavy querying. In these cases particularly, adding this layer helps minimize duplicate query logic.

A Repository mediates between the domain and data mapping layers, acting like an in-memory domain object collection. Client objects construct query specifications declaratively and submit them to Repository for satisfaction. Objects can be added to and removed from the Repository, as they can from a simple collection of objects, and the mapping code encapsulated by the Repository will carry out the appropriate operations behind the scenes. Conceptually, a Repository encapsulates the set of objects persisted in a data store and the operations performed over them, providing a more object-oriented view of the persistence layer. Repository also supports the objective of achieving a clean separation and one-way dependency between the domain and data mapping layers...


答:
The earliest mention of it that I can find is in this paper, "An Introduction to Software Architecture", by David Garlan and Mary Shaw (1994, first published 1993). That predates the Gang of Four by a year, so it's an older pattern rather than a newer one.

Martin Fowler and Eric Evans have both mentioned it in their books and popularised it, but it's been around for a while.

Title: Who's the author/creator of the Repository Pattern?

Body: I´m pretty sure it´s not the gang of four. I have a feeling this is a newer pattern. Where was it first published/mentioned?</p>


问:
How do you organize your projects?
Do you have any particular style of organizing projects?

For example, currently I'm creating a project for a couple of schools here in Bolivia, this is how I organized it:

```<code>TutoMentor (Solution)
TutoMentor.UI   (Winforms project)
TutoMentor.Data (Class library project)
</code>```

How exactly do you organize your project? Do you have an example of something you organized and are proud of? Can you share a screenshot of the Solution pane?

In the UI area of my application, I'm having trouble deciding on a good schema to organize different forms and where they belong.

Edit:

What about organizing different forms in the .UI project? Where/how should I group different form? Putting them all in root level of the project is a bad idea.

答:
Each time I start on a new project I get a broad specification of what it is supposed to do. Having this input helps me by providing me of a context, therefore I go ahead and think the best (or most appropriate) method to achieve the projects goals.
At this point I start thinking in which design patterns may help me provide the intended solution. Here is where I start organizing the project, taking into account the design patterns I will adopt for the project.

A couple of examples:

If the project only refers to building input data screens. Most probably I would use an MVC pattern.

If the project is going to be used as a heavy duty UI which most support multiples platforms, an MVVM design pattern becomes helpful.

Have in mind that each of this will force you to organize your project on a specific way.

Here is some reading for you:

.Net Design Patterns.

Design Patterns.

Object Oriented Design.

Hope this helps.

OwnerDisplayName: Sergio

LastEditorDisplayName: Sergio

Title: How do you organize your projects?

ContentLicense: CC BY-SA 4.0


答:
I agree that writing it in terms of the system owner seems wrong, because the system owner doesn't initiate this story - the user does, when they check their email.  But I don't think you need to talk in terms of what the user wants, but rather what they expect to happen.

```<code>As a customer
When I check my email
I should be charged
So I continue to recieve Service X
</code>```

The user would expect to be charged because you've outlined your payment plan to them.

Title: How do I format negative user stories?

Body:
I agree that writing it in terms of the system owner seems wrong, because the system owner doesn't initiate this story - the user does, when they check their email.  But I don't think you need to talk in terms of what the user wants, but rather what they expect to happen.

As a customer
When I check my email
I should be charged
So I continue to recieve Service X

The user would expect to be charged because you've outlined your payment plan to them.


问:
Can we use Java for commercial use?
The Java is GPL license (reference from wikipedia). I am not sure I can use it in in commercial projects. I already have a website written in Java and I plan to use this for commercial use. Is that illegal?</p>

答:
You are confusing several things.

The GPL is a license concerning the redistribution of software. Even if the Java compiler you used was GPL'ed, this wouldn't prevent you from distributing your own software, because that's different from redistributing Java. (And the Java runtime can be downloaded separately from Oracle, anyway).

The GPL is not incompatible with commercial software. Some answers here seem to be confusing "proprietary vs free (as in speech)" with "commercial vs free (as in beer)". It's true certain care must be taken when selling GPL'ed software (selling does count as "redistribution"), but it's not impossible to do.

Oracle's implementation of Java is not GPL'ed. Read its license here.

Open JDK is a GPL'ed implementation, but as mentioned above, this doesn't make it incompatible with commercial software.

OwnerDisplayName: Shisoft

Title: Can we use Java for commercial use?


答:
Never mind "best practices" (bear with me) this is a management problem - fundamentally you are not able to do you job properly because of the constraints placed upon you.

It doesn't actually matter what "best practice" is - this is a simple, demonstrable, issue that will affect the productivity of you and your team and you need to take it up with your line management on that basis.

I can see that brandishing a best practice document might (but only might) be an aid in attempting to persuade them but far better is the notion that you will have to have dev team members sitting on their hands whilst waiting for someone in a different timezone to get their act together unless the processes are improved/rationalised.

And don't be too confrontational - as much as anything you want to know why the restrictions are in place, what the justification is...

Title: Source Control: Roles and Responsibilities - Best Practices

Body:
I'm looking for "Best Practices" concerning roles and responsibilities, specifically who is responsible for merges from development branches to trunk (or main). Basically I'm looking for ammunition to help my cause.

Let me describe what I'm facing. I am the lead developer (owner) of a particular application. Our company recently moved from VSS (where I was the administrator of the VSS database in which my application was stored) to TFS (where I only have permissions on development branches created by our "operations" team). In previous jobs, I was a TFS Admin, so I know my way around TFS and MSBuild.

I don't have an issue with the branching and merging strategy being used (main branch, with bug/project development branches created as needed, merged back to main then promoted to a release branch). The issues I have are:

I cannot create my own branches. I must create a TFS task to have an "operations" team member create the branch for me.

I cannot merge from Main to my development branch. I must create a TFS task to have an "operations" team member perform the merge, and then hope he doesn't "step on" any of my teams changes since the "ops guy" may or may not be a developer and certainly has little to no knowledge of the code he is merging.

I cannot merge from development to Main. Again I must create a TFS task to have the "ops guy" perform the merge, hoping that he does it correctly. Then I have to create another TFS task to merge back to my branch so that I can resolve any issues which have occured by having a non-developer merge to Main.

I cannot create or edit MSBuild scripts. Again I have to work with the "ops" team which is new to MSBuild so only the most basic build tasks can be performed. (Forget about anything complex, or heaven-forbid a custom task).

I cannot execute an MSBuild script. Again only the "ops" team can do this.

To top all of this off, typically it is an "off-shore" resource which performs the requested tasks, so even if I create the task to (branch/merge/build) in the early morning, it probably won't be completed until that evening.

Now I have no issue with the "operations" team maintaining the release branches. As all they are doing is (basically) taking the latest version from Main and promoting it to the release branch; so as long as "Main" is stable and ready, the release branch will be good.

My opinion is that technical leads (such as I) should be responsible for maintaining the trunk ("Main") and any merging to/from the development branches. The team lead should also have the ability to generate MS Build scripts to build and deploy to the Integration test environment.

Can anyone direct me to a Best Practices document that'll help me prove my case? All my searching has turned up only Best Practices concerning the techniques of branching and merging, and no mention of WHO should be performing said branching/merging.


问:
Java - using single class or multiple class for each type?
I currently have a Java class called "node" which has a number of fields. Which fields in the class are used depends on a field called "type". There are close to 10 (this can grow) different types of "nodes". I was wondering if it is good to have a single class to handle all types or have different class for each type. What is the best programming practice in these cases? I would like to know (or a link to similar question/tutorials) how the performance will be affected (like memory etc.) if I use a single class?</p>

答: This situation is the perfect case for applying the factory pattern which basically creates the required subclass based on specific inputs. Also inheritance is not to be abused as changes to the super class trickle down to sub-classes.</p>


问:
Can the ScrumMaster and other team members be managed by the Product Owner?
Our team is switching to Scrum. I would be the ScrumMaster (in addition to being a developer), and another developer would become Product Owner (in addition to our product marketing guy).

All members of the team, including me, would be managed by the would-be Product Owner. By that I mean that the guy would be the one deciding about our yearly evaluation, raises, etc. Would this hierarchical link be prone to introduce issues? How do organizations typically map hierarchical structure onto agile teams?

I suppose it's quite common that the ScrumMaster has a hierarchical link to the other developers in the team.  Here it would be the Product Owner.  Is this different?

答: As with most things there is no fixed answer here - it really depends on the team and the individuals involved and their relationships. I am the PO for a team who I functionally manage. It works fine. Can it get in the way? Sure it can, but if everybody wants it to work it can and does work. As a manager you need to be very clear about separation of your activites (manager vs PO - what hat am I wearing right now?) and also behave as more of a coach / team member than the old command and control style traditionalist. Manage with a very light touch and act as part of the team.</p>

OwnerDisplayName: Mick Maguire


问:
How to fit testing in Scrum sprints and how to write user stories in Scrum
I am the development team lead of a new project at my company. This is the first project where the company will use Scrum. We have a waterfall/iterative SDLC. The BAs write requirements docs, hands over to dev and test, dev start developing and will release to testing in iterations. Testers take long time to test a release by which devs continue development but also bug fixes for the current release.
I have a few questions

In a sprint with say 5 stories when do you release for testing ? Is it as soon as a story is completed by dev or after all stories are completed but before end of sprint giving test the required time to test.

If the BA writes user stories what should be the detail. Traditionally it takes long time to write a spec with all UI layout, behaviour, text etc to be finalised. I guess my question is how to write stories that are implementable and testable.

Our test team is non-technical. How important it is to have automated UI testing for Scrum. The UI is based on WPF.

I have solid development experience using agile methods (TDD, code reviews, refactoring etc.) but new to scrum.

edit: By iterations I mean that if there are 100 requirements we may release to testing when we have finished 30, 35, 35 requirements rather than wait till all 100 requirements have been completed.

答:
In Scrum, you're supposed to produce a potentially shippable software increment at the end of each sprint. As a result, Scrum promotes the concept of whole team or cross-functional team where every skill required to lead a given user story to done has to be present in the team.

In my current project, since a fully-tested story is part of our definition of done, we have embedded testers in the teams. During the first few days of a sprint, while developers start working on the first user stories, the testers will prepare test scenarios and set up some test data. As soon as the dev for one of the user stories is finished, they'll test it.

This is one of the biggest difficulties in Scrum IMO. You have to find the right amount of specification necessary to get an implementable, testable user story. Too much upfront analysis, documentation and specification will result in a rigid plan that will inevitably prove wrong over the course of the sprint. Conversely, a user story that hasn't been clearly defined and expressed by the Product Owner will lead to a saturated communication bandwidth between the developers and the PO during the Sprint and delays in development while the PO makes decisions about user stories halfway through the sprint.

In our case, we have defined the right amount of detail for a user story to be 1/ a description in the form of "as a ... I want ... so that..." and 2/ a series of acceptance criteria. We seldom make mockups of the UI beforehand, it can happen during sprint plannings but they are more sketches that are discarded afterwards.

In my experience, automated UI testing is extremely time-consuming and extremely brittle. There are ways to do that in WPF but I would carefully ponder the upkeep cost of such tests with the benefits before going that way.


问:
Is there a specific purpose for heterogeneous lists?
Coming from a C# and Java background, I'm used to my lists being homogeneous, and that makes sense to me. When I started picking up Lisp, I noticed that the lists can be heterogeneous. When I started screwing around with the dynamic keyword in C#, I noticed that, as of C# 4.0, there can be heterogeneous lists as well:

List<dynamic> heterogeneousList

My question is what is the point? It seems like a heterogeneous list will have much more overhead when doing processing and that if you need to store different types in one place you may need a different data structure. Is my naivety rearing its ugly face or are there truly times when it is useful to have a heterogeneous list?

答:
Long story short, heterogeneous containers trade runtime performance for flexibility. If you want to have a “list of stuff” without regard to the particular type of stuff, heterogeneity is the way to go. Lisps are characteristically dynamically typed, and most everything is a cons-list of boxed values anyway, so the smallish performance hit is expected. In the Lisp world, programmer productivity is considered more important than runtime performance.

In a dynamically typed language, homogeneous containers would actually have a slight overhead compared to heterogeneous ones, because all elements added would need to be type-checked.

Your intuition about choosing a better data structure is on point. Generally speaking, the more contracts you can put in place on your code, the more you know about how it works, and the more reliable, maintainable, &c. it becomes. However, sometimes you really do want a heterogeneous container, and you ought to be allowed to have one if you need it.


问:
Can JavaScript be used as a general scripting language?
I've used JavaScript and some frameworks (jQuery, Prototype, some node.js) for client-side web programming, but never on the desktop, where I do most of my scripting work in either Python or Bash.

But IMHO, JavaScript would make a great scripting language if used outside of the browser. Has anyone tried this? Can JavaScript be an adequate replacement for Python/Perl/Bash for quick and dirty scripting tasks?

答: If you're just talking 'purely outside the browser' then look at tools like Appcelerator and Servoy, both of which use Javascript for coding, which ultimately gets turned into Java.</p>


答:
In functional languages (like lisp), you use pattern matching to determine what happens to a particular element in a list. The equivalent in C# would be a chain of if...elseif statements that check the type of an element and perform an operation based on that. Needless to say, functional pattern matching is more efficient than runtime type checking.

Using polymorphism would be a closer match to pattern matching. That is, having the objects of a list match a particular interface and calling a function on that interface for each object. Another alternative would be to provide a series of overloaded methods that take a specific object type as a parameter. The default method taking Object as its parameter.

```<code>public class ListVisitor
{
  public void DoSomething(IEnumerable<dynamic> list)
  {
    foreach(dynamic obj in list)
    {
       DoSomething(obj);
    }
  }

  public void DoSomething(SomeClass obj)
  {
    //do something with SomeClass
  }

  public void DoSomething(AnotherClass obj)
  {
    //do something with AnotherClass
  }

  public void DoSomething(Object obj)
  {
    //do something with everything els
  }
}
</code>```

This approach provides an approximation to Lisp pattern matching. The visitor pattern (as implemented here, is a great example of usage for heterogenous lists). Another example would be for message dispatching where, there are listeners for certain messages in a priority queue and using chain of responsibility, the dispatcher passes the message and the first handler that matches the message handles it.

The flip side is notifying everyone who registers for a message (for example the Event Aggregator pattern commonly used for loose coupling of ViewModels in the MVVM pattern). I use the following construct

```<code>IDictionary<Type, List<Object>>
</code>```

The only way to add to the dictionary is a function

```<code>Register<T>(Action<T> handler)
</code>```

(and the object is actually a WeakReference to the passed in handler). So here I HAVE to use List<Object> because at compile time, I don't know what the closed type will be. At Runtime however I can enforce that it will be that Type that is the key for the dictionary. When I want to fire the event I call

```<code>Send<T>(T message)
</code>```

and again I resolve the list. There is no advantage to using List<dynamic> because I need to cast it anyway. So as you see there are merits to both approaches. If you're going to dynamically dispatch an object using Method overloading, dynamic is the way to do it. If you are FORCED to cast regardless, might as well use Object.

Title: Is there a specific purpose for heterogeneous lists?

Body:
Coming from a C# and Java background, I'm used to my lists being homogeneous, and that makes sense to me. When I started picking up Lisp, I noticed that the lists can be heterogeneous. When I started screwing around with the dynamic keyword in C#, I noticed that, as of C# 4.0, there can be heterogeneous lists as well:

List<dynamic> heterogeneousList

My question is what is the point? It seems like a heterogeneous list will have much more overhead when doing processing and that if you need to store different types in one place you may need a different data structure. Is my naivety rearing its ugly face or are there truly times when it is useful to have a heterogeneous list?

Body:
In functional languages (like lisp), you use pattern matching to determine what happens to a particular element in a list. The equivalent in C# would be a chain of if...elseif statements that check the type of an element and perform an operation based on that. Needless to say, functional pattern matching is more efficient than runtime type checking.

Using polymorphism would be a closer match to pattern matching. That is, having the objects of a list match a particular interface and calling a function on that interface for each object. Another alternative would be to provide a series of overloaded methods that take a specific object type as a parameter. The default method taking Object as its parameter.

public class ListVisitor
{
  public void DoSomething(IEnumerable<dynamic> list)
  {
    foreach(dynamic obj in list)
    {
       DoSomething(obj);
    }
  }

  public void DoSomething(SomeClass obj)
  {
    //do something with SomeClass
  }

  public void DoSomething(AnotherClass obj)
  {
    //do something with AnotherClass
  }

  public void DoSomething(Object obj)
  {
    //do something with everything els
  }
}

This approach provides an approximation to Lisp pattern matching. The visitor pattern (as implemented here, is a great example of usage for heterogenous lists). Another example would be for message dispatching where, there are listeners for certain messages in a priority queue and using chain of responsibility, the dispatcher passes the message and the first handler that matches the message handles it.

The flip side is notifying everyone who registers for a message (for example the Event Aggregator pattern commonly used for loose coupling of ViewModels in the MVVM pattern). I use the following construct

IDictionary<Type, List<Object>>

The only way to add to the dictionary is a function

Register<T>(Action<T> handler)

(and the object is actually a WeakReference to the passed in handler). So here I HAVE to use List<Object> because at compile time, I don't know what the closed type will be. At Runtime however I can enforce that it will be that Type that is the key for the dictionary. When I want to fire the event I call

Send<T>(T message)

and again I resolve the list. There is no advantage to using List<dynamic> because I need to cast it anyway. So as you see there are merits to both approaches. If you're going to dynamically dispatch an object using Method overloading, dynamic is the way to do it. If you are FORCED to cast regardless, might as well use Object.


问:
How do I impress employers with my resume?
I built an entire website from scratch in 10 days which looks and feels professional with the site being unique. The site has features like logging in, sending activation emails, tag/content search (lucence.net), syntax highlighting (prettify) and a diff (one of the js diffs), markup for comments all on this site and autocomplete in a textbox (remember, 10 days). I wrote that I have 5+ years of C# experience (I could lie and say more, but smart employers will know it's only 8 years old and 1.1 is very different from what we use now).

I had employers REPEATEDLY say they are looking for someone who has more C# experience... wtf.

Maybe they don't read my CV, maybe they don't believe it or ignore me because I am not yet a graduate. I laughed when I first read Steve Yegge The Five Essential Phone Screen Questions as I knew all of that (although i still never used graph datastruct nor know much about it).

I'm pretty sure, competency-wise, I can do the job. I am also positive that no one noticed I have markup, a diff, auto-complete nor email activation/forget password (I offer a test user account). So maybe my site/example work isn't impressive because you don't realize what is in it.

In short, I don't think they read my CV or notice my site.
How do I impress employers?

PS: The problem is that I don't get to the interview. I had one and ruined it by speaking too technical to the PM because I was nervous. The other 25+ jobs either didn't contact me or were kind enough to send a rejection email.

答:
Sending your CV to the HR department is often a crap shoot, they have a huge pile of the things and the chances that yours is going to be the one they look at is kind of small. What you want to do is network.

Go to local user groups and meet people, better yet give a talk on something you are interested in (Make sure its an amazing talk) someone there will notice. Or write for an online magazine, many of them are looking for writers most of the time. The point is you want the programmers to notice you.


答:
User stories don't exist to fulfill some sort of methodology requirement. They exist solely to clarify what a team is doing, why they are doing, and who benefits from that. If you twist the words to obscure the meaning or fit some stringent requirement for what a story is supposed to look  like, it serves no one.

So answer the question "who does this benefit" and "why are we implementing this" honestly. Your development team needs this information to do their job. Even if the story is negative from the user's point of view, that's valuable information.

That being said, what you describe sounds more like a use case scenario rather than a story. Perhaps if you reduced this down to smaller pieces it might be more clean who the owners and beneficiaries are. For example, the feature of charging for checking email has several components. At the very least there is a UI component and a back end component, and perhaps a business rule.

You might break your feature down into these stories:

As a provider of an email service,
I want to collect a fee for each read email
so that I can earn money and continue to provide and enhance the service

As a user, I want the collection of the email fee to happen automatically so that I can read my email without having to acknowledge each fee as it is collected so that my experience is more enjoyable.

As a user, I want to be able to easily review the terms of service and fee amounts so that I understand the fees that are charged so that I can feel confident that I am getting my money's worth.

As a user,
I want the collection fee for reading email to be small
so that I can afford to use this service

Title: How do I format negative user stories?


问:
How do I Integrate Production Database Hot Fixes into Shared Database Development model?
We are using SQL Source Control 3, SQL Compare, SQL Data Compare from RedGate, Mercurial repositories, TeamCity  and a set of 4 environments including production.

I am working on getting us to a dedicated environment per developer, but for at least the next 6 months we are stuck with a shared model.

To summarize our current system, we have a DEV SQL server where developers first make changes/additions.  They commit their changes through SQL Source Control to a local hgdev repository.  When they execute an hg push to the main repository, TeamCity listens for that and then (among other things) pushes hgdev repository to hgrc.  Another TeamCity process listens for that and does a pull from hgrc and deploys the latest to a QA SQL Server where regression and integration tests are run.  When those are passed a push from hgrc to hgprod occurs.  We do a compare of hgprod to our PREPROD SQL Server and generate deployment/rollback scripts for our production release.

Separate from the above we have database Hot Fixes that will need to be applied in between releases.  The process there is for our Operations team make changes on the PreProd database, and then after testing, to use SQL Source Control to commit their hot fix changes to hgprod from the PREPROD database, and then do a compare from hgprod to PRODUCTION, create deployment scripts and run them on PRODUCTION.

If we were in a dedicated database per developer model, we could simply automatically push hgprod back to hgdev and merge in the hot fix change (through TeamCity monitoring for hgprod checkins) and then developers would pick it up and merge it to their local repository and database periodically.

However, given that with a shared model the DEV database itself is the source of all changes, this won't work. Pushing hotfixes back to hgdev will show up in SQL Source Control as being different than DEV SQL Server and therefore we need to overwrite the reposistory with the "change" from the DEV SQL Server.

My only workaround so far is to just have OPS assign a developer the hotfix ticket with a script attached and then we run their hotfixes against DEV ourselves to merge them back in.

I'm not happy with that solution.  Other than working faster to get to dedicated environment, are they other ways to keep this loop going automatically?

答:
So here's my latest (last?) attempt:

(1) Make hot fix in production

(2) Commit through SSC, push change
to prod mercurial repository

(3) Terminal Service into shared DEV
SQL Server

(4) pull prod repository into dev and merge changes

(5) Go into SSMS where SSC is setup as a dedicated link to mercurial

(6)
Do a get latest and

(a) hopefully just push the new hotfix into dev because nobody has changed the objects in the hotfix in DEV since the last release

(b) manually merge the changes in if someone has modified the objects in the hotfix since the last release

(7) commit from SSC, push to hg dev

This is still awfully manual, especially if step 6 (b) is necessary, but it does establish a process and it does work.


答:
You're correct that heterogeneity carries runtime overhead, but more importantly it weakens the compile-time guarantees provided by the typechecker. Even so, there are some problems where the alternatives are even more costly.

In my experience, dealing with raw bytes through files, network sockets, etc., you often run into such problems.

To give a real example, consider a system for distributed computation using futures. A worker on an individual node can spawn work of any serializable type, yielding a future of that type. Behind the scenes, the system sends the work off to a peer, and then saves a record associating that unit of work with the particular future that must be filled in once the answer to that work returns.

Where can these records be kept? Intuitively, what you want is something like a Dictionary<WorkId, Future<TValue>>, but this limits you to managing only one type of futures in the entire system. The more suitable type is Dictionary<WorkId, Future<dynamic>>, since the worker can cast to the appropriate type when it forces the future.

Note: This example comes from the Haskell world where we don't have subtyping. I would not be surprised if there's a more idiomatic solution for this particular example in C#, but it's hopefully still illustrative.


问:
Is it better idea to call an external command-line application or to internalize that application's logic?
I have a "pipeline" sort of process that is essentially just linking together a bunch of existing tools to automate a workflow. For one of the steps, there is an existing command-line tool that already does the meat of what that step needs to do.

The external CLI tool is java-based, and so is my pipeline, so it would be possible to integrate the tool directly into the pipeline step, but the tool is very complex and is currently closely tied to having command-line input (something like 37 config flag options).

The question is: Is it a better idea to simply call out and invoke the external process, or would it be better to integrate the external code within my application?

What are the pros / cons of integrating vs. calling the external process?

答:
Is it a better idea to simply call out and invoke the
  external process, or would it be better to integrate the external code
  within my application?

It is much better to integrate these things.

The command-line interface is just an interface, and a particularly awful one.
It's essential but it's also filled with quirks and limitations that aren't sensible.

Each of the "existing tools to automate a workflow" should have a tidy class that does the real work after the command-line options have been parsed.

Ideally, the public static void main function does two things in each one of those "existing tools".

It invokes some command-line option/argument parser.

It invokes the tidy class that does the real work.  Think of an Ant task or a Maven task that does the real work after Ant or Maven has handled all of the parsing and decision-making.

When you go to integrate these things, you want the tidy classes that do the real work.

If they don't exist, then you'll have to rewrite all of those tools to create the tidy class that does the real work, separate from all command-line parsing.

For guidance on how these tidy classes should work, read Ant (or Maven) to see how they define the various worker tasks.  It's a good mental model for how multiple, disparate things are integrated without going back to the command line.


答:
I would say leave it alone if it works.

As a programmer you bring value to your organization by solving problems with software. Solving more problems in both quality and quantity within a given amount of time is directly related to your value in the organization. Spending this time to create code diminishes your value since it takes you away from solving a more important problem.

However, a couple of factors that might mitigate spending the time would be scalability and if there were any concerns for the external programs stability.

Title: Is it better idea to call an external command-line application or to internalize that application's logic?

Body:
I have a "pipeline" sort of process that is essentially just linking together a bunch of existing tools to automate a workflow. For one of the steps, there is an existing command-line tool that already does the meat of what that step needs to do.

The external CLI tool is java-based, and so is my pipeline, so it would be possible to integrate the tool directly into the pipeline step, but the tool is very complex and is currently closely tied to having command-line input (something like 37 config flag options).

The question is: Is it a better idea to simply call out and invoke the external process, or would it be better to integrate the external code within my application?

What are the pros / cons of integrating vs. calling the external process?


答:
The paper Strongly Typed Heterogenous Collections by Oleg Kiselyov, Ralf Lämmel, and Keean Schupke contains not only an implementation of heterogenous lists in Haskell, but also a motivating example of when, why and how you would use HLists. In particular, they are using it for type-safe compile-time checked database access. (Think LINQ, in fact, the paper they are referencing is the Haskell paper by Erik Meijer et al that led to LINQ.)

Quoting from the introductory paragraph of the HLists paper:

Here is an open-ended list of typical examples that call for heterogeneous collections:

A symbol table that is supposed to store entries of different types is heterogeneous. It is a finite map, where the result type depends on the argument value.

An XML element is heterogeneously typed. In fact, XML elements are nested collections that are constrained by regular expressions and the 1-ambiguity property.

Each row returned by an SQL query is a heterogeneous map from column names to cells. The result of a query is a homogeneous stream of heterogeneous rows.

Adding an advanced object system to a functional language requires heterogeneous collections of a kind that combine extensible records with subtyping and an enumeration interface.

Note that the examples you gave in your question are really not heterogenous lists in the sense that the word is commonly used. They are weakly typed or untyped lists. In fact, they are actually homogenous lists, since all elements are of the same type: object or dynamic. You are then forced to perform casts or unchecked instanceof tests or something like that, in order to actually be able to meaningfully work with the elements, which makes them weakly typed.


问:
Dealing with management that does not see value in improvements that are not immediately visible to the user
I can understand schedule pressure.  You want to please your users, as they are the lifeblood of the company. However, it is also true that certain changes will make everything easier down the road. Unfortunately, management in my organization has an instinctive resistance to such changes and this resistance is so strong that it gets in the way of long-term improvements.

For example, Apple recently introduced Automatic Reference Counting for iOS programs.  This is a major improvement over the manual retain/release calls one previously had to use.  The code is easier to write and easier to maintain. The changeover itself is likely to produce some crashes. But once those are worked out, the number of random weird crashes is likely to go down.

I recently mentioned to my boss that I wanted to switch to automatic reference counting.  His response was that he wanted to concentrate on visible improvements. It is likely that this response was in turn driven by pressure he is getting from above him - and probably right from the CEO.

There are a lot of similar examples.  The common thread is that something needs to be fixed but the short-term costs of the fix outweigh the short-term benefits, where "short term" is defined as "within the next few weeks."

How should I handle the situation?

EDIT:  Thanks for the responses.  Keep 'em coming.  Because it is relevant to my situation, I should make it clear that my manager and the CEO are both programmers -- though the CEO may by now have forgotten what this is like.  Apparently their programmer sides have been overwhelmed by other pressures.

答:
As with other questions of this nature, you need to provide numbers that management will understand. Numbers that show how much time will be saved by implementing these improvements, how many less "random weird crashes" will occur, etc. Convince them that crashes are visible to the end user and that anything done to prevent them is good for business.

You could also attempt to implement these improvements on your own time (i.e. outside of work hours) and then show the benefits to management afterward. I would only do this when it is clear that management does not understand what you are trying to convey and/or that they don't want to allocate time for you to even attempt it.

Good luck!


答:
You've stumbled across something that plagues programmers everywhere at some point in their careers: this code needs to be refactored, there are architectural issues over there, this module is becoming unmaintainable, etc. Because of the present culture of your organization, however, you're being pushed to focus on work that only yields directly visible benefits.

Its the classic Iceberg Secret all over again. The secret has to do with the fact that just as an iceberg is 90% underwater, so to is the majority of any development project: 90% of the work is going to be completely invisible to the end user. That code will have an impact on the end user but management has trouble wrapping their minds around why you spent six hours refactoring the maintain/release and automatic referencing calls when They Can't See Any Difference and everything is Working Just Fine.

Here are some facts you can take with you on this issue.

Management, unless they are programmers themselves, are not going to understand the Iceberg Secret.

This is a problem of ignorance, not malice. The CEO wants a good product - he just doesn't understand everything that goes into a good product.

The CEO (and your direct boss) are not stupid - study and prepare some facts and some concrete data for why you should spend the time on this, and other Iceberg problems.

Don't forget - you're a company man (or woman). Not a code man. You're developing this product for a company who has a vested interest in its success or failure - your projects and project proposals should reflect this. Show your passion for the company and the product, show your knowledge, and prove to your boss and CEO that they should trust you when you come to them and say that Something Needs Work. Show them how it will contribute to the bottom line - whether by adding value to product (more people buying copies) or by saving time down the road (fewer angry customers when your product fails).

Title: Dealing with management that does not see value in improvements that are not immediately visible to the user

Body:
I can understand schedule pressure.  You want to please your users, as they are the lifeblood of the company. However, it is also true that certain changes will make everything easier down the road. Unfortunately, management in my organization has an instinctive resistance to such changes and this resistance is so strong that it gets in the way of long-term improvements.

For example, Apple recently introduced Automatic Reference Counting for iOS programs.  This is a major improvement over the manual retain/release calls one previously had to use.  The code is easier to write and easier to maintain. The changeover itself is likely to produce some crashes. But once those are worked out, the number of random weird crashes is likely to go down.

I recently mentioned to my boss that I wanted to switch to automatic reference counting.  His response was that he wanted to concentrate on visible improvements. It is likely that this response was in turn driven by pressure he is getting from above him - and probably right from the CEO.

There are a lot of similar examples.  The common thread is that something needs to be fixed but the short-term costs of the fix outweigh the short-term benefits, where "short term" is defined as "within the next few weeks."

How should I handle the situation?

EDIT:  Thanks for the responses.  Keep 'em coming.  Because it is relevant to my situation, I should make it clear that my manager and the CEO are both programmers -- though the CEO may by now have forgotten what this is like.  Apparently their programmer sides have been overwhelmed by other pressures.


答:
You are really talking about technical debt.  Maybe a metaphor would help your managers.  I often compare the effect of technical debt in software to cooking in a dirty kitchen.  If the sink and counters and stove are piled with dirty dishes and there is trash on the floor, it takes longer to make a meal.  However, the fastest way to prepare the very next meal is to work around the mess.  Cleaning the kitchen, and keeping it clean, will delay the next meal, but will improve the delivery of all subsequent meals.  And just as the hungry person in the dining room can't see the messy kitchen, and won't understand why you want to clean up before starting to cook, your management can't see the mess in the code.  You need to either show them the mess, or show the quality problems and delays that are caused by the mess.

Perhaps you could also talk about urgent tasks and important tasks.  When important tasks aren't done, then urgent tasks take longer and cost more.


问:
Which commit should close a Github issue when multiple commits are responsible?
I want to close issues in Github via my commit messages, but I'm not sure which commit should contain the magic "Closes #XXX" string when multiple commits are responsible for closing the issue. Specifically, I'm wondering if the last commit on my feature branch (always merged with --no-ff) should close the issue, or if I should close it via the merge commit that sort of "summarizes" the entire feature branch? Is there a standard way of doing this, something endorsed by the Git community?

答: I generally vote for "the commit that merges the fix branch into the main line of development". Related commits should reference the issue.</p>


答:
You don't.

I see this question and all questions like it as a bit of a dead end. You can't "convince" people of anything. If they aren't already aware of things like this or investigating it, chances are they don't give a flip. And no amount of data will convince them otherwise. Change must come from within. You can lead a horse to water but you can't make him drink.

I say bake your desired changes into your next technical estimates. Be like, hey, we "have to" upgrade to this new framework Apple introduced. Don't let not using ARC be on your roadmap. There are no options; migrating to ARC is the only way.


答:
You mention that you are fortunate enough that your manager and CEO are both programmers.  So they probably do understand what technical debt is.

You should handle the situation by trying to resolve the situation based on facts, which means there is a real possibility that you won't end up making the technical improvements you want (facts can be annoying that way).

Your job is to make sure they understand the costs and benefits of paying off any particular technical debt you incur.  Their job is deciding if the best use of resources is in paying it off or in doing something else.

Just as it can be hard for people not involved with the code to see the benefits of improving the "hidden" stuff, it can be hard for programmers to see the benefits of visible code changes when the benefits accrue to areas of the business somewhat "hidden" from the developers.

It's nice if your management can explain to you why the visible features are more worth your time than paying the technical debt, but really, it's not your job to make the determination anyway.  So explaining it to you doesn't do much for the business except keep you happy.  And in a way, insisting they do so is not trusting them to do their job.  If you don't like it when they micro-manage you then you should understand.

So, as long as you are keeping them aware of the status of all technical debt and the costs and benefits of ignoring it versus paying it off, you have done your job.  Unless you really don't trust management to do theirs, in which case you have a much bigger problem that would be a whole other question to address.


问:
How to deal with the MPL in a pragmatic way?
Until recently I always avoided the use of open-source code in my applications, because of the legal headache it gives me. I rather spent a fair amount of money and not worry about attribution (since most commercial components don't require that), than paying nothing, but spending a lot of time reading legal texts, never to be sure whether I was fully compliant.

However, there is a ton of code out there that would be a shame to ignore. Also, sometimes the open-source solutions are of better quality than their commercial counterparts.

The license I encounter most and find hardest to grasp, is the MPL. All FAQs state that it is no problem to compile the code into a closed-source application, as long as changes to the code are made available. Assuming that I will not make changes to the code, what other things are there to keep in mind? For example, copyright notices and attribution; am I required to include a bunch of files with all the different copyright notices? Should I double-size my About dialog and list all open-source components with their vendor website and so on? How do you deal with this?

Please note that I have no problem with giving authors of code the credit they deserve. I would simply like to know what is reasonable, so I can take care of it in a pragmatic way, and no longer fear at least the MPL.

Hoping for your experiences.

Update

To make my question more clear, I will use an analogy. Let's say I am going to write a book A, and I would like to use some parts of a book B that someone else has written. The author of B is fine with this, as long as I credit him (very much like a clause in the MPL). But how should I do that? Am I to put his name on the cover of mine and/or in the margin of every page where I use full paragraphs from him and/or where I use full sentences from him and/or where I use a couple of words from him and/or in a dedication section with sources? Or perhaps it would suffice to print his name in black letters on a black page, or in font size .00001? Luckily, for books there aren't as many ways to do it as with software, and there is some established practice. In the field of software, I have yet to discover any, so I'm asking here if I missed something.The point is not to give as little attribution as possible, but I'm looking for what's acceptable and fair; you wouldn't like to write a book in which each page is half-filled with attributions either...

Attribution is only one of the terms that I find hard to concretize. What about making the code and the license texts available if I changed nothing? Do I link to the authors website, or mirror it on my own and link to that, or put it in my installer? And, for example, from the Firebird Project I have most files in one place, but a couple of DLLs are spread over the folders of my application. Would you suggest just to make a single folder with license texts and list which files are relevant to each? Is that enough? Is there a better way?

A complete answers addresses all requirements of the MPL. :)

答:
The MPL is an open-source license designed to protect its own code.  If you modify MPL code, you need to publish those modifications under the MPL.  That's the focus of the license.  There's no "viral" requirement to affect the licensing provisions of the rest of your code.

The idea of the attribution requirement is to make people aware of the code.  So if, as you say, you're looking for the fair thing to do and not "what can I get away with?", then you should probably just put your attributions in an "about box" or analogous feature.  Your best guide here is the Golden Rule: if you had written the MPL code, how would you want a developer who used it to provide attribution in their program?


答:
This kind of a change falls into the refactoring category. The Agile approach would be that you should be incorporating AMPLE refactoring time into each story you estimate and this is exactly why. Aside from engineers, nobody is going to understand why you want to do this and that's okay, it's not THEIR job to determine how to code correctly, it's yours.

So next time you have a chunk of work to do, make sure that these changes are part of it.  If you are providing estimates, be sure to add 30% to your estimate for refactoring, if you are not providing estimates then just do the refactoring as part of your work.

It may make you slower--well no, that's not the way to look at it, the way to look at it is that your current velocity is an illusion, essentially a lie that you are passing up the chain, you actually should be a little slower because of this work that you know needs to be done.

You could probably build houses more quickly if you didn't use concrete as a foundation--and they would look as good to the customer but--well--Even if the customer doesn't see the need for the foundation, the builder needs to.  (This is actually an interesting parallel because it turns out that builders don't always do what they know they should do so we need to pass laws to force them to--there are no such laws governing software development even though we face the same decisions and often make the wrong ones...)


答:
I've answered a similar question here before so this might be considered a duplicate. Basically, you're not going to get signoff to do a "refactoring effort". The way you make the code cleaner is to follow the boy scout rule: always leave code cleaner when you leave it than when you arrived.

Just like paying down real debt can seem like an insurmountable task (or cleaning up a messy house). The trick is to make it better piece by piece until you start seeing "islands of cleanliness". Once you have significant momentum, other developers on the team will start noticing and eventually contributing to the task.

I'd suggest reading the Clean Coder by "Uncle" Bob Martin. Writing good code is part of your job. You don't ask permission to do your job, you just do it.


问:
I feel stuck in the center of Python, How to get past beginner
I really apologize if this doesn't follow the S.O rules but I need a little help, I personally still classify myself as a beginner in python, Yet I've wrote a very small and VERY SURE impractical program for my boss to use.

I know I'm still a beginner because simple things still perplex me but every book I read for beginners honestly just rehashes what I do already know but every 'more advanced' book doesn't really allow me to learn, they depend on example files and I never really understand why they built 'said' function or 'said' class. So onto my question...

Is there any recommendations on a book or ANYTHING that pushes me out of this stage, I've used head first and normally they are really good but my issue there is they have me back tracking just to move forward again, It worked in HTML but its confusing in Python, basically I think I need to build a program while following along, Again I like HeadFirst's style but I need something that isn't going to make me have to remember one thing just to forget it...

for record, I've checked into some O'Reilly books

答:
There are two Python books that I would recommend, and one of them was already mentioned by @MikeRand:

Dive Into Python 3 is a must book that covers introductory and some more advanced topics.

Programming Python is IMHO the right book for moving into very advanced Python topics. It also covers many areas, for example (G)UIs, system applications, web programming, etc.

Note that the latest versions of both books cover Python 3. If you work with an older version of Python look for an earlier version of the books. FTR, an alternative option is Python for Software Design (former How to Think Like a Computer Scientist: Learning with Python mentioned by @oscar-mederos) but most of its content is also introductory (and in that sense I would recommend Dive Into Python instead).


答: ISTR that Lisp doesn't have any data structures other than a list, so if you need any type of aggregate data object, it's going to have to be a heterogeneous list.  As others have pointed out, they're also useful for serializing data for either transmission or storage.  One nice feature is that they're also open-ended, so you can use them in a system based on a pipes-and-filters analogy and have successive processing steps augment or correct the data without requiring either a fixed data object or workflow topology.


问:
Does making source code available affect your ability to generate revenue?
We’re working on a .Net framework which ultimately amounts to a single DLL.  We intend to charge for commercial use of the framework, but make it free for open source/non-commercial use.  The rough plan at the moment is to administer this through some form of fairly simple licence which will be issued whether you’re using it for free or paying.

We’re debating whether to make the source code available.  It’s our perception (and our own preference) that it’s far more appealing to use something where you have access to the source code.

I’m interested in whether people think making the source code available will damage our ability to make money from the framework, or whether it will encourage more usage and enough “good” people will arrange to pay for the correct licence if using it commercially.

My feeling is that, generally, commercial operations don’t mess about on the licencing front and so making the source code available will only encourage usage and therefore ultimately generate more revenue, but I’d be interested in others views/experience.

答:
In general people who will pay for your tool will pay for it anyway, and people who will steal it will always steal it.

Besides, it's just good business sense (advertising) to give away your product to people who aren't your target audience, because they either know (or will know) someone who is in your target audience, or will be there themselves.

Why do you think FogBugz has the Student and Startup license? They're providing a valuable tool for free because it costs them relatively nothing, and when you get to the point where you're making enough money to pay the $20-25/mo per developer (heck, that's at most an hour of developer time at competitive wages here in Arkansas) then you'll be perfectly happy to write that check out to FogCreek.

I haven't seen any studies, but I would certainly bet my own software on it.


答:
Maybe this isn't an answer, but a response based on mistakes I've made. Also a disagreement with some of the philosophies I read here.

Don't fall afoul of the belief that the programmer knows best.

Be honest. Re-factor as you go along but don't lie and pad estimates for your own purposes.

You don't own the code. Don't undertake work that's not approved by the lead.

You could be right about something; you could be wrong... but you should do what you're paid to do.

But certainly follow the excellent advice given on improving things.


问:
Why is it discouraged to create variables on the fly? PHP gives you a Notice Error
Are you guys familiar with those pesky PHP notice errors? You know, the ones that will appear when you do something like this:

```<code>if($some_variable == 45)
</code>```

But if $some_variable wasn't created already, PHP will be like "Hey! Idiot! This variable wasn't defined yet!" and output a Notice Error onto the screen. However, you can simply turn PHP Notice Errors off by using error_reporting(0) and the application works perfectly. What's the point? Who cares if a variable wasn't created yet? Why can't you just create it on the fly inside the if statement? I feel like this is the easy, no-brainer way to do it, but apparently PHP discourages this practice. Why?

What I find myself having to do a lot of times is something like this:

```<code>if(isset($some_variable) && $some_variable == 45)
</code>```

If $some_variable is not set, the if statement automatically fails, so the second condition of the if statement is never checked, so the Notice Error never happens. This works great, but I feel like it shouldn't be necessary. Some of the applications I am working on are huge and I fear that the extra added conditions will slow down my poor old server if there are dozens of instances of it, combined with thousands of users. I know that this is just a single extra statement which would be O(1), which isn't a lot of resources, but it's still something I worry about. Should I not worry about O(1) even if I hypothetically were to have thousands of users? Am I caring too much about being efficient?

I know PHP Notice errors can easily be turned off by using error_reporting(0). I'm not sure if certain types of errors can be turned on/off as desired because I haven't researched error_reporting() extensively.

My question is what's the point? Why is it discouraged to create variables on the fly? I feel like creating variables on the fly may be a little bit lazier but is 10000000x easier to program and should be the no-brainer encouraged way to do it.

This is meant to be both a philosophical and a technical question.

答:
While sometimes I think it would be nice to be able to create variables on the fly without generating those pesky "notices", I can often see the advantages of not being able to do so.

I think the biggest benefit to explicitly declaring variables, or checking that variables are set, is code readability. The isset in your example indicates to the person reading the code that $some_variable may not be set. While this doesn't necessarily save much time (as they'll see that it isn't set when they read the notice), it provides the reader with more information, which is always beneficial.

OwnerDisplayName: Jim D


答:
Like BoltClock and JackManey said in the first few comments, it is indeed important to declare all your variables even if something seems to work. One day, you'll run into an issue where you used two times a variables that you expected NOT to be initialized and then it'll fail.

You will then lose 2-3 hours tracing and debugging trying to find out why you are getting this funky behavior and then realize, omg, i will always initialize my variables from now on. It will prevent me from getting that one funky error.

And if you get into another language you will most probably have to do so anyway. So take the time to initialize your variables, it will save you LOTS of trouble later.

Title: Why is it discouraged to create variables on the fly? PHP gives you a Notice Error

Body:
Are you guys familiar with those pesky PHP notice errors? You know, the ones that will appear when you do something like this:

```<code>if($some_variable == 45)
</code>```

But if $some_variable wasn't created already, PHP will be like "Hey! Idiot! This variable wasn't defined yet!" and output a Notice Error onto the screen. However, you can simply turn PHP Notice Errors off by using error_reporting(0) and the application works perfectly. What's the point? Who cares if a variable wasn't created yet? Why can't you just create it on the fly inside the if statement? I feel like this is the easy, no-brainer way to do it, but apparently PHP discourages this practice. Why?

What I find myself having to do a lot of times is something like this:

```<code>if(isset($some_variable) && $some_variable == 45)
</code>```

If $some_variable is not set, the if statement automatically fails, so the second condition of the if statement is never checked, so the Notice Error never happens. This works great, but I feel like it shouldn't be necessary. Some of the applications I am working on are huge and I fear that the extra added conditions will slow down my poor old server if there are dozens of instances of it, combined with thousands of users. I know that this is just a single extra statement which would be O(1), which isn't a lot of resources, but it's still something I worry about. Should I not worry about O(1) even if I hypothetically were to have thousands of users? Am I caring too much about being efficient?

I know PHP Notice errors can easily be turned off by using error_reporting(0). I'm not sure if certain types of errors can be turned on/off as desired because I haven't researched error_reporting() extensively.

My question is what's the point? Why is it discouraged to create variables on the fly? I feel like creating variables on the fly may be a little bit lazier but is 10000000x easier to program and should be the no-brainer encouraged way to do it.

This is meant to be both a philosophical and a technical question.

OwnerDisplayName: Mathieu Dumoulin


答:
It promotes clean coding. If you get yourself into the habit of writing your apps to be free of warnings, then you can leave warnings on, and when they occur, they'll actually tell you something meaningful. For example, subtle spelling errors like the following may be incredibly difficult to track down if you're ignoring warnings:

```<code>if ($some_variabel == 45) { ... }
</code>```

However if you do this and leave warnings on:

```<code>$some_variable = 0;
...
if ($some_variabel == 45) { ... }
</code>```

Then the bug becomes immediately evident.

Body:
It promotes clean coding. If you get yourself into the habit of writing your apps to be free of warnings, then you can leave warnings on, and when they occur, they'll actually tell you something meaningful. For example, subtle spelling errors like the following may be incredibly difficult to track down if you're ignoring warnings:

if ($some_variabel == 45) { ... }

However if you do this and leave warnings on:

$some_variable = 0;
...
if ($some_variabel == 45) { ... }

Then the bug becomes immediately evident.

OwnerDisplayName: Alex Howansky


答:
Notices are not errors. They are debug messages. And PHP allows to use variables sans initialization. It is not a compiled language, and it does correctly substitute absent variables for NULL. It just gives you an additional debugging aid. It's often just in case, but oftentimes useful.

People supress notices with isset or @ and error_reporting when it becomes too overwhelming. And you do really need to differentiate between useful and pointless notices. It does not make sense to keep them everywhere, and it likewise doesn't make sense to suppress them everywhere.
(Even seasoned PHP coders are overwhelmed with that differentiation.)

OwnerDisplayName: mario


答:
If you have a code review , create a technical ticket stating that the code should be improved by using ARC and assign to the manager.

Convince him. Explain him some small examples of similar technical enhancements that you did and its benefits to the projects.


答:
You have to sell those changes in the only way that management is willing to buy:

Find a user-facing feature so compelling that management just has to have it, but would be impossible to do without some low-level improvements in the code.


答:
You should not be coding in such a way that you don't know if a variable is set.

Doing so places your code into an ambiguous state.  The end result of that is typically buggy, difficult to maintain spaghetti code.

In PHP, the main ways this situation occurs is if one is having PHP automatically create global variables from the GET/POST variables (register_globals), or one is doing too much in the global scope rather than inside functions and methods.  The former is a bad idea for a variety of security reasons, and the latter, for all but trivial applications, means the code probably isn't structured well.

To get around this,

don't use register_globals,

specifically initialze every global,

don't do a lot in the global scope,

don't use include() as a replacement for proper function and method calls.


答:
It's your boss's job to make sure the company focuses development on delivering what clients perceive as added value. There are two factors that can alter this perception:

How long does it take to deliver on a client request?

Do you deliver when you say you will?

Most would rather you say it will take 6 weeks and deliver in 5 than say you will deliver in 3 but take 4.

Having a current code base that is easier to manage and enhance allows you to deliver faster and increase predictability. If you're spendning too much time on bug fixes, you have fewer resources available to add new features. Evaluate the amount of resources spent on fixing the code and how accurate you are on feature promisses. This one way to determine if your current code (under your boss's philosophy) is costing too much.


问:
Best Practices for Handing over Legacy Code
In a couple of months a colleague will be moving on to a new project and I will be inheriting one of his projects. To prepare, I have already ordered Michael Feathers' Working Effectively with Legacy Code.

But this books as well as most questions on legacy code I found so far are concerned with the case of inheriting code as-is. But in this case I actually have access to the original developer and we do have some time for an orderly hand-over.

Some background on the piece of code I will be inheriting:

It's functioning: There are no known bugs, but as performance requirements keep going up, some optimizations will become necessary in the not too distant future.

Undocumented: There is pretty much zero documentation at the method and class level. What the code is supposed to do at a higher level, though, is well-understood, because I have been writing against its API (as a black-box) for years.

Only higher-level integration tests: There are only integration tests testing proper interaction with other components via the API (again, black-box).

Very low-level, optimized for speed: Because this code is central to an entire system of applications, a lot of it has been optimized several times over the years and is extremely low-level (one part has its own memory manager for certain structs/records).

Concurrent and lock-free: While I am very familiar with concurrent and lock-free programming and have actually contributed a few pieces to this code, this adds another layer of complexity.

Large codebase: This particular project is more than ten thousand lines of code, so there is no way I will be able to have everything explained to me.

Written in Delphi: I'm just going to put this out there, although I don't believe the language to be germane to the question, as I believe this type of problem to be language-agnostic.

I was wondering how the time until his departure would best be spent. Here are a couple of ideas:

Get everything to build on my machine: Even though everything should be checked into source code control, who hasn't forgotten to check in a file once in a while, so this should probably be the first order of business.

More tests: While I would like more class-level unit tests so that when I will be making changes, any bugs I introduce can be caught early on, the code as it is now is not testable (huge classes, long methods, too many mutual dependencies).

What to document: I think for starters it would be best to focus documentation on those areas in the code that would otherwise be difficult to understand e.g. because of their low-level/highly optimized nature. I am afraid there are a couple of things in there that might look ugly and in need of refactoring/rewriting, but are actually optimizations that have been out in there for a good reason that I might miss (cf. Joel Spolsky, Things You Should Never Do, Part I)

How to document: I think some class diagrams of the architecture and sequence diagrams of critical functions accompanied by some prose would be best.

Who to document: I was wondering what would be better, to have him write the documentation or have him explain it to me, so I can write the documentation. I am afraid, that things that are obvious to him but not me would otherwise not be covered properly.

Refactoring using pair-programming: This might not be possible to do due to time constraints, but maybe I could refactor some of his code to make it more maintainable while he was still around to provide input on why things are the way they are.

Please comment on and add to this. Since there isn't enough time to do all of this, I am particularly interested in how you would prioritize.

Update: As the hand-over project is over I have expanded this list with my own experiences in this answer below.

答:
As the hand-over project is now over, I think I would take the time and write up my own answer containing those things that worked best for me.

Get everything under version control: After making sure everything I needed to build was under version control, I also searched at the old developer’s hard drive, to look for additional scripts or utilities that would be helpful to deploy and/or test the application but weren’t checked in.

Top-down: I would start off with a high level look at the major classes and a guided tour with the old developer of the main areas. Then I would dig deeper into the rest on my own, flagging things that didn’t make sense to me with //TODO markers.

Write all documentation myself: While I had the old developer look over my writing to make sure I got it right, I insisted on writing everything myself. This way I would be sure the writing made sense to me and not only the old developer.

Comments everywhere: I added XML documentation summaries to every class and every method. This way I made sure I had at least looked at every piece of code and have enough of an understanding to summarize what it did in a sentence. It also made understanding the methods using summarize methods/classes easier as IntelliSense picks up this information. I could also easily identify areas of the code that I still had to look at.

Document close to the source: In order to make the connection between the source code and documentation easier, I put most of my documentation right in the source code. For high-level documentation that describes the interaction between various sub-systems, I used a wiki, as putting this information in just one place in the code didn't work. All of the documenation should be electronic and full-text searchable.

Diagrams: For a basic overview I used class diagrams of various granularities for the different sub-systems. For the concurrent parts, object and interaction diagrams have been really helpful; see also my other question on the topic.

Refactoring as a pair: While I did some refactoring with the old developer to get a feel for the code and make things more maintainable, this was a time consuming and also risky process, because of the lack of good refactoring tools and a bunch of nasty dependencies among the various parts. Michael Feathers' Working Effectively with Legacy Code is a really good help for this, even though refactoring without proper tool support is still painful. While refactoring I would let him have control of mouse and keyboard, as it was more fun for him tis way (see also my last bullet point) and I was free to write down what I was learning.

Separate check-ins for comments and changes: After I accidentally introduced a bug by writing a comment over an override, I have been careful to make comments and changes in separate check-ins. I used a little utility to strip all comments from the source code before checking something in, so a diff of a comment-only check-in would show 0 differences. All changes (e.g. removal of unused fields) were carefully peer-reviewed with the old developer to make sure I wasn’t removing things that were still needed.

Line-by-line walkthrough of critical passages: For the most optimized/complex passages, I would go over the code line-by-line with the old developer and sometimes even with a third colleague. This way I got a thorough understanding of the code and as more people vetted the code, we actually identified a few bugs as well as some things that could be further optimized.

Be quick and keep the old developer motivated: I noticed that the old developer was less and less interested as his last day was coming closer (not surprisingly). I would therefore make sure the most critical parts were handed over first, leaving the rest for me to figure out on my own, if necessary. I also tried to leave the more fun things (e.g. control of the keyboard when pair-programming) to him and do the boring things like documentation writing myself.

Identify feature requests: I found it helpful to ask the old developer for a list of features that people had asked for but that weren't added yet. There were a few things that to me looked simple to add, but where there was a good reason they weren't added as they would have broken other things when implemented they way I had thought at first.

OwnerDisplayName: PersonalNexus


问:
Is it possible to work with distrusting clients
One of our junior developers has been assigned a new client (we don't have the client yet, we're still working with him to see if we can meet his needs) and the junior developer said the client will hire us if we can do the work on his project without getting access to his server.

I've had a direct conversation with the client who turned out to have had his code stolen before by some offshore company that he outsourced. This made me more sympathetic but I still have mixed feelings about this.

On one hand I want to prove to the client that we're not all bad apples. Also if we do a good job with him, we get a loyal client who'll hire us for all his projects. I haven't heard of this happen before but I guess it happens more often than we'd all like to admit.

On the other hand I'm hesitant to accept working with him because deployment time is going to be a nightmare and no where in my career or education has anyone taught me how to work with clients like him. I (or the junior developer) would have to write a detailed description of exactly what to do with the source to deploy it and that is an annoying burden when I could deploy and test the whole thing in an hour myself.

As I said, I've never had to deal with this before (we're signing a non-disclosure but apparently so did the offshore company before us). We're not fully fully booked so it's not like I have an immediate replacement, but we're not begging for work either and I wonder if working under such restricted environment is worth the trouble.

Another side is that the experience itself could be rewarding for us, but is it experience worth having, as in what's even the likelihood of getting a similar client anytime soon. Are we even expected to comply with such clients?

So since I don't have any first hand experience with this and it definitely wasn't covered in school, how would those with longer experience working with clients deal with a distrusting client like this? Would you even accept the job?

答:
I have worked in IT and government for many years.  In those environments developers NEVER have access to the production system.  It should be par for the course to provide installation instructions especially for code being custom developed by the client.

I assume the client will own the code you are writing for them.


答: There is another hidden cost not mentioned in other answers. Namely that good engineers tend to leave in the type of environment described. Eventually anyone with the ambition or ability to refactor has left the company, and then things will be in a very bad way, probably unfixable. Unfortunately you can't tell your manager this without coming across as arrogant ("I'm one of your best programmers"), and a pushy jerk ("I'll leave if you don't do what I want"). However, do remember to mention it in your exit interview, to ensure you're put on no re-hire status.</p>


问:
Load testing : how to generate per second requests?
I have a server component which runs over Zeroc-ICE. When I wanted to load test it, I thought that using parallel library to create multiple requests would do it. But it dint end up that way. Using Parallel(Parallel.For) library from C# apparently was easier but it doesn't seem to be exactly generating everything parallel in the same instant. So it cannot be the definition for creating N requests per second. How should I do it ? I guess anyone who wants to do load testing first would actually think about this .

What's the efficient way to actually create N requests in really per second ?

Another myth is about the parallel programming. Please enlighten us , if you have used parallel programming patterns in C# or .Net in general . Imagine I have 5 processes. How will start all the five processes at the same time. What does it mean to my consumption of resources ? I have tried reading into many of the material available over the net but I get more and more questions than them being the answer to my questions.

I used Parallel.For and created N threads and measured time. Then I tried the same thing using Task.Factory.start for enumeration of tasks. The time measured was different. So What exactly is the different between using these ? When I should use the corresponding classes and for what purposes exactly ? we often have lots of riches but its just we exactly don't know how to differentiate one from the another. This is one such case for me, not being able to find why I should not use one from the another.

I used the stopwatch class to measure these times which claims to be the best. In the scenario of me load testing a component, what would be the way to measure the time of response. Stopwatch seems to be the best solution for me . Any opinions are welcome.

ps: There are many load testing tools for web applications. Mine is a customised case of server components. And my question is more pertaining to creating N threads per second.

All opinions are welcome. Just don't think its so much not a programming question. It ofcourse is. It should ring bells for any programmer who wants to QE stuff by himself to know the performance of his product , first hand by himself.I have tried many options and then had to fall back on how should I actually do it ?

答:
If you purely want to have X threads all hit your resource at the exact same time you can put each thread behind a countdown latch and specify a short wait period between the semaphore checks.

C# has an implementation (http://msdn.microsoft.com/en-us/library/system.threading.countdownevent(VS.100).aspx).

At the same time, if you are stress testing your system you might actually want to check for race conditions as well, in which case you would want to setup thread sleep periods on each thread that osculate over time with randomized frequency and peaks/furloughs.

Similarly you may not actually want to just rapidly send multiple requests, you might have better success at putting your server into a bad state/testing its real world performance by setting up a smaller number of threads that spend more time in consuming and sending messages back and forth over the socket, as your server likely is going to need to spin up its own threads to handle slow ongoing messages.

OwnerDisplayName: King


问:
After writing code, why do I feel that "I would have written better" after some time?
I have been working on my hobby project in C++ for more than 2 years. Whenever I write a module/function, I code it with lot of thinking. Now see the problem,

```<code>do {
  --> write the code in module 'X' and test it
  --> ... forget for sometime ...
  --> revisit the same piece of code (due to some requirement)
  --> feel that "This isn't written nicely; could have been better"
} while(true);
</code>```

Here 'X' is any module (be it small/large/medium). I am observing that, this happens no matter how much effort I put while coding. So mostly, I refrain myself from seeing a working code. :)

Is this a common feeling for many people ? Is this language specific phenomena ? (Because in C++ one can write the same thing in different ways).

What should I do, if I get this re-factoring feeling for a real world production code, where changing the working code will not earn me much accolades but rather it may invite troubles if it fails.

答:
Developing an application means improving it and making it better; this is a continuous process so while you're programming you gain more experience and knowledge. It also means you're developing too, so when you look back at your old code you may find out it can be improved.

If you don't have this feeling, it means one of two things:

You are still at the same level of skill.

Your code is already perfect (unlikely).


答:
Present a Business Case

There are many reasons why engineer recommendations often get ignored. The best way to deal with almost all of the reasons is present the business case of why it should be done.  The classic cost/benefit analysis.  This not only makes a compelling argument, but it also gives your bosses something to take to their higher-ups.

What is the upfront cost?

What is the ongoing cost?

What are the projected money/time savings and where do they come from?

How long will it take before we see the ROI?

When doing a business case you should always back up your argument with data.

How much time is development currently spending dealing with problems this will remove or mitigate?

How many user complaints do you get related to the problems this will remove or mitigate?

What other benefits will it have?

Line up the numbers and make it a rough, but simple equation.  It will cost X to do and it will benefit the company Y.

Note: Don't be surprised if it is prohibitively expensive to implement an academically good idea.