问:
GPLing an implementation of a patented algorithm
TL;DR: Can you publicly release your own implementation of a patented algorithm as a free research tool for others, under the GPL, when you do not hold the patent (but will happily give clear and thorough attribution to the owners of the patent)? see below for clarification.

First off, apologies if this question has already been answered.  After ~30 minutes of googling and stack-exchanging, I haven't found anything that quite answers what I'm facing.

I work in an academic group and part of our work has been implementing a CT reconstruction algorithm similar to what is done clinically by a major manufacturer.  This manufacturer has a patent that definitely covers what we have implemented.  (I did the implementation from a paper published almost 10 years earlier, only to find that they had also patented the algorithm a little over a year ago. Damn.)

They have a patent on the method of reconstruction and several of the equations utilized, but no source code or anything of the sort.  The code implementation is 100% unique to our group. We're talking patents, not copyright.

We are planning to write a "technical note" about our implementation (gpu-based, more detail on how we implemented the published algorithms (i.e. much more detail than what's patented), etc. all stuff which is not described in the patent) for publication in a major journal ** AND ** this would include releasing our source code.  I would like to release it under GPLv2.0 to provide folks with a research tool.

The GPL would prevent us and anyone down the road from using our code in proprietary software, and if anyone were to use it to make money, they would have to pay rights to the patent owner (and release any code derived from ours). I would like to somehow make clear that we are not claiming any rights to the algorithm, and the only the implementation would be covered by the GPL, however I recognize this distinction may not be possible under the current US legal setup (blegh).

Even if we could somehow make that distinction clear when/if we release, are we violating any of their rights with the patent?  I'm thinking they would have to somehow show that our release damaged their business covered by the patent.

Any thoughts from more experienced folks are much appreciated!  I think this may be kind of a gray area (or not! I'm not a lawyer! haha).

We do NOT wish to infringe upon the patent and don't pretend to have any claim to.  We have a good relationship with the vendor, so we'll most likely end up figuring it out with them, but if they said no, I was curious if it's just because of their feels or if thay have a legitimate claim against our group.

答:
Code doesn't infringe on patents. Code running on a computer can infringe on patents. There was a major (billion dollar) case where Microsoft wa accused of patent infringement, and it turned out that an infringing device was created at the moment when the software was installed on a computer, and not earlier. For example not when a million CDs or DVDs with the software were pressed. And there are open source implementations of mp3 encoders and decoders, for example. Which the user has to install himself, which is fine because the mp3 patent owners only want money if you install many thousands of copies.

You won't be able to use GPL v.3 because that requires that you give every user a license to use the patents, which you obviously can't. You should be fine with GPL v.2.

All that covers whether you can write the software and give it to others. It doesn't cover whether these other people can use it. If they install the software on a computer and run it, that may be infringing on the patent and require a patent license.


问:
JSP in Javascript file or multiple AJAX requests
I've been thinking about how I want to load my data for some checkboxes in an AngularJS app. I'm generating multiple checkboxes based on 2 JSON objects that are currenty hard-coded in the a Javascript file (it's currently a prototype, but in production the values for the checkboxes can change from day to day).

Now I've tried using JSP in my Javascript file (IDE is Eclipse) - while it would work, it just looks ugly (besides the fact that JSP syntax checking doesn't work in a .js file). I thought about creating a servlet that would generate those JSON objects and then loading them through AJAX, but I'm not sure if this might be "bad behaviour" since I'd generate multiple AJAX calls only to keep my code "clean".

Is there some kind of convention or best-practice for dynamically created Javascript or should I usually prefer AJAX over JSP in Javascript?

答:
What you want to do is possible and there are available in many frameworks that can help here. Look at AJAX as a callback implemented in JS and not something different - this will help simplify your problem. There is no best practice IMO, but there are some options available that I have used in the past. Here are some options,

JSP Tag UI Components: You have some widget which requires some business input to render but is mostly JavaScript. While AJAX is an option it can be unnecessary if the data is available at the point of rendering the JSP. One approach is to create a JSP Tag Lib that internally renders the HTML and JS. The benefit is fewer people are touching and working with JS which is more error prone and relatively difficult to Unit Test. In the past this was a messy option since you would have to use multiple out.println statements to render the Dynamic JS from the Tag Handler but now with the introduction of Tag Files this can be a lot cleaner.

JS Endpoint: JS Endpoints are special servlets that serve dynamic JS. Think of this instead you setting a static file in the src attribute of the script tag you have the URL pointing to a URL pointing to a Servlet that responds with content type for JavaScript or JSON as the case may be.

```<code><script src="/myapp/abc.jsx"></script>
</code>```

In the web.xml,

```<code><servlet-mapping>
<servlet-name>myServletThatServesDynamicJS</servlet-name>
<url-pattern>*.jsx</url-pattern>
</servlet-mapping>
</code>```

Client-side Frameworks: There are many JS frameworks worth your time investment that can minimize the amount of JS you write by declaratively generate a lot of JS (and CSS) something that most Java developers would prefer. AngularJS and Bootstrap are examples. So you basically add some additional attributes to regular HTML tags and there is some magic in the background that generates components, makes AJAX calls, etc. Angular will pull required JS "modules" from the server as an when needed via AJAX calls and also supports advance features like DI which can make testing your JS code a breeze and also a lot cleaner.

I personally prefer using JS frameworks to solve JS problems. So I would be in favor of option 3 for most of the issues. JS frameworks have come a long way and have wide industry support especially when you are talking of Frameworks like AngularJS or even jQuery. They also address many other concerns some that you haven't raised like cross browser compatibility which can be a huge pain even if you are supporting just one browser across versions.

ContentLicense: CC BY-SA 3.0

Body:
What you want to do is possible and there are available in many frameworks that can help here. Look at AJAX as a callback implemented in JS and not something different - this will help simplify your problem. There is no best practice IMO, but there are some options available that I have used in the past. Here are some options,

JSP Tag UI Components: You have some widget which requires some business input to render but is mostly JavaScript. While AJAX is an option it can be unnecessary if the data is available at the point of rendering the JSP. One approach is to create a JSP Tag Lib that internally renders the HTML and JS. The benefit is fewer people are touching and working with JS which is more error prone and relatively difficult to Unit Test. In the past this was a messy option since you would have to use multiple out.println statements to render the Dynamic JS from the Tag Handler but now with the introduction of Tag Files this can be a lot cleaner.

JS Endpoint: JS Endpoints are special servlets that serve dynamic JS. Think of this instead you setting a static file in the src attribute of the script tag you have the URL pointing to a URL pointing to a Servlet that responds with content type for JavaScript or JSON as the case may be.

<script src="/myapp/abc.jsx"></script>

In the web.xml,

<servlet-mapping>
<servlet-name>myServletThatServesDynamicJS</servlet-name>
<url-pattern>*.jsx</url-pattern>
</servlet-mapping>

Client-side Frameworks: There are many JS frameworks worth your time investment that can minimize the amount of JS you write by declaratively generate a lot of JS (and CSS) something that most Java developers would prefer. AngularJS and Bootstrap are examples. So you basically add some additional attributes to regular HTML tags and there is some magic in the background that generates components, makes AJAX calls, etc. Angular will pull required JS "modules" from the server as an when needed via AJAX calls and also supports advance features like DI which can make testing your JS code a breeze and also a lot cleaner.

I personally prefer using JS frameworks to solve JS problems. So I would be in favor of option 3 for most of the issues. JS frameworks have come a long way and have wide industry support especially when you are talking of Frameworks like AngularJS or even jQuery. They also address many other concerns some that you haven't raised like cross browser compatibility which can be a huge pain even if you are supporting just one browser across versions.


问:
Is there a software industry for converting old, outdated code to new standards?
There still are developers building and extending applications using languages like COBOL, since banks and other such organizations rely on ancient systems to power their day to day businesses. Some of these systems are mission critical, so instead of building up new ones, that might fail or have bugs, they prefer to continue using these ancient systems.

It would seem, that even though upgrading to newer software can be a pain, and a risk, there are tools and methodologies out there to make this transition safe. The benefits of upgrading to newer systems would of course be considerable - ease of maintenance, ease of finding skilled developers etc.

I have not yet heard of companies that are aimed at providing this service. Do they exist?

答:
I'd say there are plenty of companies that do this.

IBM for one big (400k+ people) one (I work there).

There are lots of old applications, some running on mainframes that haven't been touched in years, and now can't really be changed, ever. They could be replaced, but it is hard to replicate their function exactly without full test coverage. There are whole teams dedicated to making mainframe applications written decades ago talk to newer programs across REST calls or whatever is the latest craze and link in with the latest regulations, security requirements etc.


问:
Is using ELSE bad programming?
I've often come across bugs that have been caused by using the ELSE construct.  A prime example is something along the lines of:

```<code>If (passwordCheck() == false){
    displayMessage();
}else{
    letThemIn();
}
</code>```

To me this screams security problem.  I know that passwordCheck is likely to be a boolean, but I wouldn't place my applications security on it. What would happen if its a string, int etc?

I usually try to avoid using ELSE, and instead opt for two completely separate IF statements to test for what I expect.  Anything else then either gets ignored OR is specifically handled.

Surely this is a better way to prevent bugs / security issues entering your app.

How do you guys do it?

答:
First of all. LOL! Theres NO REASON to avoid else, at all. Its NOT bad practice in any way, shape or form.

If anything the code should be

```<code>if(!IsLoggedIn) { ShowBadLoginOrNoAccessPage(); return }
</code>```

Theres no two ifs there and it has no else. This is what i do in all my apps except one in which i throw an exception. The exception is caught in my function which checks the url for the proper page to show (or alternatively i can put the catch/check in asp.net error function). It prints out a generic page that says not authorize or whatever message i use in the exception (i always check the type of exception and set the http status code).

-Edit- as shown in ammoQ example two ifs is ridiculous. Really else is just as good or better then an if. If anything ifs are to be avoided (although i personally dont. But i do use return and break a lot) as its been said more code paths increase the likelihood of bugs. See Cyclomatic Complexity

-Edit 2- If you are worried about if/else usage. I'll also note that my preference is to put the shortest code block at top such as

```<code>if(cond == false) {
    a()
    b()
    c()
    onetwothree()
}
else
{
    a()
    b()
    c()
    more()
    onetwothree()
    code()
    longer()
}
</code>```

Rather then

```<code>if(cond)
{
    a()
    b()
    c()
    more()
    onetwothree()
    code()
    longer()
}
else
{
    a()
    b()
    c()
    onetwothree()
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Is using ELSE bad programming?

Body:
First of all. LOL! Theres NO REASON to avoid else, at all. Its NOT bad practice in any way, shape or form.

If anything the code should be

if(!IsLoggedIn) { ShowBadLoginOrNoAccessPage(); return }

Theres no two ifs there and it has no else. This is what i do in all my apps except one in which i throw an exception. The exception is caught in my function which checks the url for the proper page to show (or alternatively i can put the catch/check in asp.net error function). It prints out a generic page that says not authorize or whatever message i use in the exception (i always check the type of exception and set the http status code).

-Edit- as shown in ammoQ example two ifs is ridiculous. Really else is just as good or better then an if. If anything ifs are to be avoided (although i personally dont. But i do use return and break a lot) as its been said more code paths increase the likelihood of bugs. See Cyclomatic Complexity

-Edit 2- If you are worried about if/else usage. I'll also note that my preference is to put the shortest code block at top such as

if(cond == false) {
    a()
    b()
    c()
    onetwothree()
}
else
{
    a()
    b()
    c()
    more()
    onetwothree()
    code()
    longer()
}

Rather then

if(cond)
{
    a()
    b()
    c()
    more()
    onetwothree()
    code()
    longer()
}
else
{
    a()
    b()
    c()
    onetwothree()
}


问:
How can I know if my data needs to be a react.js component?
I'm looking at React.js, and trying to see if it can help me with my recurring sets of data that I have on various pages. All the data is from a database, say a list of names and addresses, a tabular set of data, semantically  tags.

I might need that set of information on more than one page. I'm using a PHP MVC framework (in-house), so I can call that data as needed, but I don't know if I'm able to consider the set a "component."

I don't want overkill, but I might have lots of sets of data like that, and the data will be related (from some RDBMS). If I have a name and address, I may want to see how many orders I sent there. Is that orders set a component I can build? Examples could be multiplied.

Almost everything is from a form that is submitted and returns read only data. No inserts, updates or deletes, only select.

Is something like Angular.js a better suited framework? Overkill?

I had this on SO but deleted it.  I think it is more of a design question.

答:
If you're getting some data, and you're rendering that data, it's a component. It's as simple as that. Pretty much everything that renders should be a React component. Most other things do not want to be React components.

The React framework and lifecycle is completely built around "Render this data" as it's pretty much sole purpose. If the responsibility of the code could be summarized that way, then it's a component. Otherwise, it's a poor fit for being a component.


问:
Usage of github libraries
So far there had been a lot of external libraries provided for us to reduce our efforts on coding and utilising the time to provide quality apps to the play store. Now, I am keen to understand whatever the libraries that we use to build our android apps, should we have to give some credits or attributions inside our app or in the app description? If so then what if I use multiple libraries in my app, should I have to provide the license attribution for all the libraries I use in my app separately?</p>

答:
You most certainly should credit the author(s) of any code which you yourself did not write. Not only is this the descent thing to do, but in may cases it may be a legal requirement.

When someone creates a repository on Github they are given the option to add a standard licence to the repository e.g. GPL, LGPL, BSD, MIT, Apache, etc. They may instead have opted not to include a licence or to include one of their own creation instead.

The first thing to look for is a file in the top-level of the repository called  "LICENCE.txt". Within this file there will be clear instructions on how to appropriately attribute the authorship of the library in question, and more importantly, what you may and may not do with it. Typically the licence will require you to include a copy of licence along with any of your code which uses the library.

For example the MIT licence includes the following statement:

The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

If there isn't a file called "LICENCE.txt" then look for "README.txt" or something similar.

What if you can't find a licence you may ask? Well the folks at Github say the following:

You're under no obligation to choose a license. It's your right not to
  include one with your code or project, but please be aware of the
  implications. Generally speaking, the absence of a license means that
  the default copyright laws apply. This means that you retain all
  rights to your source code and that nobody else may reproduce,
  distribute, or create derivative works from your work. This might not
  be what you intend.

For further details see https://help.github.com/articles/open-source-licensing/

Title: Usage of github libraries


问:
Is this a user story or a bug?
Consider the following user story(ies) for a manufacturing management system I am building:

As a shipper/receiver I need to be able to create work orders So that
  we can begin tracking jobs internally

As a shipper/receiver I need to be able to update work orders So in
  the case of an error at incoming I can change that before handing off
  to production

As a inspector I need to be able to change the part number/repair
  scheme of a work order So in the case of a mis-identified part I can
  change the work scope before actually starting

These are all tasks which would take several days to implement, once the work order UI dialog had been established and the CRUD facilities, etc were in place.

Now lets say three weeks down the road, after using the prototype, and inspector comes to me and says "Receiving created a new work order by accident; The work order already existed but the part had left the building for sub-contract work and upon it's return should have been expedited past work order creation"

I might write this story out as follows:

As a shipper/receiver I should not be able to re-create work orders
  already in the system as WIP; In these cases the system should
  determine the subcon and notify me of that status so I simply pass it
  on through So that multiple live work orders are not duplicating each
  others work scope

The story sounds quite verbose...but the requirement was literally a few lines of code added to the beginning of work order creation and took only 30 mins to add. Feels odd using a story for such a request.

Better suited for a bug tracker???

My question ultimately becomes this: When I am analyzing requirements, asking questions and figuring out high level components (ie: Work orders, repair orders, sales orders, etc) I am not focusing on specific business logic or rules but establishing components.

As a user I need to be able to create and manage work orders So that
  we can begin tracking parts internally

Does it make sense to further break these down into atomic user stories, such that:

As a user I should not be able to receive a work order when...

Listing out the exceptions as individual stories?

To me this is where use-case and it's format for capturing requirements makes more sense...

Anyway what has your experience been? Opinions & comments welcome...

I am attempting to find a balance between the terse agile/scrum user story and the BUFD use-case approach to project planning (please leave the they are mutually exclusive argument for another topic)

答:
My experience; Although there is a 'bug/defect' object in RTC (the collaboration tool used to capture user-stories in my workplace) for the most part my associates tag everything as a general 'task', regardless of whether it can be considered a bug (or group of bugs) or a non-bug task.

We do have a Trac-style tool to keep track of the discovery and resolution of bugs as well, but when we take on those bugs, we replicate the description in RTC, and usually just list it as a 'task', for purposes of uniformity. It may seem counter-intuitive to describe bugs in two places, but this is useful for hour tracking if nothing else. And listing everything as a 'task' helps the higher-ups with their queries... At least, that's what they tell us.

So an example SuperEpic might be Open Source Proof of Concept, Epic could be Email app on Android, the story would be Composing and Sending, and a task would be Compose screen should show recipient instead of sender.

With regards to your use case... Is it a bug? Sure. Is it a user story? It looks like one. Why not both?

That's my opinion, anyway. But you asked for it!

Title: Is this a user story or a bug?


答:
First, I think that the use of the term "bug" is a bit off. There are some questions here on Programmers about this (1, 2, 3). Generally, the word "bug" refers to a defect in code. The software does not do what we expect - it crashes, it produces incorrect results, or something along those lines. I prefer to use the word "defect", and this other answer suggests "error" as the correct term, when it comes to discussing a broad categories of issues that arise in the development process.

Rather than trying to classify your change as a unique user story or a bug, I'd classify it as a defect in your original user story. Your original user story or some aspect of it, such as the acceptance criteria, the task breakdown, or perhaps just a breakdown in communication that lead to a misunderstanding - regardless, it seems like the activity of gathering and decomposing the requirement was the issue.

Title: Is this a user story or a bug?

Body:
Consider the following user story(ies) for a manufacturing management system I am building:

As a shipper/receiver I need to be able to create work orders So that
  we can begin tracking jobs internally

As a shipper/receiver I need to be able to update work orders So in
  the case of an error at incoming I can change that before handing off
  to production

As a inspector I need to be able to change the part number/repair
  scheme of a work order So in the case of a mis-identified part I can
  change the work scope before actually starting

These are all tasks which would take several days to implement, once the work order UI dialog had been established and the CRUD facilities, etc were in place.

Now lets say three weeks down the road, after using the prototype, and inspector comes to me and says "Receiving created a new work order by accident; The work order already existed but the part had left the building for sub-contract work and upon it's return should have been expedited past work order creation"

I might write this story out as follows:

As a shipper/receiver I should not be able to re-create work orders
  already in the system as WIP; In these cases the system should
  determine the subcon and notify me of that status so I simply pass it
  on through So that multiple live work orders are not duplicating each
  others work scope

The story sounds quite verbose...but the requirement was literally a few lines of code added to the beginning of work order creation and took only 30 mins to add. Feels odd using a story for such a request.

Better suited for a bug tracker???

My question ultimately becomes this: When I am analyzing requirements, asking questions and figuring out high level components (ie: Work orders, repair orders, sales orders, etc) I am not focusing on specific business logic or rules but establishing components.

As a user I need to be able to create and manage work orders So that
  we can begin tracking parts internally

Does it make sense to further break these down into atomic user stories, such that:

As a user I should not be able to receive a work order when...

Listing out the exceptions as individual stories?

To me this is where use-case and it's format for capturing requirements makes more sense...

Anyway what has your experience been? Opinions & comments welcome...

I am attempting to find a balance between the terse agile/scrum user story and the BUFD use-case approach to project planning (please leave the they are mutually exclusive argument for another topic)


答:
Reusable components are the core of any React app. You can create a component for each type of data that you receive from the database and render them whenever the need arises. To decide how to break up components, refer to this post from Facebook.

As for the relation data you wish to work with, this is where the real design considerations might come in. If you are storing the data as props for each component, you will have to make sure that your design permits the top-bottom or bottom-top trickle of data or you may not be able to perform your relational queries. On the other hand you can store it as global or use any other approach you might deem right.

Another thing to be considered is that React is not a MVC framework so you cant task your Controller to store the data in Model and have the View work with it. In React you can either use the Isomorphic approach to get the data or you can make AJAX requests to your server. You should probably have a look at Flux Architecture for React.

As for using Angular, it's a full fledged MVC framework while React's chief concern is the View. It down to personal preferences.

Personally I use React whenever I need a 'stateful' web app. Where I need to handle view changes in real time based on user's interactions with the app. React is best suited for this purpose, but if your app is going to be more of a static nature, you can definitely use React but you won't be harnessing it's full potential.

Title: How can I know if my data needs to be a react.js component?

Body:
I'm looking at React.js, and trying to see if it can help me with my recurring sets of data that I have on various pages. All the data is from a database, say a list of names and addresses, a tabular set of data, semantically  tags.

I might need that set of information on more than one page. I'm using a PHP MVC framework (in-house), so I can call that data as needed, but I don't know if I'm able to consider the set a "component."

I don't want overkill, but I might have lots of sets of data like that, and the data will be related (from some RDBMS). If I have a name and address, I may want to see how many orders I sent there. Is that orders set a component I can build? Examples could be multiplied.

Almost everything is from a form that is submitted and returns read only data. No inserts, updates or deletes, only select.

Is something like Angular.js a better suited framework? Overkill?

I had this on SO but deleted it.  I think it is more of a design question.


问:
OO design in a data processing pipeline
I'm wondering how to design a fairly simple class whose properties are complex to compute.  Also, the properties depend upon each other for computation.

An example using graphs and graph processing (think nodes and edges, not charts or scatterplots) to motivate the problem:

Class CommunityGraphSet is a collection of Community instances.  CommunityGraphSet is initialized with an input graph (some large social network graph), along with some basic parameters describing what is known about the graph.  A Community is a subgraph of the input graph, along with some structural descriptors.

After initialization, the CommunityGraphSet contains no Community subgraphs.  After several major processing steps, it contains a set of Community subgraphs.  Each major processing step (i.e. function call) triggers a GUI for a human to tune the parameters of the algorithm being run in that step.  The human sets parameters, the processing results are visualized, and they continue to refine the parameters until the results are acceptable.  After they "accept the parameters" with a button click, the results they saw are returned by the method that triggered the GUI.

```<code>input_graph = read("graph_file.csv")

number_communities = 3
sparseness_thresh = (0.05, 0.10)

# MAJOR PROCESSING STEP
# get parameters for key community member identification based on overall graph structure
key_ident_params = compute_key_identification_params(input_graph)

# initialize the graph set
graph_set = CommunityGraphSet(input_graph, number_communities, sparseness_thresh)

# MAJOR PROCESSING STEP
# mark where community subgraphs definitely are not.
partition_mask = isolate_potential_communities(graph_set)

# use mask to extract subgraphs for refinement by different algorithms.
potential_community_subgraphs = graph_set.extract_subgraphs(partition_mask)

for community in community_list:

    # MAJOR PROCESSING STEP
    # key community member extraction
    key_members = extract_key_members(community, key_ident_params)

    # MAJOR PROCESSING STEP
    # use identified key members and community sparseness to trim community to final subgraph
    final_community = refine_community(community, key_members, sparseness_thresh)

    # put the refined community in the final set
    graph_set.add_community(final_community)

save(graph_set.serialize(), "communities.json")
</code>```

My problems with this design:

CommunityGraphSet is stateful.  It contains Community subgraphs only after the right function calls in the right order.

The processing pipeline is monolithic.  As the processing pipeline grows and changes, maintaining it will become unweildy as I'm faced by a growing number of variables used in increasingly many places.

Are these indeed problems?  Or are they inherent in data processing pipelines?

If they are problems, how can I solve them?

Notes:

None of CommunityGraphSet is not coupled to GUI logic, it is coupled to an IterativeOptimizer interface for each step.  The described GUI or a clever optimization algorithm could implement that interface.

答:
I think that the two problems you listed arise not from your design but rather out of the problem you are solving.

Depending on how generic you want to make your design, you could have some meta-data that defines each major processing step, and then some methods that you call to "push" the pipeline into the next step. Of course, since it sounds like each step requires its own specific parameters from the user, you would have to define the parameters generically as well, using more meta-data.

I don't think that what I just outlined is a particularly good design based on your problem description. It adds a lot of complexity and meta-data overhead for no real benefit. Sometimes a problem is so domain-specific that the code you design to solve it is going to be equally specialized. That's not necessarily a bad thing. You can mitigate it by writing code that is as clear and simple and well-documented as possible :-)

Update: As to your specific question of whether it's "OK to have a have a class that's designed to be incomplete on initialization, and completed by necessary processing steps," you may be thinking of the more general advice that is mentioned in some OO design guidelines:

A properly written constructor leaves the resulting object in a
  valid state.

Remember, it's up to you to decide what "valid" actually means in context. In your example, I would argue that the CommunityGraphSet is in a valid state even at the beginning because its purpose is not to serve as a static immutable representation of the graphs, but as a processing pipeline to generate the graphs based on successive stages of user input. In other words, it's not really "incomplete" because the requirements dictate that the processing requires several stages of user input. Perhaps a better name would be CommunityGraphGenerator or CommunityGraphProcessor. Further, you could define a separate class CommunityGraphSet that would hold the results of the entire process once the pipeline is finished. Even if this class is just contained within the larger one, it might make the design more understandable to an OO purist.

Title: OO design in a data processing pipeline


问:
"Comments are a code smell"
A coworker of mine believes that any use of in-code comments (ie, not javadoc style method or class comments) is a code smell.  What do you think?

答:
A good idea to have the right comments is to start with writing comments.

```<code>// This function will do something with the parameters,
// the parameters should be good according to some rules.
myFunction(parameters)
{
    // It will do some things to get started.

    // It will do more with the stuff.

    // It will end doing things with the stuff.
}
</code>```

This allows you to extract methods easily to even get rid of the comments,

just let the code tell these things! See how this is rewritten (cut/paste) in a very nice way:

```<code>// This function will do something with the parameters,
// the parameters should be good according to some rules.
myfunction(parameters)
{
  var someThing = initializedWithSomething;

  doSomethingWith(someThing);

  doMoreWith(someThing);

  endDoingThingsWith(someThing);

  return someThing;
}

// This function will do some things to get started,
// the parameters should be good according to some rules.
doSomethingWith(parameters)
{
  parameters.manipulateInSomeWay();
  ... etc ...
}

... etc ...
</code>```

For things that can't be separated just don't extract methods and type the code under the comments.

This is what I see as an useful way to keep commenting to a minimum, it's really useless to go commenting each line... Only document a single line if it's about a magic value initialization or  where it makes sense.

If parameters are used too much, then they should be private members in your class.

Title: "Comments are a code smell"

Body:
A good idea to have the right comments is to start with writing comments.

// This function will do something with the parameters,
// the parameters should be good according to some rules.
myFunction(parameters)
{
    // It will do some things to get started.

    // It will do more with the stuff.

    // It will end doing things with the stuff.
}

This allows you to extract methods easily to even get rid of the comments,

just let the code tell these things! See how this is rewritten (cut/paste) in a very nice way:

// This function will do something with the parameters,
// the parameters should be good according to some rules.
myfunction(parameters)
{
  var someThing = initializedWithSomething;

  doSomethingWith(someThing);

  doMoreWith(someThing);

  endDoingThingsWith(someThing);

  return someThing;
}

// This function will do some things to get started,
// the parameters should be good according to some rules.
doSomethingWith(parameters)
{
  parameters.manipulateInSomeWay();
  ... etc ...
}

... etc ...

For things that can't be separated just don't extract methods and type the code under the comments.

This is what I see as an useful way to keep commenting to a minimum, it's really useless to go commenting each line... Only document a single line if it's about a magic value initialization or  where it makes sense.

If parameters are used too much, then they should be private members in your class.


问:
c# application to read xml files, parsing them, storing locally in data structure and writing to csv
I have to develop a c# application that will read large xml files. XML files will have data about computer systems (i.e. Hardware, software, network, bios information). There will be separate xml file for each category i.e. hardware xml file, software xml file. A computer id is common attribute in all these xml files. It might be possible that a computer id present in one xml file but not in other. After the reading part is done, and storing data locally, it needs to be written in different csv i.e Hardware.csv, software.csv. Only those id's need to be written that are present in all xml files. I am thinking of the below approach to do this,

1) Read each xml file, store its computer id in data structure like Dictionary (with key being its computer id and value is Arraylist>). Each object will have associated attributes.
For Example - Hardware xml will be read and stored in dictionary as <1,  hwarraylist>. Each hw object will have attributes as hwmodel, hwmanufacturer etc

2) While reading the second xml file i.e software xml file, if the id already exist in dictionary then a swarraylist will be appended to its value. Otherwise a new computerid is added to dictionary.

3) After all reading is done, I'll write arraylist of only those id's which have number of arraylist = number of xml files. Separate csv for separate arraylist.

Is this approach correct ?
Will it be feasible for millions of rows in each xml file ?

One more thing to add,
the xml file is as per the below format:

```<code>    <result_sets>
      <result_set>
<cs>
  <c>
    <wh>123</wh>
    <dn>Computer ID</dn>
    <rt>1</rt>
  </c>
  <c>
    <wh>112</wh>
    <dn>Name</dn>
    <rt>1</rt>
  </c>
  <c>
    <wh>124</wh>
    <dn>System</dn>
    <rt>1</rt>
  </c>
</cs>
<rs>
  <r>
    <id>8820</id>
    <cid>230</cid>
    <c>
      <v>230</v>
    </c>
    <c>
      <v>Windows</v>
    </c>
    <c>
      <v>system32</v>
    </c>
  </r>
</rs>
</code>```

Is it possible to parse them using XMLReader or I should treat then as text files and do the processing.
Please advise

答:
Is this approach correct ?

If you mean "does it match the problem description" - yes, seems to me.

If you mean - "did you understand the requirements correctly" - who knows but you.

If you mean - is there a better approach - there is always a better approach, but maybe what you wrote is sufficient for your case, you will probably find out by trying it out.

What I probably would not do is just appending your category lists to an ArrayList . If you are not very careful, you will end up not knowing which of the different categories is at which index in your list. Using a Dictionary<string,CategoryList> can fix this - where the key is the category name, and the value is a supertype of your different category lists.

Will it be feasible for millions of rows in each xml file ?

That depends on the correct implementation and your available hardware/main memory. If your XML files are very big, you should avoid to read them completely into an XmlDocument, because that it very memory expensive. Better use something like an XmlReader, which processes the file sequentially. Nethertheless you have to test by yourself if holding all the CategoryLists in memory will work in your case.


问:
In Agile SCRUM, how do you handle even distribution of work in a sprint between "experts"?
Where I work, we have a lot of silos of knowledge. Basically each member of the development team is the expert (and sometimes the only one that knows a thing) on certain pieces of the overall software. For example, one person might be the expert on the rendering engine of a game. Another is the guy that works on the GUI. Rarely do the two intermingle. The concern is that it doesn't make sense to have the GUI guy work on Networking stuff, when there is already someone that can (in terms of efficiency) get something done better because they are already familiar with it.

This situation seems to make sprint planning difficult in SCRUM. It's quite possible that people on the team have no tasks or are seriously underutilized in a specific sprint simply because there is nothing there they are the "best fit" to work on. This makes calculating velocity unreliable as it will vary based on who actually gets more assignments during one sprint versus the other.

How would I overcome this issue? It seems like the focus should be more on the tasks and what needs to be done and less on the specific people to work on them. I think upper management will always prefer things to be done as quickly as possible. And if they see that GUI developer estimates 21 story points on a task related to the Engine, where the Engine guy estimates 5 points, they will question why we chose 21 (The goal would obviously be knowledge sharing, but this will cause the team to work inefficiently overall).

答:
Silos are bad for a number of reasons. Bus factor was already mentioned.
When you have narrow specialization you pay the price of hand off and integration as well.

I like the idea of "not doing anything" for you as a manager - that's the wise advice, however, there things you still need to pay attention to.

Priority.
This seems to almost always escape from the scene when the question comes to processes (like planning, estimation etc) - processes are there to help you deliver business value, not for their own sake. Ask yourself, or better your team, how the most important thing on your backlog can be done the quickest? They will figure this out. Do not assign work to fill up the idle cycles. Instead of having idle person work on something that is small but not important, make them spend time on improving the way they deliver important value. There is always work to automate/templatize/etc.

Team ownership.
If you actually have a team (not just hired disperse temporary consultants) work on improving the team ownership feeling in it. It's great when everyone in the team is interested in the work in progress. It is bad when one is yawning during the standup while listening to the update of others he has no interest/understanding of.
Try to have the team to work on vertical slices, so that they build one end-to-end experience at a time - then, they will be more bought in all the time, and it will encourage UI guy to help with back-end and vice-versa. As already suggested XP is great to build team ownership and improve knowledge sharing.

Smaller stories. 21 is A LOT for an estimation. Can you make smaller vertical slices? That is a skill that your team needs to develop, and it is hard to do in the beginning. What I advocate is to play the planning poker with your fingers (1,2,3,5) if you are out fingers for the estimation value - that is a signal that story is too big to be estimated. Once you master the story creation skill, you will naturally tend towards NoEstimates movement. Simply counting stories will work the best for your velocity.
Read this for drawbacks though ;)


问:
Python packages from an operations perspective
As a developer I am used to keep my Python tools updated. Especially packages needed for installing and bundling. Using the most recent releases of pip, virtualenv and setuptools is in my personal experience the most reliable choice.

I have been told recently that from an operations perspective, I should not touch the preinstalled releases of pip on the production machine. So to speak: The typical pip install -U pip in the virtualenv was a security risk.

There are valid concerns I think, but I do wonder whether this really is the best practice for running services developped with Python. Pip as it is in Debian 7 for example is quite old.

So my questions

What are the best practices here for running Python services securely?

Are there ways to move the split worlds (OS Package Tree and Python Package Tree) closer together?

答:
Linux packages shipped with a given distribution are usually heavily tested to ensure they work well with the specific distribution. Your company may do an additional step of testing those packages for the scenarios which happen specifically in the company.

If you're installing newer versions, you're on your own. It may work well, and it usually does, because it was tested by the developers of the package itself. But it may also cause problems in a given distribution.

Whether you should install the newer versions depend on:

How stable the servers should be. If you want to avoid any issue in production, don't blindly upgrade to newer versions expecting that everything will work as expected.

How critical is to have the new version. Some versions contain new features you absolutely need for your application, and it becomes acceptable to take a risk to update the package. Some versions solve bugs which are again critical enough to be kept on your platform.

In general, the update process of production servers, would it be on Linux or Windows, is not as simple as apt-get install ... or clicking on a button in Windows Update. Instead:

Updates should be tested in staging to ensure that there are no apparent regressions.

Production servers s houldn't be updated all at once, but rather one by one, to be able to failover and to step back if something bad happens.

You should make sure you can revert to earlier state if a regression is discovered later.


问:
At what point can I call GPL code my code?
I need some legal advice if possible.

So I'm going to be implementing some code under OSS license. I realize that even if I rewrote the implementation, I need to include the license.

However a lot of sources that I use to learn are under GPL Licenses. So even if I take what I learned and implemented it in my own way and heavily modified the code, with the only similarities being logic flow, I still can't claim the work as my own?

What about algorithms that are extremely proficient? (Like binary Heaps)
Do I need to include the inventor of the binary heap into my code?

Also, as I understand it from GPL, if I use the code, even modified, does this mean I need to release the all of my code that even associates with it? So if I make a whole application in a closed system and I plan to sell it, I still have to release all my code via OSS license?

Let me know if I need to provide more information about my question, thanks.

答:
The license on a given piece of software is only relevant if you are using that particular piece of software (or a part of it, or a version of it you've modified yourself, or a part of it that you've modified, etc). If you write an equivalent piece of software yourself, completely 100% from scratch, then there is no license on it until you choose one yourself.

What you appear to be worried about are software patents, not licenses. The GPL doesn't let you sue someone for writing code that uses a similar algorithm or UI elements (assuming you didn't actually use any GPL'd code in your re-implementation), but patents do. And a lot of real software companies have ludicrously broad patents that may or may not hold up in court, if only to act as a defense when other companies try to sue them with their own patents.

If you need actual legal advice on how big of a risk this is for your project, you definitely need to consult a lawyer. Patents are hard. If you're just curious, then you may find it interesting to read about some high-profile "clean room reimplementations" such as Google's Dalvik VM for Java, which Oracle attempted to sue for patent infringement but lost. I would also guess that the people/companies who publish GPL'd code in the first place are probably not the kind of people/companies who sue others over software patents, but of course there's no guarantee.


答:
Using virtual environments, you can specify which version of each package you want installing (why this is a good thing). This allows you to pin version specific to whatever you code base needs.

The main draw backs are that updating can be slower and deploying to a new machine takes longer. The former might not be too bad since you want to test that all newer version of dependencies still work with your code, right? The later has been solved by a plethora of tools -- for example Puppet-Python.

Title: Python packages from an operations perspective

Body:
As a developer I am used to keep my Python tools updated. Especially packages needed for installing and bundling. Using the most recent releases of pip, virtualenv and setuptools is in my personal experience the most reliable choice.

I have been told recently that from an operations perspective, I should not touch the preinstalled releases of pip on the production machine. So to speak: The typical pip install -U pip in the virtualenv was a security risk.

There are valid concerns I think, but I do wonder whether this really is the best practice for running services developped with Python. Pip as it is in Debian 7 for example is quite old.

So my questions

What are the best practices here for running Python services securely?

Are there ways to move the split worlds (OS Package Tree and Python Package Tree) closer together?


答:
millions of rows - you have to understand the memory requirements of each row stored, if you have 1 million rows and each row is 1k (including object overheads) then that's a gig of RAM used. Strings can get big, so you might run into memory constraints quite easily.

What you are trying to do here is a classic merge problem (you should write it in COBOL - the classic COBOL program is one that takes a list of employees, and another list of work and merges them together to run payroll!) that works best if the input files are sorted.

If they were sorted in id order, then you can open each and read an entry from each, 1 at a time, if the IDs match write out a row to the output file, then repeat until all input is exhausted. Memory usage is minimal, efficiency is great (as you do not need to store and remember all IDs, they will come to you in order)

So I would work on a sorter for the xml inputs first.

Title: c# application to read xml files, parsing them, storing locally in data structure and writing to csv

Body:
I have to develop a c# application that will read large xml files. XML files will have data about computer systems (i.e. Hardware, software, network, bios information). There will be separate xml file for each category i.e. hardware xml file, software xml file. A computer id is common attribute in all these xml files. It might be possible that a computer id present in one xml file but not in other. After the reading part is done, and storing data locally, it needs to be written in different csv i.e Hardware.csv, software.csv. Only those id's need to be written that are present in all xml files. I am thinking of the below approach to do this,

1) Read each xml file, store its computer id in data structure like Dictionary (with key being its computer id and value is Arraylist>). Each object will have associated attributes.
For Example - Hardware xml will be read and stored in dictionary as <1,  hwarraylist>. Each hw object will have attributes as hwmodel, hwmanufacturer etc

2) While reading the second xml file i.e software xml file, if the id already exist in dictionary then a swarraylist will be appended to its value. Otherwise a new computerid is added to dictionary.

3) After all reading is done, I'll write arraylist of only those id's which have number of arraylist = number of xml files. Separate csv for separate arraylist.

Is this approach correct ?
Will it be feasible for millions of rows in each xml file ?

One more thing to add,
the xml file is as per the below format:

```<code>    <result_sets>
      <result_set>
<cs>
  <c>
    <wh>123</wh>
    <dn>Computer ID</dn>
    <rt>1</rt>
  </c>
  <c>
    <wh>112</wh>
    <dn>Name</dn>
    <rt>1</rt>
  </c>
  <c>
    <wh>124</wh>
    <dn>System</dn>
    <rt>1</rt>
  </c>
</cs>
<rs>
  <r>
    <id>8820</id>
    <cid>230</cid>
    <c>
      <v>230</v>
    </c>
    <c>
      <v>Windows</v>
    </c>
    <c>
      <v>system32</v>
    </c>
  </r>
</rs>
</code>```

Is it possible to parse them using XMLReader or I should treat then as text files and do the processing.
Please advise


答:
Millions of rows !! Think performance first :-)

1) You can probably think of creating a WCF service or Windows service to process the XML parsing & CSV generation steps.

2) Use SSIS package to parse the huge XML file into data to be stored into the database. This will help you to churn the massive large XML file into records. Then you can use to generate the CSV file from .net code. Recently, i used SSIS package to process huge record set and it took very less time to churn it.

Since there will be million of records in the XML file, i think it will add plenty of constraint on the memory while parsing the XML into object form.


问:
Why I need to make method of my class private, If I need to access it throughout my application?
I am going through the beginners tutorial for C# from a website
http://www.homeandlearn.co.uk/csharp/csharp_s10p1.html
On chapter of classes, it makes the method of class private and then use property to get and set values. I am unable to understand why I need to make anything private in my class if I have to use/reuse it throughout the projects?

I am not asking for getters and setters, I am more concern about why I need to use Private keyword if all things are working fine with Public in tutorial example.

答:
The author provided a simple example which, due to its simplicity might make it more difficult for one to understand the importance of private methods.

Private methods are a way in which you can encapsulate and break down the behavior of a given object without exposing them to the outside.

Let us say that we have an object of type Person:

```<code>public class Person
{
     public string Name {get; set;}
     public int Age {get; set;}
}
</code>```

In the above, there is nothing stopping me from creating a person with a negative age:

```<code>Person p = new Persion() {Name = "Bob", Age = -1}
</code>```

I could have a method to ensure that the age is within a set of established ranges.

```<code>public class Person
{
    private int age;

    public string Name {get; set;}
    public int Age {get {return this.age}; set {this.ValidateAge(value);}

    public void ValidateAge(int age) { if(age > 0) this.age = age; }
}
</code>```

The problem now is that I have a ValidateAge method which is exposed to who ever consumes the Person class. This exposes an internal mechanism of the class and also provides a means to someone to change the internal data of the class without going through the appropriate property, thus breaking encapsulation.

Making the method private will hide it from outside callers, thus giving you better control over how and when are properties changed.

Body:
The author provided a simple example which, due to its simplicity might make it more difficult for one to understand the importance of private methods.

Private methods are a way in which you can encapsulate and break down the behavior of a given object without exposing them to the outside.

Let us say that we have an object of type Person:

public class Person
{
     public string Name {get; set;}
     public int Age {get; set;}
}

In the above, there is nothing stopping me from creating a person with a negative age:

Person p = new Persion() {Name = "Bob", Age = -1}

I could have a method to ensure that the age is within a set of established ranges.

public class Person
{
    private int age;

    public string Name {get; set;}
    public int Age {get {return this.age}; set {this.ValidateAge(value);}

    public void ValidateAge(int age) { if(age > 0) this.age = age; }
}

The problem now is that I have a ValidateAge method which is exposed to who ever consumes the Person class. This exposes an internal mechanism of the class and also provides a means to someone to change the internal data of the class without going through the appropriate property, thus breaking encapsulation.

Making the method private will hide it from outside callers, thus giving you better control over how and when are properties changed.


答:
The tutorial is trying to teach you about encapsulation.

Encapsulation is an important part of Object Oriented Programming.  It's a technique programmers use to keep their large codebases clean and easy to work with.  Essentially, it means that anything that can be left as a private implementation of a class should be left private.  This reduces the "public surface" of your class, and helps keep your application responsibilities isolated into individual classes.

You can read up on this on wikipedia:

Ecapsulation

related: SOLID

Title: Why I need to make method of my class private, If I need to access it throughout my application?

Body:
I am going through the beginners tutorial for C# from a website
http://www.homeandlearn.co.uk/csharp/csharp_s10p1.html
On chapter of classes, it makes the method of class private and then use property to get and set values. I am unable to understand why I need to make anything private in my class if I have to use/reuse it throughout the projects?

I am not asking for getters and setters, I am more concern about why I need to use Private keyword if all things are working fine with Public in tutorial example.


答:
The tutorial appears to be demonstrating what you can do, not giving examples of what you should do.

Specifically in this case, their use of properties means b.MyProperty below doesn't equal "Bob", which would fail code review in any shop I've worked in.

```<code>HappyBirthday a = new HappyBirthday();

a.MyProperty = "Bob";

a.MyProperty = a.MyProperty;

HappyBirthday b = new HappyBirthday();

b.MyProperty = a.MyProperty;
</code>```

Body:
The tutorial appears to be demonstrating what you can do, not giving examples of what you should do.

Specifically in this case, their use of properties means b.MyProperty below doesn't equal "Bob", which would fail code review in any shop I've worked in.

HappyBirthday a = new HappyBirthday();

a.MyProperty = "Bob";

a.MyProperty = a.MyProperty;

HappyBirthday b = new HappyBirthday();

b.MyProperty = a.MyProperty;


问:
How do I know my data is relational or object oriented in nature?
Just read these lines-

If your data is object in nature, then use object stores ("NoSQL"). They'll be much faster than a relational database.

If your data is relational in nature, the overhead of a relational database is worth it.

from-

http://seldo.com/weblog/2011/06/15/orm_is_an_antipattern

So, how do I know whether my data is relational in nature or object-oriented?

答:
Data is not 'object in nature' or 'relational in nature'.
Any kind of data can be represented in both relational or a object model/graph structure. What is appropriate depends on how the data is going to be used by the applications. Often you might even have both. For example data used on a website could be stored in a relational database, but on-demand loaded into a graph structure which is then cached in an in-memory key-value store.

The statement that object stores/NoSql will be faster than relational for some kinds of data is simply wrong. What matters is again how your application use the data, not the form of the data itself. An object store will be faster at loading an object graph stored as a unit, but will be much slower at ad-hoc querying across many objects, or updating properties on many object.


答:
As a consultant, my teams similarly have members with specializations. We need to achieve high quality as quickly as possible in order to best meet our clients needs and our organization's profit margins. It is entirely valid to have team members that are specialized for optimum performance.

HOWEVER: This does not mean cross-training should not occur.

We have front-end developer specialists, but when they are busy our projects can't grind to a halt. If it looks like a .NET developer has some extra time in a sprint, they do not sit idle. They grab something they are less familiar with and use the expert as somebody they can ask questions of. Since the specialist is already working on other things (otherwise the story wouldn't be available to grab) you are not 'wasting' velocity, but are rather increasing the overall team's ability and capacity in that speciality (assuming the time for questions does not negate the increase in productivity). This is a great way to use 'idle' team members to help the overall team velocity and increase the cross-functional ability of the team.

Another option is to use idle developers to pair program, write unit tests for others, write any necessary documentation, help out the product owner with any tasks that might need doing. Remember always that ANY work that needs to be done by the team can always use an extra set of hands to make it happen faster!

Title: In Agile SCRUM, how do you handle even distribution of work in a sprint between "experts"?

Body:
Where I work, we have a lot of silos of knowledge. Basically each member of the development team is the expert (and sometimes the only one that knows a thing) on certain pieces of the overall software. For example, one person might be the expert on the rendering engine of a game. Another is the guy that works on the GUI. Rarely do the two intermingle. The concern is that it doesn't make sense to have the GUI guy work on Networking stuff, when there is already someone that can (in terms of efficiency) get something done better because they are already familiar with it.

This situation seems to make sprint planning difficult in SCRUM. It's quite possible that people on the team have no tasks or are seriously underutilized in a specific sprint simply because there is nothing there they are the "best fit" to work on. This makes calculating velocity unreliable as it will vary based on who actually gets more assignments during one sprint versus the other.

How would I overcome this issue? It seems like the focus should be more on the tasks and what needs to be done and less on the specific people to work on them. I think upper management will always prefer things to be done as quickly as possible. And if they see that GUI developer estimates 21 story points on a task related to the Engine, where the Engine guy estimates 5 points, they will question why we chose 21 (The goal would obviously be knowledge sharing, but this will cause the team to work inefficiently overall).


问:
What is the preferred way to store application configurations?
Most of the time, I store development application config in root directory of the project, like this:

```<code>app
|-- config.json
</code>```

But that doesn't seem to be the best approach, since this config ends up being stored in version control system - possibly resulting in leaked usernames, passwords and other sensitive stuff.

12 Factor App guide recommends dropping config files altogether and using environment variables for configuration setup:

... stores config in environment variables. Env vars are easy to change between deploys without changing any code; unlike config files, there is little chance of them being checked into the code repo accidentally; and unlike custom config files, or other config mechanisms such as Java System Properties, they are a language- and OS-agnostic standard.

That sounds really nice to me, but where does one store said environment variables, without checking them into source control? And what tools can I use to pass those variables to the app? There can be dozens of config options, and typing them by hand each time you launch the app is not nice - so they have to be stored in some kind of file somewhere. Said file thus will end up in source control, and we return back to where we started.

Is there some universally accepted way of handling configuration options, that doesn't have the risk of storing local configuration in source control?

答:
Possibly there is no one good answer to this. It seems that you need to store this data somewhere safe, as it will be needed for disaster recovery purposes one day. This applies equally to properties files and scripts that set environment variables.

With the source code (in SVN/GIT etc) is a really bad idea, as this data will contain production database passwords and the like.

Your corporate nightly backup may be sufficient, but it is unlikely to keep a readily-accessible history of change.

The data needs to be versioned separately to the consuming software. In our current system, a change of configuration leads to a new application build, and this is just plain wrong.

We are currently looking at solutions to this problem, and are leaning towards a code repository with restricted access. This repository would contain cofiguration data only. Do others have experiences to share?


问:
Design method to return List of objects
I need to create a method which will return a List of IRule objects.

This is what I have written, am I correct in the approach? Or should I follow any patterns/principles?

```<code>public IList<IRule> GetRules()
{
    return new List<IRule> {
         new Rule1(),
         new Rule2(),
         ...etc
     }
}
</code>```

答:
Consider the code:

```<code>foreach (Object o in Items)
{
    foreach(Rule r in GetRules())
    {
        //apply rule
    }
}
</code>```

This will create multiple copies of your list of objects. these will eventually be collected by the garbage collector. but in the mean time they eat memory.

Now if you called it "CreateRules()" or added some xml comment, you are less likely to do this by accident. But its still somewhat risky and begs the question of what you are attempting to achieve.

Be careful about falling the other way and providing access to a mutable list, where you don't want changes in one list of GetRules() to affect a second call

Title: Design method to return List of objects

Body:
Consider the code:

foreach (Object o in Items)
{
    foreach(Rule r in GetRules())
    {
        //apply rule
    }
}

This will create multiple copies of your list of objects. these will eventually be collected by the garbage collector. but in the mean time they eat memory.

Now if you called it "CreateRules()" or added some xml comment, you are less likely to do this by accident. But its still somewhat risky and begs the question of what you are attempting to achieve.

Be careful about falling the other way and providing access to a mutable list, where you don't want changes in one list of GetRules() to affect a second call


问:
"Sweep" a vector of pointers
I'm using a vector to store pointers to objects. In some cases I destroy one or more of these objects (setting the vector spaces to NULL after each delete call), which are externally selected:

```<code>for (int i=0; i<form->SelectListBox->Items->Count; i++) {
    if (form->SelectListBox->Selected[i]) {
        delete items[i];
        items[i]=NULL;
    }
}
</code>```

After that, I have erase all NULL pointers. This is what I'm doing and it works:

```<code>ItemVector::iterator it;
while ((it=std::find(items.begin(), items.end(), (MyObjects*)NULL))!=items.end()) {
    items.erase(it);
}
</code>```

Is there a more idiomatic way to "sweep" a vector of pointers? [1]

[1] As you may have guessed, I'm using C++Builder (version 6) and its VCL and try to migrate from using TList to using std::vector as to reduce static casts (the class TList provides a Pack method.

答:
Your algorithm is O(N²) - if you have 1000 elements in your vector and the first 100 are null, it will run the while loop 100 times, each repositioning up to 999 elements.

In implementation, you would use two iterators, one which you read from and one which you write to. If the read element is null, do not write it, otherwise write it back and increment.

The standard algorithm for doing this is called remove_if and there's detail discussion in this stackoverflow question.

Title: "Sweep" a vector of pointers


问:
How does the result of Product Backlog revision during Sprint Review influence the next Sprint's Backlog?
On scrumguides.org, the following is said about the result of a Sprint Review:

The result of the Sprint Review is a revised Product Backlog that defines the probable Product Backlog items for the next Sprint.

However, a Sprint Review is something you do at the end of a Sprint, meaning the next one is about to start and the top items of the Product Backlog should already be ready for that.

How does the revision of a Product Backlog during Sprint Review influence the next Sprint's Backlog? Are changes during Review typically used in last-minute changes to the next Sprint's Backlog? Do the Product Owner and Development Team both have a say in how the next Sprint is adjusted? Or should revisions to the Product Backlog typically not influence the next Sprint (but tops the one after that)?

I've tried answering my own question by carefully reading through aforementioned guide, and have checked similar questions and suggested duplicates on programmers.se, but haven't quite found an authorative answer.

答:
I've come across this and similar problems in scrum, basically I think this comes down to whether you have a period of time where no 'work' (in terms of tasks on the board) is being done between sprints

Some teams will move right into the next sprint with only a couple of short meetings

Some teams will have a break of a couple of days between sprints where they do the various meetings, sort the back log, estimate etc

Some teams will have whole weeks, or maybe release/bug fix sprints between 'normal' sprints

Personally I feel the 'no break' option is the best. It de-emphasizes meetings and artifacts in favor of task progress and encourages all tasks to be put into the backlog rather than having special, non sprint tasks

Hopefully your Scum master has sorted the backlog during the previous sprint and it can be quickly reordered without running out of well defined/well estimated tasks.


问:
Is there a software industry for converting old, outdated code to new standards?
There still are developers building and extending applications using languages like COBOL, since banks and other such organizations rely on ancient systems to power their day to day businesses. Some of these systems are mission critical, so instead of building up new ones, that might fail or have bugs, they prefer to continue using these ancient systems.

It would seem, that even though upgrading to newer software can be a pain, and a risk, there are tools and methodologies out there to make this transition safe. The benefits of upgrading to newer systems would of course be considerable - ease of maintenance, ease of finding skilled developers etc.

I have not yet heard of companies that are aimed at providing this service. Do they exist?

答:
There are many companies that claim to provide "commercial off the shelf" (COTS) products that will replace your legacy systems. My observations:

If the system being replaced adheres strongly to some standard, then a COTS solution is likely to be a good fit. Examples are enterprise accounting, payroll and tax packages provided by companies like SAP, IBM and Oracle. There are also niche providers that cover specialist fields like hospital management, hotel management, conference management etc.

If your system comes close to adhering to a standard, consider changing your business to fit the COTS product. Legacy systems often contain logic and business rules that have not been used for years, sometimes making this a viable alternative.

If your legacy system is unique and cannot be bent to fit the package, you may need to customize the package. This is where it gets interesting.

The customization may be only for you. When the next upgrade comes out you may have to pay a small fortune to the vendor to port the customized code, and there is nowhere else to go to get the work done.

Adding new features is easy if the package supports the new functionality, but can be extremely expensive if not. If the new feature is a customisation just for you, see the previous point.

Most modern COTS products provide some sort of configuration language or extension callouts to Java or similar. You can find yourself trying to write applications in a severely constrained environment using a poorly designed custom language - not a pleasant task.

If you regularly need to employ contractors, are there any available that know your COTS product?

So yes, there are companies out there that do replace legacy software, but the current trend seems to be towards COTS packages.


问:
Models, types, different views and meta data
We have a software which purpose is to be used to help users build their own applications. It has to be very loose coupled with the infrastructure: for example, I can imagine users running it on MySQL database as well on MongoDB.

We have modules of functionalities. In each module we do have what I call pure models - containing only what is required. For example, a Book contains authors, title, number of pages and so on.

The problem is that we need to bundle additional meta-data with the models that depends on the other infrastructure! Trivial example is a technical key of the Book: for MySql repos this is primary key of the table, some other ids as well; for MondoDB repos is just its own string key. As you see, the meta-data information is not unique and depends on infrastructure.

This additional data is provided by concrete repository implementation, every time when model is stored or retrieved from repo.

Now the problem: we would like to 'hide' this from the Book (i.e. model) interface - since there is no sense to bundle all variants of meta data to the Book.

How to solve this?

[A] We can have factories that builds our models, depending on used repo. So for SQL repo, we have a SQL factory, that builds a SQL variant of the model. Not sure that I like this.

[B] We simply add a property to Book for additional meta-data, like repoMetaData. This property is strictly technical, i.e. it is not related to the business. Then any repository implementation may inject whatever inside. Book would become RepositoryAware (an interface).

I like the [B] more, but some don't like the fact we are adding technical stuff to the book interface. How far it make sense to add additional, technical info to the models?

答:
The answer i've seen most often is to add :

```<code>public object MetaData
</code>```

To the class. Obviously this provides plenty of flexibility, but no type saftey.

Another option would be to add a GUID Id to all 'entity' style classes. This would allow consuming classes to implement thier own store of metadata keyed off the Id

Body:
The answer i've seen most often is to add :

public object MetaData

To the class. Obviously this provides plenty of flexibility, but no type saftey.

Another option would be to add a GUID Id to all 'entity' style classes. This would allow consuming classes to implement thier own store of metadata keyed off the Id


答:
I think the key line from the article is :

```<code>"Likewise, sometimes the output will be a single object X, which is easy to represent. But sometimes the output will be a grid of aggregate data, or a single integer count"
</code>```

It seems to me the author is making a good point in that if your code is for example getting the Number of customers in Spain for some bit of logic, you shouldn't populate a list of customers with all the customers in spain and then count the customer objects. (which an ORM might push you towards)

Obviously you cant tell from the customer data structure itself whether it will be used like that. so I think we should interpret 'data' to mean 'All of the information used by your application'. If this includes thing likes like aggregates or 'All X related to Y' then your 'data' is not suitable for the atomic NoSql approach

Title: How do I know my data is relational or object oriented in nature?

Body:
Just read these lines-

If your data is object in nature, then use object stores ("NoSQL"). They'll be much faster than a relational database.

If your data is relational in nature, the overhead of a relational database is worth it.

from-

http://seldo.com/weblog/2011/06/15/orm_is_an_antipattern

So, how do I know whether my data is relational in nature or object-oriented?

Body:
I think the key line from the article is :

"Likewise, sometimes the output will be a single object X, which is easy to represent. But sometimes the output will be a grid of aggregate data, or a single integer count"

It seems to me the author is making a good point in that if your code is for example getting the Number of customers in Spain for some bit of logic, you shouldn't populate a list of customers with all the customers in spain and then count the customer objects. (which an ORM might push you towards)

Obviously you cant tell from the customer data structure itself whether it will be used like that. so I think we should interpret 'data' to mean 'All of the information used by your application'. If this includes thing likes like aggregates or 'All X related to Y' then your 'data' is not suitable for the atomic NoSql approach


问:
BDD: Is it wrong to call it "Behaviour Driven *Design*"?
I learned the concept of BDD in this nice book, where the authors continuously refer to it as Behavior Driven Design, rather than using the term "Development". I've been using this definition since then (and it makes sense for me, especially when combined with a Test-Driven Development cycle). However, after presenting the concept of BDD to a colleague, he googled it and found out that most of the references call it "Behavior Driven Development".

Is there a difference between the two definitions? Should I call it Behavior-Driven Development, even if some relevant sources use the other translation?

答:
Dan North and others did refer to it as Behaviour-Driven Design back in the early days, when JBehave was just a replacement for JUnit.

However, when it moved up the stack to the system level, with examples that described the behaviour of entire applications rather than just individual classes, it became apparent that it affected more than just the design, and we started calling it Behaviour-Driven Development.

So, Development is now correct, and Design is old and out-of-date. You could feasibly think of Behaviour-Driven Design practices as a subset of Behaviour-Driven Development.


问:
Bundling and minifying options for MVC2
I've just been handed an MVC2 application and noticed that there is no bundling or minifying of the JavaScript or Stylesheets. I've used the built in bundling and minifying logic that comes out the box with MVC3+ but unfortunately this doesn't seem to be available with MVC2.

I am unable to upgrade the project to a later version so my question is as follows...

What are my options for bundling and minifying within an MVC2 application?

答:
You can manually minify and bundle the files and add some compilation instructions to switch between the two options depending on whether you are building for release or debug

If its your own javascript/css and it changes often you can automatic the minify process into your build script.

Title: Bundling and minifying options for MVC2


答:
I think your options are somewhat defined by the OS you are deploying to

I would suggest, yes put the values in source control. BUT only the 'dev' versions. You want your source code to compile AND work! not include extra secret steps

Your build and deploy process should then swap these values out per environment during deployment. (octopus has this kind of model)

Title: What is the preferred way to store application configurations?

Body:
Most of the time, I store development application config in root directory of the project, like this:

```<code>app
|-- config.json
</code>```

But that doesn't seem to be the best approach, since this config ends up being stored in version control system - possibly resulting in leaked usernames, passwords and other sensitive stuff.

12 Factor App guide recommends dropping config files altogether and using environment variables for configuration setup:

... stores config in environment variables. Env vars are easy to change between deploys without changing any code; unlike config files, there is little chance of them being checked into the code repo accidentally; and unlike custom config files, or other config mechanisms such as Java System Properties, they are a language- and OS-agnostic standard.

That sounds really nice to me, but where does one store said environment variables, without checking them into source control? And what tools can I use to pass those variables to the app? There can be dozens of config options, and typing them by hand each time you launch the app is not nice - so they have to be stored in some kind of file somewhere. Said file thus will end up in source control, and we return back to where we started.

Is there some universally accepted way of handling configuration options, that doesn't have the risk of storing local configuration in source control?


答:
By-products of the sprint review include a possible change to average velocity, and feedback from the stakeholder. That feedback might end up being "no, that's not what I wanted" or "excellent! Let's use that design for the rest of the app!". All of that can potentially change the items or order of items on the backlog.

Are changes during Review typically used in last-minute changes to the next Sprint's Backlog?

I wouldn't say typically, but it can happen. The reason for the review is to make sure you're meeting the needs of the stakeholders. The whole point of agile is to be able to adapt to changing requirements, and the review is perhaps the first place where a need for change becomes apparent.

Title: How does the result of Product Backlog revision during Sprint Review influence the next Sprint's Backlog?

Body:
On scrumguides.org, the following is said about the result of a Sprint Review:

The result of the Sprint Review is a revised Product Backlog that defines the probable Product Backlog items for the next Sprint.

However, a Sprint Review is something you do at the end of a Sprint, meaning the next one is about to start and the top items of the Product Backlog should already be ready for that.

How does the revision of a Product Backlog during Sprint Review influence the next Sprint's Backlog? Are changes during Review typically used in last-minute changes to the next Sprint's Backlog? Do the Product Owner and Development Team both have a say in how the next Sprint is adjusted? Or should revisions to the Product Backlog typically not influence the next Sprint (but tops the one after that)?

I've tried answering my own question by carefully reading through aforementioned guide, and have checked similar questions and suggested duplicates on programmers.se, but haven't quite found an authorative answer.


问:
What is your favorite whiteboard interview problem?
Just as the title says, what is your favorite whiteboard interview problem, and why has it proven effective for you?

Junior, senior, Java, C, Javascript, PHP, SQL, pseudo-code, etc.

答: I usually let them sketch a block diagram of the last system they've worked on, asking about the relations between the blocks and than let them elaborate on the block they were working/in charge on. You can learn many from this exercise, like how one looks beyond his small domain, how much is it important to him to know 'where' he is acting, also you can learn about the role he was playing, was it a key or side role.</p>


问:
Should I prefer properties with or without private fields?
The codebase I'm working in now has the convention of using private fields and public properties. For example, most classes have their members defined like this:

```<code>// Fields
private double _foo;
private double _bar;
private double _baz;

// Properties
public double Foo
{
    get{ return _foo; }
    set{ _foo = value; }
}

public double Bar
{
    get{ return _bar; }
    set{ _bar = value; }
}

public double Baz
{
    get{ return _baz; }
}
</code>```

I know these can be rewritten without their internal private properties:

```<code>public double Foo{ get; set; }
public double Bar{ get; set; }
public double Baz{ get; private set; }
</code>```

I'd like some input on this:

Is there a good reason to prefer the older, more explicit style over the
newer, more concise one?

Should I write any new classes using the
concise style, or should I try to match the older code for
consistency? Is consistency worth enough in this case to justify the older format?

答:
Even though the question is quite old I thought of adding couple of points which I read from a book worth mentioning here.

The run-time serialization engines persist the name of the filed in a serialized stream. The name of the backing field for an Automatically implemented property ( AIP )is determined by the compiler, and it could actually change the name of this backing field every time you recompile your code, negating the ability to deserialize instances of any types that contain an AIP. So do not use AIP with any type you intend to serialize or deserialize .

When debugging, you cannot put a breakpoint on an AIP get or set method, so you cannot easily detect when an application is getting or setting this property. You can set breakpoints on manually implemented breakpoints


问:
Does it always make sense to "program to an interface" in Java?
I've seen the discussion at this question regarding how a class that implements from an interface would be instantiated. In my case, I'm writing a very small program in Java that uses an instance of TreeMap, and according to everyone's opinion there, it should be instantiated like:

```<code>Map<X> map = new TreeMap<X>();
</code>```

In my program, I'm calling the function map.pollFirstEntry(), which is not declared in the Map interface (and a couple others who are present in the Map interface too). I've managed to do this by casting to a TreeMap<X> everywhere I call this method like:

```<code>someEntry = ((TreeMap<X>) map).pollFirstEntry();
</code>```

I understand the advantages of the initialization guidelines as described above for large programs, however for a very small program where this object would not be passed to other methods, I would think it is unnecessary. Still, I'm writing this sample code as part of a job application, and I don't want my code to look badly nor cluttered. What would be the most elegant solution?

EDIT: I would like to point out that I'm more interested in the broad good coding practices instead of the application of the specific function TreeMap. As some of the answers have already pointed out (and I've marked as answered the first one to do so), the higher abstraction level possible should be used, without losing functionality.

答:
"Programming to an interface" does not mean "use the most abstracted version possible". In that case everyone would just use Object.

What it means is that you should define your program against the lowest possible abstraction without losing functionality. If you require a TreeMap then you will need to define a contract using a TreeMap.

OwnerDisplayName: jimijazz

OwnerDisplayName: Jeroen Vannevel


答: Agreeing with the other answers that you should use the most generic class (or interface) of which you actually need something, in this case TreeMap (or like someone suggested NavigableMap). But I would like to add that this is most certainly better than casting to it everywhere, which would be a much bigger smell in any case. See https://stackoverflow.com/questions/4167304/why-should-casting-be-avoided for some reasons.</p>

Title: Does it always make sense to "program to an interface" in Java?

Body:
I've seen the discussion at this question regarding how a class that implements from an interface would be instantiated. In my case, I'm writing a very small program in Java that uses an instance of TreeMap, and according to everyone's opinion there, it should be instantiated like:

```<code>Map<X> map = new TreeMap<X>();
</code>```

In my program, I'm calling the function map.pollFirstEntry(), which is not declared in the Map interface (and a couple others who are present in the Map interface too). I've managed to do this by casting to a TreeMap<X> everywhere I call this method like:

```<code>someEntry = ((TreeMap<X>) map).pollFirstEntry();
</code>```

I understand the advantages of the initialization guidelines as described above for large programs, however for a very small program where this object would not be passed to other methods, I would think it is unnecessary. Still, I'm writing this sample code as part of a job application, and I don't want my code to look badly nor cluttered. What would be the most elegant solution?

EDIT: I would like to point out that I'm more interested in the broad good coding practices instead of the application of the specific function TreeMap. As some of the answers have already pointed out (and I've marked as answered the first one to do so), the higher abstraction level possible should be used, without losing functionality.

OwnerDisplayName: Sebastiaan van den Broek


答:
If you still want to use an interface you could use

```<code>NavigableMap <X, Y> map = new TreeMap<X, Y>();
</code>```

it is not necessary to always use an interface but there is often a point where you want to take a more general view that allows you to replace the implementation (perhaps for testing) and this is easy if all references to the object are abstracted as the interface type.

Body:
If you still want to use an interface you could use

NavigableMap <X, Y> map = new TreeMap<X, Y>();

it is not necessary to always use an interface but there is often a point where you want to take a more general view that allows you to replace the implementation (perhaps for testing) and this is easy if all references to the object are abstracted as the interface type.

OwnerDisplayName: redge


问:
Failover for High Frequency Jobs
I have a job that runs at a fairly high frequency (~1x every second).

This job needs to be executed constantly as long as the web app is running. However, I really only want 1 instance of the job running at a time.

Currently, I just fire up a thread that performs the job in the background, sleeping for ~800ms each loop. That causes a problem when I want redundancy, because the thread starts up as part of the app.

I know I can do something simple, like add a table in a database and have a "primary" and "secondary" server lock the record, track who's in charge, etc. But it seems a bit ugly, so I was curious if anyone had experience with a similar situation, and what solution you ended up using?

答:
Good Question,

I would move the task out to a seperate service. This gets around your link with the website but you'll still have to make the service redundant. You can go two ways with this.

1: services dont know about each other. If you can change the job so that no error occurs when it runs concurrently with itself this is the best solution as you can simply fire up 2 or more services and not worry.

2 the services know about each other. This is more complicated but worth it if the job is long running as it allows you to spread the load over workers. You can use a queue (msmq,zmq,rabbit) or a database table (mark jobs as in progress) to affect the communication

Title: Failover for High Frequency Jobs


答:
You could avoid the 2nd pass by calling erase as you delete the element.  You need to convert the index to an iterator and be sure you account for the fact that erasing items changes subsequent indexes</p>

```<code>int deleted = 0;
for (int i=0; i < Count; i++) {
    if (Selected[i]) {
        delete items[i];
        items.erase(items.begin()+i-deleted++);
    }
}
</code>```

Title: "Sweep" a vector of pointers

Body:
I'm using a vector to store pointers to objects. In some cases I destroy one or more of these objects (setting the vector spaces to NULL after each delete call), which are externally selected:

```<code>for (int i=0; i<form->SelectListBox->Items->Count; i++) {
    if (form->SelectListBox->Selected[i]) {
        delete items[i];
        items[i]=NULL;
    }
}
</code>```

After that, I have erase all NULL pointers. This is what I'm doing and it works:

```<code>ItemVector::iterator it;
while ((it=std::find(items.begin(), items.end(), (MyObjects*)NULL))!=items.end()) {
    items.erase(it);
}
</code>```

Is there a more idiomatic way to "sweep" a vector of pointers? [1]

[1] As you may have guessed, I'm using C++Builder (version 6) and its VCL and try to migrate from using TList to using std::vector as to reduce static casts (the class TList provides a Pack method.

Body:
You could avoid the 2nd pass by calling erase as you delete the element.  You need to convert the index to an iterator and be sure you account for the fact that erasing items changes subsequent indexes

int deleted = 0;
for (int i=0; i < Count; i++) {
    if (Selected[i]) {
        delete items[i];
        items.erase(items.begin()+i-deleted++);
    }
}


问:
Smallest and Largest contiguous repeating sub-sequence in a sequence
I am trying to solve a outdated quiz problem.

I am tasked to find the smallest and largest contiguous sequence of repeating numbers in a larger sequence.
e.g.

```<code>{1,3,6,17,19,3,6,5,4,2,5,6,17,19,3,6,7,5,78,100,101}
</code>```

For the sequence above, the smallest (non-zero element sequence) and largest non extensible sub sequence would be smallest - 3,6 and largest - 6,17,19,3,6

Could not get started with an algorithm. Any help to get me started would be much appreciated.

答:
You could use patterns … To find the longest repeating subsequence try this …

```<code>{1, 3, 6, 17, 19, 3, 6, 5, 4, 2, 5, 6, 17, 19, 3, 6, 7, 5, 78, 100,
  101} /. {___, Longest[y___], ___, Longest[y___], ___} :> y
</code>```

This returns Sequence[6,17,19,3,6]

To find the shortest non-trivial (i.e., length 2 or greater) repeating subsequence try this …

```<code>{1, 3, 6, 17, 19, 3, 6, 5, 4, 2, 5, 6, 17, 19, 3, 6, 7, 5, 78, 100,
  101} /. {___, Shortest[y___ /; Length[{y}] >= 2], ___,
   Shortest[y___], ___} :> y
</code>```

This returns Sequence[3,6]

Note: the answers are returned as Sequence objects. If, instead, you want *** lists *** returned change the final y that appears after the :> symbol to {y}.

I can express the same solution in more verbose terms as …

```<code>{1, 3, 6, 17, 19, 3, 6, 5, 4, 2, 5, 6, 17, 19, 3, 6, 7, 5, 78, 100,
  101} /. {BlankNullSequence[], Longest[y___], BlankNullSequence[],
   Longest[y___], BlankNullSequence[]} :> y

{1, 3, 6, 17, 19, 3, 6, 5, 4, 2, 5, 6, 17, 19, 3, 6, 7, 5, 78, 100,
  101} /. {BlankNullSequence[], Shortest[y___ /; Length[{y}] >= 2],
   BlankNullSequence[], Shortest[y___], BlankNullSequence[]} :> y
</code>```

Body:
You could use patterns … To find the longest repeating subsequence try this …

{1, 3, 6, 17, 19, 3, 6, 5, 4, 2, 5, 6, 17, 19, 3, 6, 7, 5, 78, 100,
  101} /. {___, Longest[y___], ___, Longest[y___], ___} :> y

This returns Sequence[6,17,19,3,6]

To find the shortest non-trivial (i.e., length 2 or greater) repeating subsequence try this …

{1, 3, 6, 17, 19, 3, 6, 5, 4, 2, 5, 6, 17, 19, 3, 6, 7, 5, 78, 100,
  101} /. {___, Shortest[y___ /; Length[{y}] >= 2], ___,
   Shortest[y___], ___} :> y

This returns Sequence[3,6]

Note: the answers are returned as Sequence objects. If, instead, you want *** lists *** returned change the final y that appears after the :> symbol to {y}.

I can express the same solution in more verbose terms as …

{1, 3, 6, 17, 19, 3, 6, 5, 4, 2, 5, 6, 17, 19, 3, 6, 7, 5, 78, 100,
  101} /. {BlankNullSequence[], Longest[y___], BlankNullSequence[],
   Longest[y___], BlankNullSequence[]} :> y

{1, 3, 6, 17, 19, 3, 6, 5, 4, 2, 5, 6, 17, 19, 3, 6, 7, 5, 78, 100,
  101} /. {BlankNullSequence[], Shortest[y___ /; Length[{y}] >= 2],
   BlankNullSequence[], Shortest[y___], BlankNullSequence[]} :> y


问:
What are the benefits of a device driver when I can access the I/O registers directly?
I was interested in what modern, C-based, Linux device driver development looked like, and so I took a good gander at this excellent article.

I didn't read every single line, but perused the majority of it, and my take away is this: writing device drivers for Linux seems like an incredibly painful process. Now that's my opinion, and I'm sure many Linux/C gurus out there would disagree, but there's one thing that I just can't wrap my head around here.

Every CPU/MCU exposes a C library that defines I/O registers, ports, etc. for accessing (both reads and writes) every single pin on the chip. On AVR controllers, for instance, there is <avr/io.h>. For ARM chips there is CMSIS.

So my question is this:

Why would I go to all the 'trouble' (more work) of following the guidelines in that article and building a proper device driver in Linux, when I could just write a C library that uses one of these processor-provided I/O registry accessors (again, avr/io.h, CMSIS, etc.) to access all the pins on the chip (which seems like less work)?

I'm sure there's a reason: I'm just not seeing it. What is gained by using a proper device driver? What is lost by not using one and just using one of these libs directly?

答:
The main answer is uniformity - if your device is a webcam, you can expose a C library and tell every application that to receive images from your cam, they can easily write to your custom API. I guarantee you will not have a working webcam in any application other than the ones you write!

That's typically why you abstract hardware behind a device driver - you say it yourself, you can access AVR chips via io.h, and ARM via CMSIS. If you write an application that works for AVR, it'll never work for ARM unless you have a big switch statement and an abstracting code anyway, and if someone uses your application with a different CPU, it just won't work at all.