问:
Manufacturing vs Software Development
It's often said that the software industry is immature compared to manufacturing. Specifically with regard to being process driven.

Question:
Can we as developers learn from the processes of the manufacturing industry? Can adopting their processes increase the success rate of software development?

My take:
In manufacturing the creation of a product is heavily process driven. You may have a factory where each person has a specific set of tasks they follow. A worker (or robot) may tighten a screw all day long. Then the next task in the process is performed by the next specialist. The workers (and robots) do not deter from the process or make something up "on the fly". The parts churn through the through the process, and the output is a finished product. It works well and companies achieve 99.99966% defect free products. Companies iron out inefficiencies over time. This is impressive and very well may be the sign of a mature industry.

In manufacturing a defined process can literally create the finished product. I don't think this is the case in software. We may have processes for source control, code review, check in sheets, requirements gathering, the SDLC, etc.  But executing those processes does not in and of itself create a finished product. These processes may be beneficial, but are orthogonal to the actual creation.

Suppose your company is contracted to create software that will search millions of images to find the faces of a criminals. Despite the heavy process driven environment, the developer must engage in creating things "on the fly". Doing things on the fly is against the spirit of manufacturing. A good manufacturing process can be executed without thought by a robot.

For the creation of complex algorithms which have yet to be fathomed in the mind of a human, it is a necessity to create things on the fly. Software development is not the following of a process, but the creation of a processes to be exucuted by a computer. That is a fundamental difference. No matter how many orthogonal processes we put up around development, we will always resort to doing it "on the fly" when it comes to creation.

Everyone I talk to seems to agree with the manufacturing mindset. Am I alone in my thoughts?

答:
If you wanted to write the same exact software over and over again (as opposed to simply copying it) you could do that very efficiently via an assembly line.

But software creation is not a repetative task, each module is uniqe. That is why the comparison to manufacturing is invalid.

Title: Manufacturing vs Software Development


问:
Finding all nearby points in a point cloud
What's the best way to store 3D point cloud data, optimising for time it takes to find all the points in a sphere of 3D space, and also for time it takes to insert new data points into the data set?

Background:

I have a cloud of 3D point data (with each point also including some further attached data), and need to be able to query it to quickly find all the points within a user-specified sphere of 3D space, as well as to quickly add points to the data set.

My current implementation uses a naive linear array of data points, but unsurprisingly, that's not scaling well as my data set grows.

My priority is speed, both for finding points in the cloud and for inserting new points into the cloud (I'd really like to avoid needing to rebalance trees after every insertion, if I can).  I never delete points from the data set, so speed for point removal isn't important at all.  Memory usage also isn't important -- I'm quite happy to throw memory at this problem, if it'll speed things up!

答:
Computer languages translate multi-diminsional arrays to single diminsional arrays so that elements can be addressed effectively. For example (assuming row-major, base is not important in your case, so assume it is zero):

A(0,0,0)  has address base+(single dim index=0)

A(0,0,1)  has address base+(single dim index=1)

A(0,0,2)  has address base+(single dim index=2)

A(1,0,0)  has address base+(single dim index=3)
...
The single dim index value can be calculated from the array x,y values above using a formula given in references below.

So given value like x, y, z you can calculate f(x,y,z)=single dim index.

You could use this method to store the data in a dictionary structure (or similar) where the key would be f(x,y,z).

Also, given f(x,y,z) as a value (say 3), you could calculate x,y,z to be 1,0,0.

The technique is simpler than devising a hashing function, requires no search and preserves order, so it may help you find other near by elements fast. I am not quite clear on your definition of a sphere, do you mean geometric sphere?

It is usually discussed in Data Structures books.

Here are some references:

Book-1

Pdf-1

StackOverFlow-Similar case

ContentLicense: CC BY-SA 3.0


答:
I think that the answer you are looking for is applicable or realistic here.  What I feel like you want to know is how can we set our processes up to be more like the manufacturing industry.  Instead I think the real question becomes "Knowing what manufacturing and other industries do to build quality products what can we learn?" or "What can the software industry do to improve quality?"

Unfortunately the answer to this is unclear because the software industry itself still does not know the answer.  In order to be able to answer this the software industry needs to do research on what works and why?  For example there have been studies that show that Test Drive Design (TDD) leads to an improvement in quality.  Although the question of productivity still seems to be unanswered or at least not completely understood yet.  As far as what the evidence shows so far:

Code reviews are excellent, and shown to find the most bugs, but the effectiveness of a review drops fairly sharply after the first hour of review.  Given that the average person can only read a few hundred lines of code an hour it suggests that developers should break changes up into smaller pieces.

The longer it takes to find a bug the more expensive (time and money) it will be to fix it.  So if a developer finds it while writing the code we say the cost is 1.  If a unittest finds it later the cost is 10, if EVT finds it the cost is 100 and so on.

There is some evidence that suggests the more complex the requirements are the more complex the solution is and the more complex the solution the more likely there will be bugs.

There is a man named Greg Wilson who gave an excellent talk about some of this a few years ago.   Here is a link to the talk: Greg Wilson Talk

In addition to this I would say look back on your own work and find the themes with the types of errors that you introduce as well as which parts you struggle with.  Compile these results and then create a checklist to insert into your process at difference places to help you do a better job.  Personally I have looked back at the past few years of my work and found that there are some common themes to the problems I introduce.  Specifically I have found that

I don't often remember to build all the variants leading to me breaking the build.

Many times I don't think about the following for each change.  The good case, the bad case and the exceptional cases.

All of the possible scenarios that might happen.  Note that this is really hard because there are a lot of them.

Since I have found some themes to my errors I have created checklists that I automatically use, due to inserting them into my scripts, that help me work around these issues.  There was a book written about this call the "Checklist Manifesto" which details how they can be put to good use. Personally I found it very insightful.

ContentLicense: CC BY-SA 4.0

Title: Manufacturing vs Software Development

Body:
It's often said that the software industry is immature compared to manufacturing. Specifically with regard to being process driven.

Question:
Can we as developers learn from the processes of the manufacturing industry? Can adopting their processes increase the success rate of software development?

My take:
In manufacturing the creation of a product is heavily process driven. You may have a factory where each person has a specific set of tasks they follow. A worker (or robot) may tighten a screw all day long. Then the next task in the process is performed by the next specialist. The workers (and robots) do not deter from the process or make something up "on the fly". The parts churn through the through the process, and the output is a finished product. It works well and companies achieve 99.99966% defect free products. Companies iron out inefficiencies over time. This is impressive and very well may be the sign of a mature industry.

In manufacturing a defined process can literally create the finished product. I don't think this is the case in software. We may have processes for source control, code review, check in sheets, requirements gathering, the SDLC, etc.  But executing those processes does not in and of itself create a finished product. These processes may be beneficial, but are orthogonal to the actual creation.

Suppose your company is contracted to create software that will search millions of images to find the faces of a criminals. Despite the heavy process driven environment, the developer must engage in creating things "on the fly". Doing things on the fly is against the spirit of manufacturing. A good manufacturing process can be executed without thought by a robot.

For the creation of complex algorithms which have yet to be fathomed in the mind of a human, it is a necessity to create things on the fly. Software development is not the following of a process, but the creation of a processes to be exucuted by a computer. That is a fundamental difference. No matter how many orthogonal processes we put up around development, we will always resort to doing it "on the fly" when it comes to creation.

Everyone I talk to seems to agree with the manufacturing mindset. Am I alone in my thoughts?


答:
Question: Can we as developers learn from the processes of the
  manufacturing industry? Can adopting their processes increase the
  success rate of software development?

Answer: Yes, of course. There are many lessons that software developers can learn from manufacturing despite the fact that software development is a creative process. Software development is itself a process, and it includes many other processes. The better you can define and control those processes, the better you can control the process of software development overall. That doesn't mean that you should prescribe every keystroke a developer makes; it just means that as a developer, you naturally perform tasks in a certain order, and those tasks can often be managed. Here are some examples:

defect tracking: When a bug is observed or reported, what happens to it? Do you write it down on a scrap of paper and stick it on an 'investigate' spike? Do you later remove those scraps one at a time, investigate them, and eventually move them to the 'resolved' spike? If you do that without fail every time you get a bug report, you've got a well-defined, measurable process, and you're probably much better off than someone who has a fancy, high-tech defect tracking system that's so onerous that some team members track bugs other ways, or not at all.

version control: There's a good chance that you use version control where you work, and version control is obviously a lot more useful when everyone uses it the same way.

product design: Do you decide which features to implement by throwing darts at a wall covered with post-it notes? If so, you've got a process. I don't think anyone would argue that it's a great process, but at least it's a starting point. If you change the process how can you know for certain that your change was actually an improvement unless you measure before and after? You can't.

code reviews: Would a code review be useful if the review process and coding criteria changed for each review? Of course not.

software development life cycle: The whole analysis -> design -> implementation -> test -> maintenance cycle is a process that should be defined clearly.

In each of these cases, having a process in place lets you measure inputs and outputs and determine whether changes you make have the intended effect. Not having processes in place means that you're just guessing when you try to improve the way you work. This is really what manufacturing is all about, and it only makes sense to borrow the successive refinement tools of manufacturing when they're appropriate.

There's an entire field devoted to defining and improving processes used to create and maintain software; it's called software engineering. It's no surprise that you have questions about the development process while reading about CMMI -- CMMI is a product of the Software Engineering Institute.

Software development has already adopted many manufacturing concepts:

It's hard not to see the influence of Eli Whitney's interchangeable parts on both OOP and component-based development.

Project management techniques used in software development aren't very different from those developed for manufacturing. As just two examples, the software world has only recently adopted the Kanban concept that was developed decades ago at Toyota, and Gantt charts were used in manufacturing long before the first electronic computer was built.

Quality management methodologies like Six Sigma that were developed for manufacturing have been adapted to software development.

Despite the heavy process driven environment, the developer must engage in
  creating things "on the fly".

Are you telling me that someone is going to decide on their own to add a patch to the facial recognition package, and they're going to add it into the production build without first creating an issue in the tracking system, having the design reviewed, checking the code into version control, or having the testing folks look at it first? Our process requires those things for some very good reasons. If by "on the fly" you mean "outside the process," that's unacceptable.

Doing things on the fly is against the spirit of manufacturing.

Again, if "on the fly" means "outside the process," you're right. But if you think that manufacturing doesn't require quick thinking and developing creative solutions to problems, you're wrong. All kinds of problems come up in the manufacturing process -- the cupcakes don't have enough cream filling, painted surfaces suddenly stop passing QA's scratch test, 20% of finished parts are missing an important retaining ring, the dough mixing system has broken a critical part...

Title: Manufacturing vs Software Development


答:
The fundamental difference between software development and manufacturing is that for software, the design phase is practically the entire thing. The actual production (assembly line part in traditional manufacturing) is a matter of copying a few files around. In software, the product design is the product.

So yes, we can learn from manufacturing processes, but only if we keep in mind that we have to look at the design phase, not the production phase, and that many manufacturing processes are built to cope with the specific limitations of an expensive production chain, which simply doesn't apply to software.

One example of a process model that works very well in software, but often fails horribly in product design, is iterative design - you start with a minimal prototype, and add features with each iteration. Building a prototype car to see what the new rear window knob design looks like is ridiculous, but in software, it makes sense (just hit F5 and wait a few seconds - voilà, ready to test drive).

If we do look at product design processes, the best industries to look at fall into two categories:

those where production can be realized at commodity rates; e.g. the record industry (1% or less of the price for a CD is baking and printing), graphical media, etc.

those where quantities are so low that the design phase is the most prominent cost factor (luxury articles, highly customized products, niche markets...)

It is a fundamental error to try and apply processes from physical manufacturing to software development: software development is not repetitive (if it is at your job, go find another job), it is only partially predictable, there are only very few physical limitations (hardware speed being one), and both the approach taken and the results can be highly personal. Applying assembly-line philosophies to what is basically a matter of analytic and creative thinking can (and often does) have devastating effects.

Title: Manufacturing vs Software Development


问:
Ordered enumeration: IEnumerable or Array (in C#)?
Typical context: I make an extension method for a collection which considers that the elements are ordered. The function starts at the beginning, at index 0, and the order has significance. Examples: Grouping by sequence or Indexes of an item.

However, I'm always stumped as to what to extend: IEnumerable<T> or T[]. My rationale was clarity of purpose: An array has a notion of ordering, whereas an IEnumerable is implemented by many generic collections, not all of which have a notion of order:

Dictionary - unordered

HashSet - unordered

LinkedList - ordered

List - ordered

Queue - ordered

SortedDictionary - sorted (not original order)

SortedList - sorted (not original order)

SortedSet - sorted (not original order)

Stack - reversed

As well as any other implementation which might or might not be ordered.

Also, I'm not certain if the enumerator is reset if an enumeration is not completed, so if that's a worry, then who knows at what point the enumeration would start? Enumerating an array would always start at the beginning.

So to me, it makes more sense to extend a T[]. But am I correct in thinking that? Am I worrying too much? What's the proper approach for ensuring "ordered" enumeration?

答:
I'm not certain if the enumerator is reset if an enumeration is not completed, so if that's a worry, then who knows at what point the enumeration would start? Enumerating an array would always start at the beginning.

These two sentences make me think that you have deep misunderstandings about how the enumerable pattern works. Can you explain why you think that an abandoned enumerator has anything whatsoever to do with a later enumeration?

An enumerable is a device which produces enumerators. If an enumerator is abandoned, that does not in any way affect the enumerable. If I sell books, and Bob buys a book and only reads it halfway, that doesn't mean that when I sell a different copy of the book to Alice, she has to start reading where Bob left off.

I'm always stumped as to what to extend: IEnumerable<T> or T[]. My rationale was clarity of purpose: An array has a notion of ordering, whereas an IEnumerable is implemented by many generic collections, not all of which have a notion of order:

Does your extension method need to (1) access the collection out of order? (2) write to the collection?

If so, then extend IList<T> If not, extend IEnumerable<T>.

What about: (3) pass the collection on to a method that expects an array?

Then extend array.

Your question is basically "I don't know whether to extend Animal or Giraffe". If your extension method is not specific to Giraffes, extend Animal. If your extension method is not specific to arrays, extend all lists. If it is not specific to lists, extend all sequences. If it is not specific to sequences, odds are good that an extension method is the wrong mechanism for you; I recommend against extending all objects.


答:
It's not about adopting "their" processes. It's about adopting "some" processes, that do not have the usual and well appreciated detriments of using assembly line processes for creative endeavours. The most important thing to note here is the idea that the quality of the processes translates directly to the quality of the product.

The best processes, or products for that matter, are the ones that fit the intended usage scenario like a hand in glove. The thing to think about is that actual code writing part is about the only one that is , atleast at a macroscopic level, not repetitive. All other facets, such as version control, bug tracking, planning, estimations, measurements etc. are, and use of a standard, tailored and proven process can help you at least in these areas.

So no, the software development process can not be likened to assembly line production and as such "their processes" are not OK, but the production design/product design phase of the product in a manufacturing industry can be the one to take inspiration from.

Title: Manufacturing vs Software Development


问:
How can a PHP programmer best prepare for a C++ course?
I have never programmed in C++, but am going to be taking a class that involves programming in C++ in January. I want to be able to excel in the class, and looking for advice, as I come from a PHP background. How can I best prepare myself for success?</p>

答: The best thing to do is to forget everything you know about PHP. It will only serve to hold you back in the C++ world. Many things which appear similar are in fact not similar at all, and it's best to just not try to apply your PHP knowledge.</p>


问:
Be liberal in what you accept... or not?
[Disclaimer: this question is subjective, but I would prefer getting answers backed by facts and/or reflexions]

I think everyone knows about the Robustness Principle, usually summed up by Postel's Law:

Be conservative in what you send; be liberal in what you accept.

I would agree that for the design of a widespread communication protocol this may make sense (with the goal of allowing easy extension), however I have always thought that its application to HTML / CSS was a total failure, each browser implementing its own silent tweak detection / behavior, making it near impossible to obtain a consistent rendering across multiple browsers.

I do notice though that there the RFC of the TCP protocol deems "Silent Failure" acceptable unless otherwise specified... which is an interesting behavior, to say the least.

There are other examples of the application of this principle throughout the software trade that regularly pop up because they have bitten developpers, from the top off my head:

Javascript semi-colon insertion

C (silent) builtin conversions (which would not be so bad if it did not truncated...)

and there are tools to help implement "smart" behavior:

name matching phonetic algorithms (Double Metaphone)

string distances algorithms (Levenshtein distance)

However I find that this approach, while it may be helpful when dealing with non-technical users or to help users in the process of error recovery, has some drawbacks when applied to the design of library/classes interface:

it is somewhat subjective whether the algorithm guesses "right", and thus it may go against the Principle of Least Astonishment

it makes the implementation more difficult, thus more chances to introduce bugs (violation of YAGNI ?)

it makes the behavior more susceptible to change, as any modification of the "guess" routine may break old programs, nearly excluding refactoring possibilities... from the start!

And this is what led me to the following question:

When designing an interface (library, class, message), do you lean toward the robustness principle or not ?

I myself tend to be quite strict, using extensive input validation on my interfaces, and I was wondering if I was perhaps too strict.

答:
You're right, the rule applies to protocols, and not programming. If you make a typo while programming, you'll get an error as soon as you compile (or run, if you're one of those dynamic types). There's nothing to be gained by letting the computer guess for you. Unlike the common folk, we are engineers and capable of saying exactly what me mean. ;)

So, when designing an API, I would say don't follow the Robustness Principle. If the developer makes a mistake, they should find out about it right away. Of course, if your API uses data from an outside source, like a file, you should be lenient. The user of your library should find out about his/her own mistakes, but not anyone else's.

As an aside, I would guess that "silent failure" is allowed in the TCP protocol because otherwise, if people were throwing malformed packets at you, you would be bombarded with error messages. That's simple DoS protection right there.

ContentLicense: CC BY-SA 2.5


问:
Where is the M in MVC?
I'm trying to refactor my application into MVC, but I'm stuck on the M part.

In a database-backed app, the model is implemented in the app code, right?

But then, what is in the database -- is that not also the model?

(I'm not using the database as a simple object store -- the data in the DB is an enterprise asset).

答:
The M(odel) in the MVC should capture the model of the business/domain in one single place.

That should ideally include business rules of the domain as well as it's structure.

The C(controller) sholuld ideally only concern itself with mediating the information of business model to the presentation (e.g. the View) and capturing user input from V(iew) to initiate changes in the state of the model.

Database layer only deals (or rather should only deal) with persistence of the state of the model at particular point in time.

As such it is not something that belongs to either Model or Controller part of the MVC pattern, but rather it is a completely separate concern which can be implemented implicitly by transparently persisting any change to the model (as a function of the facade, providing the interactions with your Model to the Controller) or as it's done more often than not, called explicitly by Controller after it has finished making mutations to the model.

Title: Where is the M in MVC?


问:
What's the term for "while(true)" loop with "break" inside?
Suppose I have a loop in C++ or C# that goes like this:

```<code>while( true ) {
    doSomething();
    if( condition() ) {
        break;
    }
    doSomethingElse();
}
</code>```

This is commonly called "infinite loop". Yet it is not technically infinite - it will stop once control flows through break.

What's the term for such loop - that has "loop forever" loop control statement and "break" inside?

答:
There is no standard term, but I would say it as Partial loop.

This loop is used when you want to break only after executing some part of the loop one last time (i.e. partial execution). It's used when you don't find a suitable situation where you may want to break the whole loop.

In this case, you want to break the loop after at least executing doSomething() one last time.


问:
Does it make sense to use a personal Amazon Cloud Drive to host an SVN repository?
I have 5GB of free storage on Amazon's Cloud Drive service that I'm not using, so I'm wondering: is it possible to create an SVN repository and be able to commit/update through TortoiseSVN?

I have an account at Assembla.com and use it for all my personal/school projects and love it, but Assembla has a 2GB limit.

答: If you can access this cloud drive as a regular system, yes you can. In addition to checking out repositories using https, svn+ssh etc., you can use file URLs.</p>


问:
Design Methodology for Developing Interoperable Systems?
A bit of background

The company I work for has been creating database applications since around 1980 and, until relatively recently, most of these systems have been stand-alone "silo" systems.

However, in the last few years, we've seen more of a shift towards gathering "intelligence" across all systems within our customers requirements.  For example, a system that might collect data about people's dental records may need to talk to a system that collects data about people's optician records, share information about the same person and provide search capabilities across both systems (makes sense, although the example I've used is fictional).

In the fictional example above, the dental and optician systems may or may not both be written by the company I work for (in other words we are looking at both internally-developed interfaces and interfaces to systems from third-party providers).

What we've done so far

We have a basic web-services API (.asmx) for one of our products, but I'm concerned about the change management, in terms of keeping it up-to-date as we add new features to the main product (in terms of providing the new features through the API without breaking compatibility with older interfaces).

We have also produced one WCF service.  The rigid contracts put my mind slightly more at ease than working with the ASMX service, but I think a lack of experience within the company is holding us back, so I'm looking for some guidance on best practice that I can read up on to help move us along (or at least point us in the right direction).

The question

Is there a particular methodology or programming practice for designing systems to maximise their ability to interface to other systems?

Are there any good online (or offline) resources for these programming practices (assuming they exist)?

Any other advice you can provide based on the information above would be appreciated, but not essential.

We primarily develop in Microsoft .NET (mainly ASP.NET, with some windows forms applications as well) with a SQL Server/Oracle database back-end, although I expect the programming practices might be language independent.  (I've used the .NET tag as an afterthought, but I might take it out later..!)

Thanks for your time.

答:
I would suggest designing a suite of example programs that interoperate with your system. Use the platforms most likely to be used to interact with you- say maybe a .NET suite, a Java suite, a PHP suite... considering which versions might be in use (i.e. if you provide a Java 5+ suite... are you sure there are not people stuck in 1.4 in your area?).

Maintain those suites, use them as test suites (you can use them to check for breaking changes), provide them freely to whomever wants to interact with your system.

If you give me a jar with classes which encapsulate communication to your system and examples of use, I'll be happy. Moreover, if someone has a problem you'll have less problems like "huh, we are using XFire for Soap, not Axis...".

And above all, communicate!


答:
The model in an ideal world should only contain business logic, it models some real object such as a House. However in nearly all circumstances the model needs to persist its data to some storage.

Interactions between the model and the stored data can either happen on a separate data layer or directly in the model, which is the case when using an ORM (Object Relational Mapper). In other words either the model connects directly to the database or its passes its data to some other "data access" object which connects to the database.

An ORM (Object Relation Mapper) maps fields in the database table to the attributes of your model object, providing getters and setters. In this case there is no separate data layer and the model is directly responsible for persisting its data.

Here is an a Ruby example using ActiveRecord a popular ORM:

```<code>class House < ActiveRecord::Base
end

house = House.new
house.price = 120000
house.save
</code>```

Price is a field in the houses table which is automatically detected by ActiveRecord which adds a getter and setter to the object. When save is called the value of the price attribute is persisted to the database.

From my point of view the pro of having a data layer is that you get a point in which you can manipulate the data before it gets to the model, the model has less it worry about, it has less responsibilities. For example you may need to combine data from several none compatible data sources, this is something an ORM can not easily handle.

The main con is its another layer of abstraction to manage, if you don't need it, don't bother, keep it simple. Less moving parts, less to go wrong.

Title: Where is the M in MVC?

Body:
I'm trying to refactor my application into MVC, but I'm stuck on the M part.

In a database-backed app, the model is implemented in the app code, right?

But then, what is in the database -- is that not also the model?

(I'm not using the database as a simple object store -- the data in the DB is an enterprise asset).

Body:
The model in an ideal world should only contain business logic, it models some real object such as a House. However in nearly all circumstances the model needs to persist its data to some storage.

Interactions between the model and the stored data can either happen on a separate data layer or directly in the model, which is the case when using an ORM (Object Relational Mapper). In other words either the model connects directly to the database or its passes its data to some other "data access" object which connects to the database.

An ORM (Object Relation Mapper) maps fields in the database table to the attributes of your model object, providing getters and setters. In this case there is no separate data layer and the model is directly responsible for persisting its data.

Here is an a Ruby example using ActiveRecord a popular ORM:

class House < ActiveRecord::Base
end

house = House.new
house.price = 120000
house.save

Price is a field in the houses table which is automatically detected by ActiveRecord which adds a getter and setter to the object. When save is called the value of the price attribute is persisted to the database.

From my point of view the pro of having a data layer is that you get a point in which you can manipulate the data before it gets to the model, the model has less it worry about, it has less responsibilities. For example you may need to combine data from several none compatible data sources, this is something an ORM can not easily handle.

The main con is its another layer of abstraction to manage, if you don't need it, don't bother, keep it simple. Less moving parts, less to go wrong.


问:
Algorithm for the shrinking of pixel art
This is something I've been wondering about for a while - are there any algorithms out there to scale pixel art down?

I'm sure we all know about the upscale versions on the Wikipedia page on Image Scaling.

I would have thought something like nearest neighbour resampling to get the colour pattern right, and then redrawing the outline, or high-contrast areas, over the top. Is there anything out there or am I going to have to learn how to do this myself?

Thanks!

答:
This process is known as "downscaling". There are many algorithms for this. Which is appropriate will depend on many factors, such as performance requirements and the nature of the images you are scaling.

See e.g. https://stackoverflow.com/questions/875856/interpolation-algorithms-when-downscaling for further information.

OwnerDisplayName: bonzairob


问:
What's the best way to handle multiple simultaneous "streams" of development in version control?
My department is planning on working on our next several releases (spanning a year) simultaneously.  The powers that be are advocating we support this by refactoring all affected code into classes like AbstractGizmo, R1Gizmo, R2Gizmo, etc and use configuration (via Spring and/or ANT) to control which classes are used in a particular release.  Ostensibly this is to save us the work of merging changes into multiple branches, especially when the changes are in the common code.  However, I see this as a clear cases for branching and merging in version control (TFS, in our case).

However, I have very little experience on projects that have active streams of development like this.  I'm sure others have (like Microsoft, with Windows XP, Vista, and 7).  What's the best way to handle multiple simultaneous "streams" of development in version control?  Do you branch and merge changes in version control, try to develop everything in one branch and use configuration or build scripts to assemble the different version, or something else?

P.S. We use TFS right now, but our version control strategy may not be constrained by it.  A coworker of mine is pushing to switch to Git or Mercurial, and it seems like he's getting a bit of traction.

答:
As pointed out in the other answers, this is the classical use case for branching & merging, so I'd also recommend to try this.

However, this is not the only solution. An alternative might be to use "feature flags":

Basically, any changes that are not supposed to be active (yet) are wrapped into an if block, so they can be switched on/off by configuration. Something like:if

```<code>($cfg.enable_unicorn_polo) {
    // do something new and amazing here.
}
else {
    // do the current boring stuff.
}
</code>```

This has advantages and disadvantages compared to the branching&mergin solution, but it's good to know about it.

This is apparently how Flickr does their development. Source:

http://code.flickr.com/blog/2009/12/02/flipping-out/

Body:
As pointed out in the other answers, this is the classical use case for branching & merging, so I'd also recommend to try this.

However, this is not the only solution. An alternative might be to use "feature flags":

Basically, any changes that are not supposed to be active (yet) are wrapped into an if block, so they can be switched on/off by configuration. Something like:if

($cfg.enable_unicorn_polo) {
    // do something new and amazing here.
}
else {
    // do the current boring stuff.
}

This has advantages and disadvantages compared to the branching&mergin solution, but it's good to know about it.

This is apparently how Flickr does their development. Source:

http://code.flickr.com/blog/2009/12/02/flipping-out/


答: Lacking an official name, I'd call it the Broken Loop. The ambiguity of this term is intended, since a break in the middle of a loop is a bit unclean, almost like a goto.

Title: What's the term for "while(true)" loop with "break" inside?

Body:
Suppose I have a loop in C++ or C# that goes like this:

```<code>while( true ) {
    doSomething();
    if( condition() ) {
        break;
    }
    doSomethingElse();
}
</code>```

This is commonly called "infinite loop". Yet it is not technically infinite - it will stop once control flows through break.

What's the term for such loop - that has "loop forever" loop control statement and "break" inside?


答:
There is no definitive name. Infinite loop is, I think, the appropriate term. No loops are truly infinite, but this has the potential to be effectively infinite since it's possible that the branch that contains the break will never occur.

If you tell someone "create an infinite loop, and use a break for condition X" and they'll know what you mean. If someone is reviewing your code and says nothing more than "I don't like the infinite loop you wrote" you'll know what they are talking about (unless you have more than one, of course).


答:
If Branching does not work, Consider Continous Integration on build-server like Cruise Control. Each build on the build server should run all unit and integration tests (and possibly other checks like database consistency, code coverage etc.). If a build is unsuccessful, the person/persons that checked in should immediately fix this -- no other tasks should outrank build fixing besides death or childbirht (consider delaying both, if a build is broken). Check-ins by others should not be allowed before the fix is checked in and verified. </p>

<p>Note: Branching AND continous integration could work side by side. </p>

Body:
My department is planning on working on our next several releases (spanning a year) simultaneously.  The powers that be are advocating we support this by refactoring all affected code into classes like AbstractGizmo, R1Gizmo, R2Gizmo, etc and use configuration (via Spring and/or ANT) to control which classes are used in a particular release.  Ostensibly this is to save us the work of merging changes into multiple branches, especially when the changes are in the common code.  However, I see this as a clear cases for branching and merging in version control (TFS, in our case).

However, I have very little experience on projects that have active streams of development like this.  I'm sure others have (like Microsoft, with Windows XP, Vista, and 7).  What's the best way to handle multiple simultaneous "streams" of development in version control?  Do you branch and merge changes in version control, try to develop everything in one branch and use configuration or build scripts to assemble the different version, or something else?

P.S. We use TFS right now, but our version control strategy may not be constrained by it.  A coworker of mine is pushing to switch to Git or Mercurial, and it seems like he's getting a bit of traction.

Body:
If Branching does not work, Consider Continous Integration on build-server like Cruise Control. Each build on the build server should run all unit and integration tests (and possibly other checks like database consistency, code coverage etc.). If a build is unsuccessful, the person/persons that checked in should immediately fix this -- no other tasks should outrank build fixing besides death or childbirht (consider delaying both, if a build is broken). Check-ins by others should not be allowed before the fix is checked in and verified.

Note: Branching AND continous integration could work side by side.


答:
While you can use Supersampling to downsize, you'll quickly notice that you receive "averaged grey stuff". Human perception is based on edge contrasts and patterns and exactly those are lost with naiive "averaging".

Perfect downsampling would need "semantic" knowledge of the object properties. In other words: which properties are important to "attenuate" in down-sampled image to preserve perception of the object. Artists do this intuitively!

Amongst lower-tech methods you could try: Lanczos filter or B-splines. These filters preserve some of the sharpness. But there are tons of other filters that may work depending on type and relative sizes of the features in your images.

Title: Algorithm for the shrinking of pixel art

Body:
This is something I've been wondering about for a while - are there any algorithms out there to scale pixel art down?

I'm sure we all know about the upscale versions on the Wikipedia page on Image Scaling.

I would have thought something like nearest neighbour resampling to get the colour pattern right, and then redrawing the outline, or high-contrast areas, over the top. Is there anything out there or am I going to have to learn how to do this myself?

Thanks!


答:
Amazon Cloud Drive is based on Amazon S3. The problem with S3 is that it's designed for hosting of media files. Only reading predetermined file  has speed anything close to decent, any other file operations (including listing directories and changing permissions) are extremely slow. </p>

<p>I'm afraid SVN hosted in such a way would be so slow, that it would be completely unusable. </p>

Title: Does it make sense to use a personal Amazon Cloud Drive to host an SVN repository?

Body:
I have 5GB of free storage on Amazon's Cloud Drive service that I'm not using, so I'm wondering: is it possible to create an SVN repository and be able to commit/update through TortoiseSVN?

I have an account at Assembla.com and use it for all my personal/school projects and love it, but Assembla has a 2GB limit.

Body:
Amazon Cloud Drive is based on Amazon S3. The problem with S3 is that it's designed for hosting of media files. Only reading predetermined file  has speed anything close to decent, any other file operations (including listing directories and changing permissions) are extremely slow.

I'm afraid SVN hosted in such a way would be so slow, that it would be completely unusable.


问:
How can Continuous Delivery work in practice?
Continuous Delivery sounds good, but my years of software development experience suggest that in practice it can't work.

(Edit: To make it clear, I always have lots of tests running automatically. My question  is about how to get the confidence to deliver on each checkin, which  I understand is the full form of CD. The alternative is not year-long cycles. It is iterations every week (which some might consider still CD if done correctly), two weeks, or month; including an old-fashioned QA at the end of each one, supplementing the automated tests.)

Full test coverage is impossible. You have to put in lots of time -- and time is money -- for every little thing. This is valuable, but the time could be spent  contributing to quality in other ways.

Some things are hard to test automatically. E.g. GUI. Even Selenium won't tell you  if your GUI is wonky. Database access is hard to test without bulky fixtures, and even that won't cover weird corner cases in your data storage. Likewise security and many other things. Only business-layer code is effectively unit-testable.

Even in the business layer, most code out there is not simple functions whose arguments and return values can be easily isolated for test purposes. You can spend lots of time building mock objects, which might not correspond to the real implementations.

Integration/functional tests supplement unit tests, but these take a lot of time to run because they usually involve reinitializing the entire system on each test. (If you don't reinitialize, the test environment is inconsistent.)

Refactoring or any other changes break lots of  tests. You spend lots of time fixing them. If it's a matter of validating meaningful spec changes, that's fine, but often tests break because of meaningless low-level implementation details, not stuff that really provides important information. Often the tweaking is focused on reworking the internals of the test, not on truly checking the functionality that is being tested.

Field reports on bugs cannot easily be matched with the precise micro-version of the code.

答:
First, CD takes one big mental adjustment -- you have to admit that sometimes things will go out broken no matter what you do. At the end of the day, you cannot prove a negative.

Once you get past this, you realize that you need tools and procedures to a) catch these errors very quickly and b) either roll back or deploy the update very efficiently. Moreover, if you are truly drinking the CD cocktail, you are really delivering lots of small, pointed changes that are easy to roll back and should not be able to introduce major, application-wide bugs. Even the guys really practicing CD are handling major changeovers in a more traditional manner.


问:
VB.Net vs C# debate
I've been in workplaces where, at the start of a project, the "Should we use VB.Net or C#" question has been raised.

Granted, it's probably less common to have to make that decision now than it was in the early days of .Net, particularly given the trend towards language convergence, but it can still be a heated debate.

So, between VB.Net and C#, Which language do you prefer and why?

答:
I've done a lot of work with VB.NET, but I understand enough C# to get the gist of what is happening in the code.  My current preference is VB.NET because I am most familiar with it (obviously), but I don't really have a preference between verbose BASIC syntax and C-style syntax, both are very readable and understandable to me.

Most of my coworker's programming background is COBOL and VB6, so VB.NET was the more comfortable .NET language choice for us as a team.  There wasn't a solid reason for us that made learning C# a requirement since they are functionally the same.

That said, learning C# is most definitely on my list of things to do.

Title: VB.Net vs C# debate


答:
2gb is a ton of code, what are you storing in there? Have you considered alternate SVN hosts? Or upgrading to something more modern like Mercurial on bitbucket (unlimited private repos, TortiseHg is arguably better than TortiseSVN).

I'm not sure if Amazon is even capable of what you want to store from a technical sense, but my general experience with SVN and local network shares was pretty poor. I suspect something in the cloud will be nearly impossible to use.


答:
What's the term for such loop - that has "loop forever" loop control
  statement and "break" inside?

Its an infinite loop with a break condition.

I would agree with ammilind in that if you wanted to give it a special name you could call it an Infinite Partial Loop


问:
Offline data that will need imported later
My existing application is a .NET 3.0 winform app that talks to a WCF service which in turn updates a MS SQL Server database; I can make changes at all spots (Windows client, WCF, server). I've had an inquiry into the possibility of allowing users to work offline and later sync their data back up. I have concerns about stale data mostly as the data is not "owned" by them and another user could have updated the same record while they were offline. I also use NHibernate for my ORM.

What are your thoughts as to the best implementation to add a sync feature?

答:
The actual logistics of this aren't too tricky (last-modified date on each record, and a "disconnected-since" or "last-synced" timestamp stored somewhere), the real issue is probably going to be your conflict resolution technique.  What should the system do when two people modify the same field in the same record?

I'd suggest logging all offline changes made to the database, then try to simply replay or apply those changes the next time the user syncs up.  That's probably more efficient than simply checking each table to see if it has any changes made since the last sync time.  You could also store both the old and new values for any fields that got changed.  This would help with conflict resolution, since you could still update any fields that still contained their old values, even if the last-modified date indicated that the record had been changed.


答: I'd vote for "unconditional loop", similar to "unconditional jump". It illustrates exactly what is going on (the code loops unconditionally), without lying (unlike "infinite loop").


答: It's a do-while loop with the conditional in the wrong place.</p>


答:
The change in reality is the timing window associated with updating the data. If the data can be updated by multiple users today; concurrency, locking at the DB level, etc... should already be in place. After that, the time at which a user holds on to the data before updating the database is somewhat irrelevant.

Unless you are going to offer a merging option, the sync should be trivial. DB wins or user wins, allow that choice to be made by the user.

Title: Offline data that will need imported later

Body:
My existing application is a .NET 3.0 winform app that talks to a WCF service which in turn updates a MS SQL Server database; I can make changes at all spots (Windows client, WCF, server). I've had an inquiry into the possibility of allowing users to work offline and later sync their data back up. I have concerns about stale data mostly as the data is not "owned" by them and another user could have updated the same record while they were offline. I also use NHibernate for my ORM.

What are your thoughts as to the best implementation to add a sync feature?


问:
Mobile applications in Delphi
Many of us know that Delphi executables are little bit gigantic, but again it is acceptable as nowadays 1.5 mb is not a big issue in PC.

But what about mobile devices? Currently Firemonkey supports iOS and in the near future it is going to Android and so on. Isn't 4 mb of executable size for mobile devices is too much for a simple application?

Will Delphi team try to reduce the size of executable in the future OR is it possible to do without loosing most of the features in Firemonkey?

答:
It depends on the device.

Personally I think that 4MB is not a big deal for either Android or iOS.  These devices have several GB of storage, with capacity to handle much more.  And, they have high speed data connections even over a cellular network.

I've downloaded apps (mostly games) for both platforms that are 30 MB and didn't give it a second thought.

Title: Mobile applications in Delphi


问:
Chromebook - is it interesting for Programmers?
Google announced the chromebook yesterday (11 May 2011). While this is surely a nice thing, I have no clue whether it was interesting to buy one for a (non-javascript)-programmer.

What do you think? Will there be, for instance, a Java IDE in the cloud? A command line, even?

答:
What if I want to develop a transcoding utility. To transcode video files (say like FFmpeg).
I could not do that on ChromeBook itself. Because it has no IDE for C++?
And if I have a 4GB file on my USB stick ready to be transcoded, and the transcoder itself is on a server. Then I would first have to sit and wait for the transfer of the 4GB video file to the server is completed. Before I could start testing my transcode utility.

And then again, a different file, a new test for transcoding.
The idea is good, but I do not think for high-end users/programmers.
Will you be able to run something like Adobe Premiere Pro, Avid Media Composer, Final Cut Pro?

Premiere Pro and Avid need good video cards in order to work. No way one would be able to shuttle a 220 mbps movieclip over any vnc/remote desktop client smoothly.

Just some of my concerns.


问:
Is Silverlight suitable for an enterprise class web-based product UI?
Our team is currently working on building our next generation HIS (Hospital Information System) comprising of over 30 modules (currently estimated at 400 man months), to be possibly hosted in a central location and accessed across geographies.  Hence the primary UI NFRs (Non Functional Requirements) would be

Multi browser compatibility

Fast loading pages with rich GUI

Ability to integrate with hardware devices like biometric scanners, biometric readers etc.

Ease of development, maintenance (incorporating changes), shorter development cycle

Ability to open multiple forms within the same browser window (without launching additional windows)

Pros:

UI would be browser agnostic, we do not have to worry about ensuring that our web pages work with IE 7, 8, 9++/ Chrome 8, 9, 18++/ Mozilla Firefox (currently a lot of development effort goes into this compatibility check and fixing)

We could possibly make our application more modular, unlike a monolithic ASP.Net application

Usage of isolated storage on the client PC

Cons:

Silverlight memory leak issues.  We faced them in a few samples that we built using SL and have the same problem in a legacy XBAP application.  The following links, substantiate the fear
http://davybrion.com/blog/2010/08/silverlight-getting-worse-when-it-comes-to-memory-leaks/
https://stackoverflow.com/questions/5091636/silverlight-4-memory-leaks

Microsoft does not appear very gung ho about SL future.  They seem to be investing more on HTML 5.  The future releases of a SL 5 or 6 is also uncertain.
http://support.microsoft.com/gp/lifean45
http://www.zdnet.com/blog/microsoft/microsoft-our-strategy-with-silverlight-has-shifted/7834
http://www.zdnet.com/blog/microsoft/will-there-be-a-silverlight-6-and-does-it-matter/11180

The HIS modules would open as multiple tabs within the same browser window  (we are talking about a maximum of 8 tabs open simultaneously).  How much of a load would it put on that browser instance and how would that effect the memory leak problem?

Learning curve for ASP.Net developers

Another Stack link on SL
https://stackoverflow.com/questions/251718/silverlight-wpf-web-app-xbap-or-click-once-pros-and-cons

Neutral

SEO compatibility is not a concern

My queries are?

Would you use SL, knowing the above (and other) Pros and Cons

In case we use the MVVM pattern to build a product with SL as the front end, would it possible to replace the UI tomorrow with another UI (ASP.Net or something else).   My understanding is that the rework would be substantial.  What does the community think?

We have spent a considerable time in the above analysis (and in creating proof of concepts).  Is there an important fact / decisive factor that we are overlooking?

Please do not mark this as a duplicate, as a lot of research and effort has gone into this exercise.

PS:  We have spent the past 6 months in building the product using ASP.Net web forms (using MVP pattern) and now are looking at a technology shift due to the above reasons.

答:
If JS doesn't concern you, I'd go Html5 + JS all the way. No external plugin required, old IE can be made to reason with Html5 through JS, and it will work on mobile devices too.

SL like Flash requires a plugin, won't work on mobile devices, etc.

If you like the MVVM pattern you can marry Html5 with Knockout.js, a JS library that uses the MVVM pattern, I already used it in a couple of projects and it's amazing.

So to answer, stay clear of SL or Flash if you want something as compatible and as fast as possible.

OwnerDisplayName: Tushax

OwnerDisplayName: Matteo Mosca


答:
Ability to integrate with hardware devices like biometric scanners,
  biometric readers etc.

This one can be hard, and will require OutOfBrowser mode for Silverlight, you will have to use COM for this to work, and this will ruin you cross browser requirement. COM only works in Internet Explorer.

IMHO the most difficult requirement for WEB application is working with external devices. Usually they come with C, C++ libraries to work with them, and you need a way to interop in C, C++.

I don't think these requirements can be satisfied by any WEB technology, only if Java applets, but I don't know about java applets interop capabilities. In any way I would think about Java, either applet, or desktop application, depending in ability to work with hardware.

Title: Is Silverlight suitable for an enterprise class web-based product UI?

Body:
Our team is currently working on building our next generation HIS (Hospital Information System) comprising of over 30 modules (currently estimated at 400 man months), to be possibly hosted in a central location and accessed across geographies.  Hence the primary UI NFRs (Non Functional Requirements) would be

Multi browser compatibility

Fast loading pages with rich GUI

Ability to integrate with hardware devices like biometric scanners, biometric readers etc.

Ease of development, maintenance (incorporating changes), shorter development cycle

Ability to open multiple forms within the same browser window (without launching additional windows)

Pros:

UI would be browser agnostic, we do not have to worry about ensuring that our web pages work with IE 7, 8, 9++/ Chrome 8, 9, 18++/ Mozilla Firefox (currently a lot of development effort goes into this compatibility check and fixing)

We could possibly make our application more modular, unlike a monolithic ASP.Net application

Usage of isolated storage on the client PC

Cons:

Silverlight memory leak issues.  We faced them in a few samples that we built using SL and have the same problem in a legacy XBAP application.  The following links, substantiate the fear
http://davybrion.com/blog/2010/08/silverlight-getting-worse-when-it-comes-to-memory-leaks/
https://stackoverflow.com/questions/5091636/silverlight-4-memory-leaks

Microsoft does not appear very gung ho about SL future.  They seem to be investing more on HTML 5.  The future releases of a SL 5 or 6 is also uncertain.
http://support.microsoft.com/gp/lifean45
http://www.zdnet.com/blog/microsoft/microsoft-our-strategy-with-silverlight-has-shifted/7834
http://www.zdnet.com/blog/microsoft/will-there-be-a-silverlight-6-and-does-it-matter/11180

The HIS modules would open as multiple tabs within the same browser window  (we are talking about a maximum of 8 tabs open simultaneously).  How much of a load would it put on that browser instance and how would that effect the memory leak problem?

Learning curve for ASP.Net developers

Another Stack link on SL
https://stackoverflow.com/questions/251718/silverlight-wpf-web-app-xbap-or-click-once-pros-and-cons

Neutral

SEO compatibility is not a concern

My queries are?

Would you use SL, knowing the above (and other) Pros and Cons

In case we use the MVVM pattern to build a product with SL as the front end, would it possible to replace the UI tomorrow with another UI (ASP.Net or something else).   My understanding is that the rework would be substantial.  What does the community think?

We have spent a considerable time in the above analysis (and in creating proof of concepts).  Is there an important fact / decisive factor that we are overlooking?

Please do not mark this as a duplicate, as a lot of research and effort has gone into this exercise.

PS:  We have spent the past 6 months in building the product using ASP.Net web forms (using MVP pattern) and now are looking at a technology shift due to the above reasons.

OwnerDisplayName: Alex Burtsev


答:
We have actualy this problem. We start developpement on Silverligth. It's a prety technology, but it's probably give up by Microsoft. So we change to develop on ASP.NET MVC.

So :

Probably does'nt work in Windows 8 metro. Not work on other OS.

It's very difficult to change Pattern MVVM to another technology. For our case, change to MVC with HTML 5 change all the code.

...

I hope that can be help you.

OwnerDisplayName: Cedric


答:
To answer a couple of your questions:

The HIS modules would open as multiple tabs within the same browser window (we are talking about a maximum of 8 tabs open simultaneously). How much of a load would it put on that browser instance and how would that effect the memory leak problem?

Why do you need to open 8 tabs simultaneously? With Silverlight you could have a single application tab and all the controls/pages etc tabbed within that. This would put no greater strain on the browser instance and not make the memory leak issue worse.

In case we use the MVVM pattern to build a product with SL as the front end, would it possible to replace the UI tomorrow with another UI (ASP.Net or something else). My understanding is that the rework would be substantial. What does the community think?

Virtually any technology you choose now will give you the same headaches if you try to replace the UI. Unless you can totally divorce the application logic from the UI there will be major reworking involved. The least pain would be had if you were to convert it to a WPF application.

However, this statement:

Ability to integrate with hardware devices like biometric scanners, biometric readers etc.

leads me to think that using any web based technology is going to cause you problems in this area. Here I agree with Alex - a better bet might be to write a native application. Using Java will give you some interoperability across multiple platforms, but at the cost of not using native UI elements.


问:
Does simplicity always improve Readability?
Recently, I was developing a set of coding standards for our company.  (We're a new team branching out into a new language for the company.)

On my first draft, I set the purpose of our coding standards as improving Readability, Maintainability, Reliability, and Performance.  (I ignored writability, portability, cost, compatibility with previous standards, etc.)

One of my goals while writing this document was to push through the idea of simplicity of code. The idea was that there should be only one function call or operation per line.  My hope was that this would increase readability.  It's an idea that I carried over from our previous language.

However, I've questioned the assumption behind this push:

Does simplicity always improve readability?

Is there a case where writing simpler code decreases readability?

It should be obvious, but by "simpler", I don't mean "easier to write", but less stuff going on per line.

答:
You're all missing some fundamental definitions. Simple, from the root sim-plex, means one fold. Simple means doing one thing. Easy, from the root ease, means lie near. Easy means that it is close at hand. The examples of simple code given in other answers aren't exactly what they appear.

Take rotsor's display of a very large value. He says this is simple. Is not, in my estimation, simple. It's easy. It's close at hand to type the number of required 0s.

```<code>10000000000000000000000000000000000000000000
</code>```

The readable version is simple. It does one thing. It expresses the number by describing its size in a notation purpose built for this function.

```<code>1e43
</code>```

Could you describe Aidan's "simple" code snippet as doing one thing? It contains 10 lines of code (not counting comments) and at least 7 blocks (as I'd count them). If you follow the comments, you'd see that it does at least 4 things!

```<code>count :: [Integer] -> [[Integer]]
count [] = [[]]
count (x:xs) =
  -- get all possible sequences for the remaining digits
  let
    remDigits :: [[Integer]]
    remDigits = count xs
  in
  -- pull out a possible sequence for the remaining digits
  do nextDigits <- remDigits
     -- pull out all possible values for the current digit
     y <- [0..x]
     -- record that "current digit" : "remaining digits" is
     -- a valid output.
     return (y:nextDigits)
</code>```

But, one of the recommendations for rewriting this code was one statement. Aidan does state that a reader would have to be or become familiar with monadic statements, pointer free code, etc. That's fine. Those concepts are singular and independent to learn.

```<code>count = mapM (enumFromTo 0)
</code>```

You'll find that truly simple code is more readable than easy code because it does only one thing. You may need to go off and learn more "one things" to understand the simple code. But it should always be more readable.

Body:
You're all missing some fundamental definitions. Simple, from the root sim-plex, means one fold. Simple means doing one thing. Easy, from the root ease, means lie near. Easy means that it is close at hand. The examples of simple code given in other answers aren't exactly what they appear.

Take rotsor's display of a very large value. He says this is simple. Is not, in my estimation, simple. It's easy. It's close at hand to type the number of required 0s.

10000000000000000000000000000000000000000000

The readable version is simple. It does one thing. It expresses the number by describing its size in a notation purpose built for this function.

1e43

Could you describe Aidan's "simple" code snippet as doing one thing? It contains 10 lines of code (not counting comments) and at least 7 blocks (as I'd count them). If you follow the comments, you'd see that it does at least 4 things!

count :: [Integer] -> [[Integer]]
count [] = [[]]
count (x:xs) =
  -- get all possible sequences for the remaining digits
  let
    remDigits :: [[Integer]]
    remDigits = count xs
  in
  -- pull out a possible sequence for the remaining digits
  do nextDigits <- remDigits
     -- pull out all possible values for the current digit
     y <- [0..x]
     -- record that "current digit" : "remaining digits" is
     -- a valid output.
     return (y:nextDigits)

But, one of the recommendations for rewriting this code was one statement. Aidan does state that a reader would have to be or become familiar with monadic statements, pointer free code, etc. That's fine. Those concepts are singular and independent to learn.

count = mapM (enumFromTo 0)

You'll find that truly simple code is more readable than easy code because it does only one thing. You may need to go off and learn more "one things" to understand the simple code. But it should always be more readable.


答:
Full test coverage is impossible. You have to put in lots of time -- and
  time is money -- for every little thing. This is valuable, but the time could
  be spent contributing to quality in other ways.

You don't need 100% coverage, you need enough to be confident in your system, that changes to one place won't break things you've previously proven work.

Some things are hard to test automatically. E.g. GUI. Even Selenium won't

  tell you if your GUI is wonky. Database access is hard to test without bulky
  fixtures, and even that won't cover weird corner cases in your data storage.

Database access is trivial to write however.  You shouldn't need many tests on your data layer as it's just getting and setting data.  The most important thing is ensuring that when it fails, it rollsback and logs the issue so you can fix it.

Likewise security and many other things. Only business-layer code is effectively
  unit-testable.   Even in the business layer, most code out there is not simple
  functions whose arguments and return values can be easily isolated for
  test purposes.

Then many of your functions/classes are too large.  They should be written to be testable.

You can spend lots of time building mock objects, which
  might not correspond to the real implementations.

The I/O of the mock object should match what is expected however.  What happens inside it unimportant.

Integration/functional tests supplement unit tests, but these take a lot of
  time to run because they usually involve reinitializing the
  entire system on each test. (If you don't reinitialize, the test
  environment is inconsistent.)

These shouldn't be run all the time.  Just as needed.

Refactoring or any other changes break lots of tests. You spend lots of time
  fixing them. If it's a matter of validating meaningful
  spec changes, that's fine, but often tests break because of
  meaningless low-level implementation details, not stuff that really
  provides important information. Often the tweaking is focused on
  reworking the internals of the test, not on truly checking the
  functionality that is being tested.

Then your code is too tightly coupled, and your tests are poorly written.

Field reports on bugs cannot easily be matched with the precise micro-version
  of the code.

Not sure what you're getting at here?  If there's a bug, write a test to show it's existence, then fix it.

Title: How can Continuous Delivery work in practice?

Body:
Continuous Delivery sounds good, but my years of software development experience suggest that in practice it can't work.

(Edit: To make it clear, I always have lots of tests running automatically. My question  is about how to get the confidence to deliver on each checkin, which  I understand is the full form of CD. The alternative is not year-long cycles. It is iterations every week (which some might consider still CD if done correctly), two weeks, or month; including an old-fashioned QA at the end of each one, supplementing the automated tests.)

Full test coverage is impossible. You have to put in lots of time -- and time is money -- for every little thing. This is valuable, but the time could be spent  contributing to quality in other ways.

Some things are hard to test automatically. E.g. GUI. Even Selenium won't tell you  if your GUI is wonky. Database access is hard to test without bulky fixtures, and even that won't cover weird corner cases in your data storage. Likewise security and many other things. Only business-layer code is effectively unit-testable.

Even in the business layer, most code out there is not simple functions whose arguments and return values can be easily isolated for test purposes. You can spend lots of time building mock objects, which might not correspond to the real implementations.

Integration/functional tests supplement unit tests, but these take a lot of time to run because they usually involve reinitializing the entire system on each test. (If you don't reinitialize, the test environment is inconsistent.)

Refactoring or any other changes break lots of  tests. You spend lots of time fixing them. If it's a matter of validating meaningful spec changes, that's fine, but often tests break because of meaningless low-level implementation details, not stuff that really provides important information. Often the tweaking is focused on reworking the internals of the test, not on truly checking the functionality that is being tested.

Field reports on bugs cannot easily be matched with the precise micro-version of the code.


答: Works fine for us, but our customers are mostly internal.  Multiple builds done during the day, broken builds are not tolerated, web start mechanism used so users get the latest version every launch.  One thing is that CD makes a lot of problems go away.  Yes, you have compatibility concerns all the time, however, since you're only deploying small changes each time, the concerns are really easy to get a handle on.  Stress level of CD is MUCH lower than when we made big updates and had to hope that everything was just right since there'd be so much code to review in the case of a breakage.</p>


问:
Users and roles: Where to put queryUsersWithRole()?
I have two model classes User and Role and two managers/DAOs (UserManager and RoleManager) plus a method which gives me all users with a certain role (List<User> getUsersWithRole(Role)).

In which manager does this method belong and why?

答:
Since you are expecting a list of Users from the getUsersWithRole(Role) method it belongs in the UserManager.

You a making a query for Users (which are handled by UserManager), just with a filter on their Role.


答:
My two cents-

Data Types: PHP is a dynamically typed language, while C++ is statically typed. So, you have to mention and keep track of data type explicitly everywhere.

Declaration: You have to declare a variable with it's type before using.

Array: The concept of an array is very much different in C++ compared to PHP. In C++, only numbers can be used as array indices. Like other variables, the array has to be declared with specific size which cannot be changed later. The index is 0-based.

String Handling: In C++(and C), strings are related with arrays and are manipulated differently.

Pay attention to C++ specific OO features, some C features like pointers and it's libraries. Good luck.

Title: How can a PHP programmer best prepare for a C++ course?

Body: I have never programmed in C++, but am going to be taking a class that involves programming in C++ in January. I want to be able to excel in the class, and looking for advice, as I come from a PHP background. How can I best prepare myself for success?</p>


答:
I guess if we are going to try to make up a term for this, maybe:

Escapable Loop


答:
Studying CS, this professor taught us that there are pre-checking loops (while(cond) {}), post-checking loops (do {} while(cond);), and middle-checking loops. (I might have badly translated this into English, but you get the idea.)

C and C++ do not have the latter (ISTR Ada having it, BICBW), so your construct is used for that in C and C++.


问:
Why is it impossible to produce truly random numbers?
I was trying to solve a hobby problem that required generating a million random numbers. But I quickly realized, it is becoming difficult to make them unique. I picked up Algorithm Design Manual to read about random number generation.

It has the following paragraph that I am fully not able to understand.

Unfortunately, generating random numbers looks a lot easier than it really is. Indeed, it is fundamentally impossible to produce truly random numbers on any deterministic device. Von Neumann [Neu63] said it best: “Anyone who considers arithmetical methods of producing random digits is, of course, in a state of sin.” The best we can hope for are pseudo-random numbers, a stream of numbers that appear as if they were generated randomly.

Why is it impossible to produce truly random numbers in any deterministic device? What does this sentence mean?

答:
Because You need to write code to generates the random numbers and Code is NOT random. (It's deterministic)

So you wind up starting with a "Seed value(s)" that is picked at "Random" (usually the current time stamp) then use it in an algorithm to start generating numbers. But the entire set of is based off the original Seed value!

So if you run your code again with the exact same Seed value(s), you will get the EXACT same SET of numbers! How can any reasonably person call that random? But it sure does LOOK random.

Regarding making them unique, After generating a number simply check if you already have that number, if you do, throw it away and generate a new one.


答:
One function call per line is simpler? Let's try an example!

```<code>=== One call per line ===
x = y.getThis()
a = x.getThat()
b = a.getSomethingElse()

=== Less "simple" version ===
b = y.getThis().getThat().getSomethingElse()
</code>```

What do you think? Is one call per line actually simpler?

Title: Does simplicity always improve Readability?

Body:
Recently, I was developing a set of coding standards for our company.  (We're a new team branching out into a new language for the company.)

On my first draft, I set the purpose of our coding standards as improving Readability, Maintainability, Reliability, and Performance.  (I ignored writability, portability, cost, compatibility with previous standards, etc.)

One of my goals while writing this document was to push through the idea of simplicity of code. The idea was that there should be only one function call or operation per line.  My hope was that this would increase readability.  It's an idea that I carried over from our previous language.

However, I've questioned the assumption behind this push:

Does simplicity always improve readability?

Is there a case where writing simpler code decreases readability?

It should be obvious, but by "simpler", I don't mean "easier to write", but less stuff going on per line.

Body:
One function call per line is simpler? Let's try an example!

=== One call per line ===
x = y.getThis()
a = x.getThat()
b = a.getSomethingElse()

=== Less "simple" version ===
b = y.getThis().getThat().getSomethingElse()

What do you think? Is one call per line actually simpler?


答: Since you are generating random numbers, you should expect the generated values to be non-unique. This is a property of randomness - you can't say a sequence of truly random (or even pseudo-random) numbers is unique, because that requirement would allow the final value in the range to be predicted, as well as changing the probability of all the unchosen numbers each time a new one is selected.</p>

Title: Why is it impossible to produce truly random numbers?

Body:
I was trying to solve a hobby problem that required generating a million random numbers. But I quickly realized, it is becoming difficult to make them unique. I picked up Algorithm Design Manual to read about random number generation.

It has the following paragraph that I am fully not able to understand.

Unfortunately, generating random numbers looks a lot easier than it really is. Indeed, it is fundamentally impossible to produce truly random numbers on any deterministic device. Von Neumann [Neu63] said it best: “Anyone who considers arithmetical methods of producing random digits is, of course, in a state of sin.” The best we can hope for are pseudo-random numbers, a stream of numbers that appear as if they were generated randomly.

Why is it impossible to produce truly random numbers in any deterministic device? What does this sentence mean?


答:
One should look for a cryptographically secure pseudo-random number generator. Most PRNG are linear congruence generators (so next number is a linear function of previous number), so if you plot next number vs previous number you'll get a chart of parallel lines. A CSPRNG will not do that. The trade-off is that they're slow.

I group random number generators into 3 categories:

Good enough for homework.

Good enough to bet your company on.

Good enough to bet your country on.

Why is it impossible to produce truly random numbers in any deterministic device ?

A deterministic device will always produce the same output when given the same starting conditions and inputs - that is what it means to be deterministic. "Truly random number" is more of a philosophical viewpoint, as what does it mean to be random is the crux of the philosophical navel gazing (folks aren't even certain if atomic decay is random or follows some pattern we just can't figure out yet). A cryptographically secure random number generator is going to take some external source of entropy to make the device non-deterministic.


答:
The second chapter of the book Discrete-Event Simulation: A First Course by Lawrence Leemis gives a fantastic introduction to random number generators (or more accurately, psuedo-random number generators).

An excerpt from his book explains it well in my opinion:

Historically three types of random number generators have been
  advocated for computational applications: (a) 1950's-style table
  look-up generators like, for example, the RAND corporation table of a
  million random digits; (b) hardware generators like, for example,
  thermal "white noise" devices; and (c) algorithmic (software)
  generators. Of these three types, only algorithmic generators have
  achieved widespread acceptance. The reason for this is that only
  algorithmic generators have the potential to satisfy all of the
  following generally well-accepted random number generation criteria. A
  generator should be:

random - able to produce output that passes all reasonable statistical tests of randomness;

controllable - able to reproduce its output, if desired;

portable - able to produce the same output on a wide variety of computer systems;

efficient - fast, with minimal computer resource requirements;

documented - theoretically analyzed and extensively tested.

So while it could be possible to use a white-noise generator to get "better" random numbers, they have not gained acceptance because they do not follow most of the criteria above.

I would recommend that you get your hands on a copy of that book (or on something similar). Understanding exactly how PRNG's work will definitely assist you in your efforts.


问:
Are JavaScript MVC Frameworks only for 'single-page' apps?
I've been looking into several of the JavaScript MVC Frameworks (Backbone.js, Spine, SproutCore,etc.) and it seems to me that all of these are designed to act as 'single-page' applications. All of the examples I see have an index page that act as a front controller, and use # or #! style URLs for different pages, and handle the entire rendering of the page.

I have several projects where I would like to use a more 'traditional' style of URLs, and having more structured JavaScript to handle some of the more complicated parts of the application. are JS MVC frameworks the answer here, or should I be looking for something different?

答:
JavaScript MVC is just a code organization pattern.

They happen to work well with SPA but they can be used in normal applications.

However you don't actually need a JS MVC framework. You can just write modular JavaScript using some kind module loading strategy.

As long as you separate modules into separate objects / functions / units the code should be structured and clean.


问:
How do I find test users for my Chrome extension with Google App Engine back end?
I am new to developing Chrome extensions and I used Stack Overflow to ask many questions and got great answers. I finally finished a beta version and uploaded it to Chrome store only for test users. Now I am not sure where to find test users so I decided to ask here. Is there a separate forum where people post their apps or extensions for review?</p>

答:
Where you find testers is a case by case kind of issue.

If your extension solves a very specific problem then I would recommend finding the group that would be the most excited about your solution. Offering limited invites to that group. The group will give good feedback from their desire to get a fully working product.

A different solution is to pay for people to test your application using a service like Amazon Mechanical Turk. This would allow you to incentives your workers and get results fast.

The last obvious solution would be to just release the software as beta to the public and get feedback from them. This is very common for home grown software as it gives you the opportunity for many people to look at the extension.


答:
I call it what it is, a "while true loop."

Also see is while(true) bad programming practice?


答:
True randomness implies nondeterminism. If it's deterministic, it can be accurately predicted (this is what determinism means); if it can be predicted, it is not random.

The best thing you can get from a deterministic pseudo-random number generator is a stream of numbers that has a very long cycle (non-repeating is impossible unless your RNG device has unlimited storage) which, for the length of the cycle, produces a stream numbers that meets all the other properties of a random sequence (a uniform distribution of values being the most interesting one).

To solve this issue, many modern UNIXes and Unix-likes have kernel RNG's that use physical noise sources to generate true randomness.

Another common approach is to take the current time as the seed for a deterministic RNG (srand(time(NULL)); in C); cryptographically speaking, this is worthless, since the current time is no secret, but for things like physical simulations or video games, it is good enough.


问:
FP and OO orthogonal?
I have heard this time and again and I am trying to understand and validate the idea that FP and OO are orthogonal.

First of all, what does it mean for 2 concepts to be orthogonal ?

FP encourages immutability and purity as much as possible.
and OO seems like something that is built for state and mutation(a slightly  organized version of imperative programming?). And I do realize that objects can be immutable. But OO seems to imply state/change to me.

They seem like opposites. Does that meant they are orthogonal ?

A language like Scala makes it easy to do OO and FP both, does this affect the orthogonality of the 2 methods ?

答:
Orthogonal roughly means "independent."

So if FP and OO are orthogonal, that means that you can use immutability whether you use objects or not, and you can use objects whether they're immutable or not.

Title: FP and OO orthogonal?


问:
PHP, structural or OOP based language?
I would like to discuss why is PHP called a structural language? what are the OO concepts that cannot be implemented using PHP?</p>

答:
1) the first paragraph of the wikipedia-artical on structured prog langs says why

2) there are no OO concepts you cannot apply in PHP

OwnerDisplayName: Awais Qarni

Title: PHP, structural or OOP based language?


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

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

答:
Honestly, it all depends on the employer. If all they have to go on is your GPA, without any listed experience, it can be a factor. There are so many variables that are accounted for in the hiring process, such as the type of personality you exhibit, the degree of professionalism you exhibit when you answer questions, your on-hand technical knowledge that applies to the job in question, etc. When compared to these other factors, I think that grades are somewhat of a low priority, but can be a determining factor when weighing one job candidate vs. another.

I'm currently a new developer and my educational background is in geology/GIS. When I interviewed with my currently employer, I had very little to go on in terms of experience in the industry. I ended up getting through the interview based on the other factors I listed earlier. I think my good GPA was further support in proving that I have the ability to be disciplined in following tasks and getting them done.

With that said, there are many more important factors in getting past an interview, but for many employers that have very little else to go on when shuffling through a stack of resumes, GPA can have importance in determining if someone makes the cut or if they're being compared to someone else with similar abilities.


问:
What can be the cause of new bugs appearing somewhere else when a known bug is solved?
During a discussion, one of my colleagues told that he has some difficulties with his current project while trying to solve bugs. "When I solve one bug, something else stops working elsewhere", he said.

I started to think about how this could happen, but can't figure it out.

I have sometimes similar problems when I am too tired/sleepy to do the work correctly and to have an overall view of the part of the code I was working on. Here, the problem seems to be for a few days or weeks, and is not related to the focus of my colleague.

I can also imagine this problem arising on a very large project, very badly managed, where teammates don't have any idea of who does what, and what effect on other's work can have a change they are doing. This is not the case here neither: it's a rather small project with only one developer.

It can also be an issue with old, badly maintained and never documented codebase, where the only developers who can really imagine the consequences of a change had left the company years ago. Here, the project just started, and the developer doesn't use anyone's codebase.

So what can be the cause of such issue on a fresh, small-size codebase written by a single developer who stays focused on his work?

What may help?

Unit tests (there are none)?

Proper architecture (I'm pretty sure that the codebase has no architecture at all and was written with no preliminary thinking), requiring the whole refactoring?

Pair programming?

Something else?

答: It doesn't have much to do with focus, project size, documentation, or other process issues.  Problems like that are usually a result of excessive coupling in the design, which makes it very difficult to isolate changes.</p>


答: Improve the breadth of your automated test regimen. ALWAYS run the full set of tests prior to committing code changes. That way, you'll detect the pernicious effect of your changes.

Title: What can be the cause of new bugs appearing somewhere else when a known bug is solved?

Body:
During a discussion, one of my colleagues told that he has some difficulties with his current project while trying to solve bugs. "When I solve one bug, something else stops working elsewhere", he said.

I started to think about how this could happen, but can't figure it out.

I have sometimes similar problems when I am too tired/sleepy to do the work correctly and to have an overall view of the part of the code I was working on. Here, the problem seems to be for a few days or weeks, and is not related to the focus of my colleague.

I can also imagine this problem arising on a very large project, very badly managed, where teammates don't have any idea of who does what, and what effect on other's work can have a change they are doing. This is not the case here neither: it's a rather small project with only one developer.

It can also be an issue with old, badly maintained and never documented codebase, where the only developers who can really imagine the consequences of a change had left the company years ago. Here, the project just started, and the developer doesn't use anyone's codebase.

So what can be the cause of such issue on a fresh, small-size codebase written by a single developer who stays focused on his work?

What may help?

Unit tests (there are none)?

Proper architecture (I'm pretty sure that the codebase has no architecture at all and was written with no preliminary thinking), requiring the whole refactoring?

Pair programming?

Something else?


答: It's easy for one bug to mask another.  Suppose bug "A" results in the wrong function being called to handle input.  When bug "A" is is fixed, suddenly the correct function is called, which has never been tested.</p>


问:
Sharing buffer between multiple threads
I had a job process that was executing a lot of IO to read and write  temporary files.

Now I want to (need to) reduce the quantity of IO executions.

So I want to create  a sort of circular buffer that is going to be filled up with a data from a text file within first thread.

The consumer (reading) thread will fetch data from this buffer.

The problem is that there could be multiple consumers that need to read from same one buffer.

For buffer implementation I prefer not to use any existing wrappers (simple  array, where i just "play"  with indices is enough).

I also don't want to create a separate buffer for every reader.
And ofcourse I want to avoid any deadlocks and unnecessary  blockings.

UPDATE

Right now I am using circular buffer (an array and 2 indices)

The question is how to implement such buffer that can be accessed by  multiple consumers where each consumer can read from it interdependently from other consumers (one costumer may read faster than the other one).

IMPORTANT UPDATE

The first thread don't know (and should not know) about it's consumers!!!
It should write data to a buffer, when data ends it should raise a flag.

答:
what unholysampler says + you MUST know all consumers (because without it you don't know whether all of them actualy read some byte),
and if there is one that reads slower than others (and than producer produces), you will end with full array not read by him.

You can either
1) on producer side: throw or block
2) remove him as consumer and start his own queue (but use something that can grow)
3) remove him as consumer and throw exception when he wants to read.

Title: Sharing buffer between multiple threads


答:
One of the causes can be tight coupling between the components of your software: if there are no simple, well-defined interfaces between components, then even a small change in one part of the code can introduce unexpected side-effects in other parts of the code.

As an example, lately I was working on a class that implements a GUI component in my application. For weeks new bugs were reported, I fixed them, and new bugs appeared somewhere else. I realised that that class had grown too large, was doing too many things, and many methods depended on other methods being called in the right sequence in order to work properly.

Instead of fixing the latest three bugs, I did some strong refactoring: split the component into a main class plus MVC classes (three additional classes). In this way I had to split the code into smaller, simpler pieces and define clearer interfaces. After the refactoring all the bugs were solved and no new bugs were reported.


答:
Well, the immediate cause is two wrongs making a right, or at least making a not-obviously-wrong. One part of the code is compensating for the incorrect behavior of the other part. Or if the first part isn't "wrong" as such, there's some unwritten agreement between the two parts which is being violated when the code is changed.

For example, suppose functions A and B use a zero-based convention for some quantity, so they work together correctly, but C uses one, you might "fix" A to work with C and then discover a problem with B.

The deeper problem is a lack of independent verification of the correctness of the individual parts. Unit tests are designed to address this. They also act as a specification of the proper inputs. E.g. a good set of tests would make it clear that functions A and B  expected 0-based input and C 1-based.

Getting specifications right can also be done in other ways, from official documents to good comments in the code, depending on the needs of the project. The key is understanding what each component expects and what it promises, so you can find inconsistencies.

Good architecture helps with the problem of understanding the code, making this easier. Pair programming is helpful for avoiding bugs in the first place, or finding them more quickly.

Hope this helps.


答: Your requirements sound ideal for Microsoft's Sync Framework. Except for the NHibernate bit, Sync Framework needs to add a few columns to the data to handle synchronization, and those extra columns "don't play well" with NHibernate. A previous employer had an in-house developed synchronization system, and there are a lot of edge cases you have to worry about, including updates that just keep going (data item X is updated on computer A, synched over to computer B, then is picked up as a change and sent back to A, who then sends it back to B, and so on). If you really have to create your own system, and I strongly advise against it, then I'd recomend taking a look at SyncML. I think volume 4 of Pattern Languages of Program Design has a chapter on a sync pattern.</p>