答:
If the problem is to find the first element of list L1 which is also contained in L2, run through the elements of L1 one-by-one and check if the current element is in L2. The second test ("is element in L2") can be either done by a simple loop over all elements in L2. Or you put all elements of L2 into a hashset first, which can speed-up the process fairly.

Now it should be obvious that you can switch roles of L1 and L2 when you are looking for the first element in L2 which is also part of L1. And if you are looking for a common element from one of the lists which has the lowest positional index either in L1 or L2, run both steps described so far, and if you find two different elements, choose the one with the lowest index in either L1 or L2.

This approach has one disadvantage: if L1 and L2 are huge, and you have some non-common elements at the beginning of each lists, you have to read either the full list L1, L2 or both, even when there are some common elements among the first elements of L1 and L2. So the idea of your solution above is to use the following subsets:

```<code>K1(n)="the first n elements of L1" (or L1 if n>length(L1))
K2(n)="the first n elements of L2" (or L2 if n>length(L2))
</code>```

with n running from 1 to max(length(L1),length(L2) and check if K1 and K2 have a common element, for each n. The smallest n where K1(n) and K2(n) have a common elements shows you that either the n-th element of L1 or the n-th element of L2 is the element you are looking for.

It should be obvious that when K1(n) and K2(n) are disjoint, and you are going from n to n+1, you only have to check if the new introduced n+1st elements from L1 and L2 are in K2(n+1) or K1(n+1). The use of a fast hashset data structure for K1 and K2 which is incrementally extended keeps this process fast even for bigger n. And if you found a common element for a certain n, you can stop the process immediately. That is what you described in your post.

This approach will work fairly fast even when L1 and L2 have, for example, more than a million elements, but the first common element in both lists is among the "top ten" in both lists. It won't save you much when L1 and L2 do not have any element in common, but that is also true for any other approach.

Title: How do you find the first common element in two arrays

Body:
If the problem is to find the first element of list L1 which is also contained in L2, run through the elements of L1 one-by-one and check if the current element is in L2. The second test ("is element in L2") can be either done by a simple loop over all elements in L2. Or you put all elements of L2 into a hashset first, which can speed-up the process fairly.

Now it should be obvious that you can switch roles of L1 and L2 when you are looking for the first element in L2 which is also part of L1. And if you are looking for a common element from one of the lists which has the lowest positional index either in L1 or L2, run both steps described so far, and if you find two different elements, choose the one with the lowest index in either L1 or L2.

This approach has one disadvantage: if L1 and L2 are huge, and you have some non-common elements at the beginning of each lists, you have to read either the full list L1, L2 or both, even when there are some common elements among the first elements of L1 and L2. So the idea of your solution above is to use the following subsets:

K1(n)="the first n elements of L1" (or L1 if n>length(L1))
K2(n)="the first n elements of L2" (or L2 if n>length(L2))

with n running from 1 to max(length(L1),length(L2) and check if K1 and K2 have a common element, for each n. The smallest n where K1(n) and K2(n) have a common elements shows you that either the n-th element of L1 or the n-th element of L2 is the element you are looking for.

It should be obvious that when K1(n) and K2(n) are disjoint, and you are going from n to n+1, you only have to check if the new introduced n+1st elements from L1 and L2 are in K2(n+1) or K1(n+1). The use of a fast hashset data structure for K1 and K2 which is incrementally extended keeps this process fast even for bigger n. And if you found a common element for a certain n, you can stop the process immediately. That is what you described in your post.

This approach will work fairly fast even when L1 and L2 have, for example, more than a million elements, but the first common element in both lists is among the "top ten" in both lists. It won't save you much when L1 and L2 do not have any element in common, but that is also true for any other approach.


问:
In TDD, if I write a test case that passes without modifying production code, what does that mean?
These are Robert C. Martin's rules for TDD:

You are not allowed to write any production code unless it is to
make a failing unit test pass.

You are not allowed to write any more
of a unit test than is sufficient to fail; and compilation failures
are failures.

You are not allowed to write any more production code
than is sufficient to pass the one failing unit test.

When I write a test that seems worthwhile but passes without changing production code:

Does that mean I did something wrong?

Should I avoid writing such tests in the future if it can be helped?

Should I leave that test there or remove it?

Note:  I was trying to ask this question here: Can I start with a passing unit test?  But I wasn't able to articulate the question well enough until now.

答:
Your test pass but you aren't wrong. I think, it happened because the production code is not TDD from the beginning.

Let's suppose canonical(?) TDD. There is no production code but a few test cases (that is of course always fail). We add production code to pass. Then stop here to add more fail test case. Again add production code to pass.

In other words, your test could be a kind of functionality test not a simple TDD unit test. Those are always valuable asset for the product quality.

I personally don't like such totalitarian, inhuman rules ;(

ContentLicense: CC BY-SA 3.0


问:
Scoring/analysis of Subjective testing for skills assessment
I am lucky in the sense that I have been given the opportunity to be a 'Technical Troubleshooter' for our offshore development team. While I am confident and capable of dealing with most issues, I have come across something that I am not. Based on initial discussions with various team members both on and offshore, a requirement for a 'repeatable, consistent' skills assessment has been identified.

In my opinion, the best way to achieve this would be a combination of objective and subjective tests. The former normally being an initial online skills assessment on various subjects, for example General C#, WCF and MVC. The latter being a technical test where the candidate would need to solve various problems and (hopefully) explain the thought processes involved with the  solution whilst doing so.

Obviously, the first method is consistent, repeatable and extremely accurate. The second is always going to be subjective and based on the approach, the solution (or possibly not) and other factors. The 'scoring' of this is also going to be down to the experience and skills of the assessor and this is where my problem lies;

The person that is expected to be the assessor initially (me) has no
experience.

The people that will ultimately continue this process for other
people will never remain the same due to project constraints and
internal reasons, this changes the baseline for comparison.

I am not aware of any suitable system that can be classed as
consistent and repeatable for subjective tests with the 2 factors
above, let alone if those did not exist.

So anyway, I have to present a plan that will ultimately generate a skills/gap analysis and it is unlikely that I will be able to use an objective method (budget constraints most likely reason). The only option left is the subjective methods and the issues above.

Does anyone have any suggestions for an approach that may tick all the boxes?

答:
A "skills assessment" to me sounds like the classic problem of mixing requirements with solution.

I would backtrack and document the business problem and expected benefit. I don't know the specifics in your case, but an example might be:

Problem: "40% of the candidates we hire do not meet our needs, which causes our team to lose 200 hours of productivity each month."

Expected benefit: "Improve candidate selection to reduce our costs to no more than 40 hours per month."

Estimate: "One FTE month of effort."

Month 1: Result = -140 hours invested
Month 2: Result = 20 hours saved = Monthly savings (200 - 40) - 140 implementation hours
Month 3: Result = 160 hours saved = Monthly savings (160) + 20 hours accumulated
1 Year: Result = ...
2 years: ...
3 years: ...

Getting to the heart of the problem opens up alternatives that may not be considered otherwise.

The problem with "consistent tests" is that the questions you ask will eventually leak to your candidates, and will no longer be consistent.

You could try solving this by creating many questions and only providing a subset to each candidate, however you would not achieve consistency until a sufficiently large population took your tests.

I suggest you read up on ways to predict IT performance. You are likely to find some surprises, and tests are not required.


问:
How does public API designer come to the conclusion what shall be provided for future and what not?
Often working with various jars and exploring the features specially in corner cases, I often realize and think that how is that they thought that it might be a useful scenario somewhere in future that it might be used and an API is made handy. So, how do they come to the conclusion what shall be provided and what not?

Other problem I faced once was that I was in need of a certain feature and it was missing from the list which struck me with immense drawback of using API's.

Shouldn't it be that if some feature is missing then programmer should be able to program it himself rather than depending entirely on APIs all the time?

答:
API writing is indeed one of the most difficult tasks in computing. Obviously it's possible to simply expose everything you have and let people use whatever they like. That prevents your second problem: a task the the code clearly could do, but that you can't do via the API.

Unfortunately, that is the only advantage of exposing everything. The drawback is that the API becomes more difficult to understand the bigger it is, and the less clearly it is organized. An API that is confusing to use isn't used by many people (unless it has some "unique selling point"), so code authors try to make their libraries easy to understand. But smallness and clarity are almost impossible to achieve with an "everything is public" approach, so you have to choose what to expose, whether to allow One Right Way to do anything or Orthogonal Building Blocks that are easy in themselves but can be combined without restriction.

This is a very difficult call to make. Entire programming languages follow different principles on this point (Perl officially claims that There's More Than One Way To Do It, while Python prefers that there be One Obvious Way to do it), so it isn't surprising that individual coders disagree as well.

As for what to allow at all in the first place... may of the most successful programming projects start out as something that the author does for their own immediate requirement. When something works well, looks coherent and seems something that others might want, then people start wondering whether it might make sense to publish it as a library. At this point very different things can happen. Some coders just take the set of things they use the code for and publish that. They may respond to community feedback by adding more API calls, or they may completely ignore them. Others interview possible users in advance and try to find a set of methods that will allow them to do what they want, and is still reasonably well-designed. (Still others interview possible users and include absolutely everything they suggest...)

(It should also be noted that API design is almost never taught to beginning programmers in the way that structured programming, OO principles, or even project management and revision control are now routinely taught. Apparently the task is considered either to difficult or too rare to be taught to programmers in general.)


问:
Why is it so hard to get employees to update the issue tracker?
I've always had this struggle to get folks to update their issues, both at my company and at work. I've had a few cases when people actually do it from the goodness of their heart, but ~70% of the time I have to be chasing people down.

Being the one that generally does some or other form of management (I am firstmost a developer), the main reason I try to give is that I don't want to be chasing people down and interrupting to query on progress, but I don't think in the end people mind that much being asked. In some rare and extreme cases I end up updating their tickets (when I need to create reports).

So, have you ran into this problem?, how have you encouraged developers to update the issue tracker frequently?, what degree of success have you had?

答:
Stop asking about coding progress (its usually an arbitrary percentage plucked out of thin air anyway) until the ticket is closed give no credit. If the main thing you measure is number of tickets closed it will improve.

Do note however that all metrics can be gamed and metrics tend to work better when teamed up with complementary metrics e.g. you probably also want to look at issues that get reopened as this implies they are being prematurely closed


问:
Dependency Injection - Dependency Chain Pattern
On my last large project, I used dependency injection really heavily. I started out using constructor injection but even two or three dependencies resulted in really ugly code.

```<code>public MyClass(
    IDependency1 dependency1,
    IDependency2 dependency2
    IDependency3 dependency3)
</code>```

I am not a fan of property injection. Some people say it implies an "optional" dependency. I think what they mean is that there will be a default dependency (the production class) but it can be replaced with a mock object during test. Many times, my dependencies have dependencies, too, so I can't provide a default value unless I used a singleton or something. My problem with property injection is that I prefer fully initialized objects and don't want to accidentally forget to mock out a dependency during test.

So, I found a compromise. I created a "parameter object" that had properties for all of my dependencies. I passed these to my constructors. This had the benefit of keeping my code somewhat cleaner and I could ignore some dependencies during test if they weren't touched.

Based on feedback I got the impression this was a bad idea. It was constructor injection or parameter injection - no compromise allowed. Later I realized that these parameter objects sometimes became their own classes (or set of classes).

That's when I discovered an interesting pattern. Many business objects depended on other business objects, which had their own dependencies. What I ended up with was an interesting data structure, similar to a linked list.

This data structure could become fairly complex depending on the number of interacting classes. In most cases, the structure was closer to an n-ary tree. Each parameter object could link to any number of other objects (including other business objects). The business objects were the nodes of the tree and the parameter objects were like the edges connecting them.

I think connecting all these objects together without using a declarative dependency injection framework would be mind-numbing. The dependency injection framework I was using was going 8 levels deep in my code building the dependencies from the bottom up in the worst case.

The parameter objects usually just exposed the dependencies. On rare occasions, I would hide them behind friendly function calls and made them their own business objects (usually resulting yet another parameter object). I had to remind myself that the parameter objects only existed because I didn't want to construct dependencies in the constructor (or pass them to the constructor). It only made sense to create new business objects when I started repeating myself. Even then, I ended up with an explosion of parameter objects.

I've read plenty of books explaining that this situation should never happen. Classes should have very few dependencies. It was a sign that my classes did "too much". But in most of these cases, a business object used data from multiple database tables (repositories), configuration settings, services, etc. in order to calculate something. This occurred most often when implementing a series of steps making up a unit of work. When N things are needed to do a task, the best you can do is push those N things to other classes or on up the call stack. Is one class with 6 dependencies better or worse than 3 classes with two dependencies each?

I am hoping to get some feedback on this approach to dependency injection - in how it relates to architecting a business layer.

答:
IMHO creation of "complete" classes via constructor has always been appealing, however setter injection requires a no-arg constructor, allowing pre-conditions (e.g. assertions) to be a reasonable alternative to guarantee "completeness" in the context of DI containers.

To me it is a trade-off between adding complexity versus implementing a simple, pragmatic, solution. And simplicity always wins.


问:
Alternative Scripting Language to Lua?
I would like to add scripting support to an applications and with plenty scripting languages available I am a bit overwhelmed.

At first I thought about Python but I guess Python is a little too big for my taste and the application (although I like it very much, it gets a lot of things right in my opinion while the syntax is clean and simple especially if you are not doing heavy OOP).

I am also very fond of Lisps. I like scheme and it is the perfect extension language - at least in some ways, but I would like to stay syntactically more conservative.

I remember having heard a lot of positive things about Lua and indeed Lua seems a good possibility. Unfortunately there is this one thing that really "turns me off": Its the  local keyword for local binding. This is really ugly to my taste and I frankly do not quite grok why languages are still designed this way and in essence knowing about local. This is also a major drawback of JavaScript in my opinion and I feel like it all boils down to bad language design. My major concern is, that a user might just override a function from just within her/his function just by omitting local.

But then Lua gets a lot of things right, size, speed, and it is surprisingly scheme-esque. Yet I am really afraid that it is not suitable for non-programmers who have no sense of scope.

Any alternatives on the horizon?

Might hacking the Luacore to make local the default be an option?

Lua sources appear to be quite decent and modular, so this would be an interesting project ;)

答:
I'd suggest TCL, its designed to be an embedded scripting language that can define DSLs for non-programmers.

The key thing with TCL, scheme or any solution here though is designing a DSL that the user can understand, with a good enough DSL the user should rarely need general programming constructs (which could be harder to comprehend)

WRT your comment TCL doesn't really have a grammar so I wonder if you are misunderstanding something about it? Or rather its grammar is about as complex as schemes.

Title: Alternative Scripting Language to Lua?


答:
First of all: what do you mean with "people updating their progress"?

Do you mean "developers updating the current estimation", or "developers not setting an issue to resolved", or rather "customers/testers not closing a resolved issue", or all together?

From a developer's perspective, it is a mixture of mindset and culture.

mindset: when you set an issue to resolved it means you are done, and responsible if it is buggy

culture: if the whole company is not very keen to use such tools, but prefer other organisation strategies

My experience is: you need the culture to point in the right direction, at least. What helps next is to define a DoD (definition of 'done') - if a developer (works for other roles, too) can say (s)he fulfilled the whole list it's relieving to mark the issue resolved and move on with no need to look back.

Title: Why is it so hard to get employees to update the issue tracker?

Body:
I've always had this struggle to get folks to update their issues, both at my company and at work. I've had a few cases when people actually do it from the goodness of their heart, but ~70% of the time I have to be chasing people down.

Being the one that generally does some or other form of management (I am firstmost a developer), the main reason I try to give is that I don't want to be chasing people down and interrupting to query on progress, but I don't think in the end people mind that much being asked. In some rare and extreme cases I end up updating their tickets (when I need to create reports).

So, have you ran into this problem?, how have you encouraged developers to update the issue tracker frequently?, what degree of success have you had?


问:
Creating a Application in Winrt that requires Internet
I am making a paid App for Windows 8, c#. I am wondering which is better?

If my application doesn't need internet connection normally but does requires internet connection for the first time to download content data. --Makes my life easier

Load the default data when installing. Then ask the user if he wants to update in app. -- Making the default data will be pain.

Now my big question is, is it safe to assume user has access to internet now-a-days when using application that shouldn't require internet?

答:
Yes it would be safe to assume that most of the people will have internet 90% of the time. But   for a better user experience you should consider designing you app in such a way that it is still usable even if there is not internet connection.

However it totally depend on the nature of the application and since you have not mentioned details about your app, so try to identify features which can still work without internet with the help of offline storage. (sqllite and Indexeddb are couple of option you might want to consider).

This will surely make the user experience much better, may be in background based on whether you are connected or not you can inform the user with the help of Toasts like

"App is connected"
"App is in offline mode"


问:
Are there any limitations to using WinRT instead of .Net?
From my understanding creating an application that runs on multiple architectures requires virtualization, and virtualization reduces performance since it creates a layer of abstraction.

With Windows 8 supporting both Intel and ARM architectures should we expect slower performance with a WinRT app versus a .Net app running on an Intel device?

Also, will WinRT support database connectivity and active directory access?

答:
Regarding your question about database connectivity part, as of now winRT does not have support for most of the database drivers. SQLLite is the one which is supported as of now.

Ideal-way would be to access your data layer via services. and your should not be directly connecting to database like sql server, oracle and any other DB for that matter.

you can use Indexed db and sqllite for local data storage options.


答:
It's hard, because employees clearly feel that updating issue tracker is not important. You have to change that, but there's a catch. Communication is hard. Effective communication is really hard -- way harder than you might think it is. So hard, that communication usually fails, except by accident.

Show, don't tell. Eg. don't tell that you (or your boss) need the data for a report. Show from employees' point of view how up-to-date issue tracker affects and helps them.

Lead by example.


问:
Written communication skills courses, how important are they for developers?
We usually worry about coding standards, ethics, latest technology etc. But at times we tend to ignore our writing skills and communicating skills.
Do we need to pursue a communication skills courses? Which ones do you prefer? Any online courses available which you might have tried? </p>

答:
I would focus more on communication in terms of often used documents whether in the general populus or specific to your company. Wireframing, prototyping, flowcharting, etc. can make a huge difference to the project. Many are leaning towards user experience design where you communicate user needs in various ways such as with personas, concept models, usability tests and reports, and so forth. And in terms of web development at least there's also content inventories, site maps, and screen designs.

I imagine a lot of it depends on your role within the company. You might also consider slides, interactive demos, video tutorials, context sensitive help, or tutorials. Then there are a whole host of technical writing documents.

I find having a technical writing background helps my development in that I can help clarify communication between programmers, designers, users, and other members of the team such as business analysts and marketers. Being able to translate between technical documentation and everyday language with a newbie can really help.

Business communication can be very important in a co-operative environment where team-building is desired. Even something as simple as critical thinking and debating can help draw out a project and get everyone contributing and on track.

ContentLicense: CC BY-SA 2.5


问:
Why is Java boolean primitive type name not 'bool'?
Java has

int and Integer

boolean and Boolean

This seems a bit inconsistent, why not either

bool vs Boolean to use an established shorter name for primitive type?

or

integer vs Integer to keep type names consistent?

I think C++ had decided to use bool quite a bit earlier than Java decided to use boolean, and maybe also some (non-standard at the time?) C extensions too, so there would have been historical precedence for bool. I've noticed I often instinctively try to use bool at first (good thing modern editors immediately spot this without extra compilation round), so it'd be nice to know the rationale behind current state of affairs.

If someone remembers (a part of) the story, or can even find and link to relevant historical discussion in the net, that would be great.

答:
Actually, Java is more accurate to history here. The theory of true and false values was invented by George Boole and is commonly referred to as Boolean Algebra in his honor.

bool is really just a shortcut to avoid a longer name, however, given the auto-completion support of modern IDEs, this is no longer a valid reason (and wasn't even back in the days when Java decided to go for boolean).

I have not been part of the decision process for Java, but if someone cares for history, then "Boolean algebra" is the relevant historical precedence, and one might as well question the C/C++ decision on why they mutilated Boole's name by cutting off the e.


问:
Where to add the license file?
I have written an application in Python using Tkinter and want to distribute under the WTFPL license. But I don't understand where to add the copying.txt file that needs to be added in the folder that is distributed.

Please clarify.

答:
You need to create an archive copying.txt in your root folder with follow content:</p>

```<code>            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
                    Version 2, December 2004

 Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>

 Everyone is permitted to copy and distribute verbatim or modified
 copies of this license document, and changing it is allowed as long
 as the name is changed.

            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. You just DO WHAT THE FUCK YOU WANT TO.
</code>```

Title: Where to add the license file?

Body:
You need to create an archive copying.txt in your root folder with follow content:

            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
                    Version 2, December 2004

 Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>

 Everyone is permitted to copy and distribute verbatim or modified
 copies of this license document, and changing it is allowed as long
 as the name is changed.

            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. You just DO WHAT THE FUCK YOU WANT TO.


问:
Configuration file that can be modified by user in C#
I want to create a configuration file (text file preferred) that can be modified by user. A windows service will read from that file and behave accordingly. Can you recommend a file format for this kind of process?
What I have in my is a config file like the game config files, but could not imagine how to read from it.

My question is very similar to INI files or Registry or personal files?, but my question is different because I need to consider user editing.

答:
Personally I'd use Settings, its xml based, but the real benefit is that MS have already done all the coding for you for most types (including both global settings and per user overrides), so it really simple to use. as Wyatt points out in his answer it is also possible to extend using custom configuration sections (personally I find this overkill for most configuration needs, but its nice to have available when you do have a complex configuration scenario).

Depending on how tech savvy the users are you could use Settings and allow the user to edit the xml themselves.

If the users are not tech savvy then I'd suggest you provide a GUI to allow editing anyway as otherwise you will quickly find you have support calls about corrupt config files (regardless of what format you use)


答:
local is mandatory attribute of full lexical scoping:

```<code>local x = 0
function f(inc)
    x = x + inc -- if you auto-localize it, this is broken
end
</code>```

On the other hand, we probably could remove local from the language, but add complementing outer (bound, upvalue, you name it):

```<code>x, y = 0, 0
function f(inc)
    outer x
    x = x + inc -- uses outer slot: "0 + inc"
    y = y + inc -- creates local (and raises "nil + number" error)
end
</code>```

If you do not have either (including regular globals), your scoping is just useless.

Lua parser is written well, although I don't think it will be trivial fix.

Title: Alternative Scripting Language to Lua?

Body:
I would like to add scripting support to an applications and with plenty scripting languages available I am a bit overwhelmed.

At first I thought about Python but I guess Python is a little too big for my taste and the application (although I like it very much, it gets a lot of things right in my opinion while the syntax is clean and simple especially if you are not doing heavy OOP).

I am also very fond of Lisps. I like scheme and it is the perfect extension language - at least in some ways, but I would like to stay syntactically more conservative.

I remember having heard a lot of positive things about Lua and indeed Lua seems a good possibility. Unfortunately there is this one thing that really "turns me off": Its the  local keyword for local binding. This is really ugly to my taste and I frankly do not quite grok why languages are still designed this way and in essence knowing about local. This is also a major drawback of JavaScript in my opinion and I feel like it all boils down to bad language design. My major concern is, that a user might just override a function from just within her/his function just by omitting local.

But then Lua gets a lot of things right, size, speed, and it is surprisingly scheme-esque. Yet I am really afraid that it is not suitable for non-programmers who have no sense of scope.

Any alternatives on the horizon?

Might hacking the Luacore to make local the default be an option?

Lua sources appear to be quite decent and modular, so this would be an interesting project ;)

Body:
local is mandatory attribute of full lexical scoping:

local x = 0
function f(inc)
    x = x + inc -- if you auto-localize it, this is broken
end

On the other hand, we probably could remove local from the language, but add complementing outer (bound, upvalue, you name it):

x, y = 0, 0
function f(inc)
    outer x
    x = x + inc -- uses outer slot: "0 + inc"
    y = y + inc -- creates local (and raises "nil + number" error)
end

If you do not have either (including regular globals), your scoping is just useless.

Lua parser is written well, although I don't think it will be trivial fix.


答:
Writing a simple DSL in Boo is an excellent solution for this kind of problem and near-infinitely extensible as the rules get more complicated. You can even, without too much effort, give the user basic Intellisense by shamelessly reusing a bit of SharpDevelop. And you can easily validate the rules they create.

However, seriously consider providing a user interface. It's more work on your side to develop but it's less work later to support.

Title: Configuration file that can be modified by user in C#

Body:
I want to create a configuration file (text file preferred) that can be modified by user. A windows service will read from that file and behave accordingly. Can you recommend a file format for this kind of process?
What I have in my is a config file like the game config files, but could not imagine how to read from it.

My question is very similar to INI files or Registry or personal files?, but my question is different because I need to consider user editing.


问:
Web Developer or Software Engineer?
A question that I have been asking myself and really confused which path to take.

So I need your guys help as to the pros and cons of these 2 professions in today's world. I love web applications development as the Web is the best thing to happen in this age and nearly everyone gets by on the World Wide Web. And also tend to keep learning about new technologies and about web services.

On the other hand I like software engineering also for the desktop applications as I have had experience with development small scale software in VB.Net, Java, C++, etc.

Which path has more scope and better future? What's your view?

答: My personal opinion is that the line between these will blur more over time if it hasn't already.  Consider Adobe's Integrated Run-time that allows internet applications to run outside of the browser as an example here where the web skills of some developers can now be used to make desktop applications.  This is ignoring a few other realms of development like mobile applications and embedded systems.</p>

Title: Web Developer or Software Engineer?


问:
How to process an endless XML data stream
There is an endless data stream of XML messages (and "heartbeats"), that I receive via a telnet connection and through a site-to-site VPN IPsec tunnel.

I'm still pondering. What is the best/most elegant solution to process the XML messages without losing any data, without redundance and with a (nearly) constant processing time? A never-ending process/script? Writing the stream in file(s) and processing it/them periodically step by step? Or something completely different?

The messages usually come every few seconds. Sometimes every second. Sometimes maybe every 10 seconds. It differs but not a lot. One XML message within the stream contains 45 rows. The messages should be stored afterwards.

Note: The concrete structure of the XML messages and the infrastructure of the participating systems are negligible in my opinion.

答: Event stream based is your best bet! in C I will use Expat. In Java, I will use SAX parser.</p>


答:
The reason is they don't grok why they should be updating the issue tracker, apart from the fact that you say so.

Why is that? My guess is that updating the tracker doesn't affect their job in any meaningful way, so the solution is probably to implement a tracking system which actually helps them do their job better.


问:
Converting Business Process Maps into Software
I am fairly new to web application development. I have defined my problem domain through talking to various stakeholders and putting a process map together - basically a flow chart showing the different steps and processes that the web application must be able to recreate.

The problem I am having is that I'm struggling to map this process into application design and code. I was wondering if there are any best practices or development methods that help map a business process into an application design?

I have briefly read up about Domain Driven Development and that seems like it may be a good approach.

To clarify, I am after a methodology or design principle that will help turn the business process into code. For example, I COULD just map every box in the process map to an identically named class in my code. Thus translating the business process into a domain model (i.e. object orientated) in my code. But is this the best way to do it?

答: You might want to take a look at various open source Business Process Management suites.  BPM is this exact idea, identifying the process a business takes to effect some activity, and mapping it into software in a way that manages the flow of the process.  It seems like it would lend itself well to your issue.  I work professionally with IBM BPM, but that is a proprietary and non-free solution, and is probably overkill for what you might be looking to achieve, which is why I provided a list of open source ones.  I suggest looking through how those platforms/framworks operate on a conceptual level, even if they aren't the direct implementation of a solution for you, understanding how they handle the concept can be useful to you in 'rolling your own' solution.</p>


答: Maybe they consider it too much work to open a browser, log in, find the ticket and fill it. Maybe you can try to encourage them with hooks. Nowadays it is common feature that in git/hg message [ I assume you use one of these ] you can type something like   liked FIXED #123, and ticket will automagically change once you push your commit. That way it is almost no work for developer [ if he works on each issue in separate branch - he already has ticket id ] and most likely he will add those couple of characters in commit message. If this solution is not enough, maybe it means that tickets' scope is too big, and should be divided into many smaller tickets?


问:
How should I structure a C# application that reads & writes binary data?
I have to read and write binary "chunks" of approximately 1Mb each.  The data can come in the form of a stream or a in-memory byte[].

Normally I would use a Struct with a fixed layout, but there are a few properties of this binary data that are making this harder:

Byte 4 describes the "version" of the chunk

Byte 5 starts either as variable array of sub-chunks or as a human readable blob

Each sub-chunk has a version, and has a variable array of data within it.

The endian-ness of the data is inconsistent

How should I structure a program that needs to handle binary data thats in this format?

答:
I once had to implement a versioned de/serialization abstractions similarly to what you're describing before, I'll detail what I (can remember I) did:

I created an unversioned form of the objects that were to be serialized/deserialized which just decorated the latest version so all consuming code always pointed to the versionless ones which were always the latest versions; this way when new versions came out I didn't have to change any consuming code, just those versionless abstractions had to be pointed to the new versions.

So let's say an example like..

```<code>public class Person : V4.Person { }
</code>```

Then in the implementation, I had each versioned object upconvert on deserialization by passing down to older until one of them recognized the version so it was something like..

```<code>public class V4.Person : V3.Person
{
    public string SomethingNewInV4 { get; set; }

    public static Person FromBytes(BinaryReader personReader)
    {
        Person person = base.FromBytes(personReader);

        if (person.Version >= 4) // If this version or newer, it will have the SomethingNewInV4 property, deserialize it.
        {
            int stringLength = personReader.ReadInt();
            person.SomethingNewInV4 = personReader.ReadString(stringlength);
        }
        else
        {
            person.SomethingNewInV4 = "default string used when upconverting from V3";
        }

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

In this way, each new version is just a modification of the previous, inheriting the previous version and adding (or hiding) parts from it, and using it's serialization/deserialization which it then adds onto it's particular parts special to it's version. There is the possibility for a breaking change in the chain but that just means that particular version may have to reimplement serialization/deserialization from scratch including all the intelligence for branching if previous versions should do it or not, but scenarios like that are likely minimal.

The versionless facade in front ensures all new serializations are serialized in the latest format, and all old deserializations start at the top of the stack which will call down to the bottom through inheritance, and each version will upconvert from there, so that versionless facade redirecting to the latest is necessary (unless each time a new version comes out you want to update all consuming code).

V1 will have to do the version picking and full deserialization etc, but above that each version will check which version and choose whether the data for it is there or it needs to fake it up.

When I did this, the subchunking you're referring to was totally there as well and I handled this by having this same layout for each subchunk type, so you could have Person's deserialization call to Arm's deserializer when it got to the Arm chunk, and if it had a numeral in front counting the Arms it would use that to deserialize in a loop. Each versioned subchunk needs a versionless front piece where all the main chunks call to, so V4.Person would call to the versionless Arm's deserializer which may point to V3 if that's the latest Arm, or etc.

Last point: I strongly suggest memory stream for this, I remember going back and forth on this and realizing the byte array was terrible because the forward movement meant I had to pass pointers around between versions, with the memory stream version 1 takes all the initial V1 data, V2 takes all the V2 data which is layered after that, and so on and so forth without needing to maintain the pointer to your current position in the array.

Your problem is almost step by step identical to the one I faced and solved in this manner, it worked pretty well, hope this helps! To make things a little easier I made extension methods on BinaryReader for some of the types that pointed to the versionless stuff so there would be like

```<code>public Arm ReadArm(this BinaryReader target) { return Arm.FromBytes(target); }
</code>```

then in person you would have..

```<code>int numberOfArms = personReader.ReadInt();
List<Arm> arms = new List<Arm>();
for(int i = 0; i < 1; i++) arms.Add(personReader.ReadArm());
</code>```

I made it fit with BinaryReader's normal naming, don't remember if it's Read or To.. Either way it was a handy shortcut.

Body:
I once had to implement a versioned de/serialization abstractions similarly to what you're describing before, I'll detail what I (can remember I) did:

I created an unversioned form of the objects that were to be serialized/deserialized which just decorated the latest version so all consuming code always pointed to the versionless ones which were always the latest versions; this way when new versions came out I didn't have to change any consuming code, just those versionless abstractions had to be pointed to the new versions.

So let's say an example like..

public class Person : V4.Person { }

Then in the implementation, I had each versioned object upconvert on deserialization by passing down to older until one of them recognized the version so it was something like..

public class V4.Person : V3.Person
{
    public string SomethingNewInV4 { get; set; }

    public static Person FromBytes(BinaryReader personReader)
    {
        Person person = base.FromBytes(personReader);

        if (person.Version >= 4) // If this version or newer, it will have the SomethingNewInV4 property, deserialize it.
        {
            int stringLength = personReader.ReadInt();
            person.SomethingNewInV4 = personReader.ReadString(stringlength);
        }
        else
        {
            person.SomethingNewInV4 = "default string used when upconverting from V3";
        }

        return person;
    }
}

In this way, each new version is just a modification of the previous, inheriting the previous version and adding (or hiding) parts from it, and using it's serialization/deserialization which it then adds onto it's particular parts special to it's version. There is the possibility for a breaking change in the chain but that just means that particular version may have to reimplement serialization/deserialization from scratch including all the intelligence for branching if previous versions should do it or not, but scenarios like that are likely minimal.

The versionless facade in front ensures all new serializations are serialized in the latest format, and all old deserializations start at the top of the stack which will call down to the bottom through inheritance, and each version will upconvert from there, so that versionless facade redirecting to the latest is necessary (unless each time a new version comes out you want to update all consuming code).

V1 will have to do the version picking and full deserialization etc, but above that each version will check which version and choose whether the data for it is there or it needs to fake it up.

When I did this, the subchunking you're referring to was totally there as well and I handled this by having this same layout for each subchunk type, so you could have Person's deserialization call to Arm's deserializer when it got to the Arm chunk, and if it had a numeral in front counting the Arms it would use that to deserialize in a loop. Each versioned subchunk needs a versionless front piece where all the main chunks call to, so V4.Person would call to the versionless Arm's deserializer which may point to V3 if that's the latest Arm, or etc.

Last point: I strongly suggest memory stream for this, I remember going back and forth on this and realizing the byte array was terrible because the forward movement meant I had to pass pointers around between versions, with the memory stream version 1 takes all the initial V1 data, V2 takes all the V2 data which is layered after that, and so on and so forth without needing to maintain the pointer to your current position in the array.

Your problem is almost step by step identical to the one I faced and solved in this manner, it worked pretty well, hope this helps! To make things a little easier I made extension methods on BinaryReader for some of the types that pointed to the versionless stuff so there would be like

public Arm ReadArm(this BinaryReader target) { return Arm.FromBytes(target); }

then in person you would have..

int numberOfArms = personReader.ReadInt();
List<Arm> arms = new List<Arm>();
for(int i = 0; i < 1; i++) arms.Add(personReader.ReadArm());

I made it fit with BinaryReader's normal naming, don't remember if it's Read or To.. Either way it was a handy shortcut.


答: This sounds like a company culture issue more than anything else.  Who instituted the need to use the tracker?  If this is something one person or group tossed out there, and expects everyone else to just accept and use, good luck.  Unless people understand what it is, know how to use it, and accept that it does actually make their lives easier (their lives, NOT yours), they will not use it unless coerced by management.  That being said, if using the tracker is a company decision, then it should be on management to enforce it.  Unless your role includes the responsibility and authority to get/make people use the tracker (sounds like no, as you indicated you're a developer), you're not going to get very far, regardless of what you do (realistically, IMHO).</p>


答:
This is probably similar to why it's so hard to get people to enter their time regularly. It's a tedious job...

Many issue trackers integrate with the IDE. For example, the TFS Work Item Tracker lets you mark a task as resolved when you perform a check-in. There's even an option to require that a check-in is associated with a task. Making the update of a work item part of the checkin process simplifies things. The alternative being opening up the issue tracker in a separate interface to perform the change.

Another option is having a status meeting (or during the daily standup) where someone opens the tracker and updates tasks as people provide status.


问:
I don't know C. And why should I learn it?
My first programming language was PHP (gasp).  After that I started working with JavaScript.  I've recently done work in C#.

I've never once looked at low or mid level languages like C.

The general consensus in the programming-community-at-large is that "a programmer who hasn't learned something like C, frankly, just can't handle programming concepts like pointers, data types, passing values by reference, etc."

I do not agree. I argue that:

Because high level languages are easily accessible, more "non-programmers" dive in and make a mess

In order to really get anything done in a high level language, one needs to understand the same similar concepts that most proponents of "learn-low-level-first" evangelize about.

Some people need to know C; those people have jobs that require them to write low to mid-level code. I'm sure C is awesome, and I'm sure there are a few bad programmers who know C.

Why the bias?  As a good, honest, hungry programmer, if I had to learn C (for some unforeseen reason), I would learn C.  Considering the multitude of languages out there, shouldn't good programmers focus on learning what advances us? Shouldn't we learn what interests us?  Should we not utilize our finite time moving forward?  Why do some programmers disagree with this?

I believe that striving for excellence in what you do is the fundamental deterministic trait between good programmers and bad ones.

Does anyone have any real world examples of how something written in a high level language—say Java, Pascal, PHP, or JavaScript—truly benefited from a prior knowledge of C? Examples would be most appreciated.

答:
A practical rule of thumb is that you need to understand at least one level of abstraction below the one you usually work in. Consider that your PHP or JavaScript interpreter may actually be implemented in C or C++. Eventually you are going to hit a bug in the interpreter or even a C runtime error. If you don't understand C you are going to be limited to sending a bug report to the maintainer, hoping they can reproduce it and care about it, and then twiddling your thumbs. If you know C you can tell them exactly where the problem is and what it is.

This also means that if you work in C/C++ you should at least be able to read assembly on your platform.

As for learning C when you need it: my observation is that most programmers can learn Perl/Python/Javascript on demand, but assembler/C/Lisp seem to require a lot more time, so it's worth learning at least some basics before the need arises.


问:
Do frameworks put too much abstraction?
I've been programming for a little under a year and have some experience writing systems applications, web apps, and scripts for businesses/organizations. However, one thing I've never really done is working with a framework like Django, Rails or Zend.

Looking over the Django framework, I'm a little frustrated with how much is abstracted away in frameworks. I understand the core goals of DRY and minimal code, but some of this over-reliance on different modules and heavy abstraction of core functions feels like it:

Makes programs get dated really fast because of the ever-changing nature of modules/frameworks,

Makes code hard to understand because of the plethora of frameworks and modules available and all of their idiosyncrasies,

Makes code less logical unless you've read all of the documentation; i.e., I can read through some list comprehensions and conditional logic and figure out what a program is doing, but when you see functions that require passing in arbitrary strings and dictionaries, things get a little hard to understand unless you're already a guru in a given module; and:

Makes it difficult and tedious to switch between frameworks. Switching between languages is already a challenge, but it's manageable if you have a strong enough understanding of their core functionality/philosophy. Switching between frameworks seems to be more a matter of rote memorization, which in some ways seems to encourage the very inefficiency these frameworks were designed to eliminate.

Do we really need to put like 50 layers of abstraction on top of something as simple as a MySQL query? Why not use something like PHP's PDO interface, where prepared statements/input testing is handled but the universally understandable SQL query is still a part of the function?

Are those abstractions really useful? Isn't feature bloat making them useless, making applications more difficult compared to similar applications written without using a framework?

答:
Yes, they are useful.  They provide you the benefit of lots of other experienced developers doing work to solve a problem you need to solve, with the added benefits of having tested it, fixed lots of bugs, and provided solutions to tricky problems you don't have to worry about yourself by using the framework.

Can they be bloated overkill?  Sure.  This all depends on what you need, and what the framework brings to the table.  If you have a simple web app, maybe Rails is overkill for you, and you should look at something simpler like Sinatra as a solution.

There is definitely a learning curve to all frameworks, and it's steeper with the more work that it saves for you.  However, learning the framework means you've saved time and can leverage all of that knowledge on the next project, instead of rewriting your application from scratch, a second time.

But, you say, I'll just copy my code from the old project, and I can use that as a starting point for my new project!  I'll just change what is different, and maybe make some of my objects/functions more general, and think of a better way to solve that tricky bit of code!  Congratulations, you've just created a framework.  Do this a few thousand more times, and you have something like Django, Rails or Zend.

Title: Do frameworks put too much abstraction?


问:
Mobile-first implementation or desktop-first?
When working with CSS media queries, I am unsure of whether I should program in a mobile-first style, or a desktop-first style.

For example, let's say I'm given a design that consists of a set of blocks that are side-by-side. On desktop, I'll stick to spec, but on mobile, given the reduced screen area, two blocks stacked on top of one another would be better.

Which is better, this (desktop-first):

```<code>div {
    width: 50%;
    display: inline-block;
}

@media all and (max-width: 600px) {
    width: 100%;
    margin: 0 auto;
    display: block;
}
</code>```

or this (mobile first)?

```<code>div {
    width: 100%;
    margin: 0 auto;
    display: block;
}

@media all and (min-width: 600px) {
    width: 50%;
    display: inline-block;
}
</code>```

Wordpress' latest theme follows the mobile-first method, by using min-width, but am I correct in assuming that older browsers without media query support would be unable to parse these directives, and load the "mobile" css?

What are the advantages/disadvantages of both?

答:
Which is more important to you? Or more accurately, do you think you're going to draw a larger number of users from mobile than from desktop, or vice versa?

Having a responsive site is excellent, but you need to decide whether you want it mobile first and respond upward, or desktop first and respond downward. There's no real right or wrong answer to it, it just depends entirely on whether you think you're going to cater more to one audience than the other.


问:
Why do relational databases only accept SQL queries?
As far as I know, most relational databases do not offer any driver-level API for queries, except a query function which takes an SQL string as an argument.

I'm thinking how easier it would be if one could do:

```<code>var result = mysql.select('article', {id: 3})
</code>```

For joined tables, it would be slightly more complex, but still possible. For example:

```<code>var tables = mysql.join({tables: ['article', 'category'], on: 'categoryID'});
mysql.select(tables, {'article.id': 3}, ['article.title', 'article.body', 'category.categoryID'])
</code>```

Cleaner code, no string parsing overhead, no injection problems, easier reuse of query elements... I can see a lot of advantages.

Is there a specific reason why it was chosen to only provide access to queries through SQL?

答:
Because SQL provides a common API.  You can write an ANSI 92 SQL compliant driver that emits SQL and exposes the API you desire. As a special bonus, it will work with almost any SQL database without rewriting.

If it was done your way, every SQL database would have a different API.  Unless, of course, we all standardized on your API.  But then, we'd have SQL again, more or less, wouldn't we?  Except that your API appears to be programming language-specific, whereas SQL is not.


答:
Databases are out of process - they run on a different server usually. So even if you had an API, it would need to send something across the wire that represents your query and all of its projections, filters, groups, subqueries, expressions, joins, aggregate functions etc. That something could be XML or JSON or some proprietary format, but it may as well be SQL because that is tried, tested and supported.

It is less common these days to build up SQL commands yourself - many people use some sort of ORM. Even though these ultimately translate into SQL statements, they may provide the API you are after.

Title: Why do relational databases only accept SQL queries?

Body:
As far as I know, most relational databases do not offer any driver-level API for queries, except a query function which takes an SQL string as an argument.

I'm thinking how easier it would be if one could do:

```<code>var result = mysql.select('article', {id: 3})
</code>```

For joined tables, it would be slightly more complex, but still possible. For example:

```<code>var tables = mysql.join({tables: ['article', 'category'], on: 'categoryID'});
mysql.select(tables, {'article.id': 3}, ['article.title', 'article.body', 'category.categoryID'])
</code>```

Cleaner code, no string parsing overhead, no injection problems, easier reuse of query elements... I can see a lot of advantages.

Is there a specific reason why it was chosen to only provide access to queries through SQL?


问:
What is the term that describe objects representing both logic and data?
The reason I am asking this question is I want to know how to properly call an architecture where classes have either data or logic but not both. I know this goes against object orientation and encapsulation. I want to use the proper terms for discussing this architecture.

EDIT: By reading the answers I have received, I can see my question wasn't clear. I also feel the edit that was made didn't push the question in the direction I was going for.

I will restate the question in other terms.

Suppose you are working in C#, Java or some other OO language.

You have 2 designs:

DESIGN A:

```<code>class Car
{
     // data
     int numberOfWheels;
     Engine carEngine;

     // methods
     public void StartCar();
}
</code>```

DESIGN B:

```<code>class Car
{
     // this class contains only data (be it entity, DTO, whatever)
     int numberOfWheels;
     Engine carEngine;
}

class CarStarter
{
     public void StartCar(Car aCar);
}
</code>```

In DESIGN B, some classes are used as data structures/DTO/entities (they contain only data and should not contain methods). Other classes contains logic and work with the data classes.

Now suppose you have a design/architecture where DESIGN B, should be applied throughout rather than design A.

I was looking either for a term that described DESIGN B, or the OOP term/notion that consist of DESIGN A. Preferably both.

For the OOP term I guess encapsulation could be it. From Wikipedia Encapsulation

A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.

I still don't know how to call DESIGN B though.

答:
Homoiconicity.

In computer programming, homoiconicity is a property of some
  programming languages, in which the primary representation of programs
  is also a data structure in a primitive type of the language itself,
  from the Greek words homo meaning the same and icon meaning
  representation. This makes metaprogramming easier than in a language
  without this property. To put that another way, homoiconicity is where
  a program's source code is written as a basic data structure that the
  programming language knows how to access.

The most obvious example being Lisp.  "Code is Data."


问:
Are generic programming and OOP mutually exclusive?
I never did generic programming before, being more of a python guy, and generally using OOP. As I moved into generic programming, I faced some issues. I read the FAQ, but I am not satisfied. What I want to ask are the following questions (I am mostly interested in the first, but answering the others will be extremely welcome):

Are generic programming and OOP mutually exclusive? Meaning, for example, are you supposed to have methods and functions accepting the template, instead of baseclass or abstract pure class?

Some other questions I've got, only to provide context to my lack of understanding are: How do traditional design patterns react to generic programming approach and concepts? How to prevent (or control) the genericity of each class/template to "bubble up" in the dependencies dictated by the program logic, in particular when two types are related and go always together (e.g. a RealNumberProducer class and double vs ComplexNumberProducer and std::complex)?

答:
No, they aren't mutually exclusive. Eiffel and C++ have both had generics and OOP for a long time, and newer languages also support both features.

Design patterns are mostly written in terms of object-oriented programming, and relate to decomposition of a problem into classes. Those classes could be generic or not in terms of the data types they accept; generics and OOP are orthogonal in that sense.

You just choose whether a collection of code (OO or otherwise) is going to be generic or is going to use specific types; there's not really any "control" to be gained or lost. Taking your case, you could maybe fold those two pairs of types into a NumberProducer<T> that returns numbers of type <T>, though the question doesn't go into enough detail to work out whether that's feasible or appropriate.


答:
Nope. In fact, many of the best systems use both in combination. Containers are worthless if they are not generic- case in point, Java or C#'s containers when those languages were launched.

Indeed, generic programming is virtually identical to OOP, except that it occurs at compilation/interpretation time rather than execution time, which has a large number of advantages, including increased performance, safety, and flexibility.

are generic programming and OOP mutually exclusive? Meaning, for
  example, are you supposed to have methods and functions accepting the
  template, instead of baseclass or abstract pure class?

They are not mutually exclusive, but you should use templates whenever possible to achieve a generic method. Do not ever use inheritance unless you cannot use a template. Inheritance is one of the worst tools that is in the arsenal.

How do traditional design patterns react to generic programming
  approach and concepts?

They get absolutely blown out of the water. Some patterns are simply completely worthless to begin with (e.g. Singleton), many others are useless in the face of templates or all possible instances of them are implemented directly by one template, such as Listener.

How to prevent (or control) the genericity of each class/template to
  "bubble up" in the dependencies dictated by the program logic, in
  particular when two types are related and go always together (e.g. a
  RealNumberProducer class and double vs ComplexNumberProducer and
  std::complex)?

Don't. Encourage it. Also, I'm just guessing by the names here, but that really just sounds like std::function<double(args)>, rather than an actual class.

Body:
I never did generic programming before, being more of a python guy, and generally using OOP. As I moved into generic programming, I faced some issues. I read the FAQ, but I am not satisfied. What I want to ask are the following questions (I am mostly interested in the first, but answering the others will be extremely welcome):

Are generic programming and OOP mutually exclusive? Meaning, for example, are you supposed to have methods and functions accepting the template, instead of baseclass or abstract pure class?

Some other questions I've got, only to provide context to my lack of understanding are: How do traditional design patterns react to generic programming approach and concepts? How to prevent (or control) the genericity of each class/template to "bubble up" in the dependencies dictated by the program logic, in particular when two types are related and go always together (e.g. a RealNumberProducer class and double vs ComplexNumberProducer and std::complex)?


答:
I wonder if some sort of lexer/parser set-up would be in order, since:

it seems like you're going from an input stream (of some sort) to a tree-like structure (if I'm reading things right)

it would be a way to do the back-tracking you mentioned you might need to do

it could probably handle some of the endianness uncertainty/switching you might encounter

I don't know if you could use one that's pre-written in this use case, but it might be a place to start with thinking about structuring things.

Title: How should I structure a C# application that reads & writes binary data?

Body:
I have to read and write binary "chunks" of approximately 1Mb each.  The data can come in the form of a stream or a in-memory byte[].

Normally I would use a Struct with a fixed layout, but there are a few properties of this binary data that are making this harder:

Byte 4 describes the "version" of the chunk

Byte 5 starts either as variable array of sub-chunks or as a human readable blob

Each sub-chunk has a version, and has a variable array of data within it.

The endian-ness of the data is inconsistent

How should I structure a program that needs to handle binary data thats in this format?


问:
If it was for you to chose Game Development vs Application Development, which will you chose?
Today I was asked if I want to do Game development or Application Development.
I never thought to that I will ever do Games for a living. I will try it for a couple of weeks maybe but what are your thoughts on this topic?

P.S.  the apps or games will be for mobile devices.

答: I work as a business application developer but here is my two cents to share what it is like. The stuff you have to implement tend to stay the same, if it's not generating a report with existing data then it's a new form for data entry with a few gadgets here and there such as event triggers, so most of the complex stuff tend to lie in the database layer when you start writing PL/SQL code or procedures to handle the business logic eg. batch processes, claim validation engines, business intelligence. There are change requests are frequently submitted for the system from the users and that is where most of the money is coming from, but often times, the users themselves don't even know what they want so you are often plagued with twice the amount of work when it's time for user acceptance testing. If you are new to the company, you often have little to no knowledge of the business processes of the clients you are serving so you need to have the intuition and common sense usually helps. The biggest challenge I find is plugging in changes that somehow fit in with the complex business logic that is already embedded into the system because you might run into contradictions of existing rules that were implemented and long forgotten by even the users themselves until you remind them.</p>


问:
How to interact with C++ API through http commands?
I have a C++ API, I want to send commands through http to run any c++ method from this API. I'm using libmicrohttpd.

What steps should I follow to do such a work?

答:
You would write your code to listen for specific requests from your HTTP server. When one of those requests comes in you process it to get the data you need (passed as GET or POST parameters most likely) and then make the appropriate call against the C++ library that you have. You handle the return value (if there is any) to create a response that you send back to the user.

Making the request

[User] -> [GET /dosomething] -> [libmicrohttpd] => [Your Code] => [DoSomething on API.dll]

Handling the response

[DoSomething Return Value] => [Your Code] => [libmicrohttpd] => [HTTP Response] => [User]

For specifics related to libmicrohttpd have you looked at the tutorial? Chapter 3 (Exploring Requests) and 6 (Processing POST Data) seem applicable to what you are doing.


问:
Should a new class refactored out of an existing one have history pointing back to it's progenitor
If I split one class into two classes should both classes have history in source control tracing back to the original class that contained both; or should the new class be added as a new file without any history tracing back?

When splitting a large class into two similar sized parts this seems like the natural approach since the older versions of the combined class will have large amounts of relevant history for both descendents.  When I'm just pulling one or two methods out to create a helper class, having the complete history for the new class be >90% changes in the parent that affected code that wasn't split out seems like a recipe for confusion in the future.

答:
That's what code repositories are for (Git, Subversion, et.al.).

Having maintained some very, very old code I can say that one of the worst things you can do is leave "history" in code files.

Ancient, esoteric code fragments and cruft is not documentation.

A functioning, in production code base is not a museum.

Every line of code costs time and money to maintain, every line; including non-functioning, irrelevant, obsolete ones.

Each successive code change makes all earlier ones less relevant, less informative, and harder to understand.

How can I explain it... I want to take flying lessons, but wait! What's this about the Wright Brothers? Oh, I need to stop and learn all about how the Wright Flyer worked and after too much time wasted realize that explicit details about how that thing worked are totally irrelevant to using this airplane. And what in the wide world of sports is this old rusted dohickey in the instrument panel?

In the final analysis Anything I need to know is incorporated in the current design.


答:
In theory, OOP and Generic are two different paradigms and the mental state for coding is different from each other. In practical terms, you can combine OOP with template meta-programming. However, I wouldn't suggest to combine them unless you are very comfortable with OOP and generics  and if you are in a learning process it might confuse you. Also, there some caveats in C++ when combining inheritance with templates. Take a look Scott Meyer's book (I believe item 48) and he mentions good points on it.

Good luck in your learning journey Stefano

Armando.

Title: Are generic programming and OOP mutually exclusive?


问:
What is a good design for a container, assignment and items
```<code>    ------------- 1    * -------------- *       1 --------
    | Container |--------| Assignment |-----------| User |
    -------------        --------------           --------
          ^                     ^
          |                     |
      ----------            -------------
      |        |            |           |
---------- ----------  ---------- ---------------
| Flight | | Dinner |  | Booking| | Reservation |
---------- ----------  ---------- ---------------
</code>```

This problem is one that I've stumbled upon in several different occasions but never found an elegant solution for:

In my system model (in rails), which maps to the database, I need to have Users that can be added to Containers through Assignments.

Now, there can be many things that can be containers:

A Flight is a Container. It can hold Users. In such a case the concrete Assignment is a Booking.

A Dinner is a Container. It can hold Users. In such a case the concrete Assignment is a Reservation.

And many more. You get my point.

So I have Abstract notions of Container and Assignment. Containers hold Assignments and I also have concrete implementations of them, with each concrete implementation of Container matching a concrete implementation of Assignment. The straight forward design is as above. My main problem with it is that it doesn't express the relation between each concrete container and the concrete assignment.

Any ideas how to better design this?

答:
You've actually got a basic implementation of the Bridge Pattern.

Where things break down is that a Dinner shouldn't contain a Booking. However, your model indicates that it can. From your comments, you indicated that there is a lot of shared logic in the Container class that works on a collection of Assignments.

I am going to assume that the Assignment class performs its work using template method to delegate implementation details to the sub-classes and that Container doesn't need to be aware of which Assignment type it is working with. In this case, the only concern is limiting what types of Assignments can be associated with a Container.

In a typed language, you could create a "protected" addAssignment method in the Container class. Then in each Container subclass provide a public type-safe addReservation or addBooking method that just calls the protected addAssignment. You could enforce this will a runtime check in a dynamic language, but this seems like overkill.

Another solution is to recognize that both Booking and Reservation contain a single User. Technically you could create an "abstract" method in the Container called addAssignment accepting a User rather than an Assignment. The Container sub-classes then "override" the method by decorated the passed User object and adding to the underlying collection.

My point is that there are a lot of options, which might change on the way your objects are interacting. For instance, you could even pass an AssignmentFactory to the Container that moved the creation logic somewhere else. You really have to decide to what level of control you want over your code. With a dynamic language it is a little more difficult to make explicit. I hope at least some of my examples also demonstrated just how over-engineered a solution can be when you start being paranoid.


答:
No they are not mutually exclusive, but I guess that point has come across by now.

In my mind OOP is a about semantics.
It's a way to separate concerns and to help maintainability and use (reuse if you will) of the code.

Furthermore, Generics is about expressiveness.
When I can implement an algorithm and express it in such a way that it can, and will, accept many types - then generics is the right tool.

Some languages combines the two by allowing the programmer to specify a contract/interface for the type as a way to guarantee the semantics of the type. Does it have an overload for multiplication? Can it be compared to other instances of the same type? etc etc
Most languages (at least that I use) offer both, side by side.

If you're hell bent on using generics without using OOP then I suggest you start looking into some dynamically typed functional language.


问:
Is there a reason that tests aren't written inline with the code that they test?
I've been reading a bit about Literate Programming recently, and it got me thinking... Well-written tests, especially BDD-style specs can do a better job at explaining what code does than prose does, and have the big advantage of verifying their own accuracy.

I've never seen tests written inline with the code that they test. Is this just because languages don't tend to make it simple to separate application and test code when written in the same source file (and nobody's made it easy), or is there a more principled reason that people separate test code from application code?

答:
Actually, you can think of Design By Contract as doing this.  The problem is most programming languages don't let you write code like this :(  It's very easy to test for preconditions by hand, but the post conditions are a real challenge without changing the way you write code (a huge negative IMO).  </p>

<p>Michael Feathers has a presentation about this and this is one of the many ways he mentions you can improve code quality.  </p>

Body:
Actually, you can think of Design By Contract as doing this.  The problem is most programming languages don't let you write code like this :(  It's very easy to test for preconditions by hand, but the post conditions are a real challenge without changing the way you write code (a huge negative IMO).

Michael Feathers has a presentation about this and this is one of the many ways he mentions you can improve code quality.


问:
strategies for dealing with machine epsilon
Say you have a situation where you divide and then multiply a float, and you need to guarantee that it survives macheps (ie multiplication output equals division input). What are known strategies for guaranteeing this? Rounding would work, but anything else?</p>

答:
You can't guarantee that.  Not while using floats, anyway.  As the comment says, if you need a guarantee, you can use arbitrary-precision fractions.

In general, rounding doesn't offer such a guarantee, either -- you need to do some actual math before you can be confident it works within the range of your particular application.

The real question is:  why do you think you need a guarantee?  Your question suggests that you need to actually, seriously devote some effort to considering this, because its answer is likely the most relevant and important part of actually solving your problem, and you have not provided enough information to enable any more detailed constructive advice.


问:
Is there a difference between multi-tasking and time-sharing?
Just going over my school notes, my teacher identifies multi-tasking OS, and time-sharing OS as two different things.

I really don't see a difference between the two.

MULTI-TASKING: You load a number of programs in the memory and execute them. You execute another program if the time quantum allocated to the current program expires OR if it goes on to do I/O and leaves the CPU OR if it finishes execution.

TIME-SHARING: the same,again.

The same applies in case of serial processing and batch processing. Although they are the same, I guess the only difference would be the way in which control information is passed to the CPU. Maybe, and again MAYBE, in serial processing you need to provide the punch cards with all the processes while in batch, the entire batch uses the same set of control information.

Like all the print jobs would have the same control information.

答: I hadn't been born when these terms were invented, but I always understood them as the two sides of the same coin. The machine (and its operating system) has to run multiple tasks in order to let the users share their machine time. So I believe the difference is in the perspective, one is the user's, the other is the machine's (or the OS programmer's).</p>


问:
Designing models for a generic service layer
We are building a web interface to a tiered membership system, which will interface with a third-party CRM web service for the creation and management of accounts. The web service, unfortunately, is not yet built; however, we need to begin work.

I have created an interface, IMembershipService, in which I am beginning to define "best-guess" prototypes, so we can begin building our User Controls. Most of these methods will return some data bundled in a Model object, e.g.:

```<code>ContactModel GetContact (string userId);
</code>```

When the web service methods become available, I will create a concrete implementation of IMembershipService that will wire up the controls to the web service.

The problem I have is that I don't yet know whether the web service will consist of:

calls returning complex objects; e.g. a User object with a nested Membership object, which, in turn, has a nested PaymentMethod object

simple calls for specific pieces of information; e.g. String GetUserMembershipType (string userId);

This is causing me to have trouble specifying the structure of the models and interface, which is causing problems for the developers beginning work on the User Controls:

If the service returns complex objects, I don't want my IMembershipService methods to be too simple, forcing me to use multiple web service calls where it is not necessary.

If the service consists of simple calls, I don't want to have a load of complex models defined that I then can't implement, thereby having to do a load of refactoring.

In theory, creating IMembershipService should allow me to abstract away from the actual nature of the web service, but the fact that each call to a method in IMembershipService will, ultimately, result in a web service call, thereby adding overhead, is making this difficult to spec.

How can I design my models and IMembershipService in order to minimize the amount of refactoring I have to do when the nature of the web service becomes less elusive?

答:
Decide on the most convenient interface for your application, and define an interface according to that. What information will you need, and in what discrete units? Define models according to those units.

After all is said and done, that's the information you need. Let the implementation later be an adapter to the webservice. It won't matter if it needs to do multiple callstothe webservice or not - that's just an implementation detail.


答: I agree -  most frameworks become bloated dictators. They promise freedom but you end up in servitude. so look at a framework like a tool - the best tool is the one that stays out of your way. If in PHP I would suggest checking out the Codeigniter framework, because its an elegant balance between conventions and freedom and has a great community. And to the poster who used the example of an e-commerce cart - I so wish I could agree with you. but having looked at the code for many e-commerce solutions - and designed a few - I would respectfully disagree with your example. </p>

Title: Do frameworks put too much abstraction?

Body:
I've been programming for a little under a year and have some experience writing systems applications, web apps, and scripts for businesses/organizations. However, one thing I've never really done is working with a framework like Django, Rails or Zend.

Looking over the Django framework, I'm a little frustrated with how much is abstracted away in frameworks. I understand the core goals of DRY and minimal code, but some of this over-reliance on different modules and heavy abstraction of core functions feels like it:

Makes programs get dated really fast because of the ever-changing nature of modules/frameworks,

Makes code hard to understand because of the plethora of frameworks and modules available and all of their idiosyncrasies,

Makes code less logical unless you've read all of the documentation; i.e., I can read through some list comprehensions and conditional logic and figure out what a program is doing, but when you see functions that require passing in arbitrary strings and dictionaries, things get a little hard to understand unless you're already a guru in a given module; and:

Makes it difficult and tedious to switch between frameworks. Switching between languages is already a challenge, but it's manageable if you have a strong enough understanding of their core functionality/philosophy. Switching between frameworks seems to be more a matter of rote memorization, which in some ways seems to encourage the very inefficiency these frameworks were designed to eliminate.

Do we really need to put like 50 layers of abstraction on top of something as simple as a MySQL query? Why not use something like PHP's PDO interface, where prepared statements/input testing is handled but the universally understandable SQL query is still a part of the function?

Are those abstractions really useful? Isn't feature bloat making them useless, making applications more difficult compared to similar applications written without using a framework?


答:
There's more to do on the database for administrative purposes, so being able to script and submit text to add users, run backups, load data, change the schema etc. is important. Most DBA's won't want to do this inside some other programming language.

If DBA's want to hang on to SQL, you have to have another language, the database would have the burden of processing both.

There are many new features in databases, so I don't think they're getting stagnant. They're just not doing what you propose for some reason.

SQL Server has the ability to execute .NET code from the inside through SQL CLR. This is helpful for some of those tasks that don't fit into a relational model, but want to maintain performance. I realize this isn't what you're looking for. It's an example of the many things databases are doing.

It's not going to go away any time soon. One of the more recent databases to hit the market is NuoDB. They kept SQL, provide ACID while adding the ability to distribute servers and run it in a cloud. You may want to look into why they went to all that trouble to promote the continuation of SQL (Not their only reason, but it's a huge selling point.).


问:
Checking if my app is using any undocumented parts of the API
I just read through this question, but I am still confused.

How can I know if my app is using undocumented API calls before submitting to it to the app store? Are there any tools I can use?

答:
The problem is not only with using an undocumented API, but reportedly with using any method which looks like an undocumented API to Apple (which, not being publicly documented, there's no way for you to know).  Therefore, to reduce risk of rejection, make sure that any of your own methods don't even look like an iOS or UIKit-named method or variant or future extension thereof.

If you are really concerned, you could dump all the method and class names from your compiled executable, and google them all to make sure they either show up nowhere, or on an official Apple public API page.


问:
What situations are appropriate for C# to C interop?
Given that C# has the unsafe keyword, are there situations in which it would still be beneficial to interoperate with C libraries?

I could see the need for very fast number crunching, graphical manipulation or matrix operations, using pre-existing C libraries.  But is there a use case for writing greenfield DLL's in, say, C99, and interoperating with them from C#?

I imagine that there might be edge cases where dropping down to C (in the sense that it is closer to the metal) would be the only way to get the needed performance characteristics.

答:
There are a couple of things C has over C#.

Can do real time code with C. Not that windows is the best platform for it.  But I have done realtime control systems with it.  It would be nice to do it in C#, and most of the time it is predictable, but not always, and that's killer for RT systems.

Portability of C code over a number of platforms  ( not just linux / windows, but any number of embedded systems ).    I use things like encryption and compression from windows to embedded devices,  rather than having a C and C# version of the code, easier to have one library with C# interop.


问:
How do you name your private variables in C#?
What is the best practice, most commonly accepted naming conventions for private variables in C#?

private int myInteger;

private int MyInteger;

private int mMyInteger;

private int _myInteger;

private int _MyInteger;

Mysterious other option

Which do you use and why?  (My company is fairly new to C# and I would like to pick the most "industry accepted" method to try and get into our coding standard.)

答:
I think the option 4 is really the most readable option. It helps you from having to do this:

```<code>public Person(string name, int age)
{
    this.name = name;
    this.age = age;
}
</code>```

It also makes all private members more noticeable. In the following example, where the heck is age coming from? Without the this qualifier it is harder to tell.

```<code>private void Method()
{
    var x = 2;
    var y = age + x;
}
</code>```

This is way easier to understand:

```<code>private void Method()
{
    var x = 2;
    var y = _age + x;
}
</code>```

Body:
I think the option 4 is really the most readable option. It helps you from having to do this:

public Person(string name, int age)
{
    this.name = name;
    this.age = age;
}

It also makes all private members more noticeable. In the following example, where the heck is age coming from? Without the this qualifier it is harder to tell.

private void Method()
{
    var x = 2;
    var y = age + x;
}

This is way easier to understand:

private void Method()
{
    var x = 2;
    var y = _age + x;
}


答:
SQL DBMS provide substantially optimised access to the store through the native language and many, as you note provide no other API.

The observation that the database is out of process does not apply in a number of cases and is not really directly relevant.

Even databases that require the use of the SQL DML often provide a cursor library to provide iterator access to a result set, and the well known Microsoft Access and Btrieve SQL DBMS both provide a direct record interface to the individual tables in a database as a mechanism for very high performance access under specific circumstances.

As noted, complex queries using such a syntax would reproduce the behaviour of network databases from the late '70s.

The alternate access mechanisms are less attractive to the mainstream users due to the unfamiliarity, but the growth in popularity of the NoSQL databases could increase interest in other APIs to achieve specific performance gains. There seems little else to recommend such an approach.


问:
Is there an opposite for the term "Backporting"?
As I understand, the term "Backporting" is used to describe a fix which is applied in a future version which is also ported to a previous version. Wikipedia definition is as follows:

Backporting is the action of taking a certain software modification (patch) and applying it to an older version of the software than it was initially created for. It forms part of the maintenance step in a software development process...

For example:

A problem is discovered and fixed in V2.0. The same fix is ported and applied to V1.5.

What is the term when this is done in the opposite direction?

The problem is discovered and fixed in V1.5. The same fix is ported and applied to V2.0.

Would the term "Backporting" still apply? Or is there a term such as "Forwardporting" (which amusingly sounds a lot like "Port Forwarding")?

答: There is not a commonly used term for merging a set of changes from an older branch of software to a newer one. Unless the latest branch of the software is highly unstable most developers will develop bug fixes on the latest branch of the software regardless of what version the bug was found in. This is done in order to reduce merge conflicts since the latest branch of the software changes more frequently than older branches. Any software bug reported by a customer is by definition reported in an earlier version than it is fixed in since the customer doesn't have access to the latest branch of your software. </p>


问:
Calling blocking functions and execute code when result is ready, but without callbacks
I am designing an application that has some scripting capabilities: the host application may call the scripts to perform some operations when some events occur. To keep it easy and newbie-friendly, there is a single thread for everything: this means that if the script calls something blocking, the entire application hangs. So, I either use callbacks or polling to wait for a result of a blocking call to be ready. What is ugly in this approach, is that a function that happens to call a blocking function, has to be split in parts. For polling, I'd have

```<code>function do something part 1
    blabla
    launch something lengthy
    schedule do something part 2
end

function do something part 2
    if result not ready then schedule do something part 2
    use result
    blabla
end
</code>```

Callbacks are only slightly better:

```<code>function do something
    blabla
    launch something lengthy, when done call callback
end

function callback
    use result
    blabla
end
</code>```

If one has several blocking calls, and each one depends on the result of the previous, code gets uglier and uglier. What I'm looking for is for some programming language that have some builtin support for this pattern. Something like

```<code>function do something
    blabla
    launch something lengthy
    when done:    //fictional keyword
    use result
    blabla
    ....          //more and more blocking calls
end
</code>```

Of course if there are better solutions I'm glad to listen.

答:
What I'm looking for is for some programming language that have some builtin support for this pattern.

Don't they all have them by now? ;)

I know of two, they all work the same: launch a function in parallel, possibly on a different thread, and get the result later:

C# async

```<code>var task = BlockingFunction(arg);
// ...later...
var result = await task;
</code>```

C++ std::async

```<code>auto handle = std::async(std::launch::async, blocking_function, arg);
// ...later...
auto result = handle.get();
</code>```

Body:
What I'm looking for is for some programming language that have some builtin support for this pattern.

Don't they all have them by now? ;)

I know of two, they all work the same: launch a function in parallel, possibly on a different thread, and get the result later:

C# async

var task = BlockingFunction(arg);
// ...later...
var result = await task;

C++ std::async

auto handle = std::async(std::launch::async, blocking_function, arg);
// ...later...
auto result = handle.get();


问:
CMS updates into subversion -> review process
We manage a range of client sites built in Wordpress and Joomla and these require regular updates to the core CMS and extensions. We keep these sites in subversion and place updates in subversion. We try to use a single revision for this.

We face some difficulties in making this process efficient, over time we would like to automate it, so we can offer the process on a fixed price basis

The process is currently as follows

make copy of whole folder

svn status |grep '^!' |sed 's/^!\s*/svn delete "/g' |sed 's/$/"/g' |sh

svn update

svn status |grep '^?' |sed 's/^?\s*/svn add "/g' |sed 's/$/"/g' |sh

svn ci -m "Commit message"

svn remove -m"temporarily remove" http://subversion.repository.com/svn/automatem/projects/client/trunk/project/foldername

Steps 5-6 are usually repeated multiple times.

What I'm looking for help with

we are using subversion version 1.6 and 1.7, because there are no .svn folders in 1.7 in subdirectories, I wonder if the process is much easier on 1.7?

we've added step 3 because it reduces the number of repeats in steps 5-6. However this was just trial and error and I can't quite get my head around why this is

As I understand it, the issue in step 5-6 is that when the an extension is updated, it may delete a whole folder and then re-insert that folder with changed files. In subversion 1.6, this would remove the .svn folder, which causes a 405 Access denied error (the folder gets added, but already exists in svn). What I would need is something that inserts all .svn folders back into my working copy if the folder already exists in svn. Is there a way to accomplish this?

Any other improvements of course appreciated.

答:
Upgrading to SVN 1.7 will help alot -- it makes SVN almost bearable.

If I was stuck managing something like this in SVN and I didn't want to look at using svn externals, I would take a much different tactic here -- I would not version the core CMS with the framework at all but rather have that in a separate repo that could be pulled via svn export when needed. Upgrades involve just deploying to a new folder.