答:
All a thread does is interleave operations so that parts of the process appear to overlap in time.  A single-core machine with multiple threads merely jumps around: it executes small bits of code from one thread, then switches to another thread.  A simple scheduler decides which thread is highest priority and is actually executed in the core.

On a single-core computer, nothing actually happens "at the same time".  It's all just interleaved execution.

There are many, many ways to achieve interleaving.  Many.

Let's say you have a simple two-threaded process that uses a simple lock so that both threads can write to a common variable.  You have six blocks of code.

T1-before lock

T1-with lock

T1-after lock

T2-before lock

T2-with lock

T2-after lock

[This can be in a loop or have more locks or whatever.  All it does is get longer, not more complex.]

The steps of T1 must run in order (T1-before, T1-with, T1-after) and the steps of T2 must run in order (T2-before, T2-with, T2-after).

Other than the "in-order" constraint, these can be interleaved in any way.  Any way.  They could be run as listed above.  Another valid ordering is (T1-before, T2-before, T2-lock, T1-lock, T2-after, T1-after).  There are a lot of valid orderings.

Wait.

This is just a state machine with six states.

It's a non-deterministic finite state automata.  The ordering of T1-xxx states with T2-xxx states is indeterminate, and doesn't matter.  So there are places where the "next state" is a coin toss.

For example, when the FSM starts, T1-before or T2-before are both legitimate first states.  Toss a coin.

Let's say it came up T1-before.  Do that.  When that's done, there is a choice between T1-with and T2-before.  Toss a coin.

At each step in the FSM there will be two choices (two threads -- two choices) and a coin toss can determine which specific state is followed.

Title: State machines vs threads

Body:
Alan Cox once said "A Computer is a state machine. Threads are for people who can't program state machines".

Since asking Alan directly is not an option for humble me, I'd rather ask here:  how does one achieve multi-threading functionality in high-level language, such as Java, using only one thread and state machine? For example, what if there are 2 activities to perform (doing calculations and doing I/O) and one activity can block?

Is using "state-machine only" way viable alternative to multi-threading in high-level languages?


问:
What are the consequences of still sticking with Windows XP despite there are Windows Vista, 7 and very soon 8?
From a .Net programmer perspective, what are the consequences of still sticking with Windows XP despite there are Windows Vista, 7 and very soon 8? How does having windows XP limit programmers development in .Net platform?</p>

答:
Support.  That's what will be removed by Microsoft.

Most likely, the lack of security updates will become a (larger) problem.

ContentLicense: CC BY-SA 3.0


答:
The latest .NET frameworks will not run on windows XP, nor would Visual Studio 2011 be a supported option (it will probably work, but if you have problems, you are on your own).

You will not be able to create any metro applications as WinRT will also not be part of XP, ever (there is no way MS would backport a whole new OS API to an unsupported OS).

Title: What are the consequences of still sticking with Windows XP despite there are Windows Vista, 7 and very soon 8?

Body: From a .Net programmer perspective, what are the consequences of still sticking with Windows XP despite there are Windows Vista, 7 and very soon 8? How does having windows XP limit programmers development in .Net platform?</p>


问:
Java/C# - When should AOT be considered if reverse engineering is a concern?
Long and short is really in the question title.  For a language which compiles to an intermediate language like MSIL or Java byte-code, if there's concern about something like reverse engineering or hacking to disable security features, should AOT (ahead of time) compilation be considered rather than just obfuscation?  Obviously, there's a bit of wiggle room in this question as there's no one answer I wouldn't imagine, but when would you start looking at performing an AOT compilation before distributing something versus sending it out obfuscated?

For anyone that stumbles across this and isn't familiar:

Wikipedia Entry on AOT Compilers:  http://en.wikipedia.org/wiki/AOT_compiler

Mono AOT Compiler feature:  http://www.mono-project.com/AOT

答:
Its my understanding that .NET assemblies (and, I assume java .class files, too) include a hash value of some sort. If the hash value fails when the .class or assembly is loaded then, I believe, its rejected and an exception is thrown. So, if someone did decide to take a hex editor to an assembly or .class file, they'd have to know how the hash value was calculated and update that part of the file with the correct value as well.

In addition, .NET assemblies can also be Strongly Named which can also help in ensuring an assemblies integrity and provenance.


问:
How important is multithreading in the current software industry?
I have close to 3 years experience writing web applications in Java using MVC frameworks (like struts). I have never written multithreaded code till now though I have written code for major retail chains.

I get a few questions on multithreading during interviews and I answer them usually (mostly simple questions). This left me wondering how important is Multithreading in the current industry scenario ?

答:
Historically people had to struggle by doing multithreaded programming by hand. They had to work with all of the core components (threads, semaphores, mutexes, locks, etc.) directly.

All these efforts resulted in applications that were able to scale by adding additional cpus to a single system. This vertical scalability is limited by "whats the biggest server I can buy".

Nowadays I see a shift towards using more frameworks and different design models for software design. MapReduce is one such model which is focused towards batch processing.

The goal is scaling horizontally. Adding more standard servers instead of buying bigger servers.

That said the fact remains that really understanding multithreaded programming is very important. I've been in the situation where someone created a race condition and didn't even know what a race condition is until we noticed strange errors during testing.


答:
Security - XP had some huge ingraned security flaws that were fixed by longhorn. XP was written before the internet or viruses became as big as they are now

Productivity - Simple things like having a searchable task bar save you a couple of seconds every time you need to launch a new application.


问:
State machines vs threads
Alan Cox once said "A Computer is a state machine. Threads are for people who can't program state machines".

Since asking Alan directly is not an option for humble me, I'd rather ask here:  how does one achieve multi-threading functionality in high-level language, such as Java, using only one thread and state machine? For example, what if there are 2 activities to perform (doing calculations and doing I/O) and one activity can block?

Is using "state-machine only" way viable alternative to multi-threading in high-level languages?

答:
Writing blocking functions is for people who can't create state machines ;)

Threads are useful if you can't get around blocking. No fundamental computer activity is truly blocking, it's just that lots of them are implemented that way for ease of use. Instead of returning a character or "read failed", a read function blocks until the whole buffer is read. Instead of checking for return message in a queue, and returning if none is found, a connect function waits for reply.

You can't use blocking functions in a state machine (at least one that can't be allowed to "freeze").

And yes, using state machine is a viable alternative. In Real Time systems, this is the only option, the system providing a framework for the machine. Using threads and blocking functions is just "the easy way out", because usually one call to a blocking function replaces about 3-4 states in the state machine.

Title: State machines vs threads


答:
Your question raises a few questions of its own. What hardware do you have at the moment? Do you have any desire or ability (financial primarily) to upgrade? What are you coding as a hobbyist, games? Web sites? utilities?

Windows 7 is a worthy upgrade to Windows XP simply because you can happily run with more than 3 GB of memory. In use it's nicer than XP, a good incremental improvement. On the development side, well IE9 is Windows 7 or above only, so if you're doing ASP.NET stuff that could be a consideration. It runs happily on everything I've put it on, so I have it on Netbooks with ickle processors and 1 GB right through to 12 GB i7 based desktops. Generally I think it's a worthy upgrade you'd like, but it doesn't affect you too much as a developer unless you want the latest and greatest.

Windows 8 is still a year away, but you can download the developer preview which includes an early version of Visual Studio Express 2012. You can download that and install it in VirtualBox (didn't work for me in vmware, didn't try virtual PC). It will give you an idea of where they are going. Windows 8 is different, the whole operating system stack is different from WinRT through to Metro apps. It will still run legacy (I.e. your stuff) though.

I've tried to include some extra information that doesn't directly answer your question but might help you ask a different question. It really depends on what you're developing. For info, I'm at work at the moment using Visual Studio 2010 on an XP machine. The Windows 7 roll out will happen over the next 12 months or so at least and we're actually ahead of a lot of similar companies (banks). My neighbour's PC uses XP and she has no reason to upgrade. I installed Chrome which she now uses instead of IE and suddenly the machine is "10 times faster, what did you do you amazing person you!" etc etc.


答:
If you're a software developer (vs. web developer), you may have another concern: Windows XP is old, it has an old UI, not a very good user experience, etc.

<tl-dr>

People are usually inspired by the software they use when creating their own. For example when it comes to designers, most very bad web designers I knew were using more often the very bad quality websites, not the professional ones. The ones who used for example Stack Exchange websites regularly used to do a more professional user-friendly websites design. The ones who used websites like Apple.com had the best designs. In the same way, a person who never used a touch screen will not think at optimizing his application for touch.

</tl-dr>

As a result, if you still use Windows XP and no other operating systems, you may have a risk to start creating Windows XP style applications from the visual design point of view which, in 2011, is not appreciated too much.

You can of course reduce this risk by either use regularly other operating systems (for example Windows XP at home and the latest MacOS at work), or be always up-to-date about how the new software is done, including by watching webcasts.


问:
How to set up for selective pushing with Mercurial?
I have a situation, when I'm working on a project, but at same time small issues arise which require quick fix. I would like to push just the fixes for these problems to the main repo while keeping the rest locally. Problem is that, as I've already found out, it's not possible to cherry pick changsets when pushing from my repository upwards.

So the question is, how to set up my Hg environment to have such a possibility. I want to preserve all the Hg metadata, so sending patches around is not a option.

BTW, if the whole thing can be managed directly from MercurialEclipse, that would be a big plus.

答:
Mercurial Queues is the easiest and fastest way:
1. You have not create (and work with) additional (even local) clone
2. You have all non-bugfix changes stored only locally (in your repo)

Another solutions (acceptable) can be
- Named branches (for "work-in-progress");
- LocalBranch extension.


问:
Unit testing methods that call suppliers webservices
I have a class with one public method Send() and a few private methods. It calls a couple of webservices and processes the reponse. The processing is done in private methods.

I want to unit test the code. My understanding is that unit tests should test my code in isolation (ie mock up supplier responses).

I also believe that private methods should not need to be unit tested But if I just test the Send() method my code isnt being tested in isolation and is dependent on the supplier resonse.

Should I then make my private methods public so I can test them with mock responses? It seems bad practice since I only the class should need to call them.

Apologies if its a basic question, im fairly new to unit testing.

Im using c# and VS2010

答: I think a test with such dependencies (calling suppliers webservices) is an integration test rather than a unit test.


答:
As others have stated, if your unit tests have external dependencies like web services or database calls then they are NOT unit tests at all, they are integration tests.

True unit tests can run independently of outside components aside from the component they are intended to test and should be repeatable regardless of environment.  If the outside web services go down, your unit test should not fail.

We get around this by using a Mocking Framework.  Mock objects allow us to create a mock of a component so that the component in our unit test uses these mock objects instead of real ones.  We can inject mock objects into the testable component, and specify what argument(s) we are expecting, what we would like it to return when it is called, even what exception we would like it to throw.  I highly recommend reading more on the subject as it will improve the reliability and independence of your unit tests.

For a good post on different C# mocking frameworks see the following SO thread:

https://stackoverflow.com/questions/37359/what-c-mocking-framework-to-use

EDIT:  For the overtly sensitive, I will own that I did neglect to mention DbUnit or other transactional tools that can rollback database changes at the end of the test.  These are also repeatable and can be environment agnostic with generated test data thus a Mocking Framework is not needed in this case.

Title: Unit testing methods that call suppliers webservices

Body:
I have a class with one public method Send() and a few private methods. It calls a couple of webservices and processes the reponse. The processing is done in private methods.

I want to unit test the code. My understanding is that unit tests should test my code in isolation (ie mock up supplier responses).

I also believe that private methods should not need to be unit tested But if I just test the Send() method my code isnt being tested in isolation and is dependent on the supplier resonse.

Should I then make my private methods public so I can test them with mock responses? It seems bad practice since I only the class should need to call them.

Apologies if its a basic question, im fairly new to unit testing.

Im using c# and VS2010


问:
How do you respond to "Tell me a little bit about yourself." question in interviews?
I've been asked this in a few interviews. And it always catches me off guard.My professional and academic background are already in the resumé, which the interviewer has obviously looked at. What more to tell him/her? Should I start with my hobbies? I like gardening, or looking at NSFW pictures on reddit in my free time?

What and how do you answer to this specific question? Do you have a prepared answer for it? Am I wrong if I think this question is a bit silly?

UPDATE There have been a lot of great answers to this question. I'm in pickle which to choose as the 'correct' answer, because most of them are very insightful. I found a great writing on this subject matter. It's a bit crazy for my taste, but it's interesting:

How To Introduce Yourself… I Mean Practically

答:
Here's how I answered on career overflow:

This question is a chance to summarize your resume and point out the things you think are important. "I'm a ..." what noun phrase would you put there? "... with ... " what attributes or background are important to you? "... who has been ... " how would you describe what you've been doing lately, for better or worse? "... and wants to ... " what do you want, anyway? Done right you tell them why you are a great hire, why you are changing jobs, and what questions to ask next all in a few sentences.

So,

"I'm a new Computer Science grad who's managed to get 3 years of paid software development experience while earning this degree, and has seen enough different kinds of companies to know that I want to work at a place like this, that uses [technology or methodology] and [something else important like is making the world a better place or is impressive to my friends or is financially stable.]"

"I'm a 30+ year veteran of this industry who has run my own life for many years. I'm ready to join a big team so that I can take on work that solo practioners don't get. I'm looking forward to [specific tasks] and I believe I can get that here."

"I'm a published author, experienced speaker, amazing trainer and quick learner who needs some new challenges. I want to learn [technology] and I believe joining a firm like this one will give me those opportunities. I know my [specific skills and abilities] can make a real contribution here and I want to demonstrate that fit to you."

"I'm a new graduate who stands out from the rest of the class because I [have/did something amazing] and I want [something other than a paycheque]."

Thirty seconds. If I want the details of your two year sailing trip around the world, or why you are leaving your old job, I'll drill in.

ContentLicense: CC BY-SA 2.5


答:
In theory, this true. In real life, threads are just an efficient abstraction used to program such a state machine. They are so efficient that they can be used to program Statecharts and Petri nets as well (i.e., parallel behaviours, where state machines are basically sequential).

The problem with state machines is combinatorial explosion. The number of states of a computer with 4G RAM is 2^(2^32) states (not counting 2T disk drive).

To a man whose only tool is a hammer, every problem looks like a nail.

Title: State machines vs threads


答:
How does one achieve multi-threading functionality in high-level
  language, such as Java, using only one thread and state machine? For
  example, what if there are 2 activities to perform (doing calculations
  and doing I/O) and one activity can block?

What you're describing is called cooperative multitasking, where tasks are given the CPU and expected to relinquish it voluntarily after some self-determined amount of time or activity.  A task that doesn't cooperate by continuing to use the CPU or by blocking gums up the entire works and short of having a hardware watchdog timer, there's nothing the code supervising the tasks can do about it.

What you see in modern systems is called preemptive multitasking, which is where tasks don't have to relinquish the CPU because the supervisor does it for them when a hardware-generated interrupt arrives.  The interrupt service routine in the supervisor saves the state of the CPU and restores it next time the task is deemed deserving of a time slice, then restores the state from whatever task is to be run next and jumps back into it as if nothing had happened.  This action is called a context switch and can be expensive.

Is using "state-machine only" way viable alternative to
  multi-threading in high-level languages?

Viable?  Sure.  Sane?  Sometimes.  Whether you use threads or some form of home-brewed cooperative multitasking (e.g., state machines) depends on the tradeoffs you're willing to make.

Threads simplify task design to the point where you can treat each one as its own program that happens to share data space with others.  This gives you the freedom to focus on the job at hand and not all of the management and housekeeping required to make it work an iteration at a time.  But since no good deed goes unpunished, you pay for all of this convenience in context switches.  Having many threads that yield the CPU after doing minimal work (voluntarily or by doing something that would block, like I/O) can eat up a lot of processor time doing context switching.  This is especially true if your blocking operations rarely block for very long.

There are some situations where the cooperative route makes more sense.  I once had to write some userland software for a piece of hardware that streamed many channels of data through a memory-mapped interface that required polling.  Every channel was an object built in such a way that I could either let it run as a thread or repeatedly execute a single poll cycle.

The multithreaded version's performance wasn't good at all for exactly the reason I outlined above:  each thread was doing minimal work and then yielding the CPU so the other channels could have some time, causing lots of context switches.  Letting the threads run free until preempted helped with throughput but resulted in some channels not getting serviced before the hardware experienced a buffer overrun because they didn't get a time slice soon enough.

The single-threaded version, which did even iterations of each channel, ran like a scalded ape and the load on the system dropped like a rock.  The penalty I paid for the additional performance was having to juggle the tasks myself.  In this case, the code to do it was simple enough that the cost of developing and maintaining it was well worth the performance improvement.  I guess that's really the bottom line.  Had my threads been ones that sat around waiting for some system call to return, the exercise would probably not have been worth it.

That gets me to Cox's comment:  threads aren't exclusively for people who can't write state machines.  Some folks are quite capable of doing that but choose to use a canned state machine (i.e., a thread) in the interest of getting the job done sooner or with less complexity.

Title: State machines vs threads


问:
How a .NET dev team should be designing and delivering greenfield projects?
Some of the hottest topics in the software world atm are:

Domain-Driven Design

SOLID principles

Agile methodologies

ORM

Now assuming that you are not currently using all of these in your team, if you were to go and ask your team (individually, not as a group) what they knew about the topics they were not applying - how much do they know about those other topics - they've probably "heard about it/read it somewhere once". The problem is that, increasingly, tech is changing so fast that a lot of people (average Joe programmers) just can't keep up with the latest thinking.

Now while those that are academically gifted can read 20+ books on the above subjects every year and combine it into some kind of order in their heads in order to apply it to a new software project, most of us will not be inclined to do all that studying. Personally, I sit at a desk all day programming, and so the last thing I want to do is go home and do the same. I want to go play sport, see friends, spend time with the gf, and generally have a life.

So, given a nice shiny new greenfield project, many of us (make that most, if we are honest) are still pretty confused about how to tackle a new project with the latest, greatest thinking that is most commonly accepted by our more academically inclined piers.

So my question - I was wondering if there was any book out there present or future, that combines the latest thinking into something more manageable for the average mortal to digest and apply? (preferably using .net and the most popular current related tech)

From my experience in the market, it would look something like this to be relevant to most real developers:

Examples based on some kind of internet website, so all tiers can be involved.

Explain how to identify and map the real business objects, this would currently be done with domain-driven design as the latest commonly-accepted thinking, while obeying SOLID principles.

Explain how (2) goes from model to database schema, using latest ORM tech (this might be the biggest section).

Use MVC (or whatever tech that becomes) as a platform for the examples.

Very briefly explain TDD, then show you how to plug-in unit testing, probably visual studio testing/nunit or latest tech.

When to use IoC.

Show you how to write a couple of very simple integration tests using whatever the current tool of choice is (Fitnesse or whatever).

Show you (in no more than one chapter) how to set-up TFS for continuous integration.

The book would then be revised every year to reflect the latest and most agreed concepts, so software teams always knew the best way to handle a new project, without wading through this year's mountain of new books themselves to try and identify the common themes for this year's hottest topics. It would be important that the revisions did not reflect the author's own opinion, but rather the general opinion of the majority of his piers, so it built an accepted, uniform approach to .net development projects.

The real key to this book is that it would be a "How to" book, not a "Why you should" book. It could (and probably should) reference the "Why" books for those that wanted to be better programmers or just needed to know more, but it wouldn't have the space to explain it anything more than briefly, given the target of the book.

Perhaps the book could more accurately be called "How to correctly and practically apply the current state of the art .NET software development design and technology to real world projects this year (for idiots)" but I guess the title needs work ;-)

So, to fit into the sites "ask a question" directive - is there any book out there even vaguely similar to this? (although I doubt it gets revised regularly).

Right, I'm off to read another dry, theoretical book, on my week off to try and keep up :(  It's a shame that I'll probably have forgotten all the content by the time I come to use it, and for all I know it might be out of date already...

Oh btw, where's the best place to kick this off as a discussion as opposed to a question? reading the FAQ only suggested the real-time chat, which I had a quick look at, but tbh it's pretty dead and seems to be mostly one-liners, not suitable for something long-winded (another website would be fine).

答:
You want to know if there's a cookie-cutter template for technologies and processes to use for a new software project? Well, there's not.

Determining the appropriate process depends on the organization, team, scheduling, budgeting, familiarity with the domain, and so forth. The techniques and tools to support the process depend on the process that you are following. Along the same lines, the best languages, libraries, and frameworks depend on the requirements that you need to satisfy to deliver an acceptable project.

You aren't going to find a book (or any other resource) that explains how to run every single project, how to choose what technologies, and how to make everything fit into your project. What you can find, though, are good resources that help you to learn about various technologies and techniques and from there, you can learn how to best apply them to your problem.

The questions that you should be asking need to be focused on specific projects, processes, and technologies. These can't really be generalized across every project in every organization carried out by every team. That's why we have project managers and leads with the knowledge, education, and experience to assess the situation and make the appropriate decisions given a specific context.

To address a few specific statements that you made:

The problem is that, increasingly, tech is changing so fast that a lot of people (average Joe programmers) just can't keep up with the latest thinking.

The job of a software engineer is to stay on top of the latest in his field or domain. One can't be expected to know everything about all aspects of software development, but I would expect a networked applications/distributed systems programmer to stay up to date about the latest technologies and protocols for networking and building distributed systems, just like I would expect a software project manager to stay up to date on the latest techniques on how to lead and manage software projects. And beyond staying up to date, I would expect the individuals to apply personal thought as to how what they are learning can be applied to their organization, team, and project.

The book would then be revised every year to reflect the latest and most agreed concepts, so software teams always knew the best way to handle a new project, without wading through this year's mountain of new books themselves to try and identify the common themes for this year's hottest topics.

You aren't going to find many books revised at that rate. A lot of work happens continually, and it takes a long time for something to go from an idea in someone's head to an implementation to realized as adding value that is worthy of being explained in a book. This goes back to my first point - as a professional, you can't be expected to be spoonfed. It's up to you to know your field and domain and stay current or get left behind (and perhaps be out of a job).

The real key to this book is that it would be a "How to" book, not a "Why you should" book.

There's no way to address "how to" for large scale software projects with so much variability. That's why most books address a specific technique or set of techniques, when they are applicable and when they aren't applicable, why you should consider using them. You'll get some general best practices for implementing, but with the variations between projects and requirements, there aren't many hard rules, but rather general guidelines to work within.


答: This is exactly what branches are for -- use them. In this case, I would be developing in my branch while the main line of development was in default. Keep your fixes cleanly in the right branch, merge as necessary. If it is the sort of app where breaking flow and doing a hg update hurts, just keep 2 distinct copies locally, pointed at appropriate branches. Working on a hotfix is as expensive as another instance of the IDE.

Title: How to set up for selective pushing with Mercurial?

Body:
I have a situation, when I'm working on a project, but at same time small issues arise which require quick fix. I would like to push just the fixes for these problems to the main repo while keeping the rest locally. Problem is that, as I've already found out, it's not possible to cherry pick changsets when pushing from my repository upwards.

So the question is, how to set up my Hg environment to have such a possibility. I want to preserve all the Hg metadata, so sending patches around is not a option.

BTW, if the whole thing can be managed directly from MercurialEclipse, that would be a big plus.


问:
Writing robust code vs. overengineering
How do you guys know that you are writing the most robust code possible without overengineering?

I find myself thinking too much about every possible path that my code can take, and it feels like a waste of time sometimes. I guess it depends on the kind of program you are writing, but I don't want to use too much of my time taking situations into account that will never happen.

答:
How do you guys know that you are writing the most robust code
  possible without overengineering?

What do you consider robust code? Code that is already future proof and so powerful that it can deal with any situation? Wrong, no one can predict the future! And wrong again, because it'll be a complicated, unmaintainable mess.

I follow various principles: First and foremost YAGNI (yet) and KISS, so I don't write unecessary code. That also effectively prevents overengineering. I refactor the application when extensions are needed. Modern refactoring tools let you quite easily create interfaces and exchange implementations afterwards when you need them.

Then I try to make the code I write as robust as possible, that includes eliminating as many paths the program can take (and also states) as possible and a bit of Spartan programming. A great help are "atomic" functions/methods that do not rely on external states or at least don't leave the program in an inconsistend state when they fail. If you do that well, it's also very unlikely that you'll ever end up with spaghetti code and it's a blessing for maintainability, too. Also, in object oriented design, the SOLID principles are a great guide to robust code.

I've really found out that often times you can reduce complexity, for example combinatorial explosions of program paths or states, by deeply thinking about how you could design it as the straightest path possible. Try to keep the possible combinations at a minimum by choosing the best ordering of your subroutines and designing them for this purpose.

Robust code is most always simple and clean code, but simplicity is a trait that is not always easily achieved. Yet, you should strive for it. Always just write the simplest code possible and only add complexity when you have no other choice.

Simplicity is robust, complexity is fragile.

Complexity kills.

Title: Writing robust code vs. overengineering


答: I make this distinction by writing code with well-defined, but not necessarily optimal behaviour for very unlikely execution passes. For example, when I am quite sure (proven, but not tested) that a matrix will be positive definite, I insert an assertion or exception into the program to test the state, but do not write an own code path for it. Thereby, the behaviour is defined, but suboptimal.</p>

Title: Writing robust code vs. overengineering

Body:
How do you guys know that you are writing the most robust code possible without overengineering?

I find myself thinking too much about every possible path that my code can take, and it feels like a waste of time sometimes. I guess it depends on the kind of program you are writing, but I don't want to use too much of my time taking situations into account that will never happen.


答:
As of today, I don't see any glaring issues. When I rode on the train, there were plenty of corporate laptop users running XP (At least that's what the sticker said.).

Our company is still on XP (a computer I frequently use remotely) and I use Windows 7 at home. Newer versions of Office seem to run better on Windows 7. We had a couple users that created gargantuan Excel files (The screwed one up so bad, MS couldn't fix it.), so the company bought them 64 bit versions with tons of memory.

If there is a hardware upgrade in your future, make the leap to Windows 7.


问:
Implementing your own Membership Provider in ASP.NET MVC
Are there are any specific rules and regulation to follow while developing a custom membership provider. Like, implementing a particular Interface or Abstract class. Or a definite model architecture to follow.

If yes, then what are the rules or I am free to design, model and code anything ?

答:
First rule is don't reinvent the wheel -- the built-in SQL membership provider is quite good, especially at pure membership stuff. If you treat it as a black-box authentication scheme you can build just about anything on top of it. There are very few good reasons not to use it.

If you must, the whole provider model has some pretty specific requirements, you can read about implementing a membership provider or check out an example ODBC membership provider.


答:
1) Get requirements.

2) Write minimum code to meet requirements. If something is ambiguous, make an educated guess. If it is super ambiguous, go back to 1.

3) Send to testing.

4) If the testers say its good, document the approval. If something is off, go back to 1.

Focus on passing tests, not predicting tests. If you do not have testers...get testers! They are essential not only to verifying code correctness, but to the entire development process.

Title: Writing robust code vs. overengineering


答:
The difference between robust and overengineering is the difference between gracefully handling all possible use cases, even the bizarre and fringe use cases that SHOULDN'T happen.  When I say gracefully I mean, the user enters a bizarre exception case or runs into a situation which calls for an unsupported or unspecified feature that wasn't defined and the code gracefully exits without crashing or informs the user of unsupported functionality.

Overengineering on the other hand could fall in the realm of complete implementation of features that were not needed or asked for (some features the client does NEED but were never asked for!) OR it can be defined by deriving an overly complex design or overly complex code to handle a relatively simple problem.

Title: Writing robust code vs. overengineering


问:
Choosing a JavaScript Asynch-Loader
I’ve been looking at various asynchronous resource-loaders and I’m not sure which one to use yet. Where I work we have disparate group-efforts whose class-modules may use different versions of jQuery (etc). As such, nested dependencies may differ, as well. I have no control over this, so this means I need to dynamically load resources which may use alternate versions of the same library.

As such, here are my requirements:

Load JavaScript and CSS resource
files asynchronously.

Manage dependency-order and
nested-dependencies across versions.

Detect if a resource is already
loaded.

Must allow for cross-domain loading
(CDN's)

(optional) Allow us to unload a
resource.

I’ve been looking at:

Curl

RequireJS

JavaScriptMVC

LABjs

I might be able to fake these requirements myself by loading versions into properly-namespaced variables & using an array to track what is already loaded...but (hopefully) someone has already invented this.

So my questions are:

Which ones do you use? And why?

Are there others that my satisfy my
requirements fully?

Which do you find most eloquent and
easiest to work with? And why?

UPDATE:

For those interested, I tried all the AMD libraries above (and more).  In the end, I went with RequireJS.  It's just cleaner and easier overall...and I'm glad to be using it.

答:
If you're looking at RequireJS and want to depend on CSS files, you can checkout the CSSP RequireJS plugin :

CSS with Padding. This project implements a plugin for the RequireJS
  project that allows modules to list CSS files as dependencies. This
  allows RequireJS to wait until specific style rules are known to be in
  effect before it releases the JavaScript module to be evaluated. This
  would be useful if, for example, if your JavaScript module required
  certain CSS rules, defined in a separate file, to be applied to the
  DOM before it could be initialized.

Title: Choosing a JavaScript Asynch-Loader


答:
A good way to grok the way state machines and multithreading interact is to look at GUI event handlers. Many GUI applications/framework utilize a single GUI thread that will poll the possible sources of input and call a function for each received input; essentially, this could be written as a huge switch:

```<code>while (true) {
    switch (event) {
        case ButtonPressed:
        ...
        case MachineIsBurning:
        ....
    }
}
</code>```

Now, it becomes clear quite quickly that level of high-level control in this construct can't be high: The handler for ButtonPressed must finish without user interaction and return to the main loop, because if it doesn't, no further user events can be processed. If it has any state to save, this state must be saved in global or static variables, but not on the stack; that is, normal control flow in an imperative language is limited. You are essentially limited to a state machine.

This can get pretty messy when you have nested subroutines which have to save, for example, a recursion level. Or are in the middle of reading a file, but the file is unavailable at the moment. Or are just in a long computation. In all these cases, it becomes desirable to save the state of the current execution and return to the main loop, and this is multithreading. Nothing more, nothing less.

The whole thing became a bit more convoluted with the introduction of preemptive multithreading (i.e. the operating system deciding when threads should yield control), and that's why the connection isn't immediately clear today.

So, to answer the final question: Yes, the state machine is an alternative, most GUIs work that way with the GUI thread. Just don't push the state machine too far, it becomes unmaintainable really quickly.

Title: State machines vs threads

Body:
A good way to grok the way state machines and multithreading interact is to look at GUI event handlers. Many GUI applications/framework utilize a single GUI thread that will poll the possible sources of input and call a function for each received input; essentially, this could be written as a huge switch:

while (true) {
    switch (event) {
        case ButtonPressed:
        ...
        case MachineIsBurning:
        ....
    }
}

Now, it becomes clear quite quickly that level of high-level control in this construct can't be high: The handler for ButtonPressed must finish without user interaction and return to the main loop, because if it doesn't, no further user events can be processed. If it has any state to save, this state must be saved in global or static variables, but not on the stack; that is, normal control flow in an imperative language is limited. You are essentially limited to a state machine.

This can get pretty messy when you have nested subroutines which have to save, for example, a recursion level. Or are in the middle of reading a file, but the file is unavailable at the moment. Or are just in a long computation. In all these cases, it becomes desirable to save the state of the current execution and return to the main loop, and this is multithreading. Nothing more, nothing less.

The whole thing became a bit more convoluted with the introduction of preemptive multithreading (i.e. the operating system deciding when threads should yield control), and that's why the connection isn't immediately clear today.

So, to answer the final question: Yes, the state machine is an alternative, most GUIs work that way with the GUI thread. Just don't push the state machine too far, it becomes unmaintainable really quickly.


答:
The quick method would be :
 - to update to the last stable production changeset;

Make the change, then commit the change;

Create a version tag;

Export the patch;

Update to the working changeset;

Merge the working changeset with the tag previously create to bring
back the fix;

For more detail see http://hginit.com/05.html


答:
Asking whether using a state machine is viable in a high level language is a little like asking whether writing in assembler is a viable alternative to using a high level language. They both have their place, given the right situation.

The abstraction of using threading makes more complex parallel systems easier to implement, but ultimately all parallel systems have the same issues to deal with. Classic problems like Deadlock/Livelock and priority inversion are just as possible with state machine based systems as they are with a shared memory parallel, NUMA or even CSP based system, if it is complex enough.

Title: State machines vs threads


答:
I try to keep a balance, focusing on

handling all possible execution paths in the existing use cases (this is the "robustness" part),

enabling features / requirements I am fairly sure that are going to come in the foreseeable future, and

things I know from experience that are going to be needed for long term maintainability of the code base (i.e. keeping the code clean and testable).

It is a fuzzy border area - sometimes I manage to do some unneeded work, sometimes I fail to do something which turns out to be necessary later. If the misses aren't big, I am fine. At any rate, I strive to learn from my mistakes.

Title: Writing robust code vs. overengineering


问:
Algorithm Vs Design

Possible Duplicate:

  Is it essential to learn algorithms to be a real programmer?

This question is, perhaps, related mostly to web developers who, like myself, code enterprise applications and use high level languages like Java, C# mostly.

Due to nature of enterprise web-apps, which essentially do CRUD operations, and since we rely heavily on libraries that the language provide, what is the significance of learning algorithms?

I know the web is filled with articles profoundly stating that "code is algorithm", but when was the last time anyone wrote quicksort algorithm in such an application?

I see far more benefits in learning Design patterns and anti-patterns, which are used a lot.

答:
In primary school I used to complain about learning math, as electronic calculators can do all the work — I thought.

What I want to say: As a developer you should always try to understand, how things work, instead of just excepting that they work — although you can rely on other developers work in 99.9% of all cases.

OwnerDisplayName: SIJAR

Title: Algorithm Vs Design


答:
Being able to write a correct quicksort implementation is one level of knowledge. I sort of agree that it is rarely needed in the life of an average web developer (however, when you need it, you need it much).

Understanding how quicksort works (and being able to choose between it and other sorting algorithms for a specific task at hand) is another. I think this is more often needed, and a decent developer should have this level of general knowledge about fundamental algorithms. Without this, you don't even notice when you are in the situation that needs a specific algorithm - and this can have bad consequences.

Your question is a bit analogous to asking whether it is useful for a cab driver to enroll in a course practicing how to drive on snowy/icy road, since 99.9% of the cases this knowledge provides no benefit in the well kept roads of a big city. Indeed no - however in that 0.1% when it is needed, it may make a difference between a mild shock and a serious injury. And you may never predict in advance when you are going to need it!

Similarly to a taxi driver (or to any kind of craftsperson), we are also professionals who are supposed to know our tools of the trade. Software development is about problem solving, and failing to learn algorithms seriously reduces our problem solving power, thus our market value.

Title: Algorithm Vs Design

Body:
Possible Duplicate:

  Is it essential to learn algorithms to be a real programmer?

This question is, perhaps, related mostly to web developers who, like myself, code enterprise applications and use high level languages like Java, C# mostly.

Due to nature of enterprise web-apps, which essentially do CRUD operations, and since we rely heavily on libraries that the language provide, what is the significance of learning algorithms?

I know the web is filled with articles profoundly stating that "code is algorithm", but when was the last time anyone wrote quicksort algorithm in such an application?

I see far more benefits in learning Design patterns and anti-patterns, which are used a lot.


答:
I see far more benefits in learning Design patterns and anti-patterns,
  which are used a lot.

From your point of view this is certainly true and many applications out there aren't really algorithm heavy. But a large amount of applications require a good knowledge about algorithms and datastructures, for example games or logistics applications. Those applications often require their very own algorithm for finding a shortest route or filling a knapsack, you can't just use a generic one.

I know the web is filled with articles profoundly stating that "code
  is algorithm", but when was the last time anyone wrote quicksort
  algorithm in such an application?

That's not the point. Most people aren't going to reimplement quicksort again. But quicksort demonstrates some of the most fundamental concepts of algorithm design. If you understand quicksort you can apply this sort of knowledge to other problems. As stated above, not all algorithms can be used generically. In the real world you often have to create custom algorithms for your problems, which are built with the same techniques that things like, for example, quicksort use.

And this can only be done with a fundamental knowledge about those algorithm techniques and data structures.

The one day you stumble across such a problem or a performance bottleneck in some routine, you'll be able to tackle it. And sooner or later there'll be one. I've seen CRUD developers who then simply said "It's not possible", when, in fact, it was pretty easily solvable.

Title: Algorithm Vs Design


答:
When you use someone else's algorithm, you still need to understand the tradeoffs. For example, in Java, the sort() method provided by the Collections class uses a modified mergesort that guarantees n log(n) performance. However, it also states that it dumps the collection into an array, sorts the array, and iterates over the list. This use of an array requires more memory consumption.

The question becomes: Is this good enough for your needs? If you don't understand algorithms, time complexity, and space complexity, you can't really answer that. You don't need to know as much about the underlying mathematics and theory as someone who develops new algorithms, but you do need to be able to compare multiple algorithms and determine which one best allows you to meet the requirements of the system.

Note that the exact same thing applies to data structures. Understanding the characteristics of your data and the insert and retrieval from the data structure will allow you to choose the most appropriate structure for your needs.

Now, all of this happens at a lower level than design patterns. Design patterns say nothing about what data structure or algorithm that you need, but rather that you need to have some kind of relationship between modules of your application. When talking about design, you might say "we need to sort the data", or perhaps even "we need to provide multiple sorting algorithms" (Strategy pattern, perhaps?), but you wouldn't be talking about merge sort or quick sort or any particular sorting algorithms.

Title: Algorithm Vs Design


问:
Opensource, noncommercial License?
i want to publish my software under a opensource license with the following conditions:

you are allowed to:

Share — to copy, distribute and transmit the work

use a modified version of the code in your application

you are not allowed to:

publish modified versions of the code

use the code in anything commercial

Is there a software license out there that fits my needs ?

(crosspost: https://stackoverflow.com/questions/4558546/opensource-noncommercial-license)

答:
At least in the United States, a copyright license cannot restrict use. In the United States, anyone who possesses a lawful copy of a work may use it for whatever purposes they please, including commercial ones. (Assuming they aren't commercially distributing or performing the work.) See 17 USC 106 and notice that none of the rights have anything to do with ordinary use.

So you would have to do this with an EULA or contract.

But something seems odd to me. How are you supposed to use the code in a non-commercial project if you can't publish modified versions?

OwnerDisplayName: nick-russler

Title: Opensource, noncommercial License?


答:
but when was the last time anyone wrote quicksort algorithm in such an application

It's like when was the last time someone redefined 2*2=4. Algorithm's for such problems has already been defined and redefined to the optimal solution. Hence, we don't need to write one for ourself. These sort of algorithm applies more to a system developer than a web developer.

```<code>code is algorithm
</code>```

Definitely ,everything you write to achieve a task is an algorithm in itself. If you are achieving good results with your code, then you are performing good algo's. In case your application is slow in performing a function such as CRUD, then you need to think again and decide how to increase the performance. This is where algorithm comes in handy. It doesn't mean you need to R&D in Algorithms, but think in a rational manner as to how can you achieve the optimal performance for your function. Like deciding what sorting should be done before and after. Stuff's like that are more concerned to a web and application developer than quicksort and binarytree.

Title: Algorithm Vs Design

Body:
but when was the last time anyone wrote quicksort algorithm in such an application

It's like when was the last time someone redefined 2*2=4. Algorithm's for such problems has already been defined and redefined to the optimal solution. Hence, we don't need to write one for ourself. These sort of algorithm applies more to a system developer than a web developer.

code is algorithm

Definitely ,everything you write to achieve a task is an algorithm in itself. If you are achieving good results with your code, then you are performing good algo's. In case your application is slow in performing a function such as CRUD, then you need to think again and decide how to increase the performance. This is where algorithm comes in handy. It doesn't mean you need to R&D in Algorithms, but think in a rational manner as to how can you achieve the optimal performance for your function. Like deciding what sorting should be done before and after. Stuff's like that are more concerned to a web and application developer than quicksort and binarytree.


答:
You have to learn how to understand and implement an algorithm, quicksort is just an example - right normally you will never write it yourself.

Sorting is a good example to learn that there are many different solutions for one problem, each with advantages and disadvantages depending on the data it works on.

Its is worthy to have some fundamental knowlegde of algorithms and complexity to avoid solutions like counting occurences just to check existance (just a simplified example).

Title: Algorithm Vs Design


问:
Are there any studies of cross-functional teams vs. domain-based teams (e.g. project-based vs. software/mechanics/etc)?
I work in an organization which creates many integrated systems products - i.e. it is complete products with mechanical/system/electronics/software being designed and manufactured.  At the moment most teams are organized around projects in a cross functional way.  The advantage of an organization like this is that people who are working closely together for a common goal are close.

The disadvantages come from the isolation of engineers from their peers. Typically a project is assigned only one software engineer.  This means that the projects have a high truck factor, minimal knowledge sharing and best practices, and technical development is limited.

So my question is: are there any studies comparing the cost/benefits of these two approaches?

答:
While you can have cross functional teams it also doesn't hurt to staff those teams with multiple part-time engineers.  You could for example put Bob on project a and project b and also put Jane on project a and project b.  This way they are distributed, however, if you have projects that are small enough to build out with just one software engineer, even this approach may have limitations.

Another option might be to keep the team structure the same but organize the work environment around function.  Put all the software engineers together where they can collaborate in an open environment.  This does go counter to some thinking and sometimes people get defensive when you take down the walls, but it might help to work in a bull-pen type arrangement.

The concept of co-working is based on this as well.  Independent consultants and designers that would otherwise work in a home based office, move into a shared facility where they can feed off each others strengths.

There might not be much out there on these ideas, maybe you can pitch it to the teams involved as an experiment to get better productivity and satisfaction in the jobs.  Then write up a white paper on the outcomes.


问:
Does defining the stopping point of a genetic algorithm defeat the purpose of the algorithm?
Wikipedia defines the termination point of a GA to this:

Commonly, the algorithm terminates when either a maximum number of
  generations has been produced, or a satisfactory fitness level has
  been reached for the population. If the algorithm has terminated due
  to a maximum number of generations, a satisfactory solution may or may
  not have been reached.

Now, if it terminates when a satisfactory fitness level has been reached, and you are the one defining that fitness level, why wouldn't you just be able to create the "perfect" genome from the beginning yourself, since you already know the characteristics of this perfect genome?

I guess I'm just a little confused here. I thought the purpose of a GA was to constantly evolve and show us possibly an even better solution than what we thought of, and our fitness function was just something that helped it along the way, not something we put on the pedestal as the termination "perfect" state. Doesn't that destroy the point?

答:
Iterate till a solution doesn't differ from the previos iteration one very much. For very much, please understand a fixed tolerance.

```<code>Solution in iteration n-6: 600
Solution in iteration n-5: 800
Solution in iteration n-4: 768
Solution in iteration n-3: 780
Solution in iteration n-2: 778
Solution in iteration n-1: 778.23
Solution in iteration n: 780.18
Solution in iteration n+1: 780.1815
</code>```

In this example, if your fixed tolerance was 0.01 then (n+1) tells you to stop because abs(solution(n+1)-solution(n)) < 0.01.

Resuming, thats when your algorithm can say: this wont get any better!

Body:
Iterate till a solution doesn't differ from the previos iteration one very much. For very much, please understand a fixed tolerance.

Solution in iteration n-6: 600
Solution in iteration n-5: 800
Solution in iteration n-4: 768
Solution in iteration n-3: 780
Solution in iteration n-2: 778
Solution in iteration n-1: 778.23
Solution in iteration n: 780.18
Solution in iteration n+1: 780.1815

In this example, if your fixed tolerance was 0.01 then (n+1) tells you to stop because abs(solution(n+1)-solution(n)) < 0.01.

Resuming, thats when your algorithm can say: this wont get any better!


答:
If you only ever aspire to write the same web app for the rest of your career, and never wish to improve and expand your skillset, then their significance is limited. If you want to continue to learn, improve and expand your mind, knowledge and skills... that's another story. But it doesn't stop  there, because you're wrong about one thing.

When you ask,

...when was the last time anyone wrote quicksort algorithm in such an application?

Once you're proficient, as happens when you learn design patterns... you start seeing them everywhere, even in places that were 'just code' before.

But even then... you're getting by just fine without them. Why are they important to know? They are important because there will come a time where a client makes a particular change request, or the company produces a new line of software, or you get a new job because you've got steady raises and a kid fresh out of school will be fine with the base salary, or you'll want to spread your horizons and work in a different field...

On that day, you will need this knowledge. On that day, that young pup fresh out of intro to algorithms isn't going to step up and say "move over Gramps, let the real devs work" - and be right.

Title: Algorithm Vs Design


问:
Database source control
Should database files(scripts etc.) be on source control?
If so, what is the best method to keep it and update it there?

Is there even a need for database files to be on source control since we can put it on a development server where everyone can use it and make changes to it if needed. But, then we can't get it back if someone messes it up.

What approach is best used for databases on source-control?

答:
There're tools like liquibase which are intended to provide source control for databases. It's cumbersome to maintain change/update scripts in your regular source control tool like many companies do it and you can't always redeploy the database from scratch.

We've also tried to automate this with database comparison tools (compare master vs. customer db) and that helped, but you can't trust such tools 100%, you definitely need a review process, too.

Title: Database source control


答:
Yes.

what is the best method to keep it and update it there?

Um. Write a schema-builder script. Check it in after making changes.  Check it out before running it.

It's hard to determine what you're asking for.

Write formal schema migration scripts.  Check them in after testing.  Check them out before running them.

What more is there?

What happens is that schema changes turn into gnarly problems because the schema evolves organically through a series of undocumented changes.

This organic evolution makes schema migration more difficult because there's no "authoritative" source for what's supposed to be there.  There are two slightly different production versions, a staging version, a QA version and eight development versions.  All slightly different.

If there was a single, authoritative source, then schema migration is just the delta between last version and this version.

Title: Database source control

Body:
Should database files(scripts etc.) be on source control?
If so, what is the best method to keep it and update it there?

Is there even a need for database files to be on source control since we can put it on a development server where everyone can use it and make changes to it if needed. But, then we can't get it back if someone messes it up.

What approach is best used for databases on source-control?


问:
"Gödel, Escher, Bach" still valid today?
I have just completed a course on computability and logic which was an interesting course. The lecturer recommend a few books on his slides, which include "Gödel, Escher, Bach". I can see the book is quite famous, and looks very interesting. But I have a few questions to ask regarding its content.

Is the content still valid today? I guess most theoretical stuff doesn't change over night, but are there any major points which no longer hold today that I should be aware of?

I assume we actually HAVE made some progress in the last 30 years or so. Can any of you recommend a book on the subject which includes this progress (logic, AI, computability)?

Another question: Do I have to know about Escher and Bach?

答: I can tell you for a fact that it is still entertaining today, which is a lot more than some of our ancient tomes can say.


答:
Here's the problem I've seen many times when there is no version control or change management on development databases. Programmer A makes a change to a table, view or proc. Programmer B makes a change to the same thing and overwrites what Programmer A did. Or, DBA restores a production DB to development and overwrites changes. I've seen this kind of stuff cause considerable grief so many times it's not funny. And this is only on development systems. Things can get really messy when staging/test and even production servers get caught up in this.

The database version control doesn't have to be the same as the regular code version control to be effective. However, some kind of change control and history backups will prevent many problems.

Title: Database source control


答:
Yes. You should be able to rebuild any part of your system from source control including the database (and I'd also argue certain static data).

Assuming that you don't want to have a tool to do it, I'd suggest you want to have the following included:

Creation scripts for the basic table structures including schemas, users, tables, keys, defaults and so on.

Upgrade scripts (either altering the table structure or migrating data from a previous schema to the new schema)

Creation scripts for stored procedures, indexes, views, triggers (you don't need to worry about upgrade for these as you just overwrite what was there with the correct creation script)

Data creation scripts to get the system running (a single user, any static picklist data, that sort of thing)

All scripts should include the appropriate drop statements and be written so they can be run as any user (so including associated schema / owner prefixes if relevant).

The process for updating / tagging / branching should be exactly as the rest of the source code - there's little point in doing it if you can't associate a database version with an application version.

Incidentally, when you say people can just update the test server, I'm hoping you mean the development server. If developers are updating the test server on the fly then you're looking at a world of pain when it comes to working out what you need to release.

Title: Database source control


答:
should AOT (ahead of time) compilation be considered rather than just obfuscation?

Although probably not your intent, that can be interpreted as "should we use AOT compilation as opposed to obfuscation", which implies that AOT compilation > obfuscation.  This is not necessarily the case, in fact, I would argue that good obfuscation is better than AOT compilation, since it will at least slightly irritate the person doing the RE in assembly.  In the long run though, neither will be of much help; anything can be cracked, given enough time.

Title: Java/C# - When should AOT be considered if reverse engineering is a concern?

Body:
Long and short is really in the question title.  For a language which compiles to an intermediate language like MSIL or Java byte-code, if there's concern about something like reverse engineering or hacking to disable security features, should AOT (ahead of time) compilation be considered rather than just obfuscation?  Obviously, there's a bit of wiggle room in this question as there's no one answer I wouldn't imagine, but when would you start looking at performing an AOT compilation before distributing something versus sending it out obfuscated?

For anyone that stumbles across this and isn't familiar:

Wikipedia Entry on AOT Compilers:  http://en.wikipedia.org/wiki/AOT_compiler

Mono AOT Compiler feature:  http://www.mono-project.com/AOT


答:
For a quick answer to you main question: There is a big difference between knowing what you want to achive, and knowing how to get there.

In more detail, for example, with one of the most popular problems solved by using genetic/evolutionary algorithms, usually a case study in class, finding the optimum route in a graph. This is often used in networking to find the cheapest route from one end to another. As you define costs (# of hops, cost from each hop, etc...) you also define your target cost (fitness level) at which you are happy with the result. Your algorithm might not find the best, but it will find an algorithmically acceptable optimum. By this I mean that the cost/benefit relationship of finding a better answer is prohibiting.

With GA/EA you'll find that it is normal behavior that you very quickly find a 95%+ optimum answer, but narrowing down that last 5% is exponentially more costly. So the theory is that you define an acceptable optimum to achive the best result in the least amount of time. Since the cost of finding, say the top 1%, might outweigh its benefits over the top 5%, you define your acceptable optimum.

To sum up, you don't now the answer to any particular problem, you just define, per problem, your acceptable optimum, the point in which finding a better answer is not practical.

Title: Does defining the stopping point of a genetic algorithm defeat the purpose of the algorithm?

Body:
Wikipedia defines the termination point of a GA to this:

Commonly, the algorithm terminates when either a maximum number of
  generations has been produced, or a satisfactory fitness level has
  been reached for the population. If the algorithm has terminated due
  to a maximum number of generations, a satisfactory solution may or may
  not have been reached.

Now, if it terminates when a satisfactory fitness level has been reached, and you are the one defining that fitness level, why wouldn't you just be able to create the "perfect" genome from the beginning yourself, since you already know the characteristics of this perfect genome?

I guess I'm just a little confused here. I thought the purpose of a GA was to constantly evolve and show us possibly an even better solution than what we thought of, and our fitness function was just something that helped it along the way, not something we put on the pedestal as the termination "perfect" state. Doesn't that destroy the point?


问:
Complexity vs maintainability in modern hardware
Today with the modern hardware and memory coming cheap, how much sense does it make to spend effort to analyze algoriths or data structure complexity?

Wouldn't it be better instead, to focus on clean, maintainable code, readable code than on optimizations for complexity?

Note:I not talking about embedded systems or systems with similar kinds of constraints.

答:
Look to your requirements.  Codify in specific, measurable, objective terms what constitutes acceptable performance so you have a unified view across stakeholders, management and developer.  Let this be your guide in application architecture, application and hardware design, function and performance QA as to whether you have hit your mark and where to spend the time to optimize and when to not.

If you ignore performance and it comes back to bite you as an unarticulated requirement important to a key stakeholder then you are sr*wed because its a helluva lot easier to design in performance than it is to tack it on after the fact.


问:
What are the consequences of still sticking with Windows XP despite there are Windows Vista, 7 and very soon 8?
From a .Net programmer perspective, what are the consequences of still sticking with Windows XP despite there are Windows Vista, 7 and very soon 8? How does having windows XP limit programmers development in .Net platform?</p>

答:
The biggest boon, outside of a things like security and a decade worth of kernel improvements, is having IIS7 locally. If you are doing web development on XP then you are stuck on IIS5 and at worst you should be deploying to IIS6 (Windows Server 2003) if not IIS7 (Windows Server 2008). And IIS 5/6 are entirely different beasts than IIS7.

This probably matters a bit less with IIS express about, but there are sometimes where IIS express don't quite cut the mustard and you need a more full-blown native stack. Especially when debugging strange IIS-related issues. Things like simulating app pool permissions are a bit tougher there.


答: Think of it as "Version Control" rather than "Source Control".  This implies that you can see the entire history of that particular script.  Whether or not you can rebuild the database to it's current form is going to be more a matter of your practices regarding these scripts and any frameworks used to create them.</p>

Title: Database source control


答:
Yes

Database scripts (ddl, dml) are code.  All code should be in a version control system.

Migrations

Use database migrations

Allows you to use the same db files in development, qa and releases.

Release to the database with a release number

Store the release number somewhere for auditing, many store it in the db itself.  Each release will be composed of migrations which will bring the database up to the correct version.

Title: Database source control


问:
Whats the difference between a Software Architect, a Software Engineer, and a Software Developer (Programmer)?
I'm reading through the CNN article about the highest paying jobs in America. A software architect is listed as #1. A software engineer listed as #9. And a software developer (programmer) is listed at #35. I think it's valid to replace computer scientist with programmer, right?

Prior to this I always saw "Software Engineers" as being the title for experienced programmers and team leads. But where then does a "Software Architect" fit in and what exactly do they do? I read the CNN descriptions but they don't really satisfy me so I'm assuming I can get more thorough and experienced descriptions from the awesome user base here.

Thanks in advance for any and all responses received.

答:
Here in the Great State of Texas many companies tend to shy away from the term 'Software Engineer', because in Texas we license engineers, and there is in fact such a thing as 'Sealed' Professional Engineer, Software ( http://www.tbpe.state.tx.us/eng_req.htm ).

I've never met one, nor has anyone I know.  Of course the Engineer's guild would like very much to restrict competition by requiring licenses for writing 'hello world' but that hasn't happened yet.

'Software Developer' is more commonly used for a person whose main job is writing software.

Companies also have a little easier time dealing with Visa issues for 'Software Developers' rather than 'Software Engineers'.

I've only worked in startups for the last 15 years, so I'm not used to a bunch of finely differentiated job titles, but in general a software 'Architect' is a senior developer who is good at laying out the 'big picture' design of a software project.  Every Architect I've ever known spends a great deal of time writing code, just like everyone else, especially after the main design is agreed on.


答: I suspect you've been talking to front end designers! As a front-end designer, and following Falcon's comment, let me add "its not possible" is not something we wish to hear. In the complete picture non-pattern solution may be too costly, but it demands from programmers--to be competitive--an answer to the question, "Is this possible and if so how much?"</p>

Title: Algorithm Vs Design


问:
Implementing a DAO for entity framework
Could anybody help me to find a good tutorial about how can I implement DAO pattern and also tools that help me to create this classes in automated way.</p>

答:
I think it might help you more to google for the repository pattern. It's nearly the same as a DAO, only that DAOs can be finer grained while a repository usually just encapsulates an aggregate root. The principle behind both is the same, though.

As for the code generation: You could just setup a T4 template for them or use an other template engine like NVelocity to create those DAOs automatically. However, if you implement DAOs/Repositories in a generic fashion, then there's little need for code generation in my opinion.

Here's also a tutorial for implementing DAOs with entity framework.

Title: Implementing a DAO for entity framework

ContentLicense: CC BY-SA 4.0


问:
What's the best way to use a kinect with multiple software music synthesizers?
For the past few months I've been looking into developing a Kinect based multitouch interface for a variety of software music synthesizers.

The overall strategy I've come up with is to create objects, either programatically or (if possible) algorithmically to represent various controls of the soft synth. These should have;

X position

Y position

Height

Width

MIDI output channel

MIDI data scaler (convert x-y coords to midi values)

2 strategies I've considered for agorithmic creation are XML description and somehow pulling stuff right off the screen (ie given a running program, find xycoords of all controls). I have no idea how to go about that second one, which is why I express it in such specific technical language ;). I could do some intermediate solution, like using mouse clicks on the corners of controls to generate an xml file. Another thing I could do, that I've seen frequently in flash apps, is to put the screen size into a variable and use math to build all interface objects in terms of screen size. Note that it isn't strictly necessary to make the objects the same size as onscreen controls, or to represent all onscreen objects (some are just indicators, not interactive controls)

Other considerations;

Given (for now) two sets of X/Y coords as input (left and right hands), what is my best option for using them? My first instinct is/was to create some kind of focus test, where if the x/y coords fall within the interface object's bounds that object becomes active, and then becomes inactive if they fall outside some other smaller bounds for some period of time. The cheap solution I found was to use the left hand as the pointer/selector and the right as a controller, but it seems like I can do more. I have a few gesture solutions (hidden markov chains) I could screw around with. Not that they'd be easy to get to work, exactly, but it's something I could see myself doing given sufficient incentive.

So, to summarize, the problem is

represent the interface (necessary because the default interface
always expects mouse input)

select a control

manipulate it using two sets of x/y coords (rotary/continuous
controller) or, in the case of switches, preferrably use a gesture to
switch it without giving/taking focus.

Any comments, especially from people who have worked/are working in multitouch io/NUI, are greatly appreciated. Links to existing projects and/or some good reading material (books, sites, etc) would be a big help.

答:
Every touch controller I have seen that has a knob on it, you turn the knob by moving your finger in a line.  So to turn a particular knob, I would touch the knob, and then slide my finger up to turn the knob clockwise, and down to turn it counterclockwise.  Lifting your finger releases the knob.  Your users will be accustomed to this convention, if they've ever used someone else's control surface.

Moving a slider with my finger feels like moving a slider.  Turning a knob in the usual way does not, because it relies on vertical tactile sensation.  This is in large part why I bought an Oxygen 61 for my own personal setup, so I could have some real knobs to turn.

Rendering your control surface and its mappings to an XML file is a matter of creating a schema and writing code to perform the translations between your XML and your control surface.  To get some ideas about how this might work, consider studying Microsoft's WPF or Silverlight models; they use XAML (Microsoft's own XML schema) to render user interfaces.

Rely heavily on third party XML libraries, and consider techniques such as serialization; these tools will greatly speed up your development effort.

In terms of letting people develop their own control surfaces, it seems axiomatic that they're not going to write XML to do it.  You will need to provide some kind of drag and drop from a toolbox to a designer surface, and then save that out to the XML file.

Allow your users to patch the controls into a MIDI channel by touching them after selecting a control element.  Many current music packages such as Abelton Live already support this; you click on the item you want to control, and then touch the control on your control surface that you want to map to it, and it will automatically get patched in.

Of course, all of this depends on what sort of gestures for touch (and un-touch) are available for the Kinect.  Also, if the Kinect knows how to detect rotary motion of your hand, you could simply translate that into rotary motion for the knob, with say a 2:1 scaling so that you can get a complete turn without turning your hand all the way around.

IMPORTANT: If you haven't yet, as part of your research, watch the movie "Minority Report."

See also http://en.wikipedia.org/wiki/User_interface_markup_language


问:
Advantages of object-oriented programming
Note: this question is an edited excerpt from a blog posting I wrote a few months ago.  After placing a link to the blog in a comment on Programmers.SE someone requested that I post a question here so that they could answer it.  This posting is my most popular, as people seem to type "I don't get object-oriented programming" into Google a lot.  Feel free to answer here, or in a comment at Wordpress.

What is object-oriented programming?
  No one has given me a satisfactory
  answer.  I feel like you will not get
  a good definition from someone who
  goes around saying “object” and
  “object-oriented” with his nose in the
  air. Nor will you get a good
  definition from someone who has done
  nothing but object-oriented
  programming. No one who understands
  both procedural and object-oriented
  programming has ever given me a
  consistent idea of what an
  object-oriented program actually does.

Can someone please give me their ideas of the advantages of object-oriented programming?

答:
I think OOP is basically just a name given to something you may have been tempted to do along the way, as I was.

Way back when I was a baby programmer, even in Fortran, there was such a thing as a pointer to a subroutine. It is really useful to be able to pass a pointer to a subroutine as an argument to another subroutine.

Then the next thing that would be really useful would be to store a pointer to a subroutine inside a record of a data structure. That way, you might say the record "knows" how to do operations on itself.

I'm not sure if they ever built that into Fortran, but it's easy to do in C and its descendents.

So underneath, it's a simple and useful idea that you might have been tempted to do yourself, and is easier to do in more recent languages, even if some people turned it into a giant bandwagon full of scary buzzwords.


答:
In the first place, keep the data normalized (not redundant) as much as you can.
If the data is fully normalized, no single update to the data can make it inconsistent.

You can't always keep the data normalized, in other words you may not be able to eliminate redundancy, in which case it can have inconsistent states.
The thing to do then is tolerate the inconsistency and repair it periodically with some kind of program that sweeps over it and patches it up.

There is a strong tendency to try to manage redundancy tightly by means of notifications.
These are not only difficult to be sure they are correct, but can lead to enormous inefficiencies.
(Part of the temptation to write notifications arises because in OOP they are practically encouraged.)

In general, anything that depends on time-sequence of events, messages, etc., is going to be vulnerable and require tons of defensive coding.
Events and messages are characteristic of data with redundancy, because they are communicating changes from one part to another, trying to prevent inconsistency.

As I said, if you must have redundancy (and chances are pretty good you must), it is best to be able to a) tolerate, and b) repair it.
If you try to prevent inconsistency solely by means of messages, notifications, triggers, etc., you will find it very hard to make it robust.

Title: Writing robust code vs. overengineering


答:
Yes

And furthemore, you'll want branches.

I use Git for branches:

for development per-feature (like we do for regular development of the rest of the application)

and one for the production server as well because customers using the application create contents too.

That way, you get the benefits from source control and branching for both source codes and database (and whatever other files you have).

I haven't found a all-in-one system yet [for PostgreSQL], so I had to write functions/scripts to reindex properly when merging branches (e.g. any index from the production branch should not be modified because customers rely on them whereas indexes+foreign keys from the development branch that intersect with production contents should be reindexed: it wouldn't work for all applications, but it covers all cases of our application so it's good enough).

But the general idea is that database contents are an essential part of the application, and all ressources should be in source control, ergo yes, you should use source control for the database too.

Title: Database source control


问:
Do companies care about university grades when hiring programmers?
Most of my fellow students that I've talked to claim that aiming for good grades is useless as the companies don't care about them when hiring programmers. To them, it's enough to have simply attended courses which may be important, and that's that.

Is this true? Are university grades useless when leaving campus, or do employers ask to see them for an interview?

答: Put yourself in the place of a hiring manager at a large (or not so large) company.  You have one or two entry level positions to fill, and 150 applicants.  The easiest thing to do is filter out everyone with a GPA less that 3.0 (or 3.5).  True, you may eliminate a truly good candidate.   But you will also cut down on your workload, and the time before you can hire someone.  As a hiring manager, my goal is not to fairly evaluate all of the potential candidates, it is to fill the positions with good or great people as quickly as possible.  Anything you can do to make yourself stand out in relation to your competition is a good thing.  Anything that raises questions in the mind of the person reviewing your resume, deserved or not, is a bad thing</p>


问:
Which web site gives the most accurate indication of a programmer's capabilities?
If you were hiring programmers, and could choose between one of (say) the top 100 coders on topcoder.com, or one of the top 100 on stackoverflow.com, which would you choose?

At least to me, it would appear that topcoder.com gives a more objective evaluation of pure ability to solve problems and write code. At the same time, despite obvious technical capabilities, this person may lack any hint of social skills -- he may be purely a "lone coder", with little or no ability to help/work with others, may lack mentoring ability to help transfer his technical skills to others, etc.

On the other hand, stackoverflow.com would at least appear to give a much better indication of peers' opinion of the coder in question, and the degree to which his presence and useful and helpful to others on the "team". At the same time, the scoring system is such that somebody who just throws up a lot of mediocre (or even poor answers) will almost inevitably accumulate a positive total of "reputation" points -- a single up-vote (perhaps just out of courtesy) will counteract the effects of no fewer than 5 down-votes, and others are discouraged (to some degree) from down-voting because they have to sacrifice their own reputation points to do so. At the same time, somebody who makes little or no technical contribution seems unlikely to accumulate a reputation that lands them (even close to) the top of the heap, so to speak.

So, which provides a more useful indication of the degree to which this particular coder is likely to be useful to your organization? If you could choose between them, which set of coders would you rather have working on your team?

答: If they are top 10 on either site they probably aren't great workers because they spend too much time answering questions on websites and not enough time working!! :)</p>


答:
I guess both are pretty different from each other. TopCoders evaluate the programmers, On the other hand, Programmers evaluate themselves on StackOverflow. If an interviewer comes across a candidate, who has the profile on both of these websites, he will consider one profile over the other in following conditions :-

If it's system development position or gaming development, the interviewer will seek the individual's profile on TopCoders to see how he scored in the Algorithm's contest. In essence, cartain development position might favor TopCoder over the StackOverflow.

In case when the overall intellect is needed to be checked over specific programming trait, like in case of web development and Software development, the programmer might check to see the StackOverflow profile. So for a general development position, the SO profile will overseek the TopCoder

The one thing in favor of StackOverflow is the question Stack. The questions here will and always reflect real-life development problems. Whereas in Topcoder, the contest are always made hard, no matter if they applies to real-life problems or not.

Title: Which web site gives the most accurate indication of a programmer's capabilities?

Body:
If you were hiring programmers, and could choose between one of (say) the top 100 coders on topcoder.com, or one of the top 100 on stackoverflow.com, which would you choose?

At least to me, it would appear that topcoder.com gives a more objective evaluation of pure ability to solve problems and write code. At the same time, despite obvious technical capabilities, this person may lack any hint of social skills -- he may be purely a "lone coder", with little or no ability to help/work with others, may lack mentoring ability to help transfer his technical skills to others, etc.

On the other hand, stackoverflow.com would at least appear to give a much better indication of peers' opinion of the coder in question, and the degree to which his presence and useful and helpful to others on the "team". At the same time, the scoring system is such that somebody who just throws up a lot of mediocre (or even poor answers) will almost inevitably accumulate a positive total of "reputation" points -- a single up-vote (perhaps just out of courtesy) will counteract the effects of no fewer than 5 down-votes, and others are discouraged (to some degree) from down-voting because they have to sacrifice their own reputation points to do so. At the same time, somebody who makes little or no technical contribution seems unlikely to accumulate a reputation that lands them (even close to) the top of the heap, so to speak.

So, which provides a more useful indication of the degree to which this particular coder is likely to be useful to your organization? If you could choose between them, which set of coders would you rather have working on your team?


答:
There's some research into fixing bugs in C with genetic algorithms by supplying negative and positive test cases as fitness functions, along with broken code as input. This is an example of a problem that could be solved by a human, but is easier for a genetic algorithm to do. It's important to note:

Although the methods described in this paper do not evolve new programs from scratch, they do show how to evolve legacy software to repair existing faults.

However, new programs have been evolved from scratch—just not in C. The few nontrivial programs written in the Malbolge esoteric programming language have all (to my knowledge) been evolved, not written. The language is too complex for a programmer to use, and too convoluted to efficiently deduce programs from logic alone, so the majority of programs written in it have been produced by genetic algorithms. The fitness function is generally the edit distance to the expected output.

This is nicely circular, in a way. By observing that complex genetic code is written by evolutionary processes, we can simulate evolutionary processes to produce code in a different complex language, without even knowing how the code works!


问:
When is it preferred to combine Add/Edit functionality, and when to keep them separate?
I regularly come across situations where I need to Add or Edit an item, and sometimes I use separate methods for Add and Edit, and other times I combine them into a single method.

Is one method preferred over the other? If so, why?

```<code>public void AddItem()
{
    ShowEditingPopup(new Item(), "Add Item");
}

public void EditItem(Item item)
{
    ShowEditingPopup(item, "Edit Item");
}
</code>```

OR

```<code>public void EditItem(Item item)
{
    ShowEditingPopup(
        (item ?? new Item()),
        string.format("{0} Item", (item == null ? "Add " : "Edit "))
    );
}
</code>```

where ShowEditingPopup is defined as

```<code>public void ShowEditingPopup(object popupDataContext, string popupTitle)
{
    PopupDataContext = popupDataContext;
    PopupTitle = popupTitle;
    IsPopupVisible = true;
}
</code>```

Edit: Just to clarify, I am not Saving the item, I am opening it for Editing. I almost always implement a generic Save method for saving to the database

Edit #2: Edited code samples so they more accurately reflect the sort of situation I am referring to

答:
Let's say I'm adding or editing a Person entity.  I would almost always have two models to handle the add/edit processes:

AddPersonModel

EditPersonModel

They would almost always inherit from a common abstract base class:

AddEditPersonModelBase

So the base class might have an abstract Commit method, which the derived classes override in order to either new up a new Person entity, or to save the changes to the existing Person entity.

The business logic that's common to both adding and editing goes in the base class (for instance, for editing addresses), but there's always a little bit of business logic that's different if you're adding or editing, and those go in the subclasses.  For instance, you might want to assign them a unique incrementing ID number, but you don't actually create it until you save the entity.  In that case, only your EditPersonModel has that property.

Similarly, you'd have separate Views (and ViewModels) for adding or editing a Person, but it would make sense to have both add and edit variants inherit from the same base class because a lot of it would be common.


答:
Think about your context for a second... There is no distinction between Adding a new element or editing an existing one. You just SaveChanges(). The individual element state tell the context whether its a new element being added or an existing one being edited.

EDIT: Ok... Well in that case, I do have separate Controller Actions (MVC3) for each action, however, only 1 view...

Title: When is it preferred to combine Add/Edit functionality, and when to keep them separate?

Body:
I regularly come across situations where I need to Add or Edit an item, and sometimes I use separate methods for Add and Edit, and other times I combine them into a single method.

Is one method preferred over the other? If so, why?

```<code>public void AddItem()
{
    ShowEditingPopup(new Item(), "Add Item");
}

public void EditItem(Item item)
{
    ShowEditingPopup(item, "Edit Item");
}
</code>```

OR

```<code>public void EditItem(Item item)
{
    ShowEditingPopup(
        (item ?? new Item()),
        string.format("{0} Item", (item == null ? "Add " : "Edit "))
    );
}
</code>```

where ShowEditingPopup is defined as

```<code>public void ShowEditingPopup(object popupDataContext, string popupTitle)
{
    PopupDataContext = popupDataContext;
    PopupTitle = popupTitle;
    IsPopupVisible = true;
}
</code>```

Edit: Just to clarify, I am not Saving the item, I am opening it for Editing. I almost always implement a generic Save method for saving to the database

Edit #2: Edited code samples so they more accurately reflect the sort of situation I am referring to


问:
How to create and publish a useful Java library
I've recently worked on a Java class that generates permutations per list of objects. In any case, I would like to have this library offered to the public, so I have several questions:

Most libraries I see have this complicated package naming, specifically including com/org. Is there a convention for these or is a permutations package enough?

Is there a specific format to publish these? Should I include separate WARs for source code / javadoc?

I have the files on a GitHub repository. I guess I can serve the files there, but how do I get people to find my repo?

答:
A standard way to publish (apart from the source code on GitHub) is to have formal JAR/WAR releases to Maven Central which many (Maven, Gradle, Ant/Ivy) build tools use to bring in libraries as a dependency.  To do this, the best way is to go through the Nexus process.

It's also considered friendly to host those same JAR/WARs on a code hosting repo such as Sourceforge or GitHub.

In terms of your domain.  I recommend you buy firstnamelastname.net/org/com and use that as your naming scheme (e.g. for me it's net.martijnverburg.foobar).  Otherwise using the github domain as suggested by @Daniel Moura is a good one.

To publicise it, blog about it, twitter about it, submit it to hacker news, reddit, digg, slashdot, dzone, TSS, javaworld etc

HTH!


答:
Most libraries I see have this complicated package naming,
  specifically including com/org. Is there a convention for these or is
  a permutations package enough?

There are recommendations from Oracle on how to name your packages. The reason for this naming convention is to minimize duplicates. If everyone simply used short, simple names, it becomes more likely that a project will include two permutation packages. If one class name was the same, there would be naming conflicts. Things can get confusing for the developer, if there are't naming conflicts that prevent resolution of the classes.

If you have a domain name, I would suggest using that. If you are hosting on a service such as GitHub or Sourceforge, using the path to your project would be sufficient as well. Regardless, be explicit to prevent conflicts or confusion.

Is there a specific format to publish these? Should I include separate
  WARs for source code / javadoc?

There's no specific format. At the very least, source and a convention build script (Make, Ant, Maven). It's nice to have precompiled JARs or WARs, but not essential. Some projects include the Javadoc in the library, others might produce two JARs (one with Javadoc and one without). It might also be a good idea to simply publish your Javadoc on the Internet if your project hosting solution allows for it.

I have the files on a GitHub repository. I guess I can serve the files
  there, but how do I get people to find my repo?

Advertise it. Start by showing it off to a few friends. Blog about it. Share a link on the Internet. Find someone who has a problem that they can solve using this library (but make sure you disclose that you made the library).

Title: How to create and publish a useful Java library

Body:
I've recently worked on a Java class that generates permutations per list of objects. In any case, I would like to have this library offered to the public, so I have several questions:

Most libraries I see have this complicated package naming, specifically including com/org. Is there a convention for these or is a permutations package enough?

Is there a specific format to publish these? Should I include separate WARs for source code / javadoc?

I have the files on a GitHub repository. I guess I can serve the files there, but how do I get people to find my repo?