问:
Lazy loading can lead to stale data, violates IoC?
Trying to be a better programmer

I have an application that keeps track of Roles and Permissions, I had classes for Role and Permission which were just value objects.

```<code>class Role
{
  int RoleID
  string RoleName
}

class Permission
{
  int PermissionID
  string PermissionName
}
</code>```

If I wanted to get the permissions for a Role I would do

```<code>List<Permission> permissions = PermissionDAL.GetPermissions(RoleID)
</code>```

But for convenience  (it's a Desktop application) I had to move the permission collection to the Role class so I could just do

```<code>permissions = roleInstance.GetPermissions();
</code>```

and the Role class becomes

```<code>class Role
{
  List<Permission> permissions = null;
  int RoleID
  string RoleName

  public List<Permission> Permissions
  {
     get
     {
        if(permissions == null)
           permissions = PermissionDAL.GetPermissions(this.RoleID);

        return permissions;
     }
  }
}
</code>```

Question 1: the challenge - here is the scenario

```<code>Role r = getARole();
   //for user to see
display(r.Permissions);

   //user adding permission to role
RoleDAL.AddPermission(RoleID, PermissionID);

   //display new permissions
display(r.Permissions);
   //But no, data is not refreshed because of the null check.
   //Do I need to call a new instance of this Role?
</code>```

Question 2 : I think this violate Inversion of Control?

Question 3 : How would you do an IoC for List<Role>, setting the permissions for each Role in the collection, if one were to use IoC.

Thanks

答:
Yes, this behavior is common in lazy-loaded data objects based on rapidly-changing data stores. You force a change here, but similar concurrency issues can happen in a multi-user system even when you're looking at data in a read-only fashion.

The easiest solution to your specific issue is to add the permission to the Permissions list manually in addition to writing it to the database. However, that doesn't solve concurrency; another user could add a permission after you get a list of them and you'll never know. There are many other solutions that will solve this snag; most of them require a simple SQL statement to stand in for the larger SQL statement. For instance, you could ask for a count of the number of records, and if that doesn't match the length of your list then repopulate it. You could also keep track of the "last modified date" of each element in the list, and if the most recent modified date of the records you would pull is newer than the newest last modified date of the data you have, refresh the data. Or, you can simply track how long ago you last refreshed, and if that's beyond a certain threshold you set the data is "stale" and should be refreshed. These will necessarily require a round trip to the database, but they're scalar queries so they economize on network bandwidth (and shouldn't perform terribly against a well-structured DBMS).

No, this does not break Inversion of Control, because this logic should go into the Role.Permissions accessor and thus you can continue to use one resolved instance as necessary. Even if you couldn't, there are ways to inject a factory method that can be used to produce as many "factory-scoped" (one per request) Role objects as you might need.

This depends on the IoC framework you're using (or if you aren't using one), and how you want that framework to produce Roles. If you have a factory method registered that takes a RoleID and produces a Role object, you can make that call as many times as you want. The Role object, by its nature, will then require something it can call to get the list of Permissions. Injecting the DAO is one option (and not a bad one as long as consuming code doesn't have to know about the DAO), but I would prefer a delegate Func<int, IEnumerable<Permission>> (and another Func<IEnumerable<Permission>, bool> that you'll use to determine if it's necessary to refresh data) that you can inject into Role and that Role can use without having to know where it came from; then if you had to, you could pretty much tear your data access layer out and start completely from scratch, without any other object knowing the difference.


问:
How to ease the maintenance of event driven code?
When using an event based component I often feel some pain at maintenance phase.

Since the executed code is all split around it can be quite hard to figure what will be all the code part that will be involved at runtime.

This can lead to subtle and hard to debug problems when someone adds some new event handlers.

Edit from comments:
Even with some good practices on-board, like having an application wide event bus and handlers delegating business to other part of the app, there is a moment when the code starts to become hard to read because there is a lot of registered handlers from many different places (especially true when there is a bus).

Then sequence diagram starts to look over complex, time spend to figure out what is happening is increasing and debugging session becomes messy (breakpoint on the handlers manager while iterating on handlers, especially joyful with async handler and some filtering on top of it).

//////////////

Example

I have a service that is retrieving some data on the server. On the client we have a basic component that is calling this service using a callback. To provide extension point to the users of the component and to avoid coupling between different components, we are firing some events: one before the query is sent, one when the answer is coming back and another one in case of a failure.
We have a basic set of handlers that are pre-registered which provide the default behavior of the component.

Now users of the component (and we are user of the component too) can add some handlers to perform some change on the behavior (modify the query, logs, data analysis, data filtering, data massaging, UI fancy animation, chain multiple sequential queries, whatever).
So some handlers must be executed before/after some others and they are registered from a lots of different entry point in the application.

After a while, it can happens that a dozen or more handlers are registered, and working with that can be tedious and hazardous.

This design emerged because using inheritance was starting to be a complete mess. The event system is used at a kind of composition where you don't know yet what will be your composites.

End of example

//////////////

So I'm wondering how other people are tackling this kind of code. Both when writing and reading it.

Do you have any methods or tools that let you write and maintain such code without to much pain ?

答:
So I'm wondering how other people are tackling this kind of code. Both when writing and reading it.

The model of event driven programming simplifies coding to some extent. It has probably evolved as a replacement of big Select (or case ) statements used in older languages and gained popularity in early Visual development environments such as VB 3 (Don't quote me on the history, I did not check it)!

The model becomes a pain if the event sequence matters and when 1 business action is split across many events. This style of process violates the benefits of this approach. At all costs, try to make the action code encapsulated in the corresponding event and don't raise events from within events. That then becomes far worse than the Spaghetti resulting from the GoTo.

Sometimes developers are eager to provide GUI functionality that requires such event dependency, but really there is no real alternative that is significantly simpler.

Bottom line here is that the technique is not bad if used wisely.

ContentLicense: CC BY-SA 3.0


问:
Is the GoF book still the one to read?

Possible Duplicate:

  Is there a canonical book on design patterns?

I'd like to read a design patterns book. GoF for sure is the one to read. But after 15 years is it still valid, I mean isn't there an updated one?

Something like "Charles Darwin On the origin of species" is a very important book, and some main concepts are still valid, anyway today (2010) one would read another book to study the subject.

In this question the main suggestions are the Head First and GoF books. But Head first is not a replacement for GoF.

So any suggestion or should I stick with GoF?

答:
It depends heavily on your scope. If you are more of an enterprise Java/C# or hardcode C++ type then yes, go get a GoF and probably some other books on the topic too (see other answers). However, if you can imagine working in a dynamic language with higher order functions and more advanced concepts, you mostly won't need any of those patterns. Even worse: you'll get less productive since you'll be looking for patterns to implement instead of thinking in language terms and (ab)using its power. Looking at Python, Ruby, (modern) Perl, Erlang, Scala, Clojure, Lisp, you name it, in every one of those languages no patterns from GoF are needed, since frankly, the patterns are a good way to solve some problems inherent to languages without higher-order constructs.

That being said, learn the patterns anyway either way, but be critical of them and learn to use them properly and sparingly. They are not the silver bullet and never going to be.

ContentLicense: CC BY-SA 2.5

Title: Is the GoF book still the one to read?


答:
What has worked for me is making each event stand on its own, without reference to other events.  If they are coming in asynchroniously, you don't have a sequence, so trying to figure out what happens in what order is pointless, besides being impossible.

What you do end up with are a bunch of data structures that are getting read and modified and created and removed by a dozen threads in no particular order.  You've got to do extemely proper multi-threaded programming, which is not easy.  You've also got to think multi-threaded, as in "With this event, I am going to look at the data I have at a particular instant, without regard to what it was a microsecond earlier, without regard to what just changed it, and without regard to what the 100 threads waiting for me to release the lock are going to do to it.  Then I will make my changes based on this even and what I see.  Then I am done."

One thing I find myself doing is scanning for a particular Collection and making sure that both the reference and the collection itself (if not threadsafe) are locked correctly and synchronized correctly with other data.  As more events are added, this chore grows.  But if I was tracking the relationships between events, that chore would grow a lot faster.  Plus sometimes a lot of the locking can be isolated in its own method, actually making the code simpler.

Treating each thread as a completely independent entity is difficult (because of the hard-core multi-threading) but doable.  "Scalable" may be the word I'm looking for.  Twice as many events take only twice as much work, and maybe only 1.5 times as much.  Trying to coordinate more asynchronious events will bury you quickly.

Title: How to ease the maintenance of event driven code?

Body:
When using an event based component I often feel some pain at maintenance phase.

Since the executed code is all split around it can be quite hard to figure what will be all the code part that will be involved at runtime.

This can lead to subtle and hard to debug problems when someone adds some new event handlers.

Edit from comments:
Even with some good practices on-board, like having an application wide event bus and handlers delegating business to other part of the app, there is a moment when the code starts to become hard to read because there is a lot of registered handlers from many different places (especially true when there is a bus).

Then sequence diagram starts to look over complex, time spend to figure out what is happening is increasing and debugging session becomes messy (breakpoint on the handlers manager while iterating on handlers, especially joyful with async handler and some filtering on top of it).

//////////////

Example

I have a service that is retrieving some data on the server. On the client we have a basic component that is calling this service using a callback. To provide extension point to the users of the component and to avoid coupling between different components, we are firing some events: one before the query is sent, one when the answer is coming back and another one in case of a failure.
We have a basic set of handlers that are pre-registered which provide the default behavior of the component.

Now users of the component (and we are user of the component too) can add some handlers to perform some change on the behavior (modify the query, logs, data analysis, data filtering, data massaging, UI fancy animation, chain multiple sequential queries, whatever).
So some handlers must be executed before/after some others and they are registered from a lots of different entry point in the application.

After a while, it can happens that a dozen or more handlers are registered, and working with that can be tedious and hazardous.

This design emerged because using inheritance was starting to be a complete mess. The event system is used at a kind of composition where you don't know yet what will be your composites.

End of example

//////////////

So I'm wondering how other people are tackling this kind of code. Both when writing and reading it.

Do you have any methods or tools that let you write and maintain such code without to much pain ?


问:
A phone that supports any mobile OS
What is preventing hardware manufacturers from creating a device that will allow the user to select their OS? A phone similar to a PC or a mac that can have linux, windows or mac OS installed. Are there any regulations preventing this?</p>

答:
Therearen't be any regulations that prohibit this type of hardware from being developed. However, the developers of the mobile OS might not have any incentive to provide OS deployment support. Apple, for instance, prefers a closed ecosystem where their OS is used only on their own devices.

Even for those mobile operating systems where it is easier to port to various device types, such as Android, device manufacturers have a difficult time providing timely updates to users of existing devices.

In short, while users might benefit from this type of device, a lack of vendor support would likely doom this type of hardware to a niche existence.

Title: A phone that supports any mobile OS


答:
In a few words: Software companies' interests and lack of demand.

About the first reason:

Most software companies require that the phone covers some prerequisites, before allowing the vendor to install the OS on the phone. For example, the requirements for Windows Phone 7 can be found on Wikipedia: Windows Phone.

This excludes vendors who make their own software, like RIM (Blackberry) and Apple, but they consider their software as a competitive advantage and are not interested in providing their proprietary OS-es to other vendors.

In general, Android is the least problematic of the main operating systems: you can checkout it, compile and deploy it yourself (minus some proprietary Google Apps that come preinstalled on Android phones).

However, Windows has taken steps to become even more restrictive: Windows 8 for ARM (this is not Windows Phone 8) will not allow the user to install another OS by locking the boot loader

About the second reson:

Almost nobody would want such a phone. It would provide a bad user experience, because of the mashup of different OS-es, different UIs, different apps working on each OS, etc. It would be hard to learn since to use it would require knowledge of all operating systems installed to be utilized fully.

And nobody but the software developers or a few power users would need (or like) it. Therefore there are a few potential clients. On the other hand, developing a new phone is expensive, getting it certified by all major OS providers for compliance is expensive, too.

If a vendor tries to do this, the financial results would probably be devastating and the project would be deemed a huge failure.

Title: A phone that supports any mobile OS

Body: What is preventing hardware manufacturers from creating a device that will allow the user to select their OS? A phone similar to a PC or a mac that can have linux, windows or mac OS installed. Are there any regulations preventing this?</p>


答:
I'll focus on smartphones only, because if you include feature phones, then everything gets even more complicated.

Basically there are two kinds of operating systems for mobile devices

Operating systems built for a very specific set of devices where the developer of the OS also has specific control over the device. iOS is the primary example of this, but others exist as well (BlackBerry, for example).

Operating systems built to support a wide range of devices. Windows Phone and Android are good examples here. Even with those operating system the developers usually wish to restrict which hardware gets delivered with those OSs (to enforce a basic quality level, otherwise the OS brand would suffer).

Even Android (which everyone can just use and build a phone with) has some restrictions if you want to deliver the non-opensource Google applications with it (and you do want to do that, because otherwise people won't have the full experience, for example the Play Store is part of that suite).

So while one could technically build a phone that could run multiple OSes, it would be almost impossible to convince all OS developers to let you actually run their OS on your device.

Title: A phone that supports any mobile OS


答:
There's no legal way for a company to acquire licenses to iOS. For example, 'hackintoshes' are in violation of the OS X EULA. Apple doesn't go after individual users because it's not worth it, but, considering how litigious they are, it's hard to imagine them not going after a manufacturer that sold iOS clones. They seem to have legal precedent on their side, too (see the Psystar case).

A practical issue is that it's a lot of work to get drivers working for various devices on phones. Who's going to do the work to write iOS, Symbian, RIM, or Bada drivers for the hardware that's used in the phone? For example, the ICS android update still isn't available for my current phone, six months after the initial alpha build was leaked. The current leaked build is an improvement (it doesn't crash all the time), but the wireless still doesn't work, and even regular voice is somewhat buggy.

Title: A phone that supports any mobile OS


问:
What pattern to use for this 'constructor'? Decorator vs Factory?
I'm developing a program to generate LARP characters in java and I've hit a snag.

Initially I had planned to use a decorator to iterate through the potential 'roles' (effectively classes), and then from that work out the costs for each skill depending on the combination of roles and store that in the character. I.e you might be a Java Coder/Nerdfighter, if those are your two roles, or you might just have the SysAdmin role etc.

I then prototyped out a way to buy a skill that required looking up skills in a data base that contained their name and cost. Here is the snag: If I've preworked out the costs then I don't ever need to look up the database, so no changes in the db are pushed through (if the skill costs on a SysAdmin go down I'd like to know). As well as this, I may only buy a fraction of the available skills so I'll be storing unnecessary data on skill costs, and besides the character should only know about their skills, not all skills. More over, the decorator would only decorate the skill costs, nothing more.

Instead I feel I need a factory that has two options for constructing the character, something like:

```<code>public static CharacterFactory multiRolePlayerCharacter(Role firstRole, Role secondRole) {
    /*Some code goes here*/
}
public static CharacterFactory singleRolePlayerCharacter(Role role) {
    /*Some more code goes here*/
}
</code>```

But this seems far less extensible compared to the decorator. If the game ever changes so that you can multirole morethan twice (and Java Coder/Nerdfighter/SysAdmin is an allowed role) then I need to rework from the top to add a new factory in. Also I don't quite know how each factory differs besides perhaps a flag to say if it's multirole or not, and another variable to hold the secondRole. Which doesn't seem much.

So it seems either way I lose: Decorator adds extensibility for the long run whilst bogging my classes/objects down, and Factory will work to start with but will resist change.

So how do I know which one to pick? Is there some way to combine the two?

答:
You need a Character class that can hold a list of roles.  Add roles to the constructor (or whereever) using an array, so you're never limited.  You might even have an addRole method so you can add roles later.  (And remove them?  An aging Warrior might think seriously about becoming a Wizard, or even an Accountant.  Those swords get heavy when you're older.)  (Trivia note:  this is sometimes called "Dependency Injection".)

Handling a list of arbitrary length is a bit more difficult than handling just one item, but you know you have to do it.  Sometimes, there's really only three numbers, "zero", "one", and "many".  "Two" is really just "many".


问:
Dummy float values to force floating-point operations
It is common to use idioms such as:

```<code>x/60.0
</code>```

to force a floating-point division when x is an integer in languages which do not have distinct operators for integer and decimal division.

Is this an accepted idiom or is it preferrable to cast x to a floating-point type?

I believe it is a concise and clear idiom- it might be show intent less clearly than an explicit cast, but it is more concise and easier to read. I think that it's less hack-ish than x + "" to convert to string or x+0.0 to convert to floating point (as there's no unnecessary "NOOP").

Thoughts?

Álex

答:
The return result will be language specific based upon how the language handles implicit conversions.

That having been said, if your language of choice will support returning a float from that implicit conversion, then yes, your example is a pretty common way of triggering the float point arithmetic.  It's quick, clean, and clear.

Some languages will require the explicit cast, so the norm in those cases would obviously be the explicit cast.

Update:
Alex asked:

```
would you prefer x/60.0 or float(x)/60? Why?
```

And my preference is for the first, as this example will explain.  Please note that my comments are still targeted to languages that allow the implicit conversion.  Languages that require an explicit conversion are out of scope for the answer.

```
int x = 65;
float y = 0.0;

y = x / 10.0;  //will yield 6.5
```

vs.

```
int x = 65;
float y = 0.0;

y = (float) x / 10.0;  //will still yield 6.5
```

Why?

The implicit cast is what I would "expect" the code to be doing in the first place.  When I'm mentally performing the calculations prior to typing them out, my mind switches between Integers and Reals without worrying about it.  In this case, I expect the compiler to be able to do the same.

The explicit cast muddies up the code.  Reading it out loud, I get "y equals float x divided by 10" instead of just "y equals x divided by 10."  Inserting the explicit cast interrupts my pattern of thought while reading the code.

And while this may just be my guilty conscience, I always feel like I'm doing something wrong when I require an explicit cast.  I feel like I'm telling the compiler "You wouldn't normally do this because it's wrong, but I swear to you it's okay in this case.  Really, it is, just believe me, ok?"  (I agree, I could use some therapy on the issue).  The compiler should be smart enough to allow the conversion or throw an error when there is data loss.

Finally, when adding an unnecessary explicit cast there is a chance for introducing a bug later on in the code's life.  If one of the variable types changes, the explicit cast may allow something to compile that really should not have.  Granted, this is pretty rare but it can be very difficult to hunt down.

Body:
The return result will be language specific based upon how the language handles implicit conversions.

That having been said, if your language of choice will support returning a float from that implicit conversion, then yes, your example is a pretty common way of triggering the float point arithmetic.  It's quick, clean, and clear.

Some languages will require the explicit cast, so the norm in those cases would obviously be the explicit cast.

Update:
Alex asked:

would you prefer x/60.0 or float(x)/60? Why?

And my preference is for the first, as this example will explain.  Please note that my comments are still targeted to languages that allow the implicit conversion.  Languages that require an explicit conversion are out of scope for the answer.

int x = 65;
float y = 0.0;

y = x / 10.0;  //will yield 6.5

vs.

int x = 65;
float y = 0.0;

y = (float) x / 10.0;  //will still yield 6.5

Why?

The implicit cast is what I would "expect" the code to be doing in the first place.  When I'm mentally performing the calculations prior to typing them out, my mind switches between Integers and Reals without worrying about it.  In this case, I expect the compiler to be able to do the same.

The explicit cast muddies up the code.  Reading it out loud, I get "y equals float x divided by 10" instead of just "y equals x divided by 10."  Inserting the explicit cast interrupts my pattern of thought while reading the code.

And while this may just be my guilty conscience, I always feel like I'm doing something wrong when I require an explicit cast.  I feel like I'm telling the compiler "You wouldn't normally do this because it's wrong, but I swear to you it's okay in this case.  Really, it is, just believe me, ok?"  (I agree, I could use some therapy on the issue).  The compiler should be smart enough to allow the conversion or throw an error when there is data loss.

Finally, when adding an unnecessary explicit cast there is a chance for introducing a bug later on in the code's life.  If one of the variable types changes, the explicit cast may allow something to compile that really should not have.  Granted, this is pretty rare but it can be very difficult to hunt down.


问:
What techniques do you use when interviewing developers?
I realize there have been lots of discussions about this type of thing and they often devolve into dogma around whether you ask the "100 logical pirates" type of questions or whether you get them to write "fizz buzz".

I'm interested in what techniques and questions have been effective for you when interviewing potential developers for jobs.

One technique per answer so we can vote on them, please.

答:
Besides real technical questions, and typically at the end of the interview I try to get a grasp of their level of interest in the industry and it's culture with questions like:

Have you seen anything recently programming-related that you found interesting and would like to recommend to other fellow programmers? A new language, tool, platform, technique, website?

Can you name any well known person in our industry whose work you like or find inspiring and why? (developer, web site founder, author, speaker, etc)

What are you reading now or what was the last software related book you read?

What programming related sites do you frequent?

Although failing to answer these questions at all (sadly it happens very frequently) does not mean a 'no-hire' to me, they say a lot about the way a person approaches the software development profession.


问:
async & await - poll for alternatives
Now that we know what is in store for c#5, there is apparently still an opening for us to influence the choice of the two new keywords for 'Asynchrony' that were announced by Anders Heijsberg yesterday at PDC10.

```<code>async void ArchiveDocuments(List<Url> urls) {
    Task archive = null;
    for(int i = 0; i < urls.Count; ++i) {
        var document = await FetchAsync(urls[i]);
        if (archive != null)
            await archive;
        archive = ArchiveAsync(document);
    }
}
</code>```

Eric Lippert has an explanation of the choice of the current two keywords, and the way in which they have been misunderstood in usability studies. The comments have several other propositions.

Please - one suggestion per answer, duplicates will be nuked.

答:
It's worth noting that F# also uses the async keyword in its async workflows, which is pretty much the exact same thing as the new async functionality in C#5.  Therefore, I'd keep that one the same

For the await keyword in F#, they just use let! instead of let.  C# doesn't have the same assignment syntax, so they need something on the right side of the = sign.  As Benjol said, it functions the same as yield so it should almost be a variant of that.

ContentLicense: CC BY-SA 4.0

Title: async & await - poll for alternatives


问:
What is the most basic and simple platform for collaborative development (PHP project)?
I need to work with 4-5 programmers on a fairly average PHP application using codeigniter. We're in 5 different locations in one city, and all of the programmers are all not too well educated and I'm assuming that most of them have never used any version control system.

Can you recommend some very very easy-to-get-into platform for collaborating on a project like this? I'm talking about something that is only a tad more sophisticated than a shared dropbox folder.

答:
Well, there is no way out than to use version-control.

Dropbox does have sort of version-control, but I believe that if two people save a file, the newer version will just replace the older version, which is not desirable for version control during software development.

Svn is an easy to learn (at least easier than git) version-control system, and you can find various public repositories hosted online, but I would not recommend it for geographically distributed teams.

So the way to go for ditributed teams is git. If having your source public OR buying a private plan is not a problem, then create a repository on github, otherwise setup a local git repository.

May be you can find a GUI for git which might make it easier for these developers to start grasping a version-control system conceptually. For Windows its TortoiseGIT. I haven't used any git gui client for Linux or MAC, so I won't recommend one here.


问:
Is it better to find issues myself or let the computer figure it out?
I'm about to start the process of migrating a program from one component to another.  Most of the core functionality will be the same but I'll need to change database calls, etc.  I'm sure there will be a few quirks somewhere.

Naturally, there will be many errrrrrors, some of which Ill miss completely.  Would it be better to completely scrutinize the code, checking for errors line by line, or to just write the code and see what errors occur?

答:
Running the code is the way to go unless for some reason you can only run the code in a production environment.

As for checking for syntax and configuration errors, computer time is very cheap compared to programmer time.  Ideally you would have unit and integration tests to run that would check most of the code's validity for you.  If your code is modular enough, try writing tests before making changes to ensure that the code you're changing will work.

The problem with analysing code line by line is that you may read what you want to see, not what the code really does.  It is time consuming to execute all your code on paper to check for validity and you're likely to make a mistake or two.  And eventually you have to run the code anyways which will do a dozen checks for you very quickly.


答: Scrutinize the code. This is your opportunity to understand it, validate it, refactor it and write tests for it. Otherwise, you will be inheriting all of the problems with the original code.</p>

Title: Is it better to find issues myself or let the computer figure it out?

Body:
I'm about to start the process of migrating a program from one component to another.  Most of the core functionality will be the same but I'll need to change database calls, etc.  I'm sure there will be a few quirks somewhere.

Naturally, there will be many errrrrrors, some of which Ill miss completely.  Would it be better to completely scrutinize the code, checking for errors line by line, or to just write the code and see what errors occur?


答:
This is largely a business problem -- not a technical problem.  I've got an HTC HD2, which originally shipped with Windows Mobile 6.5 (ugh!).  I bought it, however, knowing that before it was even available in the US, hackers were already working on porting Android to it.  Since then, I've loaded a couple different versions of Android on it, and I know that there are builds for Windows Phone 7, too.  At one point, I was booting Windows 6.5 and has the option to launch Android off an image on my SD card -- effectively a dual-boot solution.

Obviously, there are some technical limitations -- there are hardware features in newer phones that mine doesn't support, and so on -- but the ability of this one piece of hardware to run multiple operating systems has been impressive, IMO.  As smartphones and their OS's have become more sophisticated, the abstractions between hardware and software have matured as well, which is one of the factors that allow this sort of multiple OS support.  It's my understanding that these abstraction layers are what really lay the groundwork for which hosts can run which OS's from a technical standpoint.

As others have indicated, Apple goes to great pains to ensure that their OS is used only on genuine Apple hardware.  This is a business decision first and foremost, though it's backed by the understanding that the more liberal they are in terms of hardware that can run iOS, the less control they've got over users' experiences with Apple.  The importance of that end-user experience hasn't been lost on other vendors, though, and I think very few vendors would see a whole lot of value in making users' experiences vastly more complicated by allowing them to boot into a variety of OS's.

The closest analog we've seen to that sort of "developer phone" right now was Google's Nexus phone, which was targeted specifically at developers.  Even that phone, though, was intended to run Android only, for obvious reasons.  Given the existence of emulators running in development IDE's, I suspect that multi-boot phones aren't a huge priority even for vendors wishing to target developers.

Title: A phone that supports any mobile OS


答:
It would be best to write unit tests defining the required behavior after migration.  After all the unit tests pass, then start integration testing.  If you find any bugs in integration testing, add a new unit test or modify an existing one to test the newly discovered requirement.

The effort of writing the units tests will insure that you at least define the requirements before proceeding with the migration.


答: Find a way to automate the search for errors. If you have automated tests, run them. If you know tables or stored procedures that changed, do a textual search for them by name. If the database is completely different, search for every database call. Identify classes of errors and figure out ways to find them.</p>


问:
How do I draft user stories as a developer?
I am writing a system where both the system owner and myself are developers, and we are currently the only source of 'requests' or requirements for the system, which I would like to capture in user stories tied to features{1}. My urgent priority now is to get a managaeble backlog captured. How should I go about capturing the level of technical spec I am used to to working with in users stories, which aren't supposed to be too technical.

{1} I am evaluating agile project management service TargetProcess, and each user story must be tied to a parent feature. The system seems a good fit, so this small constraint is something I would rather work with than work around.

答:
Focus on the what's and why's and avoid the how's when writing the user stories.

What you're faced with is actually a very good exercise for all developers.  Being able to express the requirement in simple, business terms is an important skill.

You should focus on the general requirement such as "need to be able to make a single selection from a drop-down listing of objects so the user can enable Foo action" instead of specifying using a combobox or listbox or whatever that triggers a specific routine.

Another way of approaching this is pretending like the underlying code base / framework is almost complete black box.  Any time you find yourself saying "use object XYZ", you can self-check by asking if you would know of that in a black box system.

Update:

IMO, it's okay to put details into a use case that indicate the level of detail required for information.  For example, with an enrollment system it's fair game to specify

- last name; required field

- first name; required field

- account ID; system generated no input necessary

- astrological sign; optional field - (suggestion) provide lookup from entering birthdate?

- etc....

The key is that you are not specifying the technical how for that information.  If you find yourself saying "use a String class / character array / or varchar field" for last name, then you know you are over-specifying.

If you're multi-lingual, then use two disparate languages as your litmus test.  For example, strings in C are generally char(acter) arrays whereas C++, Java, and C# (okay, and almost everyone else...) have an actual String like object.  If you find that your specification is invalidated by using one of those languages then you'll know you've over-specified.

It's worth noting that I'm specifically using the term Use Case as opposed to User Story, although the variant I end up using is a hybrid of both.  My goal of a use case is to give an overview of what's going on (a User Story in the strictest sense) but then work through the actors, systems, and general functionality that's required.  My approach is closer to what Fowler is suggesting in that wikipedia article as opposed to Cockburn's approach.

So I'll have a single use case (or so) for the enrollment scenario or work item.  If it's really complex, I would break it out into multiples, but that's not a big deal.  The use case can then be broken down into individual tasks as necessary.  What's tossed into a particular scrum depends upon lots of variables, but there's nothing within this approach that prevents you from having a demonstrable component at the end of the scrum.


答:
How about complete, as in "I want the task completed"?

```<code>Task<byte[]> downloadTask = DownloadFileAsync(url);
byte[] data = complete downloadTask;
</code>```

Title: async & await - poll for alternatives

Body:
Now that we know what is in store for c#5, there is apparently still an opening for us to influence the choice of the two new keywords for 'Asynchrony' that were announced by Anders Heijsberg yesterday at PDC10.

```<code>async void ArchiveDocuments(List<Url> urls) {
    Task archive = null;
    for(int i = 0; i < urls.Count; ++i) {
        var document = await FetchAsync(urls[i]);
        if (archive != null)
            await archive;
        archive = ArchiveAsync(document);
    }
}
</code>```

Eric Lippert has an explanation of the choice of the current two keywords, and the way in which they have been misunderstood in usability studies. The comments have several other propositions.

Please - one suggestion per answer, duplicates will be nuked.

Body:
How about complete, as in "I want the task completed"?

Task<byte[]> downloadTask = DownloadFileAsync(url);
byte[] data = complete downloadTask;


问:
Release Management versions control?
We recently experienced a deployment issue where it turned out that the version objects were not in sync in one of the environments.

We have a large database group and different teams have different responsibilities and ownerships - I might code on schema X, Y, Z but I also will have dependancies on objects owned by other groups. This is the same no matter what technology - java libraries having different versions and what not.

My aim is to have something be in a webpage or a database table or something that I can see that for object A I have version X installed in Production, X + 1 in UAT and QA, and X + 2 installed in DEV.

How do other folks handle this? How do you pick up version changes? Do you rely on SCM? Build numbers? Hash value of the source code?

I'm interested in managing version consistency across technologies - java to db for instance.

答:
I used to use a wiki page to keep track of such things, but no one kept it up.  The only way to make this work is to have the page run some code to figure out the answers for itself.  I started with some php code a coworker wrote, so I continued with PHP.  But just about any language you can run in a server can work.

The easiest thing would be to have a admin page in your application that lists all the information and then have a summary page (in a different app) that generates a line per installation.  The summary page gets all the information from the admin pages of your installations.  The only thing you have to update on the summary page is the urls to the installations.

Title: Release Management versions control?


答:
The typical story template is very easy to visualize:

```<code>As a [ROLE] I need to [WHAT] so that/because [WHY].
</code>```

The interesting thing is that the importance of the components are reversed.

WHY is more more important than WHAT and that is more important than ROLE

Example using this Question

As a Software Developer I need to learn how to write User Stories so that I can populate the backlog with drafts to get discussions of the
  features started and get points assigned to them.

Anything more is over complicating the intent and the implementation of User Stories.

Additional Tools ( Integration is best )

Tools can be used to capture additional detail information about the stories that is captured when discussing them to assign points/estimation, but that detail should not be part of the story itself. Something as simple as a Wiki with 1 Page per story to put details/transcripts of discussions on is a good enough solution. Excel spreadsheet is a terrible solution.

Title: How do I draft user stories as a developer?

Body:
I am writing a system where both the system owner and myself are developers, and we are currently the only source of 'requests' or requirements for the system, which I would like to capture in user stories tied to features{1}. My urgent priority now is to get a managaeble backlog captured. How should I go about capturing the level of technical spec I am used to to working with in users stories, which aren't supposed to be too technical.

{1} I am evaluating agile project management service TargetProcess, and each user story must be tied to a parent feature. The system seems a good fit, so this small constraint is something I would rather work with than work around.

Body:
The typical story template is very easy to visualize:

As a [ROLE] I need to [WHAT] so that/because [WHY].

The interesting thing is that the importance of the components are reversed.

WHY is more more important than WHAT and that is more important than ROLE

Example using this Question

As a Software Developer I need to learn how to write User Stories so that I can populate the backlog with drafts to get discussions of the
  features started and get points assigned to them.

Anything more is over complicating the intent and the implementation of User Stories.

Additional Tools ( Integration is best )

Tools can be used to capture additional detail information about the stories that is captured when discussing them to assign points/estimation, but that detail should not be part of the story itself. Something as simple as a Wiki with 1 Page per story to put details/transcripts of discussions on is a good enough solution. Excel spreadsheet is a terrible solution.


问:
Good examples for teaching software estimation (size, schedule, effort)?
I'm going to be teaching a class that covers a broad brush of estimation techniques. I intend to cover absolute estimation techniques based on SLOC (e.g. Function Points, COCOMO II etc.) and relativistic ones like T-shirt sizing, story-point estimation etc.

I was wondering what would be some good exercises to conduct in class to help understand the what, why and how of estimation. I hope to pique their interest with actual hands-on examples rather than death by powerpoint.

An example that was suggested by a colleague of mine was to bring a newspaper to class and ask them to estimate the number of words in the paper (for short papers or just a page for long ones). Since they can't absolutely count it, they'll be forced to come up with their own heuristics and they to take the lecture from there to help them gain insights into their own estimation technique.

Although a good example, it doesn't seem to link well with software estimation IMHO. I was wondering what would be some good examples for teaching software estimation w.r.t. size, schedule and effort estimations that they'll encounter in practice. I prefer practical examples that I can actually 'conduct in class' rather than 'just talk about it'.

UPDATE: To throw some more light on the structure of the class - Yes, I'll be covering the aspects of granularity i.e. at the RFP stage what's the best one could do. How can the estimate be refined when more is known about the problem (e.g. FPs after prototyping is done) and how story-points can be useful once you have a list of stories to go by Or how COCOMO like models based on SLOC count can be applied post architecture/design. I.e. narrowing the cone of uncertainty as you progress towards completion of the project. My aim is to elicit examples that the student teams can practice in class to get a better feel for the techniques and understand its ease of use (or difficulty) and the level of accuracy that can be obtained at that level of granularity and knowledge.

PS: If you are downvoting, I'd appreciate a comment highlighting the same. This is not a subjective question and rather non-trivial to teach in a hands-on manner and does have the possibility of selecting the 'best answer'

答:
Steve McConnell's Software Estimation: Demystifying the Black Art has a number of good examples presented through the book, some tied to a specific estimation methodology as well.

As an example, for presenting "count-compute-judge", he presents the problem of counting the number of people in a large conference hall. I believe it goes something like this, since I don't have the book in front of me right now. The counting technique involves individually counting all of the people in the room. Computing involves determining that each table was designed to hold five people, and many observable tables had about five people sitting at them, and then counting the number of tables in the room. Judgement was to look at the posted maximum capacity of the room and estimate the percentage of the room that was occupied, using that percentage and the maximum capacity.

He presents other examples, from both software and other estimates, to explain other estimation techniques. If you haven't read it, I'd highly recommend reading it before you teach the course. If possible, I'd even suggest it as the course textbook (or a recommended textbook).

Estimation is something that's difficult to teach though. It's one of those things that gets better with experience. However, unlike other things in the "you learn by doing" category, estimation requires you to not only do (as in perform the estimate) but then do what you estimated and track your estimates and actuals and discuss why there are differences.

Although McConnell's book will provide good examples of what it's like to use a number of good estimation techniques, I'd consider using projects in the course. Not only do different estimation techniques provide different levels of accuracy, but some also require a certain amount of historical data with regards to both estimates and actuals. As you progress through more and more projects, you'll gain more historical data while also giving students hands-on experience with using a particular estimation technique.

Depending on the experience level of the student, I might be more inclined to focus on teaching the techniques, when they are appropriate, and their advantages and disadvantages. This would especially be true for undergraduate students or even graduate students with limited professional experience. More experienced students with more large-scale projects under their belts can probably relate to their experiences more and will have a larger historical database of estimates and actuals to draw upon.


答:
You are on a right track

The version controlling is the way to go!
It will serve well to collaborate code sharing and help with integration. In addition, frequent check-in(s) are very important discipline that all team needs to practice.

However, choosing the right version control for your project is very important.

There is a recent nice post and answers to help you decide : What is a good toy example to teach version control?

Title: What is the most basic and simple platform for collaborative development (PHP project)?

Body:
I need to work with 4-5 programmers on a fairly average PHP application using codeigniter. We're in 5 different locations in one city, and all of the programmers are all not too well educated and I'm assuming that most of them have never used any version control system.

Can you recommend some very very easy-to-get-into platform for collaborating on a project like this? I'm talking about something that is only a tad more sophisticated than a shared dropbox folder.


答:
I added to comments on Eric's blog too, I don't see any issues with using the same keyword async

```<code>var data = async DownloadFileAsync(url);
</code>```

I'm just expressing that I want to download the file asynchronously. There's a bit of redundency here, "async" appears twice, because it's in the method name too. The compiler could be extra clever and detect the convention that methods ending in "Async" are infact async methods, and add that for us in the compiled code. So instead you might just wanna call

```<code>var data = async DownloadFile(url);
</code>```

as opposed to calling the synchronous one

```<code>var data = DownloadFile(url);
</code>```

Heck, we should also be able to define them the same way, since the async keyword is there in our declaration, why must we manually add "Async" to each method name - the compiler can do it for us.

Title: async & await - poll for alternatives

Body:
I added to comments on Eric's blog too, I don't see any issues with using the same keyword async

var data = async DownloadFileAsync(url);

I'm just expressing that I want to download the file asynchronously. There's a bit of redundency here, "async" appears twice, because it's in the method name too. The compiler could be extra clever and detect the convention that methods ending in "Async" are infact async methods, and add that for us in the compiled code. So instead you might just wanna call

var data = async DownloadFile(url);

as opposed to calling the synchronous one

var data = DownloadFile(url);

Heck, we should also be able to define them the same way, since the async keyword is there in our declaration, why must we manually add "Async" to each method name - the compiler can do it for us.


问:
What are some good ways for an experienced .NET client developer to start learning web development?
My background is as follows.  I've been programming since I was young, worked in BASIC, then Asm for M68K, then C, C++, and now I've spent the past 5 years in .NET becoming a rather good .NET developer.  Somewhere along the line, I realized I have no clue how the internet works, I don't know how TCP/IP works, I have no clue what HTML is capable of, or how PHP plays into the picture, or why Ruby on Rails should make me happy.  I have no experience with LAMP or IIS, and I only have an inkling of a clue what Sharepoint is.

In short: I'm internetstupid.  I am intelligent and a capable developer, but I lack even rudimentary skills (routing, web hosting, hosting a custom DNS for intranet domain resolving, etc.) I have no clue where to start on web development learning.

Here's the good news! I know what I'd like to learn to do (at least for now!)

I want to be able to develop my own personal domain to host WSDL services, to power my applications, to showcase my work, to host my living resume, to market my brand so to speak.

Stackoverflow, I beg you, help this disconnected but talented developer become part of the current era instead of being a relic stuck in the previous great golden age of software!

Note: I'd prefer to stay wedded to MS for now for the most part as I'm already familiar with the .NET ecosystem.  I'm okay branching out, but not ready to do so (I think?)  If you can convince me otherwise that's fine.

答:
Quick Answer: You may find everything that you look for in official ASP.NET  web-site.

It has always the latest information and tutorials.

For truly stateless web application development, you may start with asp.net mvc and you may create your services through asp.net api. All this suggestions are MS technology stack.

Note: However, you need to have a very good study/practice plan. Don't over-heat yourself. Try to understand inner-workings of each framework and build application one-step at a time.
Also analyzing the existing code-base of samples (like ASP.NET MVC sample applications) may help you once you know the fundamentals.


答: I suggest, that you start the class by giving them a very simple application that has 4 business processes or so. Ask them to do their estimate before learning any thing about the course, then use this application through the course and show how estimation techniques apply to it and where would someone go wrong. I guess what I am trying to say is have the class based on simple case study and apply the principles as you go and show how various factors and/or estimation techniques could give different results.</p>

Title: Good examples for teaching software estimation (size, schedule, effort)?

Body:
I'm going to be teaching a class that covers a broad brush of estimation techniques. I intend to cover absolute estimation techniques based on SLOC (e.g. Function Points, COCOMO II etc.) and relativistic ones like T-shirt sizing, story-point estimation etc.

I was wondering what would be some good exercises to conduct in class to help understand the what, why and how of estimation. I hope to pique their interest with actual hands-on examples rather than death by powerpoint.

An example that was suggested by a colleague of mine was to bring a newspaper to class and ask them to estimate the number of words in the paper (for short papers or just a page for long ones). Since they can't absolutely count it, they'll be forced to come up with their own heuristics and they to take the lecture from there to help them gain insights into their own estimation technique.

Although a good example, it doesn't seem to link well with software estimation IMHO. I was wondering what would be some good examples for teaching software estimation w.r.t. size, schedule and effort estimations that they'll encounter in practice. I prefer practical examples that I can actually 'conduct in class' rather than 'just talk about it'.

UPDATE: To throw some more light on the structure of the class - Yes, I'll be covering the aspects of granularity i.e. at the RFP stage what's the best one could do. How can the estimate be refined when more is known about the problem (e.g. FPs after prototyping is done) and how story-points can be useful once you have a list of stories to go by Or how COCOMO like models based on SLOC count can be applied post architecture/design. I.e. narrowing the cone of uncertainty as you progress towards completion of the project. My aim is to elicit examples that the student teams can practice in class to get a better feel for the techniques and understand its ease of use (or difficulty) and the level of accuracy that can be obtained at that level of granularity and knowledge.

PS: If you are downvoting, I'd appreciate a comment highlighting the same. This is not a subjective question and rather non-trivial to teach in a hands-on manner and does have the possibility of selecting the 'best answer'


问:
View Source - is the Viewable markup important to you?
I just read a very compelling blog post from Scott Hanselman where he quoted colleague Erik Meijer as follows:

JavaScript is an assembly language. The JavaScript + HTML generate is like a .NET assembly. The browser can execute it, but no human should really care what’s there. - Erik Meijer

He goes on to give examples of how some of today's biggest sites (the one he shows is from Google+, but cites also Bing, Facebook, etc.) are producing sites where when you do a "View Source", you will see a lot of tight "minified javascript".  Essentially, unreadable on the surface.

Simply put, you cannot go into a site and look at their source and see a pretty formatted version of the markup.  My question to you is similar to what Hanselman asks: is that important to you?  If it works, is that good enough?  In my opinion, YES - results are what matters - Google is an example of that.  But I must admit, as a developer, it is nice to have the ability to, once in a while, look at the source and get ideas and examples from sites I admire.

Your thoughts?...

答:
View source is useful for only two things.

Letting a developer debug certain issues.

Allowing the holier-than-thou types to pass judgement on a random site.

The ability to view a page source is really just a relic from an earlier time, it costs essentially nothing for browsers to support it and would probably be more work to delete it, so it stays.


问:
God Files versus Ravioli Code
Recently I asked a question about whether or not I should refactor my code. the responses I received were most definitely in the camp of going through with the refactoring due to the presence of a God File.

However, now I'm pushing towards what I fear is Ravioli code. I will have around 6-7 ".c" modules (which I find perfectly manageable), but I'm pushing in to having probably around 10~ ".h" headers.

I also still have about 8000 lines of code I need to parse through and refactor into their own parts and I'm not even sure how many more headers I'm going to need. I will probably be condensing and combining a few headers, but my question is:

What is worse from a software maintainability point of view, having potentially too many modules (making it difficult to find and change definitions) or averting previous problem by potentially having fewer files but have them be bloated with excessive functions? Is my problem inevitable due to the 12k+ lines of code? Or am I simply blowing the size of the system out of proportion?

答:
What is worse from a software maintainability point of view, having
  potentially too many modules (making it difficult to find and change
  definitions)

This really isn't a problem. Any decent IDE is going to be able to immediately take you from an invocation to a definition, or from a definition to a list of all invocations. Even if you don't use an IDE, any decent editor is going to provide support for ctags or a similar tool.

I'd say organize your code to emphasize it's logical structure and to enforce separation of concerns.

Title: God Files versus Ravioli Code


答:
There could be the cases when large files are preferable, most straightforward one being don't fix it while it ain't broken - 10K lines file that has no serious bugs reported against and no requests / plans to change may be well worth keeping alone.

Other than that, tie break in favor of things that occupy 2-3 or, better yet, 1 screen in your editor / IDE.

That leaves no chance for God files. 50 smaller files (by 50 lines each) may be difficult for code maintainer to find and change definitions but they at least could

list all 50 file names at one 1280x1024 screen and stare at these, and reason about these

show the contents of a particular 50-lines file at one screen and stare at it and reason about it

Guess what? maintainer could even experiment with merging 2-3 of such files into a bigger one to see if it improves understanding and even (magic!) split the merged files back if they find it's better to rollback.

As for the same amount of code - 50x50=2500 lines - even less than half of that - 1000 lines in a single file - there is no chance for maintainer to be able to stare at it and to reason about it.

One thing not to forget is that splitting code to smaller pieces won't automagically make it good.

One can have crappy code in 50 files by 50 lines each. Maintainer can look at particular 50 lines and realize these are crap. What maintainer can not though is to look at 1000 lines and realize anything - nothing at all.

50 files by 50 lines may be difficult but still manageable. 2500 lines are unmanageable and not just difficult - impossible to deal with.

Title: God Files versus Ravioli Code

Body:
Recently I asked a question about whether or not I should refactor my code. the responses I received were most definitely in the camp of going through with the refactoring due to the presence of a God File.

However, now I'm pushing towards what I fear is Ravioli code. I will have around 6-7 ".c" modules (which I find perfectly manageable), but I'm pushing in to having probably around 10~ ".h" headers.

I also still have about 8000 lines of code I need to parse through and refactor into their own parts and I'm not even sure how many more headers I'm going to need. I will probably be condensing and combining a few headers, but my question is:

What is worse from a software maintainability point of view, having potentially too many modules (making it difficult to find and change definitions) or averting previous problem by potentially having fewer files but have them be bloated with excessive functions? Is my problem inevitable due to the 12k+ lines of code? Or am I simply blowing the size of the system out of proportion?


问:
FizzBuzz - really?
When it comes to "interview test" questions, the subject of FizzBuzz often comes up. There is also a Coding Horror post about it.

Now, if you bother reading sites such as this, you are probably less likely to be in the demographic of programmers who would find FizzBuzz anything but trivial.

But is it really true that 99% of programmers will struggle with it?

Really?

What is the evidence to back this up?

Some real-life examples would be very helpful in answering this question.

答:
I hate to say this but

The main reason I've seen programming questions fail to get answered is the fault of the asker rather than the answerer.

I can clearly remember one interview where I was being asked how to create a particular collection search algorithm that would run in constant time (Same number of look ups regardless of how many items in the collection). I fumbled and bumbled on it for 20 minutes before giving up. It was then that this genius doing the interviewing proceeded to demonstrate the answer as being something that operated in nearly constant, but still not constant time. A bit like saying "Give me an answer of zero" and then accepting 0.1.

Short of it is that I've seen too many cases where someone interviewing is asking a question that fails to meet the following criteria:

They know all the possible correct answers.

They know why the correct answers are correct.

They know how to actually provide enough information without giving the answer away.

"Problem solving" questions do not rely on knowledge of an undisclosed fact (this is the biggest issue I've seen).

It would take less than 1 minute to write the answer if you didn't have to figure it out. If it would take 5 minutes just to type the code, it really requires more problem solving than can be fit into the verbal portion of the interview.

Questions are based on more than just "A problem I ran into once or I was given in school and so you should know how to solve it right now". I'm going to bet you had more than 2 minutes to answer it, why aren't you giving the candidate the same courtesy.

Seriously (1), I think asking people to write code in the verbal portion of an interview is stupid.

Seriously (2), I think interviewing people without asking them to write code is also stupid.

Seriously (3), You should either give them "homework", ask them to bring in code samples, or give them a laptop and couple of questions and quiet office to work on them. Then leave them alone while they work on them. I usually go with the latter approach as it limits their ability to get outside help (cheat) and I can time box it.

Title: FizzBuzz - really?


问:
Coding in 'core php' and separating logic from presentation
What are the various ways of acheiving this ? Can someone please guide me?

I have to code a website for a friend (designer). The friend wants me to use core php and not any framework like codeigniter (something I really like and am comfortable with !) .

I had a look at a couple of roll your own MVC frameworks guides, but am not sure if this is the ideal approach.  Since any solution I might come up with may have various bugs/security issues.
My goal is to use plain php , without the help of thirdparty frameworks, to code a site , where the logic is separate from the view .

Thanks

答:
The first question is - how big of a project is this? You say you are coding a "website" - but not what features you want. A "website" can be anything from a single page, through to a custom content management (like an image gallery), all the way to an e-commerce site and beyond. The project scope will have a definite impact on the answer to your question.

The second question - why does your friend not want to use third-party frameworks? Or is it a specific framework? Generally, frameworks are frowned on as "untrusted 3rd party" code - if this is the case, some education about where this framework is used and how it is managed could help. Another problem is the idea of "bloated" frameworks - the idea that they are stack full of functionality that will never be called on. Part of this is addressed in the scope question above, and part of this is addressed by picking a modular framework: code is only included when you need it, reducing "bloat". The last one is complexity: people can see frameworks as needlessly complicated - there is a learning curve when maintaining or extending. What they don't realise is, most frameworks are community developed (or at least, take a lot of direction from the community), and part of what the community wants is simplicity - so these frameworks get pared down over time.

So, that should address the perceived negatives of frameworks - there are also positives: community developed frameworks tend to be more secure, simply because a broader audience has reviewed and updated insecure code. Homegrown frameworks don't get anywhere near the same kind of auditing. Similarly, homegrown frameworks can easily become complex spaghetti code - again, because of this lack of broader auditing.

That all said - there are times when a framework is not necessary: a relatively simple site (say anywhere up to an image gallery or simple blog) could be written without a third-party framework. PHP Objects, Patterns and Practices discusses various patterns that can be used for "non-framework" solutions, like page controllers and so on.


答:
I agree with @ElYusubov that you should slow down just a bit.  It takes years to learn all the topics you mentioned.  Let's break your list down:

Internet Fundamentals: You can find out superficially how computer networking works by reading a little about the OSI model.

Now that you know how data travels from one computer to the another computer, you can read about how applications make use of that data.  For example, you may want to read about how a browser and a Web server communicates (e.g. using HTTP).  HTTP carries certain content that the Web server generates, and the browser consumes.  One such content is HTML.  There is a free video on PluralSight that talks about how IIS (since you prefer MS technology) and Internet Explorer communicate.

Next, you can watch more HTML videos that explore the more advanced concepts of what HTML(5) (Some of these videos are not free, and I haven't watched them).  There are plenty of books that talk about HTML5.

PHP (or rather, the PHP libraries), Ruby on Rails, ASP.NET, Java Spring Framework, etc. are all "frameworks" that help developers write Web applications.  If you prefer Microsoft technologies, the obvious choice is to deep dive into ASP.NET.  Microsoft Web site has many videos and books online on ASP.NET.  I like the book: Pro ASP.NET MVC Framework.

Let's forget about LAMP for the moment, since they are not part of the inner circle of Microsoft ecosystem.

Let's also wait on the Web Service part (WSDL).

Instead, you can write your "living resume" application!  You can start by going to the ASP.NET tutorial site.

Title: What are some good ways for an experienced .NET client developer to start learning web development?

Body:
My background is as follows.  I've been programming since I was young, worked in BASIC, then Asm for M68K, then C, C++, and now I've spent the past 5 years in .NET becoming a rather good .NET developer.  Somewhere along the line, I realized I have no clue how the internet works, I don't know how TCP/IP works, I have no clue what HTML is capable of, or how PHP plays into the picture, or why Ruby on Rails should make me happy.  I have no experience with LAMP or IIS, and I only have an inkling of a clue what Sharepoint is.

In short: I'm internetstupid.  I am intelligent and a capable developer, but I lack even rudimentary skills (routing, web hosting, hosting a custom DNS for intranet domain resolving, etc.) I have no clue where to start on web development learning.

Here's the good news! I know what I'd like to learn to do (at least for now!)

I want to be able to develop my own personal domain to host WSDL services, to power my applications, to showcase my work, to host my living resume, to market my brand so to speak.

Stackoverflow, I beg you, help this disconnected but talented developer become part of the current era instead of being a relic stuck in the previous great golden age of software!

Note: I'd prefer to stay wedded to MS for now for the most part as I'm already familiar with the .NET ecosystem.  I'm okay branching out, but not ready to do so (I think?)  If you can convince me otherwise that's fine.


问:
Managing Entity Framework at Enterprise Projects (with hundred of tables)
I am using Entity Framework at my work and faced some problems.

Usually I hear about creating tiny Edmx´s files containing tables related to some Domain ie.: Help Desk Edmx, HR Edmx, etc. Instead of load all tables in one big Edmx, what would be much simpler, but for performance considerations(at design and build time mainly), it isn´t feasible.

It took me to some troubles, first about the commom tables, ie.: Employees Tables, it is at all Edmx´s, conflicting when I use a Employee class reference and have a using to both namespaces, then I have to reference the Empoyee class by the full name MyCompany.HelpDesk.Employee.

It doesn´t look natural.

I find myself repeatedly adding the same tables at all EDMX´s, it´s a rework, and I spend some minutes adding a table to entity framework design since I have 2k tables at Add Table Dialog.

Maybe VS2012 could be a solution to load 2k Tables at the same Edmx file(since the designer could be splitted), but I don´t believe that, because it delay to compile too, not only to open the designer.

Another option could be the Code First, but it doesn´t have a decent tool to Reverse Engineer the database to classes, since it tries to load all the tables from database, tooking about 2 hours!

答:
Short Answer: it is common to have delayed response from EDMX Designer when dealing with more than 500 tables.

We had MVC project with EF4 ORM and while having less than 500 tables in our EDM, there were number of times when EF Model Designer just hang on model update. Thus, to minimize this unpleasant behavior we maximized the resources of desktop machine (RAM to 8GB and SSD), and closed all other applications while doing update on edmx file. So, we get a dedicated one developer machine for model updates done through refreshed DB schema.

I have also made re-search on topic and find some good posts that also had positive impact on performance of EF.

Performance and the Entity Framework, an article from CodeProject

Does the Entity Framework Designer optimize the underlying table design when creating the DB?

EDM Designer's Annoying "We'll do it for you"

Performance Considerations (Entity Framework)

Last but not least, according to recent news from EF team, there are numerious improvment in performance of EF4.3, howevet i personally did not play with it.


答:
I like yield until.  yield while, already suggested, is great and doesn't introduce any new keywords, but I think "until" captures the behavior a little better.

I think yield <something> is a great idea, because yield already captures the idea of making the rest of the method a continuation so well. Maybe someone can think of a better word than "until."

Title: async & await - poll for alternatives


问:
What is the best strategy for transforming unicode strings into filenames?
I have a bunch (thousands) of resources in an RDF/XML file.  I am writing a certain subset of the resources to files -- one file for each, and I'm using the resource's title property as the file name.  However, the titles are every day article, website, and blog post titles, so they contain characters unsafe for a URI (the necessary step for constructing a valid file path).  I know of the Jersey UriBuilder but I can't quite get it to work for my needs as I detailed in a different question on SO.

Some possibilities I have considered are:

Since each resource should also have an associated URL, I could try to use the name of the file on the server.  The down side of this is sometimes people don't name their content logically and I think the title of an article better reflects the content that will be in each text file.

Construct a white list of valid characters and parse the string myself defining substitutions for unsafe characters.  The downside of this is the result could be just as unreadable as the former solution because presumably the content creators went through a similar process when placing the files on their server.

Choose a more generic naming scheme, place the title in the text file along with the other attributes, and tell my boss to live with it.

So my question here is, what methods work well for dealing with a scenario where you need to construct file names out of strings with potentially unsafe characters?  Is there a solution that better fills out my constraints?

答:
I would suggest you use regular expression for this job, you can create regular expression which matches all valid characters like alphabets, number and some special charater (be sure to use all matches and not the first one only). This way you will remove all uinsafe character but this has its downside if you miss some safe character in you regex.
 Also you can replace unsafe characters which you know by safe character like '@'(not sure if its unsafe in your case) with '[AT]' this way meaning of name will also not be lost. </p>


答:
Choose a more generic naming scheme, place the title in the text file
  along with the other attributes, and tell my boss to live with it.

This will be the best solution, as not only do you have to deal with encoding and decoding the filenames, you have to deal with filenames that might be too long or not meet your filesystem limitations as well, depending on platform.

There is no real benefit in having huge, and now partially encoded filenames on the filesystem. They won't do you any good as a human trying to dig through them with ls. If you are already saving other attributes, the title of the resource is just that another attribute. Your storage solution should be the way you search for things, not the file system.

The titles of the resource and just that titles, metadata, anything else will be polluting your domain. Keep the attributes together, figure out how to full text search them in your storage layer and be done with it, then you can full text search all the attributes. The filesystem isn't a generalized database.

Title: What is the best strategy for transforming unicode strings into filenames?

Body:
I have a bunch (thousands) of resources in an RDF/XML file.  I am writing a certain subset of the resources to files -- one file for each, and I'm using the resource's title property as the file name.  However, the titles are every day article, website, and blog post titles, so they contain characters unsafe for a URI (the necessary step for constructing a valid file path).  I know of the Jersey UriBuilder but I can't quite get it to work for my needs as I detailed in a different question on SO.

Some possibilities I have considered are:

Since each resource should also have an associated URL, I could try to use the name of the file on the server.  The down side of this is sometimes people don't name their content logically and I think the title of an article better reflects the content that will be in each text file.

Construct a white list of valid characters and parse the string myself defining substitutions for unsafe characters.  The downside of this is the result could be just as unreadable as the former solution because presumably the content creators went through a similar process when placing the files on their server.

Choose a more generic naming scheme, place the title in the text file along with the other attributes, and tell my boss to live with it.

So my question here is, what methods work well for dealing with a scenario where you need to construct file names out of strings with potentially unsafe characters?  Is there a solution that better fills out my constraints?


问:
Post-hoc testing in TDD recommended?
I have a personal project that doesn't have robust testing. I had a bit of TDD going on at the beginning, but it quickly became counterproductive as the project details changed dramatically over time. So a lot of previously written tests have become useless.

Now that the project solidified a bit, I dont' think big changes are likely. Should I go back and rewrite those tests for old functionalities or just start fresh and write tests for new functionalities only?

答:
Whenever you want to modify an untested area, rewrite the tests for the small area your are modifying and then do your modifications.

This will allow you to rediscover/specify old code.

Title: Post-hoc testing in TDD recommended?


问:
What is a good design pattern / lib for iOS 5 to synchronize with a web service?
We are developing an iOS application that needs to synchronize with a remote server using web services. The existing web services have an "operations" style rather than REST (implemented in WCF but exposing JSON HTTP endpoints). We are unsure of how to structure the web services to best fit with iOS and would love some advice. We are also interested in how to manage the synchronization process within iOS.

Without going into detailed specifics, the application allows the user to estimate repair costs at a remote site. These costs are broken down by room and item. If the user has an internet connection this data can be sent back to the server.

Multiple photographs can be taken of each item, but they will be held in a separate queue, which sends when the connection is optimal (ideally wifi).

Our backend application controls the unique ids for each room and item. Thus, each time we send these costs to the server, the server echoes the central database ids back, thus, that they can be synchronized in the mobile app. I have simplified this a little, since the operations contract is actually much larger, but I just want to illustrate the basic requirements without complicating matters.

Firstly, the web service architecture: We currently have two operations: GetCosts and UpdateCosts.

My assumption is that if we used a strict REST architecture we would need to break our single web service operations into multiple smaller services. This would make the services much more chatty and we would also have to guarantee a delivery order from the app. For example, we need to make sure that containing rooms are added before the item.

Although this seems much more RESTful, our perception is that these extra calls are expensive connections (security checks, database calls, etc). Does the type of web api (operation over service focus) determine chunky vs chatty? Since this is mobile (3G), are we better handling lots of smaller messages, or a few large ones?

Secondly, the iOS side. What is the current advice on how to manage data synchronization within the iOS (5) app itself. We need multiple queues and we need to guarantee delivery order in each queue (and technically, ordering between queues). The server needs to control unique ids and other properties and echo them back to the application. The application then needs to update an internal database and when re-updating, make sure the correct ids are available in the update message (essentially multiple inserts and updates in one call).

Our backend has a ton of business logic operating on these cost estimates. We don't want any of this in the app itself.

Currently the iOS app sends the cost data, and then the server echoes that data back with populated ids (and other data). The existing cost data is deleted and the echoed response data is added to the client database on the device. This is causing us problems, because any photos might not have been sent, but the original entity tree has been removed and replaced. Obviously updating the costs tree rather than replacing it would remove this problem, but I'm not sure if there are any nice xcode libraries out there to do such things.

I welcome any advice you might have.

答:
On mobile based device Andriod/iOS limiting bandwidth is key. We used WCF JSON (if I was doing it now would use WebAPI MVC4) and Msmq to ensure message delivery. Server pushes data to mobile device by placing into a Msmq. Wcf always reads from Msmq for any requests
Mobile device stores data in SQLite and uses local queue to send and relieve data.

I am not familiar with IOS but I assume local data store can be used as a queue


问:
What non-programming books should a programmer read to help develop programming/thinking skills?
There are a lot of questions about what programming books should be on the programmer's bookshelf. How about non-programming related books that can help you become a better programmer or developer? It would also be interesting to know why they would help.

My first choice would be Sun Tzu's "Art of War" (however cliché), because it made it obvious that the success of any project depends on the strength of its weakest link (and warfare is a big project).

答:
Cryptonomicon:

Recommended for the morale boost.  :)


问:
Keeping "historical" migrations in Django-south
After a system has gone through many migrations, and evolved enough for a second version, does it make sense to keep the old migrations around? I mean, old versions will use them to upgrade to the new one, sure, but should a fresh install have its database go through all the "historical" changes before arriving at the current shape? My gut feeling is that a fresh install should create the database "as it is", not go through every mistake that was made in the product lifecycle until reaching a stable condition.

I've recently asked a question on SO about splitting a django app into multiple ones. Problem is: after I've done that I'll never be able to remove the old app, since the other ones' past migrations still refer to it, and would break without it, even if the current version of my project does not use it anymore. OTOH if I "rewrote the history" in a major update I could pretend that the broken app never existed in the first place, which I believe would make the code cleaner (past revisions would still exist in version control though).

The above scenario is just an example, but I'm interested in arguments about the general case: have fresh installs create the database as it is, or go through every migration ever done in the product lifecycle?

答: Yes, it's a good idea to clean up migration history. Having numerous migrations is really error prone. So it's good idea to make the current state of your servers into the new initial migration. </p>


问:
Using empty subclasses to add to the semantics of a class hierarchy?
I was wondering whether using (almost) empty derived classes to give additional semantics to a class hierarchy was a good idea (or practice) ?

Because a (not so short) example is always better than a long speech, let's assume we're writing a class hierarchy for SQL generation. You want to represent a data manipulation command (INSERT, UPDATE or DELETE), so you have two alternatives :

First version, with switch statement

```<code>enum CommandType {
    Insert,
    Update,
    Delete
}

class SqlCommand {
    String TableName { get; }
    String SchemaName { get; }
    CommandType CommandType { get; }
    IEnumerable<string> Columns { get; }
    // ... and so on
}

class SqlGenerator  {
    string GenerateSQLFor(SqlCommand command)
    {
        switch (command.CommandType)
        {
            case CommandType.Insert:
                return generateInsertCommand(command);
            case CommandType.Update:
                return generateUpdateCommand(command);
            case CommandType.Delete:
                return generateDeleteCommand(command);
            default:
                throw new NotSupportedException();
        }
    }
}
</code>```

Second version with VisitorPattern (Note that the question is NOT about whether the Visitor pattern should be used or adding new operations)

```<code>abstract class SqlCommand {
    String TableName { get; }
    String SchemaName { get; }
    IEnumerable<string> Columns { get; }
    // ... and so on
    abstract void Accept(SqlCommandVisitor visitor);
}

class InsertCommand : SqlCommand
{
    overrides void Accept(SqlCommandVisitor visitor)
    {
        visitor.VisitInsertCommand(this);
    }
}

class DeleteCommand : SqlCommand
{
    overrides void Accept(SqlCommandVisitor visitor)
    {
        visitor.VisitDeleteCommand(this);
    }
}

class SqlCommandVisitor  {
    void InitStringBuffer() { ... }
    string GetStringBuffer() { ... }

    string GenerateSQLFor(SqlCommand command)
    {
        InitStringBuffer();
        command.Accept(this);
        return GetStringBuffer();
    }

    void Visit(SqlCommand command) { ... }
    void VisitInsertCommand(InsertCommand command) { ... }
    void VisitDeleteCommand(DeleteCommand command) { ... }
    void VisitUpdateCommand(UpdateCommand command) { ... }
}
</code>```

With both examples we achieve the same result, but :

In the first version, my code feels more DRY, even though polymorphism is generally preferable over a switch statement.

In the second version, I feel like I'm needlessly deriving SqlCommand just so that the code carries more meaning.

Another similar case is deriving a class from a generic class, just to give additionnal meaning to the collection, eg :

```<code>class CustomerList : List<Customer> { }
</code>```

I'm left off wondering whether this is a good idea. Are there any pitfalls to doing so ?

I personally prefer the second version exactly because it adds meaning to the code, and helps me when I read my code later... But I clearly lack the experience to see any downside to this pattern.

答:
No, it's not a good practice in general.

Any time you encode information into the type system, you're doing it wrong (in mainstream languages like C++, java, and C#). It then requires you to use a visitor pattern, or a pile of type checks to extract that information which is fragile at best.

Further, in the mainstream languages it makes it very awkward to store/change that information. If you for example wanted to execute a command entered by the user in some SQL IDE.

In short, if you are storing information - just use a variable; that's what they're there for.


答:
I prefer the first one, but maybe that's just me - I like DRY, and like keeping things simple, and there's nothing simpler than a switch statement for this. (I always think that, unless you have a good reason to refactor the switch into a polymorphic class, this refactoring is mainly to show off how clever code can be).

You are writing a lot more code to achieve the same result, and that requires a lot of cut and paste - and I find c&p coding is one place that bugs are more likely to appear. I also think trying to read the code is more difficult as it skips through  all those classes and methods. But ultimately, its just down to taste - they both do the same thing.

For your second question.. it depends, once you derive from a class you're responsible for checking all the plumbing works. For example, you do not derive from stl container classes because they don't have virtual destructors, and thus are not designed for inheritance. Unless you know the potential pitfalls of the class you're inheriting from, its much safer to contain the base class.

The other reason is just semantics, a CustomerList is not a List of Customers, so someone reading your code would have to think "is this the same as a List<> or have they modified the functionality?" If you do not make any modifications, then leave it as the underlying type, or use a typedef/using statement that at least just says "I've renamed this for readability only".

Title: Using empty subclasses to add to the semantics of a class hierarchy?

Body:
I was wondering whether using (almost) empty derived classes to give additional semantics to a class hierarchy was a good idea (or practice) ?

Because a (not so short) example is always better than a long speech, let's assume we're writing a class hierarchy for SQL generation. You want to represent a data manipulation command (INSERT, UPDATE or DELETE), so you have two alternatives :

First version, with switch statement

```<code>enum CommandType {
    Insert,
    Update,
    Delete
}

class SqlCommand {
    String TableName { get; }
    String SchemaName { get; }
    CommandType CommandType { get; }
    IEnumerable<string> Columns { get; }
    // ... and so on
}

class SqlGenerator  {
    string GenerateSQLFor(SqlCommand command)
    {
        switch (command.CommandType)
        {
            case CommandType.Insert:
                return generateInsertCommand(command);
            case CommandType.Update:
                return generateUpdateCommand(command);
            case CommandType.Delete:
                return generateDeleteCommand(command);
            default:
                throw new NotSupportedException();
        }
    }
}
</code>```

Second version with VisitorPattern (Note that the question is NOT about whether the Visitor pattern should be used or adding new operations)

```<code>abstract class SqlCommand {
    String TableName { get; }
    String SchemaName { get; }
    IEnumerable<string> Columns { get; }
    // ... and so on
    abstract void Accept(SqlCommandVisitor visitor);
}

class InsertCommand : SqlCommand
{
    overrides void Accept(SqlCommandVisitor visitor)
    {
        visitor.VisitInsertCommand(this);
    }
}

class DeleteCommand : SqlCommand
{
    overrides void Accept(SqlCommandVisitor visitor)
    {
        visitor.VisitDeleteCommand(this);
    }
}

class SqlCommandVisitor  {
    void InitStringBuffer() { ... }
    string GetStringBuffer() { ... }

    string GenerateSQLFor(SqlCommand command)
    {
        InitStringBuffer();
        command.Accept(this);
        return GetStringBuffer();
    }

    void Visit(SqlCommand command) { ... }
    void VisitInsertCommand(InsertCommand command) { ... }
    void VisitDeleteCommand(DeleteCommand command) { ... }
    void VisitUpdateCommand(UpdateCommand command) { ... }
}
</code>```

With both examples we achieve the same result, but :

In the first version, my code feels more DRY, even though polymorphism is generally preferable over a switch statement.

In the second version, I feel like I'm needlessly deriving SqlCommand just so that the code carries more meaning.

Another similar case is deriving a class from a generic class, just to give additionnal meaning to the collection, eg :

```<code>class CustomerList : List<Customer> { }
</code>```

I'm left off wondering whether this is a good idea. Are there any pitfalls to doing so ?

I personally prefer the second version exactly because it adds meaning to the code, and helps me when I read my code later... But I clearly lack the experience to see any downside to this pattern.


答:
The downside to having more classes in the hierarchy is that when you have to debug things it's that much more complicated to figure out what's going on. The deeper your class hierarchy, and the more levels that have actual code, the harder it is to understand the code when debugging (because you always have to be mindful of where you are in the call chain at any point, and what actual object you are, etc, etc).

The real question is: Does this make your code overall more readable? If you'll only have that switch statement in one spot, then I'd say it's a win. Whereas, if you'd otherwise end up duplicating that switch statement all over the place, then the second form is probably a win.


答:
As long as the old tests were good and the business rules they cover are still valid then they are worth revisiting.  Hopefully it just takes a few alterations to those tests.  The most important thing is all the business rules are covered in tests, whether the business rules are considered "old" or "new".

Unfortunately, going back and doing this in bulk is going to take a bit of time.  But in the end it will be worth it.  Because in the end, the number of bugs found should be much much less.  Hopefully you don't fall into this same pit again.  A lot of people who do TDD tend to skip fixing tests when they are in a crunch or there are major changes.  But I think that is more counter-productive, because you aren't sure what the effects of changing a particular module will have, and you could end up with even more bugs.  Tests should be treated as another consumer of your code, and should be treated in the same category as say the user interface.

Title: Post-hoc testing in TDD recommended?

Body:
I have a personal project that doesn't have robust testing. I had a bit of TDD going on at the beginning, but it quickly became counterproductive as the project details changed dramatically over time. So a lot of previously written tests have become useless.

Now that the project solidified a bit, I dont' think big changes are likely. Should I go back and rewrite those tests for old functionalities or just start fresh and write tests for new functionalities only?


答:
There are solutions:

Chrome supports prettifying the javascript sources in the inspector. I'm sure the other browsers have similar abilities. http://cristian-radulescu.ro/article/pretty-print-javascript-with-google-chrome.html

Chrome also supports "source maps". These will eventually ensure that in the debugger you can view the original sources, while what your browser is executing is cross-compiled and minified. http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/

So I think it's a temporary problem that will get solved when IDE's and minifiers automatically start generating source maps in all cases. Then it will be a conscious decision of the developer to not upload the source map. View source will be the default again.

Title: View Source - is the Viewable markup important to you?

Body:
I just read a very compelling blog post from Scott Hanselman where he quoted colleague Erik Meijer as follows:

JavaScript is an assembly language. The JavaScript + HTML generate is like a .NET assembly. The browser can execute it, but no human should really care what’s there. - Erik Meijer

He goes on to give examples of how some of today's biggest sites (the one he shows is from Google+, but cites also Bing, Facebook, etc.) are producing sites where when you do a "View Source", you will see a lot of tight "minified javascript".  Essentially, unreadable on the surface.

Simply put, you cannot go into a site and look at their source and see a pretty formatted version of the markup.  My question to you is similar to what Hanselman asks: is that important to you?  If it works, is that good enough?  In my opinion, YES - results are what matters - Google is an example of that.  But I must admit, as a developer, it is nice to have the ability to, once in a while, look at the source and get ideas and examples from sites I admire.

Your thoughts?...


答:
I personally think you should treat this situation as if the old code was "legacy" (as in Feathers' book "Working with Legacy Code") and go on from that point.

That mean, redesign all "solidified" but untested parts, one at a time, tests-first. Maybe some parts get new. simpler, implementation, maybe not at all since the existing one is fine.

But it is just a feeling, I wasn't in a similar situation yet.

Title: Post-hoc testing in TDD recommended?