问:
Did the gradual shift in methodology of writing code affect system performance? And Should I care?
TD;DR:

There was some confusion as to what I was asking, so here is the driving idea behind the question:

I always intended the question to be what it is. I may not have articulated it well originally. But intent have always been "is modular, separated, loose coupled, decoupled, refactored code" markedly slower by its own nature than "monolithic single-unit, do-everything in one place, one file, tightly coupled" code. The rest is just details and various manifestations of this that I came across then or now or will later. It is slower for sure on some scale. Like a non-defragged disk, you have to pick up the pieces from everywhere. It's slower. For sure. But should I care?

And the question is not about...

not about micro-optimization, premature optimization, etc.  It is not about "optimize this or that part to death".

What is it then?

It is about the overall methodology and techniques and ways of thinking about writing code that emerged over time:

"inject this code into your class as a dependency"

"write one file per class"

"separate your view from your database, controller, domain".

don't write spaghetti homogenious single codeblock, but write many separate modular components that work together

It is about the way and the style of code that is currently - within this decade - seen and advocated in most frameworks, advocated at conventions, passed on via the community.  It is a shift in thinking from 'monolithic blocks' to 'microservices'.  And with that comes the price in terms of machine-level performance and overhead, and some programmer-level overhead as well.

Original Question follows:

In Computer Science field, I have noticed a notable shift in thinking when it comes to programming.  I come across the advice quite often that goes like this:

write smaller function-wise code (more testable and maintainable this way)

refactor existing code into smaller and smaller chunks of code until most of your methods/functions are just a few lines long and it is clear what is their purpose (which creates more functions, compared to a larger monolithic block)

write functions that only do one thing - separation of concerns, etc (which usually creates more functions and more frames on a stack)

create more files (one class per file, more classes for decomposition purposes, for layer purposes such as MVC, domain architecture, design patterns, OO, etc, which creates more file system calls)

This is a change compared to the "old" or "outdated" or "spaghetti" coding practices where you have methods spanning 2500 lines, and big classes and god objects doing everything.

My question is this:

when it call comes down to machine code, to 1s and 0s, to assembly instructions, to HDD platters, should I be at all concerned that my perfectly class-separated OO code with variety of refactored small-to-tiny functions and methods generates too much extra overhead?

Details

While I am not intimately familiar with how OO code and its method calls are handled in ASM in the end, and how DB calls and compiler calls translate to moving actuator arm on a HDD platter, I do have some idea.  I assume that each extra function call, object call, or "#include" call (in some languages), generate an extra set of instructions, thereby increasing code's volume and adding various "code wiring" overheads, without adding actual "useful" code.  I also imagine that good optimizations can be done to ASM before it is actually ran on the hardware, but that optimization can only do so much too.

Hence, my question -- how much overhead (in space and speed) does well-separated code (code that is split up across hundreds of files, classes, and design patterns, etc) actually introduce compared to having "one big method that contains everything in one monolithic file", due to this overhead?

UPDATE for clarity:

I am assuming that taking the same code and splitting it, refactoring it out, decoupling it into more and more functions and objects and methods and classes will result in more and more parameter passing between smaller code pieces.  Because for sure, refactoring code has to keep the thread going, and that requires parameter passing.  More methods or more classes or more Factory Methods design patterns, results in more overhead of passing various bits of information more than it is the case in a single monolithic class or method.

It was said somewhere (quote TBD) that up to 70% of all code is made up of ASM's MOV instruction - loading CPU registers with proper variables, not the actual computation being done.  In my case, you load up CPU's time with PUSH/POP instructions to provide linkage and parameter passing between various pieces of code.  The smaller you make your pieces of code, the more overhead "linkage" is required.  I am concerned that this linkage adds to software bloat and slow-down and I am wondering if I should be concerned about this, and how much, if any at all, because current and future generations of programmers who are building software for the next century, will have to live with and consume software built using these practices.

UPDATE:  Multiple files

I am writing new code now that is slowly replacing old code.  In particular I've noted that one of the old classes was a ~3000 line file (as mentioned earlier).  Now it is becoming a set of 15-20 files located across various directories, including test files and not including PHP framework I am using to bind some things together. More files are coming as well. When it comes to disk I/O, loading multiple files is slower than loading one large file.  Of course not all files are loaded, they are loaded as needed, and disk caching and memory caching options exist, and yet still I believe that loading multiple files takes more processing than loading a single file into memory.  I am adding that to my concern.

UPDATE: Dependency Inject everything

Coming back to this after a while.. I think my question was misunderstood.  Or maybe I chose to misunderstand some answers.  I am not talking about micro-optimizing as some answers have singled out, (at least I think calling what I am talking about micro-optimization is a misnomer) but about the movement of "Refactor code to loosen tight coupling", as a whole, at every level of the code.  I came from Zend Con just recently where this style of code has been one of the core points and centerpieces of the convention.  Decouple logic from view, view from model, model from database, and if you can, decouple data from the database.  Dependency-Inject everything, which sometimes means just adding wiring code (functions, classes, boilerplate) that does nothing, but serves as a seam/hook point, easily doubling code size in most cases.

UPDATE 2:  Does "separating code into more files" significantly affect performance (at all levels of computing)

How does philosophy of compartmentalize your code into multiple files impact today's computing (performance, disk utilization, memory management, CPU processing tasks)?

I am talking about

Before...

In a hypothetical yet quite real not so distant past, you could easily write one mono-block of a file that does has model and view and controller spaghetti or not-spaghetti-coded, but that runs everything once it is already loaded.  Doing some benchmarks in the past using C code I found out that it is MUCH faster to load a single 900Mb file into memory and process it in large chunks than it is to load a bunch of smaller files and process them in a smaller peace-meal chunks doing the same work in the end.

.. And Now*

Today I find myself looking at code that shows a ledger, that has features like .. if an item is an "order", show order HTML block.  If a line item can be copied, print HTML block that displays an icon and HTML parameters behind it allowing you to make the copy.  If the item can be moved up or down, display the appropriate HTML arrows.  Etc.  I can, through Zend Framework create partial() calls, which essentially means "call a function that takes your parameters and inserts them into a separate HTML file that it also calls".  Depending on how detailed I want to get, I can create separate HTML functions for the tiniest parts of the ledger.  One for arrow up, arrow down, one for "can I copy this item", etc.  Easily creating several files just to display a small part of the webpage.  Taking my code and behind-the-scenes Zend Framework code, the system/stack probably calls close to 20-30 different files.

What?

I am interested in aspects, the wear and tear on the machine that is created by compartmentalizing code into many smaller separate files.

For example, loading more files means having them located in various places of the file system, and in various places of physical HDD, which means more HDD seek and read time.

For CPU it probably means more context switching and loading various registers.

In this sub-block (update #2) I am interested more strictly in how using multiple files to do the same tasks that could be done in a single file, affect system performance.

Using Zend Form API vs simple HTML

I used Zend Form API with latest and greatest modern OO practices, to build an HTML form with validation, transforming POST into domain objects.

It took me 35 files to make it.

```<code>35 files =
    = 10 fieldsets x {programmatic fieldset + fieldset manager + view template}
    + a few supporting files
</code>```

All of which could be replaced with a a few simple HTML + PHP + JS + CSS files, perhaps total of 4 light-weight files.

Is it better? Is it worth? ... Imagine loading 35 files + numerous Zend Zramework library files that make them work, vs 4 simple files.

答:
This is a change compared to the "old" or "bad" code practices where you have methods spanning 2500 lines, and big classes doing everything.

I don't think anyone ever thought doing that is a good practice. And I doubt the people that did it did it for performance reasons.

I think the famous quote from Donald Knuth is very relevant here:

We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.

So, in 97 % of your code, just use good practices, write small methods (how small is a matter of opinion, I don't think all methods should be just few lines), etc. For the remaining 3 %, where performance does matter, measure it. And if measurements show that having many small methods actually significantly slows your code down, then you should combine them into bigger methods. But don't write unmaintainable code just because it might be faster.


问:
Should I consider loosely-coupling for class methods as well?
I'm a fan of Dependency Injection, however I don't know how much both public and private methods inside a class should be loosely-coupled.

Just to picture it better, when I have both projectId and userId as private properties in my class, and both of them have their own decent setter methods which will do the input validation also -- throwing an error in case of unexpected input, then isn't it better that all the class' methods relies on these properties instead of getting them via method arguments' and repeat the whole validation, etc. again?

In this case the methods will tightly-bind to the class itself -- and probably the constructor as well, but the advantage is that all the methods can easily rely on the setter methods and they will always assume also that the proper data is always available for me to process -- because the setter should have thrown an exception otherwise.

This seems quite helpful to me and I can make all the classes and libraries loosely-coupled in a way they don't depend to each other, however my question is, can a method inside a class be dependent on the class properties itself or not? Is it considered as a bad-practice?

答:
Design of Virtual Classes
Many of the classes I have developed have ended up being non-final. By this, I mean that I included all of the functionality in the class that I originally intended but circumstances made it to my benefit to allow extending the class.

1) Lazy evaluation. If you use the getter method for an aggregate, then the values can be imported or calculated at the time they are needed and not before. This is often important for expensive queries, such as database operations.

2) Testability. One class I designed had some expensive operations wired into it. Since I was testing the control paths in one group of tests, I was able to subclass the class-under-test and tweak some parameters (1 pass instead of 400 passes) to make the tests less onerous.

ContentLicense: CC BY-SA 3.0


答:
can a method inside a class be dependent on the class properties
  itself or not? Is it considered as a bad-practice?

No, this is not bad practice.  It is OK inside of a class to depend on common private methods and fields.  This is just good Encapsulation. The class is the a structure that allows information hiding from the rest of the application components (other classes).

Loose Coupling usually refers to protecting classes from each others internal state.

I'll also add, that if this concerns you, then most likely, the class is doing too much.  Following the Single Responsibility Principle (SRP) classes will naturally achieve high-cohesion and it won't smell like you have a lot of cross-dependency in a single class.

Hope this helps.

Title: Should I consider loosely-coupling for class methods as well?

Body:
I'm a fan of Dependency Injection, however I don't know how much both public and private methods inside a class should be loosely-coupled.

Just to picture it better, when I have both projectId and userId as private properties in my class, and both of them have their own decent setter methods which will do the input validation also -- throwing an error in case of unexpected input, then isn't it better that all the class' methods relies on these properties instead of getting them via method arguments' and repeat the whole validation, etc. again?

In this case the methods will tightly-bind to the class itself -- and probably the constructor as well, but the advantage is that all the methods can easily rely on the setter methods and they will always assume also that the proper data is always available for me to process -- because the setter should have thrown an exception otherwise.

This seems quite helpful to me and I can make all the classes and libraries loosely-coupled in a way they don't depend to each other, however my question is, can a method inside a class be dependent on the class properties itself or not? Is it considered as a bad-practice?


问:
Why and for what reasons developers may not like "daily scrum"?
There are advantages in holding daily scrum, like:

Team get coordinated with each other

Everyone knows what amount of task has been done

Burndown chart gets more and more complete

Task board is updated

It doesn't last that much, 15 minutes won't kill anybody

However, recently (after 6 months of implementing and using scrum), I feel like that our developers don't like scrum daily that much anymore. People just update the task board, without explaining enough and it seems that  they're bored of it. I see that when for any reason, we don't hold it, they kind'of become extra-happy.

I just don't know what could be wrong with this. Are there any reasons mentioned somewhere for disadvantages the "daily scrum" can have for a team? What could be the reasons for developers getting tired of daily scrum?

答:
Frankly, in 99% of the daily scrum meetings I've gone to, pretty much all the discussion/questions/answers could have been remedied with a few emails.

I honestly think we need to show more valid reasons to NOT have meetings.  Build environments where when it's time to corral everyone into a room in-person, that it had better be a good reason and be organized to maximize time efficiency.

I hate meetings in general, and would prefer to use video conferencing, phones, emails, anything that allows me to get into or stay into my work without having to get up and interrupt my productivity flow.

I personally think if you have more than four meetings in an 8-hour period then projects aren't being managed well.


问:
Is anyone doing "real" TDD with Visual-C++, and if yes, how do they do it?
Test Driven Development implies writing the test before the code and following a certain cycle:

Write Test

Check Test (run)

Write Production Code

Check Test (run)

Clean up Production Code

Check test (run)

As far as I'm concerned, this is only possible if your development solution allows you to very quickly switch between the production and test code, and to execute the test for a certain production code part extremely quickly.

Now, while there exist lots of Unit Testing Frameworks for C++ (I'm using Bost.Test atm.) it does seem that there doesn't really exist any decent (for native C++) Visual Studio (Plugin) solution that makes the TDD cycle bearable regardless of framework used.

"Bearable" means that it's a one-click action to run a test for a certain cpp file without having to manually set up a separate testing project etc. "Bearable" also means that a simple test starts (linking!) and runs very quickly.

So, what tools (plugins) and techniques are out there that make the TDD cycle possible for native C++ development with Visual Studio?

Note: I'm fine with free or "commercial" tools.

Please: No framework recommendations. (Unless the framework has a dedicated Visual Studio plugin and you want to recommend the plugin.)

Edit Note: The answers so far have provided links on how to integrate a Unit Testing framework into Visual Studio. The resources more or less describe how to get the UT framework to compile and get your first Tests running. This is not what this question is about. I'm of the opinion that to really work productively, having the Unit Tests in a manually maintained(!), separate vcproj from your production classes will add so much overhead that TDD "isn't possible". As far as I am aware, you do not add extra "projects" to a Java or C# thing to enable Unit Tests and TDD, and for a good reason. This should be possible with C++ given the right tools, but it seems (this question is about) that there are very little tools for TDD/C++/VS.

Googling around, I've found one tool, VisualAssert, that seems to aim in the right direction. However, afaiks, it doesn't seem to be in widespread use (compared to CppUnit, Boost.Test etc.).

Edit: I would like to add a comment to the context for this question. I think it does a good summary of outlining (part of) the problem: (comment by Billy ONeal)

Visual Studio does not use "build scripts" that are reasonably
  editable by the user. One project produces one binary. Moreover, Java
  has the property that Java never builds a complete binary -- the
  binary you build is just a ZIP of the class files. Therefore it's
  possible to compile separately then JAR together manually (using e.g.
  7z). C++ and C# both actually link their binaries, so generally
  speaking you can't write a script like that. The closest you can get
  is to compile everything separately and then do two linkings (one for
  production, one for testing).

答:
Maybe a bit late in the day, but if I read your question correctly, you're looking for techniques to improve the TDD cycle?  It's not been mentioned here, but have you looked at post-build events in VS?

Our solutions are typically organised (with Project Dependencies shown)...

```<code>MAIN-APP > LIB1, LIB2, UNIT-TEST-APP
UNIT-TEST-LIB1 > LIB1
UNIT-TEST-LIB2 > LIB2
UNIT-TEST-APP > UNIT-TEST-LIB1, UNIT-TEST-LIB2
</code>```

The post-build event of MAIN-APP will run UNIT-TEST-APP

The post-build event of UNIT-TEST-APP will run itself (just put '$(TargetPath)' as the command to run in post-build event).

(This does mean that when building MAIN-APP, unit tests can run twice, but that's not really been a problem in our case!)

As mentioned though, yes, there is a bit of effort in setting up this structure, but once it's there, adding tests is simple.

So all you have to do is build the main app and the unit tests will run automatically!

Body:
Maybe a bit late in the day, but if I read your question correctly, you're looking for techniques to improve the TDD cycle?  It's not been mentioned here, but have you looked at post-build events in VS?

Our solutions are typically organised (with Project Dependencies shown)...

MAIN-APP > LIB1, LIB2, UNIT-TEST-APP
UNIT-TEST-LIB1 > LIB1
UNIT-TEST-LIB2 > LIB2
UNIT-TEST-APP > UNIT-TEST-LIB1, UNIT-TEST-LIB2

The post-build event of MAIN-APP will run UNIT-TEST-APP

The post-build event of UNIT-TEST-APP will run itself (just put '$(TargetPath)' as the command to run in post-build event).

(This does mean that when building MAIN-APP, unit tests can run twice, but that's not really been a problem in our case!)

As mentioned though, yes, there is a bit of effort in setting up this structure, but once it's there, adding tests is simple.

So all you have to do is build the main app and the unit tests will run automatically!


问:
Why should I use node.js as http server?
I know what node.js is & what it does.

What I really want to know is how does it work as an http server?

A server like apache gets a request, fork a process, allocate memory to process, handle the request & release the process after it is completed. If we get thousands of http requests at a time, then apache waits for the the process queue to release process.

How does node.js with a single threaded environment handles so many http requests. All the incoming requests are given their own event loop. All these event loops share same memory.

How does using node.js to handle millions of http requests more scalable than using apache?

答:
You might find node.js pleasing a webserver because it uses an event loop, much like many UI frameworks. You simply wire up your routes to the http server's events. This is also the secret to its ability to achieve massive concurrency.

When the server gets a request, an event is raised, and your code runs asynchronously as a callback. When your code requests IO, it stops executing and continues as a callback when the IO is done. That way, it can use (and reuse) lightweight worker threads ( similar to the task framework in .NET ) instead of per-request threads or per-request processes.


问:
Shared source file between two parts of project
I have the following sort of directory structure:

```<code>part1
    build
    src
part2
    build
    src
</code>```

Now I have a header file that I would like to include in both parts of these projects, it will contain constants and some macro definitions as well as some utility functions, and I want these to be synchronized between the two parts. What would be the generally acceptable way to format my directory structure?

Something like so?

```<code>part1
    build
    src
part2
    build
    src
share
    src
</code>```

and set up my make files in the build directories to also look in ../../share/src

Or is there a more "correct" way of doing this?

答:
I don't think there really is any inherently better approach.  I've seen a few approaches to the situation, and the best I can do is share what they are:

Shared Include Folder

In this case you have one global "Include" folder that defines constants and types and potentially external functions that would be exposed to other applications.  The structure would look like this:

```<code>Solution
  project1 (library)
    build
    src
    include
  project2 (executable)
    build
    src
  include
</code>```

The make files would add the global include and library includes (as necessary) as include directories so the compiler can find them just like you would for any library.  NOTE: the reference to the actual file would be #include "filename.h".  Automake projects with subprojects essentially use this approach.

Shared Project

This is the outline you suggested in your question.  Essentially you have the equivalent of
a project for shared header files.  The only suggested change I would make to your solution would be how you reference the include files.  Instead of #include "..\..\shared\src\xyz.h" I would rather see the appropriate include path passed to the compiler.  Visual Studio makes this pretty easy to do, by providing a list of all the include paths in the project file.  If you create your Make files or use a tool to generate them, then the call to the compiler will need the appropriate parameters (commonly -I or /I followed by the path).

They are basically the same

It's really a matter of preference at this point, and what your IDE has the best support to handle.  I have seen the common files just left in the root directory of the solution, but that approach is a bit too ambiguous since you don't have any context for those files.  The bottom line is that you're thinking down the right path.

Body:
I don't think there really is any inherently better approach.  I've seen a few approaches to the situation, and the best I can do is share what they are:

Shared Include Folder

In this case you have one global "Include" folder that defines constants and types and potentially external functions that would be exposed to other applications.  The structure would look like this:

Solution
  project1 (library)
    build
    src
    include
  project2 (executable)
    build
    src
  include

The make files would add the global include and library includes (as necessary) as include directories so the compiler can find them just like you would for any library.  NOTE: the reference to the actual file would be #include "filename.h".  Automake projects with subprojects essentially use this approach.

Shared Project

This is the outline you suggested in your question.  Essentially you have the equivalent of
a project for shared header files.  The only suggested change I would make to your solution would be how you reference the include files.  Instead of #include "..\..\shared\src\xyz.h" I would rather see the appropriate include path passed to the compiler.  Visual Studio makes this pretty easy to do, by providing a list of all the include paths in the project file.  If you create your Make files or use a tool to generate them, then the call to the compiler will need the appropriate parameters (commonly -I or /I followed by the path).

They are basically the same

It's really a matter of preference at this point, and what your IDE has the best support to handle.  I have seen the common files just left in the root directory of the solution, but that approach is a bit too ambiguous since you don't have any context for those files.  The bottom line is that you're thinking down the right path.


问:
Online and offline point of sales application
I am going to develop a simple Point of Sales system. Mainly all the data will be stored in a central db (mysql server). All the application are going to be winforms. Together each local client will have its db copy stored locally and all the operation will be based on the local db except for one operation that the transfer of stock between outlet. So at certain interval there will be updates from the local db into the central db.

The reason to have the local copy of the db in each client desktop in case there is problem with connectivity with the central server so that business can go on as usual and update once it is online. I need help in deciding the right path to move to solve this solution is my design acceptable or being flaw ?

答:
If you go about developing it as a website first and then try to add an offline client, you're just doubling the amount of work you have to do.  You're better off building a C# application as your front-end from the beginning, with a local database (google for SQL Server Compact Edition).  Then synchronize the transactions to the server over web services when available.

You can write the web service (back-end) side in whatever you want (PHP or C#) with a fully-fledged database backend.  I would say you want to use C# just so you can live in the same language all the time.

Take a look at Microsoft Synchronization Services on how to synchronize local and remote databases nicely (don't use that framework, but use it to learn how to do it).  It's a bit of work, but you can make it a lot easier if you make some good choices ahead of time, like using GUID or UUID values for your database keys.

Of course you have to give some thought to security.  Those web services need to authenticate every function call to make sure the client is trustworthy (user and password, and possibly two-factor with some kind of secret file that lives on the client).

I think that's enough to point you in the general direction.  Don't discount how much effort you're talking about.


问:
How to explain OOP to a matlab programmer?
I have a lot of friends who come from electrical / physical / mechanical engineering background, and are curious about what is "OOP" all about. They all know Matlab quite well, so they do have basic programming background; but they have a very hard time grasping a complex type system which can benefit from the concepts OOP introduces.

Can anyone propose a way I can try to explain it to them? I'm just not familiar with Matlab myself, so I'm having troubles finding parallels. I think using simple examples like shapes or animals is a bit too abstract for those engineers. So far I've tried using a Matrix interface vs array-based / sparse / whatever implementations, but that didn't work so well, probably because different matrix types are already well-supported in Matlab.

答:
Matlab is just a language.  OOP is the concept.

Try explaining the concepts using a less example driven explanation.  Engineers certainly understand different domains and units (ex: adding temperature to distance would be odd), so they should intuitively understand encapsulation and polymorphism without needing concrete examples in Matlab.  You should be able to explain abstraction easily enough.  Inheritance and composition would be harder to explain without examples, but explain the concept clearly and they should understand.

Generics versus type specificity should be motivated through examples from their math background.  Functional programming, passing functions and lambdas are not OOP per se, and that is harder to explain without a more abstract math background that typically presented to engineers (having studied both engineering, software and mathematics, I have some insight into their different specializations).

You might not be able to provide examples using Matlab directly, but you could certainly explain abstraction and encapsulation using examples including structures.  Even in languages where you cannot encapsulate your functions (methods) with your data, you can still explain how certain functions are only defined for certain domains.

Considering that many developers value composition over inheritance, you could explain inheritance, composition, and the relative merits of the two.

You could motivate polymorphism in a natural way by reviewing the difference between integers, rationals, reals, and complex numbers, and then explain how the "normal" arithmetic operators are functions (methods), but even though the operator (ex '+') looks the same, it is a different function when used with different domains.

Good Luck!


问:
What data cannot be compressed by huffman codes?
What kind of data cannot be compressed by using the huffman codes and why? </p>

<p>I tried looking for the answer, but I only came across loss-less and lossy compression. I don't really understand what types of data cannot be compressed by huffman and why they can't be compressed using it. </p>

答:
Huffman codes have their basis in the probability that a given character will appear in a sequence. This is why when generating a Huffman prefix tree, the most common characters (those with the highest probability of appearing) are given priority for the shortest prefix.

For example, in the sample text "ABAABACABEDCA" the character 'A' appears 6 times and will be given the shortest Huffman code, 0. 'B' appears 3 times, and will get the next-shortest code, 10, and so on, down to E and D, which both appear only once and will get the longest codes.

In a truly random data set (that is, a string where all possible characters have an equal probability of appearing), then no Huffman tree that can be generated from that string will be any more efficient than any other.

The reason for this is the entropy of the string. A string with high entropy can't be compressed, because more data is required to describe the entropy than would be needed for low-entropy, or highly-structured, data.

The Youtube channel Computerphile has an excellent video that describes this problem quite elegantly.


问:
What is the most productive way to handle development-related failures?
We've all been there:

Your project failed or got cancelled.

The code you spent days working on got rejected by your team.

The design pattern you introduced to the team created chaos.

Everyone ignores your ideas.

My question is, what is the most productive way for a programmer to handle development-related failures such as these?

答:
Your project failed.

Software development is highly prone to project failures, and depending on the severity, this is best handled by management.

Many projects have failed and many more will fail, so take notes! Learn why your project failed so you don't make the same mistakes next time. You learn much more from your failures than from your successes.

What you have spend coding days on was rejected by your team.

Save your work (for later). There are two possibilities: (a) It sucks, and the fact multiple people responded the same way is indication of this (b) It's truly genius work, but far ahead of what people are used to or can understand. People generally do not like what they do not understand. Perhaps  its better to show it when the time is right OR in a different place with a different "Culture"

Nobody listen to your ideas in your company.

Its probably a bad idea, OR the culture is not aligned with your thinking. Either move to a place that supports your culture or critically evaluate your idea again (objectively without your own bias) -> is my idea really that good? <- Kill thy ego

The design pattern you introduced with force in your team created a mess.

Be honest, you tried your best but it did not turn out how you planned it. It may be better to start again or learn from the mistakes made in the design as a team and move forward.


问:
Why is my page load time so closely correlated with number of database queries?
Whenever I'm doing web development, and a page takes longer than half a second to be generated, I know that somewhere my code is hitting the DB too many times. The normal way to fix this situation is to ask the DB for all the information all at once instead, by doing JOINs and the like.

My question is: Why do many database queries make a page slow? There must be considerable overhead to each query, but what is it?

EDIT: Alright, let's take an example (it's a bit silly and small, but it'll do)

people table:

```<code>| name | football_team_id |
+------+------------------+
| jim  | 1                |
| mike | 3                |
| carl | 2                |
</code>```

football_team table:

```<code>| id | color |
+----+-------+
| 1  | red   |
| 2  | blue  |
| 3  | green |
</code>```

We all know that this is slow:

```<code>SELECT name,football_team_id FROM people;
# start rendering the page, realise we need colors
SELECT color FROM football_team WHERE id=1
# oops, need mike's color
SELECT color FROM football_team WHERE id=3
# oh, and carl's
SELECT color FROM football_team WHERE id=2
</code>```

This is a bit better:

```<code>SELECT name,football_team_id FROM people;
SELECT id,color FROM football_team WHERE id IN (1,3,2)
</code>```

This is best:

```<code>SELECT name,football_team_id,color FROM people JOIN football_team ON people.football_team_id=football_team.id
</code>```

In each example we're getting the same amount of data, but the latter is easily the fastest.

You wouldn't expect the same behaviour if you were reading from a file descriptor, for example.

答:
I've profiled a number of applications and I have found that:

Creating a database connection is usually the most expensive operation (between 700-1500+ ms on many major databases)

On the database server, most simple queries like you listed in your question take very little time to execute (between 1-20ms measured on the server)

A good portion of the time is spent transferring data from the database to the web page (about 100-300ms per simple query).

Armed with this information, if you aren't currently caching connections then now is a great time to start.  You can see that the actual time to execute a query really is negligible.  The problem is the time to actually get the data back to your web app.

So what's going on?

You'll find that most database protocols are very "chatty".  Basically, they they send bytes back and forth so that the database and the client know they are still present, and that the client has proper permissions, etc.  In some cases there is some overhead when cursors are shared between server and client.

Your database server returns results in chunks, and the driver may have to send acknowledgements to let the server know that the chunk was received properly.  The driver then needs to take these chunks and represent in a way your application can use.  All this processing takes time.

All communications have a couple properties that affect transmission time:

Latency: the delay between the time a packet is sent to the time it is received.

Transmission Speed: the number of bits/bytes per second that the wire can support.

The more firewalls, routers, and other infrastructure devices you have between your app and database the more that raises latency.  Transmission speed is something we are more familiar with, because we know are servers are connected with 10baseT, 100baseT, or 1000baseT Ethernet (10, 100, 1000 million bits per second respectively).

If you have high bandwidth once the data moves, it moves very quickly.  High latency can make communications with the database much slower than it should be due to the small packets moving back and forth between the database and application.

How do you deal with it?

One of the best ways to minimize the cost of dealing with the database is to minimize the number of times you call the database.  Additionally, you'll want to make sure you are only getting the data you actually need to display.

In some cases you can use some intelligent caching so you just don't have to hit the database at all for some parts of the pages you have to render.


问:
Chained ruleset parsing and evaluation code: recommendations?
So I have to write a filtering system, which may apply preprocessed ruleset to data - and trigger some actions defined in the ruleset while continuing its evaluation.

```<code><ruleset name="1">
 <rule>
  <conditions>
   <and>
    <or>
     <match image="aceofspades" level="70" />
     <match image="aceofdiamonds" level="66" />
    </or>
    <not>
     <match image="aceofclubs" level="60" />
    </not>
   </and>
  <action name="apply_ruleset" ruleset="2">
 </rule>
 <rule>
  ...
 </rule>
</ruleset>
<ruleset name="2">
</ruleset>
</code>```

(Good example of what it feels to be alike: sendmail configs; some Apache configs; IPTables ruleset, with multiple tables, JOIN/ACCEPT/DROP, etc).

What bothers me with every current design I can think of:

keeping state of and-or nodes

being able to jump between main and sub- rulesets easily

tracking circular references

keeping a vast set of possible  conditions

runtime speed: parsing/hashing may take time, but each data packet must be passed through dataset as fast as possible.

What should I read/think of to be sure that my parser will be nice enough to work with large sets and don't mess the speed/flexibility too much? (Not to mention iptables code).

Target language is C++ (however would like to implement a similar system in Perl later..), was reading through this - but still not see a good solution for switching rulesets / keeping with boolean logics within rules.

答:
This is why they used to recommend taking the Artificial Intelligence class.

Back in the 1970s and 1980s, there was a HUMONGOUS amount of work done on Rule-Based Systems, mostly for Expert Systems work.  That included huge amounts of work done on rules engines.  A fair amount of this work found its way into undergraduate AI textbooks.

Take a look at Winston's AI textbook.  Winston & Horn "LISP" has good information.  Buchanan and Shortliffe "Rule-Based Expert Systems" should have useful information.

Now, much of what is out there focuses on LISP.  There are any number of small LISP and Scheme interpreters that can be tacked onto your C++ code.  If you're working in Free Software (as in GPL), GNU GUILE would be a really good place to start.  There's also Tiny Scheme, which is BSD license.

And there's CLIPS.  From the Wikipedia article: "CLIPS is probably the most widely used expert system tool. CLIPS incorporates a complete object-oriented language COOL for writing expert systems. CLIPS itself is written in C, extensions can be written in C, and CLIPS can be called from C. Its user interface closely resembles that of the programming language Lisp. COOL combines the programming paradigms of procedural, object oriented and logical (theorem proving) languages."

---added later---

Something else you might find interesting.  Don Batory did some work 20 years ago, on compiling rule bases into efficient C.  It was a reimplementation of some earlier work.  The paper is "The LEAPS Algorithms".  From the first paragraph of the paper: "OPS5 is a forward-chaining expert system [McD78, For81]. LEAPS (Lazy Evaluation Algorithm for Production Systems) is a state-of-the-art production system compiler for OPS5 rule sets [Mir90].2 Experimental results have shown that LEAPS produces the fastest sequential executables of OPS5 rule sets; execution times can be over two orders of magnitude faster than OPS5 interpreters. This phenomenal speedup is due to the reliance of LEAPS on complex data structures and search algorithms to greatly increase rule firing rates. It is well-known that LEAPS data structures and algorithms are difficult to comprehend; this is due, in part, to the inability of relational database concepts (i.e., relations and select-project-join operators) to capture critical lazy-evaluation features of LEAPS algorithms."


答:
There are many factors which contribute to the tension over meetings.  Consider these as some of the important reasons why meetings may be costing you more than they are worth:

Focus - software versus meetings

Management - managers need measurement

Personality - Introverts vs. Extroverts

Time - interrupts, Maker and Manager time

Goals, Priorities

Each of those factors is explained below,

Focus - I enjoy developing software, and that includes thinking about the challenges (problems), creating solutions, building the software, and meetings distract from focus on the tasks that build the software.  There is a state called "Flow" where a developer is immersed in the challenge (problem), has built a mental model of the solution, and has complete focus on building the solution.  A developer may work until midnight, leave only to eat and sleep, then return to a state close to where they left.

Developers need to avoid distractions, and many find that there are advantages to code late into the night (they avoid the noise, phone calls, busy office, and non-developer colleagues interrupting their work).  And when you have worked until 10, 11, or 12pm, it is not unreasonable to come to work later (10, 11, noon?).  Is it reasonable to expect developers to work from 9am until midnight?

Scrum (and any) meetings distract the developer from their primary purpose, which is building software.

Management - Managers need to measure in order to be successful, hence the need for schedules, deliverables, timelines, priorities, and meetings to measure and report progress, and to expose dependencies, delays, and risk areas.  The challenge with a Scrum is that a manager needs these things, but the developer needs focus.  Meetings serve the manager, and provide a way for the manager to obtain, measure, and track status and progresss, but meetings seldom provide utility to developers.  Consider that managers provide more value when they handle distractions, remove barriers, and enable developers to focus on building software.

There are solutions to the need for meetings.  A manager could visit their developers, ask for status reports, adopt a protocol for when interruptions are less intrusive, or adopt a policy that the developer to notify them of progress when the developer is interruptible.  See the discussion of time for why this is important.

Personality - Consider that some people are introverts and others are extroverts.  Extroverts enjoy social interactions, and are recharged by them.  Managers are typically extroverts (because extroverts are usually better with social interactions), though introverts can be successful as managers.  Introverts can enjoy and even excel at social interactions, but are recharged by solitude.  Developers are often introverts, and are successful working alone (or in small teams) because they do not "need" social interactions; they can be happy working alone on problems (although extroverts can be developers too).  Daily scrum meetings can become social gatherings, good for extroverts, but not so good for introverts.

Time - Developers cannot write code while they are in meetings.  Neither can they think about hard problems (unless they are brainstorming), while distracted by meetings.  Developers need large blocks of uninterrupted time to focus on building software.  Meetings are interruptions which distract from their efforts.  When you have been immersed in solving a problem for hours, are nearly done, and someone says "time for the scrum", you are interrupted, and lose perhaps hours of work while "shifting gears".  Or you have stayed at work until 11:00pm, left work, travelled home, slept on the problem, woke up, travelled back to work ready to solve the problem, and then get interrupted after an hour of working on a problem, because it is "time for the scrum".

Paul Graham has an excellent article on Maker Time vs. Manager Time, which explains this problem far better than I do.  Suffice to say that a meeting interruption, whether planned or unplanned can break flow, and force a developer from Maker time onto Manager time.  Believe me, you want developers on Maker time.

Goals, Priorities - Developers and managers have different goals and priorities.  Managers have the onus to track schedules, minimize cost, ensure that their reports are responsible, and that they perform.  Developers have the goal to build the software that addresses the challenges/problems.  These goals are not in conflict, but it is the communications mechanism that creates the tension.  Meetings serve the manager's needs and optimize the managers time, but they conflict with the developer's needs.  Scrum meetings discard the first rule of meetings, "have an agenda", and tend to wander more.  And meetings are used to optimize communication (for the manager), but they cost the developer time (interruptions, loss of flow, etc).

What is the goal?  To build software that addresses the needs, quickly and with quality, while constraints are (quality, time, cost, process).  Scrum and other agile methodologies recognize the process constraint, and try to minimize that factor, and have been successful because they minimize that constraint.  But adding meetings does cost time, and the interruption costs the developer much more than the duration of the meeting.

Title: Why and for what reasons developers may not like "daily scrum"?

Body:
There are advantages in holding daily scrum, like:

Team get coordinated with each other

Everyone knows what amount of task has been done

Burndown chart gets more and more complete

Task board is updated

It doesn't last that much, 15 minutes won't kill anybody

However, recently (after 6 months of implementing and using scrum), I feel like that our developers don't like scrum daily that much anymore. People just update the task board, without explaining enough and it seems that  they're bored of it. I see that when for any reason, we don't hold it, they kind'of become extra-happy.

I just don't know what could be wrong with this. Are there any reasons mentioned somewhere for disadvantages the "daily scrum" can have for a team? What could be the reasons for developers getting tired of daily scrum?


问:
Least Change Problem with Thousands of Denominations
In a hypothetical economy there are currency units that can represent thousands of different values. So, for example there might be coins worth 1c, 3c, 5c, 7c, 7.5c, 80c, 8001.5c etc.

Given a list of all of the possible denominations and an arbitrary value how would one return a list of coins representing the smallest number of coins needed to match that value.

For bonus points, imagine that you have arbitrary finite quantities of each currency. So you may have only two 3c coins but thirty 18c coins.

Sounds like a nightmare compsci class problem but it's something I ran into recently on a personal project of mine.

The economy is a barter economy (tf2) in which every type of item has a distinct value relative to other items. I have an Item class where items have a Value attribute and this attribute is a double that represents the value of the item relative to a base item which has a value of 1. I'm trying to come up with a way so that if someone makes an offer of a value of 30 I can then look through a list of around 1200 item objects and find the smallest set of objects which combine in value to match 30.

I cannot think of a remotely efficient way to do this, but I figured the problem was interesting enough that someone would like to ponder over it with me. My program is in c# but even a psuedocode brainstorm would be helpful.

答: Sort your objects from highest value to lowest.  Find the highest value object that whose value is less than the number you're looking for.  If there is no such object, the method fails.  If such an object does exist, subtract the object's value from the target number, and use that target number to recursively call the change estimation method.  If that call succeeds, you're done.  If it fails, try the next lower value object.  </p>


答:
Mostly you have to do it the hard way in trying every combination, but if you sort the list first, there's a lot of pruning you can do.

First of all, the greedy algorithm on the Change-making problem wikipedia page (choosing the largest denomination not greater than the total amount remaining) is fairly efficient with the right data structures, and will often, but not always, give you the optimal answer.  Even when the answer is not optimal, it will usually be close, and is therefore useful as a first step for pruning.

Say the greedy algorithm gives an answer of four items.  You now only have to check combinations of three or fewer items.

The other pruning you can do is on the item values.  If your total is 30, you know you don't have to test any combinations containing items valued 31 or more.  If your first selection has value 20, you know your second selection must have a value less than or equal to 10.  Again, this pruning is fairly efficient on a sorted list with the right data structures.

This problem is also a good candidate for memoization, where you store intermediate results rather than recalculating them on every iteration.

Also, the order you perform the search makes a big difference.  If you start with the largest items first, you can prune a lot of paths more quickly.  No need to cycle through all combinations of $1 items first.

So while at first glance the problem seems intractable, if you're smart about the order you go in and do some pruning, you should be able to find answers in a reasonable amount of time in practice.  At the very worst, you might have to cut off the calculation after a certain time period, but if you order it correctly, you will have a solution that is close to optimal even if you haven't had enough time to prove it is definitely optimal.  For the purposes of a game trade, that might be good enough.

Title: Least Change Problem with Thousands of Denominations

Body:
In a hypothetical economy there are currency units that can represent thousands of different values. So, for example there might be coins worth 1c, 3c, 5c, 7c, 7.5c, 80c, 8001.5c etc.

Given a list of all of the possible denominations and an arbitrary value how would one return a list of coins representing the smallest number of coins needed to match that value.

For bonus points, imagine that you have arbitrary finite quantities of each currency. So you may have only two 3c coins but thirty 18c coins.

Sounds like a nightmare compsci class problem but it's something I ran into recently on a personal project of mine.

The economy is a barter economy (tf2) in which every type of item has a distinct value relative to other items. I have an Item class where items have a Value attribute and this attribute is a double that represents the value of the item relative to a base item which has a value of 1. I'm trying to come up with a way so that if someone makes an offer of a value of 30 I can then look through a list of around 1200 item objects and find the smallest set of objects which combine in value to match 30.

I cannot think of a remotely efficient way to do this, but I figured the problem was interesting enough that someone would like to ponder over it with me. My program is in c# but even a psuedocode brainstorm would be helpful.


问:
Doing localization each Sprint
We need to support 5 languages for our product. This means that in order to have a potentially shippable product we need to translate all text new to the Sprint to all these  languages. It doesn't make sense to me because the text might change after a few Sprints during which the users will use the application and give feedback. So paying the translating company for translating text that will most likely change doesn't seem to be a wise decision. So what do you do with localization in Scrum?</p>

答: Localization should be finished for every release. If you release once per sprint, localize once per sprint. If you release every 4 sprints, localize once every 4 sprints. Have a string freeze period before release where you do not make changes to the strings in the codebase so that your translators have time to update things.</p>

Title: Doing localization each Sprint


答:
I would make this a comment if it weren't so long...because it's not a definitive answer...but anyway:

So, imagining that you need to return 34 cents.  You have 1 quarter, 4 dimes, and 3 pennies.  You have a problem easily discernible that you have to either give the person 35 cents or 33 cents, but you cannot give exact change.

To code would need to add quarter, check delta (-9).  Save as closest delta.

No more quarters, move to dimes.  Add dime, check delta (+1).  Save as closest delta and pop the dime since we are in a positive delta.

Move to nickels, none.  Move to pennies, and add pennies while delta < 0.  Final delta when out of pennies (-1).  Save as closest delta IF negative delta is given preference over positive delta since the absolute is equal.

Check for lower currency, none.

However, there are other problems...what if you needed to give the user 40 cents...

You have to try quarter + dime + 3 pennies with above algorithm and result in a delta of -2.  However, then, you have to roll-back all the way to the quarters and remove one of your top currencies and start over with currencies below that resulting in you finding 4 dimes delta=0, DONE.


答:
Who are the real customers (as opposed to beta users)? Do they expect fully translated text?

If the idea is to let the product bake for a few sprints to get feedback, then you can defer translation so that it is scheduled to arrive in time for final delivery. Otherwise, translate for every sprint; that way the work is "done". If it needs to be changed later, accept that as a cost. The point is not to reduce every single expense at every step; it is to reduce it overall, and make the process more sane and agile.

Further, if your text "will mostly like change" after a few sprints, maybe some effort can be put into choosing better text in the first place, if possible.

Title: Doing localization each Sprint

Body: We need to support 5 languages for our product. This means that in order to have a potentially shippable product we need to translate all text new to the Sprint to all these  languages. It doesn't make sense to me because the text might change after a few Sprints during which the users will use the application and give feedback. So paying the translating company for translating text that will most likely change doesn't seem to be a wise decision. So what do you do with localization in Scrum?</p>


问:
Is it okay to make coding style changes on an open source project that doesn't follow best practices?
Recently, I came across a number of open source Ruby (or majority of it was Ruby) projects on GitHub that when checked with a code analyzing tool like Rubocop, create a lot of offenses.

Now, most of these offenses include using double quotation marks instead of single quotes (when not interpolation), not following the 2 spaces per level rule, exceeding the 80 character line length rule, or using { and } for multi-line blocks.

[The] Ruby style guide recommends best practices so that real-world
  Ruby programmers can write code that can be maintained by other
  real-world Ruby programmers. ~ Source: Ruby Style Guide

Although they are small and easy to fix, is it appropriate to change the coding style of an open source project by fixing the offenses and making a Pull Request? I acknowledge that some projects, like Rails, do not accept cosmetic changes and some are just too large to "fix" all at once (Rails for example generates over 80,000 offenses when Rubocop is run - regardless, they have their own small set of coding conventions to follow when contributing). After all, the Ruby Style Guide is there for a reason together with tools like Rubocop.

People appreciate consistency so making these kinds of changes is kind of doing a good thing for the Ruby community in general, right?

[The author(s) of the Ruby Style Guide] didn't come up with all the
  rules out of nowhere - they are mostly based on my extensive career as
  a professional software engineer, feedback and suggestions from
  members of the Ruby community and various highly regarded Ruby
  programming resources, such as "Programming Ruby 1.9" and "The Ruby
  Programming Language". ~ Source: Ruby Style Guide

Isn't not following community coding style conventions and best practices basically encouraging bad practices?

答:
I used to be big on having a good style guide, but given the state of affairs in Ruby, "I've moved on".

Basically I live with what I'm working with and otherwise follow the general conventions I've learned from a number of jobs.

For Ruby, which is my language of choice I've also (in my head) divided style into universally accepted, generally accepted, my preferences and best practices.  Things that are universally accepted I might submit a change as part of a change request for an issue or feature branch request.

Examples of each style (in my opinion):

Universally accepted for Ruby:

spaces not tabs

two space indents

method_names_use_underscores

Constants start with Caps.

Generally accepted:

Don't use parentheses if not necessary

Use { } for one line blocks and do end for multi-line blocks.

CONSTANTS_ARE_IN_ALL_CAPS

Use predicative statements (cond ? true : false) over if then if the expression fits on 1 line.

Personal preferences:

Line length of 120 character lines

case when statements are indented 2 from the case statement.

Use single quotes unless double are needed.

No Agreement:

Case Statements

Line length

Best Practices:

small methods, <= 5 lines if possible.

small classes, <= 100 lines if possible.

Avoid constants

Code has tests

Finally, as others have detailed, you should ask first. At the end of the day the key to style is communication between developers and sensitivty to others.  For example if I want to make a style change on an open source project, I will often do a pull request for one or two actual features or bug fixes first.  Once the maintainer knows me and sees that I've contributed, then I might suggest style changes.  I only suggest them though.  For example "While doing another feature on project x, I noticed that you have a 4 space indents in a couple of files and I was wondering if I could change them to 2 ?"


问:
Refactor or Concentrate on Completing App
Would you refactor your app as you go or focus on completing app first? Refactoring will mean progress of app app will slow down.

Completing app will mean you get a possibly very hard to maintain app later on?

The app is a personal project. I don't really know how to answer "What drives the functionality and design", but I guess it's to solve inefficiencies in current software out there. I like minimal easy to use software too. So I am removing some features and add some that I feel will help.

答: Refactor early and often! The time you "save" on not doing it is spent many times over trying to hack in the next feature and searching for bugs in overly complex or chaotic code.</p>

ContentLicense: CC BY-SA 2.5


问:
What are the valid test cases for method calls within if-else condition
I have a discount service that gets called if certain conditions are met. I need to write test cases to check if the discount service is called. My doubt is checking if the discount service is NOT called for type 4 and 5 is a valid test case scenario.  </p>

```<code>public void ApplyDiscount(int typeId, double amount)
{

if(typeId == 1)
{
  //call discount service
}

else if(typeId == 2)
{
  //call discount service
}

else if(typeId == 4)
{
   //do other stuff
}
else if(typeId == 5)
{
   //do some other stuff
}

}
</code>```

答:
The most easy way to discover the test you nee its thinking in the list of features you want form the code under test, for example:

"when type is 1,2 call discount service"

"when type is 4 do some stuff"

"when type is 5 do some other stuff"

Perhaps you don't need a test to explicitly check that the discount service its not called, probably you have more services in your applications and you don't want to check that there is no calls to all those services.


答: Encrypted data.  A good encryption scheme is basically indistinguishable from random data and thus it's no more compressible than random data is.</p>

Title: What data cannot be compressed by huffman codes?

Body:
What kind of data cannot be compressed by using the huffman codes and why? </p>

<p>I tried looking for the answer, but I only came across loss-less and lossy compression. I don't really understand what types of data cannot be compressed by huffman and why they can't be compressed using it. </p>


答:
Well compressed data.  Note that if the underlying data is highly repetitive you might gain some benefit from compressing the compressed data because the underlying scheme wasn't good enough--compressors are normally built to work fairly fast and that precludes finding an absolutely perfect scheme.

Note, also, that if the "compressed" data isn't really all that compressed you can get a bit this way--I've gotten 2% by zipping a zip--but only when the original zip was full of a whole bunch of small files.  The files were being compressed, the file NAMES and other directory info was not.


答:
Lets first look at what compression does.  It takes something that is big into something smaller.  Yea, thats a really high level way of looking at it, but its an important starting point.

With a lossless compression, there is a point at which you can't squeeze the information any more - its reached its maximum information density.

This gets into the information theory definition of entropy.  The pioneer in this field is Claude Shannon who wrote a paper in 1950 titled Prediction and Entropy of Printed English.  It turns out that english has between 1.0 to 1.2 bits of information per letter.  Think about the word th_   whats that blank?  You can predict it - and so there's not much information in that letter.

This really delves into what Huffman encoding does - it squeezes the information as tightly as it can.

What happens if you squeeze more tightly? Well, nothing really.  You can't fit more than 1 bit in 1 bit.  Once you've compressed the data as optimally as it can be compressed, you can't compress it anymore.

There's a tool out there that will measure how much entropy is in a given stream of bits.  I've used it when writing about random numbers.  Its ent.  The first measure it does is that of the entropy in the stream (it can do other neat tests like calculate pi).

If we take something thats pretty random, like the first 4k bits of pi, we get:

Entropy = 7.954093 bits per byte.

Optimum compression would reduce the size of this 4096 byte file by 0 percent.

Chi square distribution for 4096 samples is 253.00, and randomly would exceed this value 52.36 percent of the times.

Arithmetic mean value of data bytes is 126.6736 (127.5 = random).

Monte Carlo value for Pi is 3.120234604 (error 0.68 percent).

Serial correlation coefficient is 0.028195 (totally uncorrelated = 0.0).

And here we see that you can't compress the digits of pi because there's nearly 8 bits per byte of data there.

So... random numbers, you can't compress those at all.

There are other things that have rather high amounts of information content like encrypted data.

Going back to the simple example of the word th_ and being able to guess what comes next, we know this because of the letter frequencies in English and the valid English words. On the other hand, if we compress this, it is harder to guess what is the next letter and thus there is more information density per letter.

You can see this with (a simple cipher) the Vigenère cipher

(from Wikipedia: Vigenere letter frequencies)

Here we can see that the letter frequencies are much closer to random than regular English text.  This would make it harder for the Huffman encoding to create an optimal encoding for the text.

Modern encryption schemes do an even better job of mixing the information of the key and the pain text together and create a data stream that has extremely high information density, and thus very difficult to predict what character comes next.

And so, those are the things that compression has difficult with and why.


答:
(I'm most familiar with Java, Junit, and mockito - so what I write below is based on my understanding of this applied to what I can find)

You are looking for a mocking tool such as  Moq.

In this scenario what you would do is mock the object that contains the DiscountService.

At this point, you would do something like (I have no way of verifying if the following code is correct for the framework, but its in the right direction):

```<code>public void Test() {
    var mockService = new Mock<IDiscountService>();
    SomeClass.ApplyDiscount(1, 0.0);
    mockService.Verify(
       mockService = foo.ApplyDiscount(), Times.Once());
}
</code>```

And this will verify that the discount service was called once (and only once) when the ApplyDiscount call was made with the given parameter.

I will caution you that the structure of this code that you have psuedocoded out seems suspect too.  The int being passed in and what looks to be something that wants to be a switch statement smells like wishing to be polymorphism.

Consider that if the test is hard to write, sometimes it means that the design of the system is wrong and should be revisited.  Well written code tends to be easy to test.

Still, you will want to read up on Moq and use it in the right places (like verifying that something was called the appropriate number of times without putting test code into your actual code - which smells even worse than switches).

Title: What are the valid test cases for method calls within if-else condition

Body:
I have a discount service that gets called if certain conditions are met. I need to write test cases to check if the discount service is called. My doubt is checking if the discount service is NOT called for type 4 and 5 is a valid test case scenario.  </p>

```<code>public void ApplyDiscount(int typeId, double amount)
{

if(typeId == 1)
{
  //call discount service
}

else if(typeId == 2)
{
  //call discount service
}

else if(typeId == 4)
{
   //do other stuff
}
else if(typeId == 5)
{
   //do some other stuff
}

}
</code>```

Body:
(I'm most familiar with Java, Junit, and mockito - so what I write below is based on my understanding of this applied to what I can find)

You are looking for a mocking tool such as  Moq.

In this scenario what you would do is mock the object that contains the DiscountService.

At this point, you would do something like (I have no way of verifying if the following code is correct for the framework, but its in the right direction):

public void Test() {
    var mockService = new Mock<IDiscountService>();
    SomeClass.ApplyDiscount(1, 0.0);
    mockService.Verify(
       mockService = foo.ApplyDiscount(), Times.Once());
}

And this will verify that the discount service was called once (and only once) when the ApplyDiscount call was made with the given parameter.

I will caution you that the structure of this code that you have psuedocoded out seems suspect too.  The int being passed in and what looks to be something that wants to be a switch statement smells like wishing to be polymorphism.

Consider that if the test is hard to write, sometimes it means that the design of the system is wrong and should be revisited.  Well written code tends to be easy to test.

Still, you will want to read up on Moq and use it in the right places (like verifying that something was called the appropriate number of times without putting test code into your actual code - which smells even worse than switches).


答:
I think the essential point is to keep interfaces clean. You can always refactor or even rewrite module / class / whatever implementations later on, as long as the communication layers between them are sane. Spend some time figuring out what's easy to change later on, and what's not. Make the latter right.

This is consistent with the spirit of TDD. To write good tests, you need a good interface to test against. How messy it's behind the scenes at the moment is not that important, because you can improve it later.

Title: Refactor or Concentrate on Completing App

Body:
Would you refactor your app as you go or focus on completing app first? Refactoring will mean progress of app app will slow down.

Completing app will mean you get a possibly very hard to maintain app later on?

The app is a personal project. I don't really know how to answer "What drives the functionality and design", but I guess it's to solve inefficiencies in current software out there. I like minimal easy to use software too. So I am removing some features and add some that I feel will help.


问:
How is MVC different from Layered
Based on this book , refering to pages 156 to 159 , it talks about the two different types of software architecture model : MVC & Layered .

There are distributed system architecture patterns such as : Master-Slave , 2 tier client-server , multi-tier client server , P2P

These are my questions :

1) In MVC , there is the Model , View , Controller which is in essence a three layer architecture with View on top , Controller in the middle , Model on the bottom and all three layers are only able to communicate with the layers above and beneath them only which is exactly the same as layered architecture . What is the actual difference between them ??

2) Isnt MVC a form of client server architecture ??

3) Master-Slave seems exactly like 2 tier client-server where the server is the Master and the client is the slave , I dont understand how Master-Slave differs from Client-Server

答: If you consider any big project or enterprise application mvc is used only in presentation layer. Here model will act merely as view model. Sometimes model is maintained at separate project and shared between all layers i.e BAL, DAL and PL.You can not say it is client server architecture because in tier architecture different layers are hosted in different server.</p>

Title: How is MVC different from Layered


答:
Apply the "potentially shippable" rule as far as it makes sense. Use your common sense where it doesn't. (Common sense is sometimes called "rule 0" in agile)

A team should avoid to commit work that is beyond their own power. Translations typically rely on translators outside the team. So the team shouldn't commit to that.

In short: put in your definition of done "Ready for translation".

And reserve some time before the release to complete those little items that are left out of the D.o.D.

For the agile purists (those that interpret it all too literally), that is indeed a tiny little bit of "waterfall". But it works.

Title: Doing localization each Sprint


问:
Accurate calculation of a raster image's boundary length
I have a rasterized image that contains two colors: white and black.  The black portion is entirely connected and looks like a big blob.  Is there a good way to estimate the length of the boundary between the regions?

One method I have considered is to simply count how many "edges" of the rasterized grid have a different color on each side.  However, for e.g. a purely diagonal line, this will overestimate the distance of the boundary by a factor of sqrt(2).  Is there a better method for estimating the boundary length which does not have this problem?

答:
Issue with length overestimation for diagonal lines stems entirely from the approach you are taking, namely to count "edges of the pixel grid which different color on each side" and declare the sum a contour length. Those two are not equivalent in general case.

Essentially you are restricting yourself to calculating distances "on the grid" instead of Euclidian ("direct") or "smoothed out for multiple points" distances between actual edges of the contour (not "edges" of the grid). The reason you find your approach inaccurate for diagonal lines is because your criteria of accuracy has to do with sub-pixel precision, while in your algorithm you are operating on a pixel precision level ("edges" of rasterized grid).

Why not first apply edge detection and get a list of edges with sub-pixel coordinates (you can apply any general purpose sub-pixel edge detection algorithm). Your output from this step is going to be a list of pairs of doubles. This step will transform your problem to a sub-pixel domain, where you can calculate distances and meet your accuracy criteria.

After drilling down to edges on sub-pixel level we have two main options:

to calculate the sum of Euclidian distances between successive edges. It is going to give us acceptably accurate countour length given that we've picked a decent edge-detection algorithm;

to connect your edges in a smooth way (E.g. B-splines) and calculate a sum of arc lengths between successive edges according to the interpolating function you've picked.

UPDATE
Simplified approach for step one would be to pick a sub-pixel middle point of your your eligible "edges" of rasterized grid and declare it a center of your edge. From there you continue with calculating distances - even with Euclidian distances between center points you'll get a much accurate result then with counting elidgible "edges" of rasterized grid. At least your "overestimation by factor of sqrt(2)" issue for diagonal lines will be resolved. Hope it helps.


问:
secure photos on server
I would like to hear advice from the more experienced developers. The project is now in the design stage. It's mobile application and a simple web application. Content is pictures, comments, personal correspondence.

Pictures can be quite personal. Need a very serious attitude to security.

The question is simple: where to store photos and how to secure it?

I think it's will be in the following way:

1. User make some photo. Via SSL the application sends photo to the server.

2. The server recieve photo, encrypt it and store somewhere.

Also, via app the user can see all own photos.

1. Request to server for photos.

2. Server decrypt stored photos and send via SSL to client.

I need some technical advices: where to save images, I know that database is quite slow for this case, which algorithms use for encrypt/decrypt, what about cache. It will be highload project and performance is very important.

Mobile application is planned on cross-platform framework like phoneGap, Titanium. On the server is .NET. But it is planned. I also consider full stack frameworks for javascript.

答:
It may be not a good idea to use javascript to decrypt, if so, every one that have access to your site, will have a copy of the decryptor,
the solution I can suggest is to keep photos encrypted at database. decryption must be on the server side when a secure request come through an ssl connection.
I don't sure but maybe blocking direct links to photos is also useful, your links must be come through a secure routing</p>

Title: secure photos on server


问:
What exactly is the Garbage Collector in Java?
I think I generally know what the Garbage Collector in Java does, but It's praised a lot, so I thought maybe I'm missing something about it's functionality.

What I know is, that the GC takes care of erasing from the memory objects that have no reference to them, and thus are unreachable by the programmer.

For example, if inside a loop I'm constantly creating a new Object(), the previous ones will eventually get deleted by the GC (correct me if I'm wrong).

This is very useful for me as a Java programmer, and spares me a lot of headache that I assume C++ programmers have to deal with - manually deleting objects from the memory (again, correct me if I'm wrong).

This feature is awesome, but is there anything more to the Garbage Collector? Am I missing something?

答:
No, not missing anything about Garbage Collection.

Garbage collection frees developers from the minutia of allocating and de-allocating memory themselves.

Being part of the platform means there is a whole class of problems that Java does not have  (and .NET and other garbage collected runtimes as well).

What you may be missing is just how much trouble having to deal with memory allocations and de-allocations and the bugs inherent with not getting them right really is ;)


问:
Difference between TSimpleRWSync's BeginWrite and BeginRead methods?
I have recently switched to TSimpleRWSync from TRTLCriticalSection. The methods BeginRead and BeginWrite confuse me as wherever I read help, they seemingly do the same thing i.e. acquire the critical section whenever it gets relinquished. As the TSimpleRWSync doesn't allow multiple read threads, there is seemingly no point in having two separate methods either.

Is there a special difference between them aside from the contextual one?

答:
The BeginRead/BeginWrite methods come from the IReadWriteSync interface.
TSimpleRWSync is a simple implementation of that interface, allowing access only to a single reader or writer. But there is also another implementation of the interface (TMultiReadExclusiveWriteSynchronizer) which allows multiple concurrent readers.

By having both implementations conform to the same interface, you can easily replace your use of TSimpleRWSync with TMultiReadExclusiveWriteSynchronizer without having to touch all the places where you lock/unlock the critical sections. The only thing you need to do up front is forget that TSimpleRWSync allows only a single reader/writer and write your locking as if there can be multiple readers.


问:
What does this duration reported by ffmpeg mean?
When I run ffmpeg on an mp4 file, it says the duration is:

```<code>00:03:57.54
</code>```

What is the unit that 54 represents ? I am interpreting it as 0.0054 seconds (54 milliseconds).

答: The dot in that time representation is a normal decimal point. The 57.54 simply means 57 seconds and 54 hundreds of a second.


问:
How does persistence fit into a purely functional language?
How does the pattern of using command handlers to deal with persistence fit into a purely functional language, where we want to make IO-related code as thin as possible?

When implementing Domain-Driven Design in an object-oriented language, it's common to use the Command/Handler pattern to execute state changes. In this design, command handlers sit on top of your domain objects, and are responsible for the boring persistence-related logic like using repositories and publishing domain events. The handlers are the public face of your domain model; application code like the UI calls the handlers when it needs to change domain objects' state.

A sketch in C#:

```<code>public class DiscardDraftDocumentCommandHandler : CommandHandler<DiscardDraftDocument>
{
    IDraftDocumentRepository _repo;
    IEventPublisher _publisher;

    public DiscardDraftCommandHandler(IDraftDocumentRepository repo, IEventPublisher publisher)
    {
        _repo = repo;
        _publisher = publisher;
    }

    public override void Handle(DiscardDraftDocument command)
    {
        var document = _repo.Get(command.DocumentId);
        document.Discard(command.UserId);
        _publisher.Publish(document.NewEvents);
    }
}
</code>```

The document domain object is responsible for implementing the business rules (like "the user should have permission to discard the document" or "you can't discard a document that's already been discarded") and for generating the domain events we need to publish (document.NewEvents would be an IEnumerable<Event> and would probably contain a DocumentDiscarded event).

This is a nice design - it's easy to extend (you can add new use cases without changing your domain model, by adding new command handlers) and is agnostic as to how objects are persisted (you can easily swap out an NHibernate repository for a Mongo repository, or swap a RabbitMQ publisher for an EventStore publisher) which makes it easy to test using fakes and mocks. It also obeys model/view separation - the command handler has no idea whether it's being used by a batch job, a GUI, or a REST API.

In a purely-functional language like Haskell, you might model the command handler roughly like this:

```<code>newtype CommandHandler = CommandHandler {handleCommand :: Command -> IO Result)
data Result a = Success a | Failure Reason
type Reason = String

discardDraftDocumentCommandHandler = CommandHandler handle
    where handle (DiscardDraftDocument documentID userID) = do
              document <- loadDocument documentID
              let result = discard document userID :: Result [Event]
              case result of
                   Success events -> publishEvents events >> return result
                   -- in an event-sourced model, there's no extra step to save the document
                   Failure _ -> return result
          handle _ = return $ Failure "I expected a DiscardDraftDocument command"
</code>```

Here's the part I'm struggling to understand. Typically, there'll be some sort of 'presentation' code which calls into the command handler, like a GUI or a REST API. So now we have two layers in our program which need to do IO - the command handler and the view - which is a big no-no in Haskell.

As far as I can make out, there are two opposing forces here: one is model/view separation and the other is the need to persist the model. There needs to be IO code to persist the model somewhere, but model/view separation says that we can't put it in the presentation layer with all the other IO code.

Of course, in a "normal" language, IO can (and does) happen anywhere. Good design dictates that the different types of IO be kept separate, but the compiler doesn't enforce it.

So: how do we reconcile model/view separation with the desire to push IO code to the very edge of the program, when the model needs to be persisted? How do we keep the two different types of IO separate, but still away from all the pure code?

Update: The bounty expires in less than 24 hours. I don't feel that either of the current answers has addressed my question at all. @Ptharien's Flame's comment about acid-state seems promising, but it's not an answer and it's lacking in detail. I'd hate for these points to go to waste!

答:
So: how do we reconcile model/view separation with the desire to push IO code to the very edge of the program, when the model needs to be persisted?

Should the model need to be persisted?  In many programs, saving the model is required because the state is unpredictable, any operation could mutate the model in any way, so the only way to know the state of the model is to access it directly.

If, in your scenario, the sequence of events (commands that have been validated and accepted) can always generate the state, then it's the events that need to be persisted, not necessarily the state.  The state can always be generated by replaying the events.

Having said that, often times the state is stored, but just as a snapshot/cache to avoid replaying the commands, not as essential program data.

So now we have two layers in our program which need to do IO - the command handler and the view - which is a big no-no in Haskell.

After the command is accepted, the event is communicated to two destinations (the event storage, and the reporting system) but at the same layer of the program.

See Also

Event Sourcing

Eager Read Derivation


答:
If the bad design you want to refactor really hurts you, you better fix it now than create more code that depends on it. Refactoring later would be more difficult and more expensive; chances are you won't be able to do it anymore.

On the other hand, if your only issue is the uglyness, you might want to complete your software first, because hardly anything beats getting things done.


问:
Domain Model vs View Model
I'm in the early stages of my programming career and I've been working with MVC for just about a year now. I've spent much time learning about the pattern and the concepts behind it, but as the projects I'm working with get larger I'm starting to think that maybe I don't have the best understanding of how the model layer is supposed to work.

I hear a lot about always having a View Model to protect your Domain Model but how does this work in practice? What does the relationship between the two look like? What if a model doesn't need any extra "view" logic, should I just create a copy of it? Why?

答:
A rather general answer. Traditionally the View in MVC would request the information it needs from the Model, and the Model knows nothing about the View. Data binding (very popular in Microsoft UIs) ties the View quite closely to the underlying Model, which conflicts with the traditional MVC.

So the solution is to have one model for the view to bind to and a different model which really is the Model. These are the View Model and Domain Model.

To your questions: The relationship between them is that the VM knows about the DM, not vice versa, and the VM has extra stuff in it specifically for the View to use. If you don't have a View with these requirements, you don't need a View Model at all.

In those cases where a VM is needed, I would recommend thinking of it as a wrapper over the DM. The VM will have properties unique to view, and will delegate requests for and updates to business data to the DM. There should be no duplication of logic between them.

When I've used this in WPF or Store apps the VM is the data binding context for the view, in close proximity, and the DM accessed through a formal interface, possibly far away.

I have no idea if there is a pattern for this -- my mind doesn't work that way.

Title: Domain Model vs View Model


问:
gtkmm manage/add vs smart pointers:
gtkmm provides lifetime management of widgets using

```<code>Gtk::Widget* aWidget = Gtk::manage(new Widget());

Gtk::Widget.add(*aWidget);
</code>```

This delegates lifetime management of aWidget to its container widget.

We also have several types of smart pointers, particular the  C++ 11 smart pointers templates, which I use everywhere.

I find the manage/add syntax easier and cleaner to use, but it's not part of the C++ Standard, it's a gtkmm specific feature, which makes me think I should stick to std::shared_ptr, etc.

So I'm wondering what are the advantages/disadvantages of smart pointers vs the gtkmm manage/add model (aside from cases where you need the reference after the owner container has been deleted, or when you have a top level widget that has no containing widget).

答:
Gtk::manage() solves the specific problem of lifetime management for hierarchies of widgets. And it solves it well.

Smart pointers (std::shared_ptr in particular) have broader application range, and therefore will be less efficient when used to address this specific problem. Lifetime management for hierarchies of widgets can be solved with shared_ptr, but it will be:

not as concise as using manage() (as you pointed out yourself);

less efficient in terms of memory usage, since using shared_ptrs will introduce memory overhead: shared_ptr has a memory footprint of its reference to its reference-count, which will use size - as opposed to manage(), which uses variables such as Gtk::Object.referenced_ that are part of your Widget base class already at all times. So, if you have a significant number of Widgets, that size difference might become an issue worth considering;

not as mainstream as using manage() in gtkmm (which has quite a few consequences, including clarity and maintainability).

As of idea of favoring std::shared_ptr over Gtk::manage() because shared_ptr is part of C++ Standard, while manage() is not - I'm not sure it is going to be a game changer for average application, as by not using manage() you don't cut your dependency on Gtk anyways. So your application is not going to gain any better portability if you'd go for shared_ptr.

I would rather leverage native gtkmm API, for sake of clarity and efficiency.

P.S.: There is actually a smart pointer Glib::RefPtr, which handles lifetime management for certain gtkmm objects. Again, as it is a feature native to Glib, it leverages built-in facilities of Glib::ObjectBase, and is therefore more efficient then std::shared_ptr for certain applications, for the reasons explained in the 2nd point above.

Title: gtkmm manage/add vs smart pointers:


问:
Scrum: relaxing "done" or using spikes?
Consider what it takes to completely finish a story in our organization.

Demo requirements were met

UI design finalized (layout, styles, fonts, controls, colors, etc...)

User text finalized and mistake-proofed

All text translated to Spanish, Germal, Italian and French.

User manual updated

All bugs deemed by PO as need fixing for release were fixed

Documents for FDA updated (SRS,STD,STP,STM,UFMEA, DFMEA, SDD, installation)

Requirements were written and approved by PO

UI spec was written and approved by PO

All tests (final acceptance and integration) written/updated and executed - synced and agreed with test manager

All FAT tests were approved by QPE

Regression testing was done

Code was reviewed and documented

Unit tests were written and executed - synced and agreed with software manager.

Refactoring, if needed, was done - synced and agreed with software architect.

Design was documented

Installer was updated (If needed)

With so much work needed to fully complete a story, the team stops being nimble and it becomes more difficult to try out new features quickly.

As far as I see there are 3 ways to solve this problem:

Do more "Spike" stories which don't meet the "Done" definition but serve as quick prototypes to gather feedback from users.

Get feedback from users all the time during the Sprint rather than at the end of it. So half-way through the story you could already gauge what users think of the story and quickly adapt before doing all the heavy stuff (translations, user manual and such).

Relaxing the "Done" definition to require just basic testing and bug fixing. This way the team won't have a potentially shippable product at the end of the Sprint, but it will be very quick to try new features and technical innovations without suffering from the burden of documenting everything, writing user manual, doing design polishes, etc...

Which option would you pick and why?

Thank you.

答:
First of all, I would try to move some of the items from your "definition of done" to the "definition of ready". The definition of ready determines when a story is in a sufficient state to be implemented by the developers.

The items I would try to move to the "definition of ready" are:

Requirements were written and approved by PO

UI spec was written and approved by PO

these items typically involve a sequence of back-and-forth discussions between the PO, stakeholders and the team and give the story shape. For that reason, they should be done before the team can pick up the story for implementation.

After that, option 2 seems the best to me. One of the basic ideas behind agile (and scrum) is that you should be in close collaboration with (representatives of) the client and users, so you can easily align the idea of the team what they need to make with the actual needs/wants of the client. The demonstration at then end of a sprint in scrum is a regularly recurring milestone at which the team can show the world what they have accomplished, but there is no reason why you can't ask feedback during a sprint.

If there are regular discussions what form the new features should take, then you could consider introducing a special "proof of concept" type of story that has a relaxed definition of done and that can be utilized by the PO to get a feel for how a feature would work out. Such stories should be implemented on a separate branch to ensure they will not be included in an eventual release.
To emphasize, it is a decision of the Product Owner if a particular story is a regular story or a "proof of concept" story.

Title: Scrum: relaxing "done" or using spikes?


问:
What should and what shouldn't be in a header file?

What things should absolutely always/never be included in a header file?

Functions: what must go in the header file and what mustn't

Constants: Is it good practice to define lot of constants in a header file?

Any other good practices for C header files?

Example

I'm writing a parser for a documented industry standard format that has a lots of constants, is it a good practice to define them in a header file?

答: Statements that generate data and code as they are parsed, should not be in a .h file. As far as my point of view is concerned, a header file should only have the minimum practical interface to a corresponding .c or .cpp.

ContentLicense: CC BY-SA 4.0


答:
I can't judge, but it seems to me that your definition of done is fairly unrealistic. Of course, it's up to your organization, but I would first consider if you need, for example, localization, before delivery, after all, only one language is used at a time. Maybe it's really necessary though!

So - after I have made sure there's no value without all those conditions, and assuming the list is still valid - I'd take one of these two ideas:

Reduce the scope of each story so it fits in an iteration and make the team do multiple stories by parallelizing. In other words, maximum elapsed time must be one iteration, however more than one story can be played concurrently.

Remove a set of constraints which only apply to the actual deployment (e.g. user manuals?) so the team can be quicker, then add a "release" sprint every so often, when you actually release. Not very agile, but possibly something you need to do.

More in general: adopting an agile process is highlighting a risk factor in the way your organization works. This is quite a common occurrence and, in my opinion, is a desirable trait of agile methodologies. In particular, there seem to be a very large amount of ceremony. I would start by investigating why that can't be reduced massively first, more than trying to fit the methodology to your situation. Have you considered asking the team to help you (e.g. in a retrospective?)

Title: Scrum: relaxing "done" or using spikes?

Body:
Consider what it takes to completely finish a story in our organization.

Demo requirements were met

UI design finalized (layout, styles, fonts, controls, colors, etc...)

User text finalized and mistake-proofed

All text translated to Spanish, Germal, Italian and French.

User manual updated

All bugs deemed by PO as need fixing for release were fixed

Documents for FDA updated (SRS,STD,STP,STM,UFMEA, DFMEA, SDD, installation)

Requirements were written and approved by PO

UI spec was written and approved by PO

All tests (final acceptance and integration) written/updated and executed - synced and agreed with test manager

All FAT tests were approved by QPE

Regression testing was done

Code was reviewed and documented

Unit tests were written and executed - synced and agreed with software manager.

Refactoring, if needed, was done - synced and agreed with software architect.

Design was documented

Installer was updated (If needed)

With so much work needed to fully complete a story, the team stops being nimble and it becomes more difficult to try out new features quickly.

As far as I see there are 3 ways to solve this problem:

Do more "Spike" stories which don't meet the "Done" definition but serve as quick prototypes to gather feedback from users.

Get feedback from users all the time during the Sprint rather than at the end of it. So half-way through the story you could already gauge what users think of the story and quickly adapt before doing all the heavy stuff (translations, user manual and such).

Relaxing the "Done" definition to require just basic testing and bug fixing. This way the team won't have a potentially shippable product at the end of the Sprint, but it will be very quick to try new features and technical innovations without suffering from the burden of documenting everything, writing user manual, doing design polishes, etc...

Which option would you pick and why?

Thank you.