答:
I think first of all you have to clear your situation. What do they want from you?

It is very unlikely that they want you to learn an ancient language, because this now seems a dead end: there is a decreasing chance to find anyone knowing or wanting to learn G2, so the knowledge will be buried in the collapsing heap of code when the current scientists leave or the all-patched code fails more and more often.

Are the scientists (or some of them) ready to learn a new language and lots of programming paradigms? Or do they want to separate the programming and scientific activity in the long term, and perhaps have some more programmers if needed? This seems a rational and more efficient separation of expertise.

I think the core requirement here is to "save the knowledge in the system", so you have to go and excavate it!

The first task is to write a documentation.

Analyze the structure and the requirements as if this would be a new task, but with the help of an existing system. They will be pleased because you ASK instead of TEACHING first - and you will quickly get enough, but more organized background knowledge from a programmer's point of view: "what's going on here?" The docs (system static structure, workflow, components, problems) will be immediately valuable for them, and will perhaps show up more relevant information to them than to you (some of the guys may have "AHA!" and start fixing some codes immediately)...

You should then start asking where they want to go?

If they are ready to move away from G2, what system do they want to see (platform, language, interface, general structure)? You might start writing an external wrapper around the system if at all possible, having the target structure, but keeping the original components, thus slowly starting a kind of framework that allows new components to be implemented in a this target environment. You have to find the core services (persistent data connections and "toolkits": core calculation, drawing, ... libraries), and so you provide them a familiar environment in a new platform and language, which allows the transition either by you or them: take the old codes one by one, reimplement (and CLEAN!) them in the new environment. When that is ready, they know the new language; and the service layer (mostly made by you, sorry) is ready to host the new components.

If they don't move, you must learn G2, and create the modular framework there, into which you or they should move the components (with cleaning). Anyway, the language is just a serialization of data and algorithm tree...

While analyzing and writing the docs, read, use and advertise GoF Design patterns! :-)

... my 2 cents


问:
How would you answer this job-interview question?
One of the five people who interviewed me asked a question that resulted in an hour-long discussion: "Explain how you would develop a frequency-sorted list of the ten thousand most-used words in the English language."

My initial response was to assail the assumptions underlying the problem. Language is a fluid thing, I argued. It changes in real time. Vocabulary and usage patterns shift day-to-day. To develop a list of words and their frequencies means taking a snapshot of a moving target. Whatever snapshot you take today isn't going to look like the snapshot you take tomorrow or even five minutes from now.

Thanking you advance for your answers and consideration.

答: My immediate thought: use google to find a pre-existing list. It may not be the answer they're looking for, but it shows that you won't waste time re-inventing the wheel.</p>

ContentLicense: CC BY-SA 3.0


问:
I've inherited 200K lines of spaghetti code -- what now?
I hope this isn't too general of a question; I could really use some seasoned advice.

I am newly employed as the sole "SW Engineer" in a fairly small shop of scientists who have spent the last 10-20 years cobbling together a vast code base. (It was written in a virtually obsolete language: G2 -- think Pascal with graphics). The program itself is a physical model of a complex chemical processing plant; the team that wrote it have incredibly deep domain knowledge but little or no formal training in programming fundamentals. They've recently learned some hard lessons about the consequences of non-existant configuration management. Their maintenance efforts are also greatly hampered by the vast accumulation of undocumented "sludge" in the code itself. I will spare you the "politics" of the situation (there's always politics!), but suffice to say, there is not a consensus of opinion about what is needed for the path ahead.

They have asked me to begin presenting to the team some of the principles of modern software development. They want me to introduce some of the industry-standard practices and strategies regarding coding conventions, lifecycle management, high-level design patterns, and source control. Frankly, it's a fairly daunting task and I'm not sure where to begin.

Initially, I'm inclined to tutor them in some of the central concepts of The Pragmatic Programmer, or Fowler's Refactoring ("Code Smells", etc). I also hope to introduce a number of Agile methodologies. But ultimately, to be effective, I think I'm going to need to hone in on 5-7 core fundamentals; in other words, what are the most important principles or practices that they can realistically start implementing that will give them the most "bang for the buck".

So that's my question: What would you include in your list of the most effective strategies to help straighten out the spaghetti (and prevent it in the future)?

答:
I would throw down the following:

There is one programmer here. Screw politics. They know their trade. You know yours. Mark that territory even if you have to piss on it. They're scientists. They can respect that sort of thing or should since they're pretty much constantly doing the same themselves. Through whatever means you can, mark the boundaries now. This is what I'll fix. This is what I can't be responsible for.

Scientists write/test the algorithms. Scientists who want to can write their own algorithms in 1-3 languages everybody can agree on for you to convert to core code. That puts testing their stuff on them. Beyond that, they're going to have to help you isolate the important science stuff vs. the good-god-knows-what they did for architecture. The codebase is hosed. There's lots of slash and burn that's going to need to be done. Give them options to hand you working versions of stuff that employs what they know best so you can do what you do best. Stick their knowledge in a box that they're responsible for but that you can work with. Ideally when things go well on a mega-refactor conversations will be more about what sorts of exciting things you can do with interface rather than what tentacle Z9 of drBobsFuncStructObjThingMk2_0109 did when it pissed off global var X19a91.

Use an event-driven-friendly language with first class functions if you can. When all else fails, triggering an event or tossing a callback to some object with an interface and state mechanism that actually makes sense can be a huge time-saver when you're knee-deep in code that makes no bloody sense and quite possibly never will. Scientists seem to like Python. Not hard to glue lower-level math-intensive C stuff with that. Just sayin'

Look for somebody who has solved this or a similar problem. Spend some serious time researching. These guys heard about G2 from somebody.

Design Patterns. Adapters. Use 'em. Use 'em a lot in situations like this.

Learn what you can of the science. The more you know, the better you can determine intent in the code.


问:
I need an approach to the problem of preventing inserting duplicate records into the database
A webservice that I call returns a list of data. The data from the webservice is updated periodically, so a call to the webservice done in one hour could return the same data as a call done in an hour. Also, the data is returned based on a start and end date.

We have multiple users that can run the webservice search, and duplicate data is most likely to be returned (especially for historical data). However I don't want to insert this duplicate data in the database.

I've created a db table in which the data is stored (most important columns are)

Id int autoincrement PK
Date date not null        --The date to which the data set belongs.
LastUpdate date not null  --The date the data set was last updated.
UserName varchar(50)      --The name of the user doing the search.
```

I use sql server 2008 express with c# 4.0 and visual studio 2010. Entity Framework is used as the ORM. If stored procedures could be avoided in the proposed solution, then that will be a plus.

Another way of looking interpreting what I'm asking a solution for is as follows:
I have a million unique records in my table. A user does a new search. The search results from the user contains around 300k records of the data that is already in the db. An efficient solution to finding and inserting only the unique records is needed.

A combination of the Date, LastUpdate and UserName makes a record unique.

答: A simple solution would be to create an in-memory cache supported by a set, which should write the information in the database, only when it's full, and say only 10000 entries leaving room for other 10000 (see it as a queue). Or store it to the DB when the WS call returns different data (provided that different data in calls means that there are no duplicates in it). By using a set, you are assured that no duplicates are present in it.</p>


问:
design for supporting entities with images
I have multiple entities like Hotels, Destination Cities etc which can contain images. The way I have my system setup right now is, I think of all the images belonging to this universal set (a table in the DB contains filePaths to all the images).

When I have to add an image to an entity, I see if the entity exists in this universal set of images. If it exists, attach the reference to this image, else create a new image. E.g.:

```<code>class ImageEntityHibernateDAO {
        public void addImageToEntity(IContainImage entity, String filePath,
                String title, String altText) {
            ImageEntity image = this.getImage(filePath);

            if (image == null)
                image = new ImageEntity(filePath, title, altText);

            getSession().beginTransaction();
                entity.getImages().add(image);
            getSession().getTransaction().commit();

        }
}
</code>```

My question is: Earlier I had to write this code for each entity (and each entity would have a Set collection). So, instead of re-writing the same code, I created the following interface:

```<code>public interface IContainImage {
    Set<ImageEntity> getImages();
}
</code>```

Entities which have image collections also implements IContainImage interface. Now, for any entity that needs to support adding Image functionality, all I have to invoke from the DAO looks something like this:

```<code>// in DestinationDAO::addImageToDestination {
imageDao.addImageToEntity(destination, imageFileName, imageTitle, imageAltText);

// in HotelDAO::addImageToHotel {
imageDao.addImageToEntity(hotel, imageFileName, imageTitle, imageAltText);
</code>```

It'd be great help if someone can provide me some critique on this design ? Are there any serious flaws that I'm not seeing right away ?

答:
How about a straight Add function on the IContainImage interface. e.g.

```<code>public interface IContainImage {
    Set<ImageEntity> getImages();
    void Add(ImageEntity);
}
</code>```

This would read easier:

```<code>try
{
  getSession().beginTransaction();
  entity.Add(image);
  getSession().getTransaction().commit();
}
except
{
  getSession().getTransaction().Rollback();
}
</code>```

I have multiple entities like Hotels, Destination Cities etc which can contain images.

It sounds as if you dealing with a classic many to many table relationship. For this you need to introduce a juntion/joining table. That is a table containing the primary key of your entity table and the primary key of your images table.

Body:
How about a straight Add function on the IContainImage interface. e.g.

public interface IContainImage {
    Set<ImageEntity> getImages();
    void Add(ImageEntity);
}

This would read easier:

try
{
  getSession().beginTransaction();
  entity.Add(image);
  getSession().getTransaction().commit();
}
except
{
  getSession().getTransaction().Rollback();
}

I have multiple entities like Hotels, Destination Cities etc which can contain images.

It sounds as if you dealing with a classic many to many table relationship. For this you need to introduce a juntion/joining table. That is a table containing the primary key of your entity table and the primary key of your images table.


问:
Herding your users to your bugtracker
I have a fully configured mantis bug tracker for tracking issues in apps that I create.  When an user is disciplined and goes straight to mantis to write a issue report, he/she will have fastest response and everything regarding the issue will be very easy to track.

However, not everyone is keen to do so.  They report their problems via phone, e-mail, don't report them at all.

What would be the best way to nudge them towards the using a bugtracker system?  Clearly, they HAVE to see some immediate benefits so they can return and look for more benefits.

EDIT:

I am talking about support for the products that I sell as an ISV.

答:
Well, if you want to use a global exception handler, then you've got lots of options.  For Delphi we use MadExcept, but also have used Eureka Log, both of which will (with the user's go ahead) email, or upload via HTTP, a bug report to you.

You could have a button in your app that just throws an exception and launches this bug tracking stuff.  MadExcept is pretty cool because it takes a screenshot of the app and uploads it along with the bug, that way even if the user can't properly explain what they were doing, you can have a pretty good hankering.

Something else to think about is coding to make it obvious where bugs are coming from.  If you've got beta users, maybe include debug info with their app so you can get extra data from them when crashes happen.

None of this helps for implementation bugs (i.e. the button is in the wrong spot) though so hopefully you don't have any of those.

ContentLicense: CC BY-SA 2.5

Title: Herding your users to your bugtracker


答:
You have to find out what columns records make unique.
Then you usually set a unique constraints on one/multiple columns in the database. This will (depending on db-system) throw some error if you want to insert another record with the same unique columns.

See http://en.wikipedia.org/wiki/Unique_key

Title: I need an approach to the problem of preventing inserting duplicate records into the database

Body:
A webservice that I call returns a list of data. The data from the webservice is updated periodically, so a call to the webservice done in one hour could return the same data as a call done in an hour. Also, the data is returned based on a start and end date.

We have multiple users that can run the webservice search, and duplicate data is most likely to be returned (especially for historical data). However I don't want to insert this duplicate data in the database.

I've created a db table in which the data is stored (most important columns are)

Id int autoincrement PK
Date date not null        --The date to which the data set belongs.
LastUpdate date not null  --The date the data set was last updated.
UserName varchar(50)      --The name of the user doing the search.
```

I use sql server 2008 express with c# 4.0 and visual studio 2010. Entity Framework is used as the ORM. If stored procedures could be avoided in the proposed solution, then that will be a plus.

Another way of looking interpreting what I'm asking a solution for is as follows:
I have a million unique records in my table. A user does a new search. The search results from the user contains around 300k records of the data that is already in the db. An efficient solution to finding and inserting only the unique records is needed.

A combination of the Date, LastUpdate and UserName makes a record unique.


问:
How should I handle using two databases with a legacy PHP application?
I have a legacy PHP application that was written in 2004 and uses MSSQL as a database backend.

At this stage MSSQL is still supported by PHP but only just via a Microsoft driver.  I have looked at converting to mysql via automated tools, which work quite well, but I have quite complex views which need a lot of individual work to convert.  I don't have a great deal of time to do this.

Many tools I wish to use and frameworks I would like to move the application to, don't support MSSQL, so I was considering adding new features using a new mysql database and wondered if anyone had opinions on the pros and cons of using two seperate database backends in a single application?

答:
I think most of the PHP frameworks do not use RDBMS specific function. They use PDO (PHP Data Objects) this library adds a lot of portabilty to the applications because the functions you use are the same for MySQL, MSSQL, Postgres, etc.

If you need more portability you should take a look into an ORM(Object Relational Mapping) like Doctrine.

But as you said, if you are thinking to migrate your app to a framework, the most likely is that this framework already has an abstraction layer.


答: Your client could track which rows have changed (created/updated/deleted) and only send those changed rows to the server. With a unique key defined, you can perform inserts for the rows identified by your client as new. This way, you only have to send the changed (created/updated/deleted) rows to the database. No need to send the entire data set retrieved if it has not changed. This type of processing is available in EF via the ObjectContext, ObjectStateManager classes. </p>


答:
Try this:

```<code>IF (SELECT TOP(1) text FROM the_table WHERE text='yourtext') <> 'yourtext'
begin
 INSERT INTO the_table (text) VALUES ('yourtext')
end
</code>```

it queries the DB for yourtext and selects it, if it finds a row, it won't fire, if it doesn't find a row, it will insert.

Not reall well tested though.

Body:
Try this:

IF (SELECT TOP(1) text FROM the_table WHERE text='yourtext') <> 'yourtext'
begin
 INSERT INTO the_table (text) VALUES ('yourtext')
end

it queries the DB for yourtext and selects it, if it finds a row, it won't fire, if it doesn't find a row, it will insert.

Not reall well tested though.


问:
Microsoft UI stack
I am a C#, WPF developer and would like to know and understand the Microsoft UI Stack. I could not find much on the internet. I guess that this would be a huge topic, and might not be feasible to explain here, but any suggest online reading would be greatly appreciated.</p>

答:
I don't know what you mean by "Microsoft UI Stack", but I will try to answer.

Current development shows huge investment into XAML-based UI. WPF, Silverlight, WP and now WinRT support XAML-based UI. The main problem is, that while the bases are same, there are still some details, that makes transitioning from one implementation to another hard, or almost impossible. You can read more about that in The Manifold Blunders of Xaml. So even thought MS says that re-using XAML code between platforms will be simple, I though this is just wishfull thinking.

Windows Forms is "dead" now, where dead means that MS stopped any kind of support and are not planning to extend it in any way. I would highly discourage starting new project with WinForms.

Second thing is about web development. Here, it looks like MS is investing a lot into ASP.NET MVC instead of WebForms. But I'm not a web developer, so I cannot say more about this. It looks like WebForms is sharing same fate as WinForms.

There is also interesting move to HTML+JS for client-side application programming thanks to WinRT support. But I don't believe this is good alternative to XAML+C#. MS is only trying to look cool by supporting it, re-using resources they put into IE development and baiting developers who only programmed in JS, HTML and PHP.

Title: Microsoft UI stack


问:
using static methods and classes
I know that static methods/variables are associated with the class and not the objects of the class and are useful in situations when we need to keep count of, say the number of objects of the class that were created. Non-static members on the other hand may need to work on the specific object (i.e. to use the variables initialized by the constructor)

My question what should we do when we need neither of the functionalities?

Say I just need a utility function that accepts value(s) and returns a value based solely on the values passed. I want to know whether such methods should be static or not. How is programming efficiency affected and which is a better coding practice/convention and why.

PS: I don't want to spark off a debate, I just want a subjective answer and/or references.

答:
Methods which are not attached to any specific class like these are called "free functions", and as you have adequately noted, OO does not provide for them, and some languages also do not provide the facilities for them.

In a language like C++ you can just place the function in a namespace. But if you're working in Java or C# you must pointlessly place them in a class and make them a static member for no good reason at all.

Title: using static methods and classes


答:
I'm not sure what you mean when you say "Microsoft UI Stack". Since your question is pretty broad and general, I'd thought something general like Metro would be appropriate as an aswner.

Microsoft is pushing towards a new design style called Metro. The Windows Phone 7 UI is based on it, as is (part of) Windows 8. As you might have noticed, Microsoft is also updating its various site to use the new Metro style:

MSDN

WindowsAzure.com

Microsoft.com

...

If you wan't to use the Metro style in your applications (platform independent), these links are interesting read and a good start. Some talk about Windows Phone, some about Windows 8, but they all cover general principles you can use on any platform.

Make great Metro style apps

Planning Metro style apps

Index of UX guidelines for Metro style apps

Arturo Toledo's (@arturot) excellent series 24 Weeks of Windows Phone Metro Style Design

Jeff Wilcox's (@jeffwilcox) Metro design guide for developers, v1.00

Metro Style App Development

Title: Microsoft UI stack

Body: I am a C#, WPF developer and would like to know and understand the Microsoft UI Stack. I could not find much on the internet. I guess that this would be a huge topic, and might not be feasible to explain here, but any suggest online reading would be greatly appreciated.</p>


问:
Role Difference between StakeHolder and ProductOwner
What is actually the role difference between ProductOwner and StakeHolder ?</p>

答:
A stakeholder is anyone that is potentially affected by the outcome of the project. The term is usually used to name the management or the customers.

The product owner is a stakeholder by defintion (just like the developers in fact), but is generally the person that represents the stakeholders (given the general usage described before).

When we say that stakeholders can assist to the daily scrums & reviews, it is because one of the biggest aim of Scrum is to put lot of visibility on what is being done. That increased visibility helps impediments to be identified & solved quickly. It also helps every party to understand each other's constraints & interests.


答:
If those utility functions are relatively small and not similar to others then you can use static functions. Also, the most important thing, they should not be related with the abstraction of the object (the class) and also you should not abuse them; they do not represent a OOPish way of programming.

I mentioned about size, because if they are large then you should use objects in order to obtain a better cohesion (share some data between functions by instance variables). I mentioned about similar functions because you might want to use the power of polymorphism.

Regarding efficiency static methods might be a little faster, but you would not gain any considerable performance gain from this.

Title: using static methods and classes

Body:
I know that static methods/variables are associated with the class and not the objects of the class and are useful in situations when we need to keep count of, say the number of objects of the class that were created. Non-static members on the other hand may need to work on the specific object (i.e. to use the variables initialized by the constructor)

My question what should we do when we need neither of the functionalities?

Say I just need a utility function that accepts value(s) and returns a value based solely on the values passed. I want to know whether such methods should be static or not. How is programming efficiency affected and which is a better coding practice/convention and why.

PS: I don't want to spark off a debate, I just want a subjective answer and/or references.


问:
Is this a decent use-case for goto in C?
I really hesitate to ask this, because I don't want to "solicit debate, arguments, polling, or extended discussion" but I'm new to C and want to gain more insight into common patterns used in the language.

I recently heard some distaste for the goto command, but I've also recently found a decent use-case for it.

Code like this:

```<code>error = function_that_could_fail_1();
if (!error) {
    error = function_that_could_fail_2();
    if (!error) {
        error = function_that_could_fail_3();
        ...to the n-th tab level!
    } else {
        // deal with error, clean up, and return error code
    }
} else {
    // deal with error, clean up, and return error code
}
</code>```

If the clean-up part is all very similar, could be written a little prettier (my opinion?) like this:

```<code>error = function_that_could_fail_1();
if(error) {
    goto cleanup;
}
error = function_that_could_fail_2();
if(error) {
    goto cleanup;
}
error = function_that_could_fail_3();
if(error) {
    goto cleanup;
}
...
cleanup:
// deal with error if it exists, clean up
// return error code
</code>```

Is this a common or acceptable use-case of goto in C? Is there a different/better way to do this?

答:
In my opinion, the code you posted is an example of a valid use of goto, because you only jump downwards and only use it like a primitive exception handler.

However, because of the old goto debate, programmers have been avoiding goto for some 40 years and therefore they aren't used to read code with goto. This is a valid reason to avoid goto: it simply isn't the standard.

I would have rewritten the code as something more easily read by C programmers:

```<code>Error some_func (void)
{
  Error error;
  type_t* resource = malloc(...);

  error = some_other_func (resource);

  free (resource);

  /* error handling can be placed here, or it can be returned to the caller */

  return error;
}

Error some_other_func (type_t* resource)  // inline if needed
{
  error = function_that_could_fail_1();
  if(error)
  {
    return error;
  }

  /* ... */

  error = function_that_could_fail_2();
  if(error)
  {
    return error;
  }

  /* ... */

  return ok;
}
</code>```

Advantages of this design:

The function doing the actual work does not need to concern itself with tasks that are irrelevant to its algorithm, such as allocating data.

The code will look less alien to C programmers, since they are afraid of goto and labels.

You can centralize error handling and deallocation at the same spot, outside the function doing the algorithm. It doesn't make sense for a function to handle its own results.

Body:
In my opinion, the code you posted is an example of a valid use of goto, because you only jump downwards and only use it like a primitive exception handler.

However, because of the old goto debate, programmers have been avoiding goto for some 40 years and therefore they aren't used to read code with goto. This is a valid reason to avoid goto: it simply isn't the standard.

I would have rewritten the code as something more easily read by C programmers:

Error some_func (void)
{
  Error error;
  type_t* resource = malloc(...);

  error = some_other_func (resource);

  free (resource);

  /* error handling can be placed here, or it can be returned to the caller */

  return error;
}

Error some_other_func (type_t* resource)  // inline if needed
{
  error = function_that_could_fail_1();
  if(error)
  {
    return error;
  }

  /* ... */

  error = function_that_could_fail_2();
  if(error)
  {
    return error;
  }

  /* ... */

  return ok;
}

Advantages of this design:

The function doing the actual work does not need to concern itself with tasks that are irrelevant to its algorithm, such as allocating data.

The code will look less alien to C programmers, since they are afraid of goto and labels.

You can centralize error handling and deallocation at the same spot, outside the function doing the algorithm. It doesn't make sense for a function to handle its own results.


问:
What is agile methodology?
Can any one explain about the agile methodology in simple sentences?</p>

答:
Employing an agile methodology comes down to emphasizing the delivery of quality products over other aspects of product development and realizing that feedback from the user community is a vital part of creating quality products.

Contrast that with a traditional/waterfall development approach that emphasizes up-front design, documentation, and interface definition while de-emphasizing implementation and transitioning the product from development to release.

In my opinion there is intrinsic quality that a team can build into a product, I see this taking the form of verifying that a product functions as the development team intended and can reasonably accommodate foreseeable enhancements. There are also quality factors based entirely on perception that measure how well a product meets the needs of its users.

Agile approaches tend to deliver products iteratively, incorporating user feedback and developer feedback into each iteration, and promotes delivering each increment of functionality when it achieves minimum viability as a forcing function to elicit frequent user feedback and counteract the tendency of development activities to go  on for extended periods of time without feedback from its users. To my mind, other aspects of an agile approaches tend to support these key tenets.

Emphasizing frequent customer collaboration generates user feedback while remaining flexible to changes in requirements allows product development to regularly integrate that feedback

Frequent integration into relevant deployment configurations and environments goes hand-in-hand with ongoing identification of which configurations and environments remain relevant in order to ensure that the product remains valuable and relevant to the users providing feedback

Self-organization and promoting cross-functional teams speaks to creating personal accountability within the team and empowering the team to determine how best to remove roadblocks in an efficient manner without being held back by preassigned roles and management hierarchy within the team

Title: What is agile methodology?


问:
What is the canonical approach to using a VCS right from a project's infancy?

Background

I've used VCS (mainly git) in the past to manage many existing projects and it works great. Typically with an existing project, I would check in each change I make to the code that either optimizes or changes the overall functionality (you know what I mean, in suitable steps, not every single line I change).

Problem

One thing I've not had so much practise at is creating new projects. I'm in the process of starting a new project of my own that will probably grow quite large, but I'm finding that there is a lot to do and a lot changing in the first few days/hours/weeks/the period up until the product is actually functioning in it's most basic form.

Is there any point in me checking in each step of the process as I would with an existing project? I'm not breaking the project with changes I make since it isn't working yet. At the moment I've simply been using VCS as a backup at the end of each day, when I leave the computer.

My first few commits were things like "Basic directory structure in place" and "DB tables created". How should I use a VCS when starting a new project?

答:
Start Simple

```<code>git init
</code>```

Check-In Early, Check-In Often

Just do what you normally do with any project: "check in" for every set of changes that relates to a particular task or group of actions. If you use an issue tracker, then commit changes that relate to a task every time it's in a stable state (see this SO question on how often to commit). It may not be in a state of completion, just a stable one, in which the software is not failing to run or the site failing to be rendered. As Jeff Atwood says in his post:

If the code isn't checked into source control, it doesn't exist. [...]

I'm not proposing developers check in broken code -- but I also argue that there's a big difference between broken code and incomplete code.

Commit Often, Perfect Later, Publish Once

If the product isn't even close to a workable state, then just keep checking in changes as you see fit, using good judgment and common sense to group them together. You don't need to commit every single file's line change one by one, but committing everything as a large chunk will make it harder for you to rollback if necessary.

In the end, your VCS is here to help you. So help your VCS to help you!!

Don't Overthink It

Your first commits were fine. Don't overthink it. The most important thing is that they are checked-in. If you look at all existing open-source projects online that started from scratch and not from an existing codebase, they have has as their first revision something akin to:

created the directory structure (yay!)

Make it a Habit

At the end of each day, try to generate a log of what you've done based on your commit-logs. If the outputs you get from git shortlog and git log do NOT look satisfactory and useful, yet you've put in a significant amount of effort in the project during the day and checked those changes in, then you probably didn't do it right.

git shortlog should read like a broad overview of what you've done.

git log should read like the history AND story of your project.

Body:
Start Simple

git init

Check-In Early, Check-In Often

Just do what you normally do with any project: "check in" for every set of changes that relates to a particular task or group of actions. If you use an issue tracker, then commit changes that relate to a task every time it's in a stable state (see this SO question on how often to commit). It may not be in a state of completion, just a stable one, in which the software is not failing to run or the site failing to be rendered. As Jeff Atwood says in his post:

If the code isn't checked into source control, it doesn't exist. [...]

I'm not proposing developers check in broken code -- but I also argue that there's a big difference between broken code and incomplete code.

Commit Often, Perfect Later, Publish Once

If the product isn't even close to a workable state, then just keep checking in changes as you see fit, using good judgment and common sense to group them together. You don't need to commit every single file's line change one by one, but committing everything as a large chunk will make it harder for you to rollback if necessary.

In the end, your VCS is here to help you. So help your VCS to help you!!

Don't Overthink It

Your first commits were fine. Don't overthink it. The most important thing is that they are checked-in. If you look at all existing open-source projects online that started from scratch and not from an existing codebase, they have has as their first revision something akin to:

created the directory structure (yay!)

Make it a Habit

At the end of each day, try to generate a log of what you've done based on your commit-logs. If the outputs you get from git shortlog and git log do NOT look satisfactory and useful, yet you've put in a significant amount of effort in the project during the day and checked those changes in, then you probably didn't do it right.

git shortlog should read like a broad overview of what you've done.

git log should read like the history AND story of your project.


答:
What you are doing is the right approach.

You are using source control from day one - this will ensure that you have everything you need in source control and there's no point at which you can say:

I should be using source control but it's going to take too long to check in all of this stuff for the first time.

This is a major hurdle for people coming late to source control as they then think it's "too hard" to use. By starting early and committing changes often you have reduced that hurdle to a small step and anyone else who joins you on the project will be able to get to work straight away.

Title: What is the canonical approach to using a VCS right from a project's infancy?

Body:
Background

I've used VCS (mainly git) in the past to manage many existing projects and it works great. Typically with an existing project, I would check in each change I make to the code that either optimizes or changes the overall functionality (you know what I mean, in suitable steps, not every single line I change).

Problem

One thing I've not had so much practise at is creating new projects. I'm in the process of starting a new project of my own that will probably grow quite large, but I'm finding that there is a lot to do and a lot changing in the first few days/hours/weeks/the period up until the product is actually functioning in it's most basic form.

Is there any point in me checking in each step of the process as I would with an existing project? I'm not breaking the project with changes I make since it isn't working yet. At the moment I've simply been using VCS as a backup at the end of each day, when I leave the computer.

My first few commits were things like "Basic directory structure in place" and "DB tables created". How should I use a VCS when starting a new project?


答:
Sounds like the first step you have is to sell to the team the need to invest in new software methodology.  Per your statement, there is no concensus in the team, and you'll need it to be able to plow ahead with a slow "upgrade" of the code.

I would (if I can) personally take the hard lessons learned, and introduce each of the key concepts that you want to as the solution to the problem in the software industry.

E.g. two developers had different copies and ended up deploying a hybrid untested release -> Introduce version control, branching, and testing.

Somebody removed a few lines of code that they didn't understand and caused an outage -> introduce DDD.

If the hard lessons aren't being shared with you in sufficient detail, then just show your own examples of how things went wrong when this discipline wasn't adhered to.

Title: I've inherited 200K lines of spaghetti code -- what now?

Body:
I hope this isn't too general of a question; I could really use some seasoned advice.

I am newly employed as the sole "SW Engineer" in a fairly small shop of scientists who have spent the last 10-20 years cobbling together a vast code base. (It was written in a virtually obsolete language: G2 -- think Pascal with graphics). The program itself is a physical model of a complex chemical processing plant; the team that wrote it have incredibly deep domain knowledge but little or no formal training in programming fundamentals. They've recently learned some hard lessons about the consequences of non-existant configuration management. Their maintenance efforts are also greatly hampered by the vast accumulation of undocumented "sludge" in the code itself. I will spare you the "politics" of the situation (there's always politics!), but suffice to say, there is not a consensus of opinion about what is needed for the path ahead.

They have asked me to begin presenting to the team some of the principles of modern software development. They want me to introduce some of the industry-standard practices and strategies regarding coding conventions, lifecycle management, high-level design patterns, and source control. Frankly, it's a fairly daunting task and I'm not sure where to begin.

Initially, I'm inclined to tutor them in some of the central concepts of The Pragmatic Programmer, or Fowler's Refactoring ("Code Smells", etc). I also hope to introduce a number of Agile methodologies. But ultimately, to be effective, I think I'm going to need to hone in on 5-7 core fundamentals; in other words, what are the most important principles or practices that they can realistically start implementing that will give them the most "bang for the buck".

So that's my question: What would you include in your list of the most effective strategies to help straighten out the spaghetti (and prevent it in the future)?


答:
We got the biggest increase in uptake by configuring a service to pick up email from an address and automatically log it as an issue. The nice side effect of this system is that you can also easily add conversations to an issue by including a special syntax in the subject (eg. TeamITNo:12345). Also, if you send all your email communication via this system, and they hit reply then you'll get the reply right back into the bug tracker, with the issue updated.

This had the biggest positive effect, as it uses technology users are comfortable with, and also means you get all your issues in one place.

Title: Herding your users to your bugtracker

Body:
I have a fully configured mantis bug tracker for tracking issues in apps that I create.  When an user is disciplined and goes straight to mantis to write a issue report, he/she will have fastest response and everything regarding the issue will be very easy to track.

However, not everyone is keen to do so.  They report their problems via phone, e-mail, don't report them at all.

What would be the best way to nudge them towards the using a bugtracker system?  Clearly, they HAVE to see some immediate benefits so they can return and look for more benefits.

EDIT:

I am talking about support for the products that I sell as an ISV.


问:
Why would I want to use CRaSH?
Justed stumbled across CRaSH and although it looks mighty interesting, I'm wondering why a Java developer should invest time & energy into learning (yet another) shell language. What sort of standard- and cool-applications can CRaSH be used for? Is this like a Groovy-version of Jython?

I guess, when the dust settles, I'm looking for CRaSH's "wow" factors. I'm sure they're there, but after spending ~20 minutes perusing the documentation I'm just not seeing them. Thanks in advance!

答:
Possible Uses

Fast Prototyping

You could do this with Groovy or others, so that's not a very strong point, but as CRaSH gives you code-level access to the JVM and the processes it runs, it may come in handy to just keep a JVM running and experiment with small code snippets (for instance, using it as a REPL to implement solutions to StackOverflow questions).

The JCR extension would seem potentially useful to supplement this, by giving you shell access to remote repositories, and contains a notion of workspace to separate projects.

Interacting with a Running Process

I could see this being an interesting use case. I don't know of many good process inspection command-line tools for JVM processes, apart from the JDK-packaged ones. CRaSH might help in interacting with them in novel ways.

For instance, you can use the Attach Mode to attach to a running JVM, and then use the thread command to ls, dump or interrupt threads.

You could also write some additional control commands for non-programmers to use CRaSH to perform routine maintenance and monitoring.

Content Repository Management

The JCR extension seems to be very interesting as well, as it would give a Java-scriptable access to remote development environments.   It could also simply allow content-editors to access and edit remote content, when used in the context of CMS-type apps built on top of a JCR-capable content repository.

What Others Say About CRaSH

An introductory blog post by the CRaSH author, about its use at eXoPlatform. And the fact that it is officially supported by eXoPlatform is an indicator that's it potentially good stuff :)

Not much to read, but of interest: French technologist Didier Girard re-posted it.

Summary

Basically, I see it as a power-user or administrator interface to JVM processes, built on top of Groovy and networking protocols. So it combines the power of scripting with a nice facade and some built-in connectors.

Note on Flexibility

I agree with SK-logic: most of this can be done with most JVM-languages, and they provide more and flexibility. But CRaSH might provide a shorter path to achieving such goals.

The same applies to the JCR extension capabilities: you can achieve this by glueing together a few age-old and time-tested tools. But this might be a shorter and simpler path (like commands for the heroku platform, or PaaS services, for instance).

Title: Why would I want to use CRaSH?


答:
Wow. Sounds like you have a really big challenge ahead of you! I'd do something along the following lines:

First of all: Prioritize. What do you want to achieve first? What is the most important for the current state of the project? What will you get the most from vs how much time it'll take to get there.

Ensure that you have a version control system. Git or Mercurial for instance.

Get some kind of continuous integration system (e.g. Jenkins) up and running.

Get a bug tracking system up and running. Mantis is quite nice in my opinion.

Look into static code analysis (if something is available for the language you're currently working with).

Try to achieve as much consistency in anything from naming of variables to general code conventions and guidelines in the code base.

Get the system under test. This is extremely important for a big legacy system like this in my opinion. Use test cases to document existing behavior, no matter if the behavior feels weird or not (usually there's a reason as to why the code looks a certain why, might be good or bad, or both ;P). Michael Feathers Working Effectively With Legacy Code is an excellent resource for this.


问:
Is it ok to replace optimized code with readable code?
Sometimes you run into a situation where you have to extend/improve some existing code. You see that the old code is very lean, but it's also difficult to extend, and takes time to read.

Is it a good idea to replace it with modern code?

Some time ago I liked the lean approach, but now, it seems to me that it's better to sacrifice a lot of optimizations in favor of higher abstractions, better interfaces and more readable, extendable code.

The compilers seem to be getting better as well, so things like struct abc = {} are silently turned into memsets, shared_ptrs are pretty much producing the same code as raw pointer twiddling, templates are working super good because they produce super lean code, and so on.

But still, sometimes you see stack based arrays and old C functions with some obscure logic, and usually they are not on the critical path.

Is it a good idea to change such code if you have to touch a small piece of it either way?

答:
Here is an example to see the difference between simple code and optimized code: https://stackoverflow.com/a/11227902/1396264

towards the end of the answer he just Replaces:

```<code>if (data[c] >= 128)
    sum += data[c];
</code>```

with:

```<code>int t = (data[c] - 128) >> 31;
sum += ~t & data[c];
</code>```

To be fair I have no idea what the if statement has been replaced with but as the answerer says its some bitwise operations giving the same result (I'm just going to take his word for it).

This executes in less than a quarter of the original time
(11.54sec vs 2.5sec)

Body:
Here is an example to see the difference between simple code and optimized code: https://stackoverflow.com/a/11227902/1396264

towards the end of the answer he just Replaces:

if (data[c] >= 128)
    sum += data[c];

with:

int t = (data[c] - 128) >> 31;
sum += ~t & data[c];

To be fair I have no idea what the if statement has been replaced with but as the answerer says its some bitwise operations giving the same result (I'm just going to take his word for it).

This executes in less than a quarter of the original time
(11.54sec vs 2.5sec)


问:
FIFO lock with mutiple threads/processes
I need to use FIFO in my application in linux+C, I have multiple threads and processes, I read some where that writing to a FIFO is atomic below some value (I believe 4k) especially I'm writing max of 300 bytes, Am I safe here?</p>

答:
It's atomic only inasmuch as how you write your FIFO queue/structure.

Wrapping a mutex or some other form of lock around the FIFO queue is probably the easiest way to guarantee concurrency and atomicity for the environment you describe.

If you'll have multiple processes attempting to write to the queue, then you'll probably need a dedicated handler for the queue.

Option A.

You could set up two write areas for the queue - the first area is where any and all processes can write to, synchronized with some sort of indexing scheme, or:

Option B.

It would probably be cleaner to have a dedicated process for the queue that has multiple threads to receive write requests.  Synchronization on writing to the queue is then handled within the FIFO queue process itself.

As a rule, unless you have documentation in your hand that declares operation Foo to be thread-safe/atomic/whatever, then assume it isn't safe.  Having "read somewhere ..." isn't going to cut it when you've got race conditions and the data in your queue has been shredded from simultaneous writes.

Option C.

Use the Pipe/FIFO structure provided by the OS.

Yes, you'll be fine/safe.
From the first link on Pipes & FIFOs that you provided in the comments:

```POSIX.1-2001 says that write(2)s of less than PIPE_BUF bytes must be atomic:```

And from the limits.h you linked:

``` 13 #define PIPE_BUF        4096    /* # bytes in atomic write to a pipe */```

Since you're writing <= 300 bytes, and the POSIX minimum buffer size for an atomic write is 512 bytes, you're very much in the clear.  To be paranoid, you could double check the PIPE_BUF size in your local limits.h, but it's not really necessary.

Your writes are guaranteed thread-safe since you're writing less than the pipe buffer size.  Likewise, your reads should be okay and/or they should have the benefit of device locking preventing two threads from accessing at the same time.

Body:
It's atomic only inasmuch as how you write your FIFO queue/structure.

Wrapping a mutex or some other form of lock around the FIFO queue is probably the easiest way to guarantee concurrency and atomicity for the environment you describe.

If you'll have multiple processes attempting to write to the queue, then you'll probably need a dedicated handler for the queue.

Option A.

You could set up two write areas for the queue - the first area is where any and all processes can write to, synchronized with some sort of indexing scheme, or:

Option B.

It would probably be cleaner to have a dedicated process for the queue that has multiple threads to receive write requests.  Synchronization on writing to the queue is then handled within the FIFO queue process itself.

As a rule, unless you have documentation in your hand that declares operation Foo to be thread-safe/atomic/whatever, then assume it isn't safe.  Having "read somewhere ..." isn't going to cut it when you've got race conditions and the data in your queue has been shredded from simultaneous writes.

Option C.

Use the Pipe/FIFO structure provided by the OS.

Yes, you'll be fine/safe.
From the first link on Pipes & FIFOs that you provided in the comments:

POSIX.1-2001 says that write(2)s of less than PIPE_BUF bytes must be atomic:

And from the limits.h you linked:

 13 #define PIPE_BUF        4096    /* # bytes in atomic write to a pipe */

Since you're writing <= 300 bytes, and the POSIX minimum buffer size for an atomic write is 512 bytes, you're very much in the clear.  To be paranoid, you could double check the PIPE_BUF size in your local limits.h, but it's not really necessary.

Your writes are guaranteed thread-safe since you're writing less than the pipe buffer size.  Likewise, your reads should be okay and/or they should have the benefit of device locking preventing two threads from accessing at the same time.


问:
What are the best practices to use NHibernate sessions in asp.net (mvc/web api)?
I have the following setup in my project:

```<code>public class WebApiApplication : System.Web.HttpApplication
{
    public static ISessionFactory SessionFactory { get; private set; }

    public WebApiApplication()
    {
        this.BeginRequest += delegate
        {
            var session = SessionFactory.OpenSession();
            CurrentSessionContext.Bind(session);
        };

        this.EndRequest += delegate
        {
            var session = SessionFactory.GetCurrentSession();

            if (session == null)
            {
                return;
            }

            session = CurrentSessionContext.Unbind(SessionFactory);
            session.Dispose();
        };
    }

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        var assembly = Assembly.GetCallingAssembly();
        SessionFactory = new NHibernateHelper(assembly, Server.MapPath("/")).SessionFactory;
    }
}

public class PositionsController : ApiController
{
    private readonly ISession session;

    public PositionsController()
    {
        this.session = WebApiApplication.SessionFactory.GetCurrentSession();
    }

    public IEnumerable<Position> Get()
    {
        var result = this.session.Query<Position>().Cacheable().ToList();

        if (!result.Any())
        {
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
        }

        return result;
    }

    public HttpResponseMessage Post(PositionDataTransfer dto)
    {
        //TODO: Map dto to model
        IEnumerable<Position> positions = null;
        using (var transaction = this.session.BeginTransaction())
        {
            this.session.SaveOrUpdate(positions);

            try
            {
                transaction.Commit();
            }
            catch (StaleObjectStateException)
            {
                if (transaction != null && transaction.IsActive)
                {
                    transaction.Rollback();
                }
            }
        }

        var response = this.Request.CreateResponse(HttpStatusCode.Created, dto);
        response.Headers.Location = new Uri(this.Request.RequestUri.AbsoluteUri + "/" + dto.Name);
        return response;
    }

    public void Put(int id, string value)
    {
        //TODO: Implement PUT
        throw new NotImplementedException();
    }

    public void Delete(int id)
    {
        //TODO: Implement DELETE
        throw new NotImplementedException();
    }
}
</code>```

I am not sure if this is the recommended way to insert the session into the controller.
I was thinking about using DI but i am not sure how to inject the session that is opened and binded in the BeginRequest delegate into the Controllers constructor to get this

```<code>    public PositionsController(ISession session)
    {
        this.session = session;
    }
</code>```

Question: What is the recommended way to use NHibernate sessions in asp.net  mvc/web api ?

答:
I am not sure if this is the recommended way to insert the session into the controller

Use constructor injection, as long as session is required for controller. Your "composition root" should be able to do this. And you had provided an example.

I was thinking about using DI but i am not sure how to inject the session that is opened and binded in the BeginRequest delegate into the Controllers constructor to get this

Usually DI containers are configured with "scope" abstraction. There are several default scopes for most of DI containers, among them are Signleton, Transient, Thread and Request (for HTTP requests). Last one will create one instance of dependency per HTTP request, and injects it into all objects that handle this request. As soon as HTTP Request will be done, DI should dispose all dependencies also. So, there is no need to explicitely create, handle and dispose session yourself.

ContentLicense: CC BY-SA 4.0


问:
How is programming affected by spatial aptitude?

Background

The longer I work on a project, the less clear it becomes. It's like I cannot seperate various classes/objects anymore in my head. Everything starts mixing up, and it's extremely hard to take it all apart again. I start putting functions in classes where they really don't belong, and make silly mistakes such as writing code that I later find was 100% obsolete; things are no longer clearly mappable in my head. It isn't until I take a step back for several hours (or days sometimes!) that I can actually see what's going on again, and be productive.

I usually try to fight through this, I am so passionate about coding that I wouldn't for the life of me know what else I could be doing. This is when stuff can get really weird, I get so up in my head that I sort of lose touch with reality (to some extent) in that various actions, such as pouring a glass of water, no longer happen on a concious level. It happens on auto pilot, during which pretty much all of my concious concentration (is that even a thing?) is devoted to borderline pointless problem solving (trying to seperate elements of code). It feels like a losing battle.

So I took an IQ test a while ago (Wechsler Adult Intelligence Scale I believe it was) and it turned out my Spatial Aptitude was quite low. I still got a decent total score, just above average, so I won't have to poke things with a stick for a living, but I am a little worried that this is such a handicap when writing/engineering computer programs that I won't ever be able to do it seriously or professionally.

Question

I am very much interested in what other people think of this...

Could a low spatial aptitude be the cause of the above described problems?

How is programming affected by spatial aptitude?

Maybe I should be looking more along the lines of ADD or something similar, because I did get diagnosed with ADD at the age of 17 (5 years ago) but the medicine I received didn't seem to affect me that much so I never took it all that serious.

As far as I know people are born with low/med/high spatial aptitude, so I think it's interesting to find out if the more fortunate are better programmers by birth right.

答:
From what you describe, your problem may have various causes :

Inexperience

Loss of focus / fatigue

Low spatial abilities

Inexperience can be solved by... well, gaining more experience, basically. However obvious it may sound, by practising more you'll find yourself in complex programming situations more often and will progressively learn to handle them. Right now you may lack the mental schemas and reflexes to make the right connections, draw the right conclusions and unlock these situations, which can make you feel like you're slow and write "obsolete code", but these problem-solving patterns will progressively take place in your head as you get more experienced (you're only 22 as I understand, which is still very young).

There are various techniques to improve your focus. Pomodoro and Getting Things Done are two examples.
In the programming field, Test Driven Development is also something I'd really recommend since it forces you to concentrate on one small, achievable goal at a time (baby steps). With a TDD approach you're much less likely to "put functions in classes where they really don't belong" since you're forced to clearly define a responsibility of your class with a test and then focus solely on implementing it when you code, as opposed to jumping between several classes and filling them randomly little by little.

Fatigue and attention drops can be avoided by adopting a sustainable rythm with frequent breaks. You might find interest in that presentation by Linda Rising on being more productive by respecting our brain : Born to Cycle.

As for low spatial abilities, I'm afraid there's not a lot you can do about it. However, hard work can attenuate it and it's far from the being only skill required in programming. Things like creativity, passion, enthusiasm, rigor, analytic skills, sharpness, good grasp of business issues, collaboration skills, can more than make up for a weaker than average mental visualization of the code base.

In short, what you need IMO is :

Discipline

Practice

A sustainable pace


答:
There are multiple options that might be used in your case.

One option is described as passing controllers an instance of a NHibernate session which is unique for the HTTP request - NHibernate sessions in ASP.NET MVC

Another options can be found in NHibernate Wiki

Title: What are the best practices to use NHibernate sessions in asp.net (mvc/web api)?

Body:
I have the following setup in my project:

```<code>public class WebApiApplication : System.Web.HttpApplication
{
    public static ISessionFactory SessionFactory { get; private set; }

    public WebApiApplication()
    {
        this.BeginRequest += delegate
        {
            var session = SessionFactory.OpenSession();
            CurrentSessionContext.Bind(session);
        };

        this.EndRequest += delegate
        {
            var session = SessionFactory.GetCurrentSession();

            if (session == null)
            {
                return;
            }

            session = CurrentSessionContext.Unbind(SessionFactory);
            session.Dispose();
        };
    }

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        var assembly = Assembly.GetCallingAssembly();
        SessionFactory = new NHibernateHelper(assembly, Server.MapPath("/")).SessionFactory;
    }
}

public class PositionsController : ApiController
{
    private readonly ISession session;

    public PositionsController()
    {
        this.session = WebApiApplication.SessionFactory.GetCurrentSession();
    }

    public IEnumerable<Position> Get()
    {
        var result = this.session.Query<Position>().Cacheable().ToList();

        if (!result.Any())
        {
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
        }

        return result;
    }

    public HttpResponseMessage Post(PositionDataTransfer dto)
    {
        //TODO: Map dto to model
        IEnumerable<Position> positions = null;
        using (var transaction = this.session.BeginTransaction())
        {
            this.session.SaveOrUpdate(positions);

            try
            {
                transaction.Commit();
            }
            catch (StaleObjectStateException)
            {
                if (transaction != null && transaction.IsActive)
                {
                    transaction.Rollback();
                }
            }
        }

        var response = this.Request.CreateResponse(HttpStatusCode.Created, dto);
        response.Headers.Location = new Uri(this.Request.RequestUri.AbsoluteUri + "/" + dto.Name);
        return response;
    }

    public void Put(int id, string value)
    {
        //TODO: Implement PUT
        throw new NotImplementedException();
    }

    public void Delete(int id)
    {
        //TODO: Implement DELETE
        throw new NotImplementedException();
    }
}
</code>```

I am not sure if this is the recommended way to insert the session into the controller.
I was thinking about using DI but i am not sure how to inject the session that is opened and binded in the BeginRequest delegate into the Controllers constructor to get this

```<code>    public PositionsController(ISession session)
    {
        this.session = session;
    }
</code>```

Question: What is the recommended way to use NHibernate sessions in asp.net  mvc/web api ?


问:
Erlang web frameworks survey
(Inspired by similar question on Haskel)

There are several web frameworks for Erlang like Nitrogen, Chicago Boss, and Zotonic, and  a few more.

In what aspects do they differ from each other? For example:

features (e.g. server only, or also client scripting, easy support for different kinds of database)

maturity (e.g. stability, documentation quality)

scalability (e.g. performance, handy abstraction)

main targets

Also, what are examples of real-world sites / web apps using these frameworks?

EDIT: Starting a bounty in hopes that it will get some conversation going

答:
I built MaxClass.com - a new social network on top of Zotonic and am so pleased with the speed and flexibility of the platform that I started developing other high performance applications based on Zotonic.
Besides obvious things (radical scalability, benefits of Erlang etc) Zotonic has built in support for templating (Django) and a great backend that has the look and feel of a WordPress but is all super fast and easily extendable. for real life sites and systems this is really important for the less technical people in a project.</p>

Title: Erlang web frameworks survey


答:
I've settled on the following solution.

On my sql server table, I added an index. Check the image for the settings

In visual studio, I updated my eddmx (Entity framework file), but when I tried to insert duplicate records, all I got was another error :

```<code>System.Data.Entity.Infrastructure.DbUpdateConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.
</code>```

So I created a simple stored procedure to update the entity. Added the stored procedure to my edmx file and called that from my code and things are working now and duplicates are ignored.

heres a link that helped me find a solution

http://sqlkit.com/2009/06/17/

http://msdn.microsoft.com/en-us/library/x480ck3b.aspx

Body:
I've settled on the following solution.

On my sql server table, I added an index. Check the image for the settings

In visual studio, I updated my eddmx (Entity framework file), but when I tried to insert duplicate records, all I got was another error :

System.Data.Entity.Infrastructure.DbUpdateConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.

So I created a simple stored procedure to update the entity. Added the stored procedure to my edmx file and called that from my code and things are working now and duplicates are ignored.

heres a link that helped me find a solution

http://sqlkit.com/2009/06/17/

http://msdn.microsoft.com/en-us/library/x480ck3b.aspx


问:
Selecting a JAX-RS implementation for a new project
I'm starting a new Java project which will require a RESTful API. It will be a SaaS business application serving mobile clients.

I have developed one project with Java EE 6, but I'm not very familiar with the ecosystem, since most of my experience is on the Microsoft platform.

Which would be a sensible choice for a JAX-RS implementation for a new project such as described?

Judging by Wikipedia's list, main contenders seem to be Jersey, Apache CXF, RESTeasy and Restlet. But the Comparison of JAX-RS Implementations cited on Wikipedia is from 2008.

My first impressings from their respective homepages is that:

CXF aims to be a very comprehensive solution (reminds me of WCF in the Microsoft space), which makes me think it can be more complex to understand, setup and debug than what I need;

Jersey is the reference implementation and might be a good choice, but it's legacy from Sun and I'm not sure how Oracle is treating it (announcements page doesn't work and last commit notice is from 4 months ago);

RESTeasy is from JBoss and probably a solid option, though I'm not sure about learning curve;

Restlet seems to be popular but has a lot of history, I'm not sure how up-to-date it is in the Java EE 6 world or if it carries a heavy J2EE mindset (like lots of XML configuration).

What would be the merits of each of these alternatives? What about learning curve? Feature support? Tooling (e.g. NetBeans or Eclipse wizards)? What about ease of debugging and also deployment? Is any of these project more up-to-date than the others? How stable are them?

答:
I've grown to love Dropwizard for an overall solution

Rather than go with some huge application container approach, Dropwizard advocates a lightweight solution that offers much faster development cycles. Essentially, it provides the glue for the following well-known frameworks:

Jetty (HTTP)

Jersey (JAX-RS)

Jackson (JSON or XML)

Guava (excellent additions to JDK libraries)

Metrics (real time application monitoring)

Hibernate Validator (input verification)

OAuth (RESTful authentication)

The combination of the above, coupled with a solid approach to functional testing, gives a complete solution to getting your service up and running quickly.

Yeah? And the JAX-RS question I asked...

You'll notice that their choice was Jersey, the reference JAX-RS implementation. Being a RESTEasy guy I thought this would be a problem, but there was zero learning curve. The two are largely interchangeable. However, I would say that the Jersey client offered a fluent interface for constructing tests. An example would be...

```<code> @Override
  protected void setUpResources() {
    addResource(new HelloWorldResource("Hello, %s!","Stranger"));

    setUpAuthenticator();
  }

  @Test
  public void simpleResourceTest() throws Exception {

    Saying expectedSaying = new Saying(1,"Hello, Stranger!");

    Saying actualSaying = client()
      .resource("/hello-world")
      .get(Saying.class);

    assertEquals("GET hello-world returns a default",expectedSaying.getContent(),actualSaying.getContent());

}
</code>```

Body:
I've grown to love Dropwizard for an overall solution

Rather than go with some huge application container approach, Dropwizard advocates a lightweight solution that offers much faster development cycles. Essentially, it provides the glue for the following well-known frameworks:

Jetty (HTTP)

Jersey (JAX-RS)

Jackson (JSON or XML)

Guava (excellent additions to JDK libraries)

Metrics (real time application monitoring)

Hibernate Validator (input verification)

OAuth (RESTful authentication)

The combination of the above, coupled with a solid approach to functional testing, gives a complete solution to getting your service up and running quickly.

Yeah? And the JAX-RS question I asked...

You'll notice that their choice was Jersey, the reference JAX-RS implementation. Being a RESTEasy guy I thought this would be a problem, but there was zero learning curve. The two are largely interchangeable. However, I would say that the Jersey client offered a fluent interface for constructing tests. An example would be...

 @Override
  protected void setUpResources() {
    addResource(new HelloWorldResource("Hello, %s!","Stranger"));

    setUpAuthenticator();
  }

  @Test
  public void simpleResourceTest() throws Exception {

    Saying expectedSaying = new Saying(1,"Hello, Stranger!");

    Saying actualSaying = client()
      .resource("/hello-world")
      .get(Saying.class);

    assertEquals("GET hello-world returns a default",expectedSaying.getContent(),actualSaying.getContent());

}


问:
Is executing SQL through a WebService a really bad idea?
Typically when creating a simple tool or something that has to use a database, I go through the fairly long process of first creating a webservice that connects to a database then creating methods on this webservice that do all the type of queries I need.. methods like

```<code>List<Users> GetUsers()
{
    ...
}
User GetUserByID(int id)
{
    ...
}
//More Get/Update/Add/Delete methods
</code>```

Is it terrible design to simply make the webservice as secure as I can (not quite sure the way to do something like this yet) and just make a couple methods like this

```<code>SqlDataReader RunQuery(string sql)
{
     ...
}

void RunNonQuery(string sql)
{
     ...
}
</code>```

I would sorta be like exposing my database to the internet I suppose, which sounds bad but I'm not sure.

I just feel like I waste so much time running everything through this webservice, there has to be a quicker yet safe way that doesn't involve my application connecting directly to the database (the application can't connect directly to database because the database isn't open to any connections but localhost, and where the appliction resides the standard sql ports are blocked anyway)

Especially when I just need to run a few simple queries

答:
The Only Real issue with this is security.. Then there is that fact that you have an API that's not defined at all, but you may not care about this.

But if this is a "Private" web service the (requires credentials and has a very small set of trusted users) I see nothing wrong with it.

Ok, I Confess.. I have (to create distributed apps) Open DB Ports over the internet and Connected my FAT apps directly to the DB over the internet, relying on only the DB security for protection. This has saved me weeks of work.

I'd also like to point out that all online DB management tools basically do something similar to this (MySql Admin for Example)..


答:
It is terrible design and you know it. You're leaving yourself at mercy of anyone with even a slight malevolent intent. Apart from being vulnerable to regular sql injection, you expose an entire webservice to throw sql at, bypassing even the need to inject it. Doing such a thing with your private database is simply unwise, doing it with a client's production database could also potentially open you to legal consequences if contents are leaked.

Use an ORM if you don't use one already, it might give you the time savings you're looking for.

Title: Is executing SQL through a WebService a really bad idea?

Body:
Typically when creating a simple tool or something that has to use a database, I go through the fairly long process of first creating a webservice that connects to a database then creating methods on this webservice that do all the type of queries I need.. methods like

```<code>List<Users> GetUsers()
{
    ...
}
User GetUserByID(int id)
{
    ...
}
//More Get/Update/Add/Delete methods
</code>```

Is it terrible design to simply make the webservice as secure as I can (not quite sure the way to do something like this yet) and just make a couple methods like this

```<code>SqlDataReader RunQuery(string sql)
{
     ...
}

void RunNonQuery(string sql)
{
     ...
}
</code>```

I would sorta be like exposing my database to the internet I suppose, which sounds bad but I'm not sure.

I just feel like I waste so much time running everything through this webservice, there has to be a quicker yet safe way that doesn't involve my application connecting directly to the database (the application can't connect directly to database because the database isn't open to any connections but localhost, and where the appliction resides the standard sql ports are blocked anyway)

Especially when I just need to run a few simple queries


答:
Yes this is a bad idea, from a security point of view. It could allow for a select credit_card_numbers from credit_card_accounts or drop table users to be executed if anyone figures out what your service does and how to send messages directly to it.

Is there a reason you can't have stored procedures (one for each query/statement you might need to execute) that take a few key inputs that the webservice passes to them, and a webservice operation for each stored proc? You could even just create one operation and it could take a stored procedure name and list of inputs to it. Not as good as separate operations, but still better than arbitrary SQL.

The only reason I can think of for allowing the webservice to take arbitrary SQL and execute it would be for a sandbox/testing environment which is on an isolated network and if anything bad happens, it can be wiped and restored to the base image easily.


答:
This is bad on 2 levels:

Obviously security is a concern

Your other problem is one of design. If you Call GetSomePeople from the wweb service it is easier to later decouple your app from the database. All you need to do is implement GetSomePeople in whatever new technology you choose.

The final question is why would you want to do this? You spent so much time asking this question that something is already telling you not to do it. If you just went ahead with the web service you could have probably already been done :)

Good design is never a waste of time!


问:
How to learn Cloud Computing and Big Data at home?
I want to learn Cloud Computing and Big Data at home.

Is it possible to learn these technologies on home PC?

Which technologies to learn in Cloud Computing?

Which technologies to learn Big Data (Hadoop)?

答: Cloud computing by definition can be learned anywhere. Just signup for one of the free tiers and learn how to start it, expand it, reconfigure it. Discover what prepackaged software and tools can by loaded, setup, used and then discarded. And when you done trash the server and start again.</p>


答:
I just feel like I waste so much time running everything through this
  webservice, there has to be a quicker yet safe way that doesn't
  involve my application connecting directly to the database (the
  application can't connect directly to database because the database
  isn't open to any connections but localhost, and where the appliction
  resides the standard sql ports are blocked anyway)

Why not just change your database to open it to any connections? By writing this web service that's what your doing. (in a bit of an arse backwards way)

I would also have huge concerns that HTTP encoding could change the meaning of some of your sql statements causing errors. (potentially destructive ones)


问:
I need an approach to the problem of preventing inserting duplicate records into the database
A webservice that I call returns a list of data. The data from the webservice is updated periodically, so a call to the webservice done in one hour could return the same data as a call done in an hour. Also, the data is returned based on a start and end date.

We have multiple users that can run the webservice search, and duplicate data is most likely to be returned (especially for historical data). However I don't want to insert this duplicate data in the database.

I've created a db table in which the data is stored (most important columns are)

Id int autoincrement PK
Date date not null        --The date to which the data set belongs.
LastUpdate date not null  --The date the data set was last updated.
UserName varchar(50)      --The name of the user doing the search.
```

I use sql server 2008 express with c# 4.0 and visual studio 2010. Entity Framework is used as the ORM. If stored procedures could be avoided in the proposed solution, then that will be a plus.

Another way of looking interpreting what I'm asking a solution for is as follows:
I have a million unique records in my table. A user does a new search. The search results from the user contains around 300k records of the data that is already in the db. An efficient solution to finding and inserting only the unique records is needed.

A combination of the Date, LastUpdate and UserName makes a record unique.

答:
Well, the obvious solution is to have a unique key on the columns that make the row unique.

A combination of the Date, LastUpdate and UserName makes a record unique.

Alternatively, you might just get rid of the surrogate key and use the above as the primary key (depends upon where else you are using it).

Inserts should be done using Merge, which will allow you to insert the record only when it doesn't already exist.


问:
New "delay" keyword for JavaScript
I had a great idea for a new javascript keyword "delay", but I don't know what I can do to bring it to the new specification. Also I want to know what you guys think about it and if it's even realistic.

What does the delay keyword ?

The delay keyword does nothing more than stop the execution of the current stack and immediately continues to the next "job" in the queue. But that's not all! Instead of discarding the stack, it adds it to the end of the queue. After all "jobs" before it are done, the stack continues to execute.

What is it good for?

delay could help make blocking code non-blocking while it still looks like synchronous code. A short example:

```<code>setTimeout(function(){
    console.log("two");
},0);
console.log("one");
delay; //since there is currently another task in the queue, do this task first before continuing
console.log("three");

//Outputs: one, two, three
</code>```

This simple keyword would allow us to create a synchronous-looking code wich is asynchronous behind the scenes. Using node.js modules, for example, would no longer be impossible to use in the browser without trickery.

There would be so many possibilites with such a keyword!

Is this pattern useful? What can I do to bring this into the new ECMAscript specification?

Note: I asked this previously
on Stack Overflow, where it was closed.

答:
In my understanding,

```<code> window.setTimeout(function() { console.log("three"); }, 0);
</code>```

does about the same thing, so there is no need for this keyword, at least not in the browser.

Title: New "delay" keyword for JavaScript

Body:
In my understanding,

 window.setTimeout(function() { console.log("three"); }, 0);

does about the same thing, so there is no need for this keyword, at least not in the browser.


答:
Just a personal opinion, but look at either:

barebone setTimeout() and setInterval(),

or a bunch of libraries like Dojo's defer().

I don't see where the point would be to make this a language keyword. This seems overboard, when there's already sufficient tools in the standard library and higher-level enhancements in 3rd party libraries.

Title: New "delay" keyword for JavaScript

Body:
I had a great idea for a new javascript keyword "delay", but I don't know what I can do to bring it to the new specification. Also I want to know what you guys think about it and if it's even realistic.

What does the delay keyword ?

The delay keyword does nothing more than stop the execution of the current stack and immediately continues to the next "job" in the queue. But that's not all! Instead of discarding the stack, it adds it to the end of the queue. After all "jobs" before it are done, the stack continues to execute.

What is it good for?

delay could help make blocking code non-blocking while it still looks like synchronous code. A short example:

```<code>setTimeout(function(){
    console.log("two");
},0);
console.log("one");
delay; //since there is currently another task in the queue, do this task first before continuing
console.log("three");

//Outputs: one, two, three
</code>```

This simple keyword would allow us to create a synchronous-looking code wich is asynchronous behind the scenes. Using node.js modules, for example, would no longer be impossible to use in the browser without trickery.

There would be so many possibilites with such a keyword!

Is this pattern useful? What can I do to bring this into the new ECMAscript specification?

Note: I asked this previously
on Stack Overflow, where it was closed.


答: To me, it sounds like an irritatingly gimped version of coroutines. Having the ability to yield to another coroutine explicitly would be far more useful than a general “yield to something, I don't know what” which is what defer is.

Title: New "delay" keyword for JavaScript


答:
Of course this is bad from a security front, as everyone has pointed out.

But it's at least as bad from the database management perspective.  How do you ensure:

the queries are competently written?

will use indexes?

will deal with competing insert/updates gracefully

will not run into dead-locking issues?

In short, there is no way in which this is a good idea.


问:
Advice and resources on collaborative environments
I need some advice on collaborative software environments. More specifically,
I am looking for books and reference materials that can aid me in understanding team and code structures and the interactions thereof. In other words books, blogs or white papers explaining:

Different strategies for structuring teams that share common code
between each other but have distinct individual functions?

To summarise my question I would like to know what would be a good source of knowledge if I were to set up teams in an organisation that shared code but each unit still remained autonomous.

I have done some research on this subject and explored:

code review tools,

distributed VCS,

continuous integration tools,

Unit testing automation.

The tough part about implementing these tools are to determine where a good place would be to start, which tools are low hanging fruit, which tools or methods provide higher success rates. If someone asks me about code quality reference I point them to Code Complete. I am looking for an equivalent guide on software team structures and tools to make this equation work better.

I realise that this question is quite vague but it arose as "we need to share code between teams without breaking each others stuff and causing management headaches and reams of red tape"

The answer is definitely not simple and requires changes on many levels, hence the question. If the question is too vague please vote to close or delete. I would accept any good starting point as an answer.

答:
More specifically, I am looking for books and reference materials that can aid me in understanding team and code structures and the interactions thereof. In other words books, blogs or white papers explaining:

Different strategies for structuring teams that share common code between each other but have distinct individual functions?
  To summarise my question I would like to know what would be a good source of knowledge if I were to set up teams in an organisation that shared code but each unit still remained autonomous.

I realise that this question is quite vague but it arose as "we need to share code between teams without breaking each others stuff and causing management headaches and reams of red tape"

This might by more of a PM question, in which case it should be migrated to http://pm.stackexchange.com, however, here is my answer...

Sharing software modules - Software modules can be "shared" as code or as binaries...

Personally I prefer sharing binaries, as it leads to less ambiguity on the matter of which version everyone has and it requires editor to open up the same environment (e.g. VS solution) as the author, thus seeing the same unit test and integration test projects and running them after local compiles.

Software modules and teams...

It is best when each software module has more than one author, that way there is no single point of knowledge which among other things, can lead to bottle necks when there is a need for changes.

Modules can be developed in a team or cross team. Infrastructure modules are usually developed either by dedicated infrastructure teams or cross teamed.

It is easier to communicate within the same team, therefore, it is preferable if modules are developed in a single team.

The are a few common divisions to teams:

Horizontal teams - e.g. Data team, Engine team, UI team

Vertical teams - team per product/project (or sub project)

Vertical teams + infrastructure/architecture team(s)

Horizontal teams are a bi-product of matrix management (a known anti-pattern) and lead to teams that may specialize in something, but do not often receive fresh minds (since the teams can be rather static) and the development time is larger this way (more points of both time and API integration).

Vertical teams are used by methodologies such as SCRUM, however, they can lead to redundancy, since different products may have a lot in common.

Infrastructure/architecture teams research points for process optimization and reuse and can provide reusable components, making product development teams' work easier (once the organization gets used to the new process).

As of books - There is no single book or source of knowledge I recommend, on the contrary, I find leaning on a single point of knowledge problematic. Even the most famous books have some strong points and some weaker. The strong points are what make them famous and are often reachable by common sense, just formalized for the first time in that book. Taking everything a book or someone says for granted is not recommended, especially since what is right in one circumstance is not necessarily right in another.

Try to read as much as you can and take the good and relevant parts for each. Do not be too theoretical about your research, check what works and when, especially what works in your circumstances.

Also, learn from others' experience, both inside your organization and others you know and online, ask how similar things have been done and what was good and bad in those solutions.


答:
Have you looked for a framework? e.g. If you are programming in Java I'd recommend investing 5 days learning the basics of Spring with its REST and Hibernate tools. Or find a similar framework for your programming language.

I learned long ago that if a problem requires writing lots of trivial code then some nice programmers elsewhere have probably built some tools/framework to make it easier.

A good framework will solve a lot of your problems, including some you haven't thought of yet. It will also make it more maintainable for another programmer. And you get some good buzzwords for your resume.


问:
Something confusing about Single Responsibility Principle
1)

In fact if two responsibilities are always expected to change at the
  same time you arguably should not separate them into different classes
  as this would lead, to quote Martin, to a "smell of Needless
  Complexity". The same is the case for responsibilities that never
  change - the behavior is invariant, and there is no need to split it.

I assume even if non-related responsibilities are always expected to change for the same reason ( or if they never change ), we still shouldn't put them in the same class, since this would still violate high cohesion principle?

2)
I've found two quite different definitions for SRP:

Single Responsibility Principle  says that a subsystem, module, class,
  or even a function, should not have more than one reason to change.

and

There should never be more than one reason for a class to change

Doesn't the latter definition narrow SRP to a class level? If so, isn't first quote wrong by claiming that SRP can also be applied at subsystem, module and function levels?

thank you

答:
I imagine that it's just a matter of how general those responsibilities are.  For instance, you might have a library/assembly called DataAccessLayer, whose single responsibility is fetching data from persistence.  Within that, you might have a class CustomerDao, whose single responsibility is fetching customers from persistence.

I guess one could make a highly semantic argument that this compositional nature means that the assembly has as many responsibilities as DAOs, but I think that's really more of a nitpick than a reasonable argument against the concept being conveyed with SRP.


问:
What electronic user-story-mapping tools can you recommend?
Agile software development relies heavily on a work item type called user stories.  For example, you have a backlog full of user stories and you can select a few of them to work on during the next sprint.

But where and how do you find user stories to put into the backlog?  There is a popular technique for doing that called story mapping.  Jeff Patton invented it and here is the definitive guide on how to do it.

The question is, what electronic tools are out there that support Patton's story-mapping technique?

I've done a bit of research, found Pivotal and Rally plug-ins (but I'm not a customer of either) and I'm currently experimenting with SilverStories.

What other tools are out there?  What have you used?  What do you (not) recommend?  Why?

UPDATE: Some people who wrote comments seem to lean towards an answer that applying this technique is simply impossible with an electronic tool and we should just accept that.  Can't someone write it up as an answer?

UPDATE (to clarify the question in light of Alex Feinman's comment): the question is about identifying options for story-mapping.  Since Jeff Patton's technique can obviously be done on a white-board with stickies, the question focuses on additional options that might be provided with electronic tools.  (Premature) commitment to any particular tool or class of tools is not the point of this question.

答: If you must use an Electronic tool because you have a distributed of dispersed team look into any electronic postit tool that allows many users at one time. However they all miss the interactive value of index cards and none are as large as a good floor or wall.</p>


问:
What is the difference between Single Responsibility Principle and Separation of Concerns
a)What is the difference between SRP and SoC? Perhaps that SRP is applied at class level, while SoC can be applied at system, subsystem, module, class or function levels.

b) If answer to a) is yes, is then SoC applied at class level a synonym for SRP?

thank you

答:
As for SRP being only applied at class level, in his books Robert C. Martin (as far as I know he popularized if not came up with the concept) states:

Clean Code, page. 138 : "The Single Responsibility Principle (SRP) states that a class or module should have one, and only one, reason to change."

In Agile Principles, Patterns and Practices in C#, page 116 : "[...] and relate cohesion to the forces that cause a module, or a class, to change."

Emphasis mine.

In APPP he talks in greater length about SRP and focused almost entirely on the class level. While he does seem to focus on the class level, I feel the principle is also directed to modules and other higher level constructs.

For such reason I would not qualify SRP as SoC at class level as you suggest in your question.