问:
How name class which display data?
Houston, we have a problem. I can't think of a simple class name. I have abstract class, something like that:

```<code>public abstract class DataDisplay {
    public abstract void dataDisplay(Data data);
}
</code>```

This class only displays data in some way: paint it to canvas, send SMS, send bytes through socket, etc.

答:
It seems like it should be an interface, not an abstract class.

It is too generic if it can do anything from printing to console to sending your data to space. You may end up violating single responsibility principle in your implementations.

If still you think it's OK, I'd say it is a Representer since it deals with some Data type and presents it in a different ways, i.e. represents what is present as Data. I have no deep enough knowledge of English, but it seems reasonable.

Title: How name class which display data?


问:
Does it make sense to express reliability as a ratio of number of tests and system failures?
I have seen a reliability of the system expressed like this:

Rel=No of tests executed / Sum of crashes or other critical events

Does it make sense and what actually is the output?

答:
No. That metric displays a fundamental misunderstanding of both testing and reliability.

Testing can only ever prove the presence of bugs, but never the absence. A test suite demonstrates that a system is capable of functioning as expected (incl. known failure modes), but except in the most simplest cases can never prove that it will always work as designed. The size of a test suite is absolutely irrelevant. Larger test suites are not necessarily better, they could simply be a symptom of high system complexity. A small test suite could just mean that nobody bothered to write many tests.

A test suite with good coverage does translate into better reliability, because problems are found (and can be fixed) before the system is deployed. However, this requires good coverage (not only a large number of tests), and that somebody is actually fixing the problems. It is entirely possible to write a very large test suite with very little coverage, e.g. when only testing one specific subsystem, but leaving other subsystems untested.

Reliability is usually defined as the probability or frequency of failures, when using a system in a specified environment. If over a period of time T we observe n failures, then our reliability expressed as a frequency is roughly r = n/T. The number of tests is not a parameter here. However, it is possible to test reliability by replicating the specified environment and running the system there. After multiple runs, it can be decided with a certain confidence whether the system meets the reliability requirement. Unfortunately, this strategy is nearly worthless for testing deterministic programs, because programs don't have wear and tear.

Examples why the formula reliability = test suite size / number of failures won't work:

Let the systems A and B be identical, with the same test suite size (= 42). We expect the same reliability. We now let A run for two days, and observe three failures. We end up with a reliability of 42/3 = 14. Then we run B for two minutes, and observe one failure. We end up with a reliability of 42/1 = 42.

Despite A and B being identical, we end up with different reliability metrics because the formula is not time-dependent.

Let system A be a simple system with a single test, and B a complex system with 1000 tests. We run both for the same amount of time, and observe one failure each. Therefore, A has the reliability index 1, whereas B has the reliability index 1000. Is B 1000 times more reliable than A? That's unlikely, considering that B probably has many more undetected failure modes.

ContentLicense: CC BY-SA 3.0


问:
how to carry a specific number of significant figures while computing?
How to carry more or less than six significant figures (4 , 5 , 7.. ) in the computation while running a program ?
i'm writing a program to solve a system of linear equations /using Gauss elimination method in the following example / . and i want to consider the relative errors happening , in this example , the result is very sensitive to the number of significant figures carried in the computation .

答:
You want to look into Arbitrary Precision Arithmetic.

In computer science, arbitrary-precision arithmetic, ... , indicates that calculations are performed on numbers whose digits of precision are limited only by the available memory of the host system.

Using arbitrary precision should allow you to specify enough significant digits to resolve the calculation you're having problems with.

And have a look at this SO answer for additional guidance on how to do that within C#.


问:
how to implement idempotent webservice calls
I'm developing a wcf based solution for a webservice layer that "occasionally-connected" mobile devices will be using.  The service will not be using queuing (at this stage) due to the additional complexities, and so it will instead be operating a simple Request / Response approach.

Of course, being a mobile device, it is possible that the devices may go out of signal mid insert / update.  The webservice itself may have completed the transaction, but the client will never receive this message.  Due to this, it will resend the request up, at which point the server needs to recognise this as a duplicate request, and return the same response that it tried on the first instance.

Hence I am trying to make the services Idempotent.  In order to achieve this, I am implementing Request Paramter DTO objects, which consist of the RequestID, plus the parameters needed to complete the call.

However, my difficulty is in implementing a way of monitoring the request ids.  SInce the service is currently stateless, the only way I can currently envision is to have a ServiceRequest table in the database, which will take the RequestID as a primary.  Obviously querying on this will indicate whether the request has already been actioned, as the client will be sending up the same RequestID. But the service also needs to know what message to send back.  In the case of an insert/update, the affected aggregate root id will also need to be stored somewhere, whether directly on the request table, or in a RequestToObjectLookup table

So, I'm wondering if there is a best practice way of implementing this? My thoughts are to have a ServiceRequest table(s) (specific to service), that stores requestids, additional info, and also a lookup to the result object id (on a save/insert/update). So when a new request comes in, this table can be consulted first before proceeding with the rest of the request, whether that be to perform the save, or just return the previously updated object (that was actioned on the first request attempt).

I'm also thinking (as stated) that I only need to keep the root aggregate id referenced with the request, as I should just be able to use relationships to attain the rest of the info.

答:
Deletion can be made idempotent by only allowing deletion based on IDs. You will need to have some way for IDs to remain "in use" and maybe expire.

With such a reservation system; creating an object can be done by first reserving an ID and then a second call to create the object with that ID (essentially an update on the new empty object). When an ID is requested the server will grab any free ID and create an uninitialized object with that ID, the second call to initialize will include the previously returned ID (plus all data required). This means that the second call is in essence an update call that is idem potent in itself (calling it with the same data multiple times will result the same result).

If reservation happens multiple times then multiple IDs are returned and initialized object will remain. These uninitialized object can be cleaned up by a rhoomba after some time automatically.

This put the onus on the client to ensure that if they do get a ID then they are responsible for calling the initialize. If the client falls off mid transaction it should keep its own log for the operations so it knows for example that he got a ID and was busy with initializing the object.

Update is more difficult to make idempotent but a compare-and-set operation (with true/false result) will help.


问:
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.

答:
[computer-time element]

 Does Refactoring towards Looser Coupling and Smaller Functions affect Speed of Code?

Yes, it does.  But it is up to interpreters, compilers, and JIT-compilers to strip down this "seam/wiring" code, and some do it better than others, but some don't.

Multiple-file concern adds to I/O overhead, so that affects speed quite a bit as well (in computer-time).

[human-speed element]

  (And should I care?)

no you shouldn't care.  Computers and circuits are plenty fast these days, and other factors take over, such as network latency, database I/O, and caching.

So 2x - 4x slow down in the native code execution itself will often get drowned out by those other factors.

As far as multiple-file loading, that is often being taken care of by various caching solutions. It may take more time to load things up and merge them up the first time, but for every next time, for static files, caching does work as if a single file is being loaded.  Caching comes as a solution to multiple-file loading.


问:
How can I get better than O(N^2) space complexity for a type sequence search?
Suppose I have a type sequence through which I want to search:

```<code>template <typename...> struct TypeSequence { using type = TypeSequence; };
</code>```

I want to create a metafunction Search that returns true if a given type exists in my type sequence, or false otherwise, and I want it to have better than O(N^2) space-complexity!

Currently I basically have to iterate through each element and create a true_type if the first element matches, or continue with 1 of the types truncated until I reach the end.

In C++ that looks something like this:

```<code>template <typename Enable, typename Type, typename... T>
struct SearchImpl;

// empty type sequence
template <typename Type>
struct SearchImpl<void, Type> : std::false_type
{
};

// first element matches
template <typename Type, typename T1, typename... T>
struct SearchImpl<
    typename std::enable_if<std::is_same<Type, T1>::value>::type,
    Type, T1, T...>
:
    std::true_type
{
};

// first element doesn't match
template <typename Type, typename T1, typename... T>
struct SearchImpl<
    typename std::enable_if<!std::is_same<Type, T1>::value>::type,
    Type, T1, T...>
:
    SearchImpl<void, Type, T...>
{
};

// check if a type exists within a type list
template <typename TypeList, typename T>
struct Search;

template <template <typename...> class TypeList, typename T, typename... Types>
struct Search<TypeList<Types...>, T>
:
    SearchImpl<void, T, Types...>
{
};
</code>```

For a type sequence of length N with the matching type located at N/2, this search operation creates N/2 unique types with a length of order N each, equating to something in the order of O(N^2) space complexity at compile time.

Is there a way of performing such a search with lower complexity?

The following would be very cheap, but is illegal because it requires a variadic pack not at the end of the argument list:

```<code>template <typename T, typename... Types>
struct Has : std::false_type
{
};

template <typename T, typename... T1, typename... T2>
struct Has<T, T1..., T, T2...> : std::true_type // illegal!
{
};
</code>```

How can I better frame a solution to this problem to reduce the space-complexity (ie. number of types instantiated). I know I can reduce it by simply searching through larger blocks, but this doesn't reduce the complexity itself (ie. it doesn't scale well).

The answer can be in pseudo-code, as long as it writable in c++ template code.

答:
The basic trick here is from a blog post describing an implementation of std::tuple. We are limited in our options for variadic template arguments, but we can use them to define the base classes for a class.

```<code>template<typename T, typename... Haystack>
struct SearchImpl : std::is_same<T, Haystack>...
{
};
</code>```

This class inherits from std::true_type for each matching type and std::false_type for each non-matching type. Thus all we need to do is determine whether it inherits from std::true_type.

```<code>template<typename T, typename... Haystack>
struct Search : std::is_base_of<std::true_type, SearchImpl<T, Haystack...>>::type
{
};
</code>```

Body:
The basic trick here is from a blog post describing an implementation of std::tuple. We are limited in our options for variadic template arguments, but we can use them to define the base classes for a class.

template<typename T, typename... Haystack>
struct SearchImpl : std::is_same<T, Haystack>...
{
};

This class inherits from std::true_type for each matching type and std::false_type for each non-matching type. Thus all we need to do is determine whether it inherits from std::true_type.

template<typename T, typename... Haystack>
struct Search : std::is_base_of<std::true_type, SearchImpl<T, Haystack...>>::type
{
};


问:
In which of the following tree traversal all the child nodes are visited first before the parent node
In an n-ary tree...

Given a reference to some child node

And a reference to a distant parent of the referenced child node

Is there a method that a parent node can use to figure out which of its children is closest to the referenced child node and has a big-oh that's less than O(number of edges between parent and child)

Picture to illustrate my question:

```<code>              A
              |
              |
              B
             / \
            /   \
           C     D <-- distant parent
                /|\
               / | \
              E  F  G  <-- which child?
             /|  |\  \
            / |  | \  \
           H  I  J  K  L
          /  /|    /|\
         /  / |   / | \
        M  N  O  P  Q  R
              ^     |
              |     |
That child node     S
</code>```

(original image)

Things I've tried:

Iterating up the tree (O(n)), from "that child node" until the parent is found, and returning the previously visited node. This is when I noticed that my program spent too much time iterating up the tree, and could use some kind of improvement.

Have each node save a reference to every single parent it had in an array, and the index used is the number of edges between the node in the array, and the root node.

Example: "that child node" will have an array of size 5, and its immediate parent would be at index 4, and the root, index 0.

Advantage: this makes finding the node to return very quick (O(1)) because, the level (number of edges between the node, and the root node) + 1 of the parent node, will give me the index in the array in "that child node" of the node that I want to return.

Disadvantage: adding nodes to the tree becomes very expensive in memory, and computational time especially if the node is very far from the root node. expensive in memory, because it will have a huge array, and computational time because the array needs to be populated, weather it be populated by tree traversal, or copying the array from it's parent, it can take a while...

Like above, except, instead of saving references to every node, it saves log2(level) node references to nodes, in a log2() like way

Example: a node at level 1000000 would have 20 references to parent nodes. these references would be to a parent at each of the following levels: 500000, 750000, 875000, 937500, 968750 ... 999999.

Advantage: finds the node to return in O(log2(n)) to O(n), not as fast as solution above, but fast enough. much more memory efficient than above solution, but still pretty bad.

Disadvantage: still quite expensive to add new nodes to the tree in computational time, but not that bad.

I can think of variations of the above 3rd method to make things slightly more memory efficient, and time efficient, but I'm wondering if there is a method that takes O(1) time to find the solution to this problem that I am not seeing ... something like the binary search tree property, but for an n-ary tree.

The binary search tree property is desirable, because given a child node, the parent can make a step towards it, regardless of the number of edges between the given child node, and the parent.

I don't mind putting an extra index or ID or whatever data into the child node to make the method possible.

答:
I can think of a variety of possible solutions, but they all involve a high memory overhead.

Let k be the number of candidate parent nodes, ℓ the level of the distant child node (i.e. the distance from the root), c the child node, and p the candidate parent node(s).

O(k) – Store directions to each node

Each node has an ordered array of IDs (e.g. pointers) of all ancestors. This array can be understood as the directions from the root to that node. To test whether a node p is parent of another node n, we simply compare the ID at the appropriate level:

```<code>fun is_parent(c: Node, p: Node): Bool =
  c.directions[p.directions.length - 1] == p.id
</code>```

Advantages: pretty compact storage.

Disadvantages: Inserting nodes is pretty expensive because their directions have to be updated.

O(k) to O(k log ℓ) – Store sets of all ancestors

This is a variant of the above solution, but using just some kind of set (or a list ordered by ID rather than by level). Depending on how that set is implemented, algorithmic complexity of the lookup differs.

```<code>fun is_parent(c: Node, p: Node): Bool =
  c.ancestors.contains(p.id)
</code>```

This shares the same advantages and disadvantages as the previous solution.

O(k log ℓc), worst case O(k ℓ) – Skip Lists

This is a variant of the first solution, but with much less memory overhead.

A skip list is a linked list that contains not only a pointer to the next element, but also to more distant elements. This allows O(log n) search in an ordered skip list, similar to a binary search in an array. Skip lists can also be used for efficient indexing in linked lists, which is what we'll do here. Our “index” is actually the relative level of a node.

In our case, each child contains at least one link to the immediate parents, but possibly also to other ancestors. A link is a pair of a pointer to the target node and of an integer that tells us how many levels this link advances.

```<code>data Link(distance: Int, target: Node)

fun is_parent(c: Node, p: Node): Bool = {
  val skip_length = p.level - c.level
  if (skip_length <= 0)
    return c.id == p.id
  // Node.links stores links sorted in descending distance
  val link = c.links.first(link => link.distance <= skip_length)
  return is_parent(link.target, p)
}
</code>```

Advantages: uses less memory than the other solutions.

Disadvantage: has O(n) worst case (when the skip list degrades to a simple linked list). This can be avoided by re-threading the skip list upon insertion.

ContentLicense: CC BY-SA 4.0

Body:
I can think of a variety of possible solutions, but they all involve a high memory overhead.

Let k be the number of candidate parent nodes, ℓ the level of the distant child node (i.e. the distance from the root), c the child node, and p the candidate parent node(s).

O(k) – Store directions to each node

Each node has an ordered array of IDs (e.g. pointers) of all ancestors. This array can be understood as the directions from the root to that node. To test whether a node p is parent of another node n, we simply compare the ID at the appropriate level:

fun is_parent(c: Node, p: Node): Bool =
  c.directions[p.directions.length - 1] == p.id

Advantages: pretty compact storage.

Disadvantages: Inserting nodes is pretty expensive because their directions have to be updated.

O(k) to O(k log ℓ) – Store sets of all ancestors

This is a variant of the above solution, but using just some kind of set (or a list ordered by ID rather than by level). Depending on how that set is implemented, algorithmic complexity of the lookup differs.

fun is_parent(c: Node, p: Node): Bool =
  c.ancestors.contains(p.id)

This shares the same advantages and disadvantages as the previous solution.

O(k log ℓc), worst case O(k ℓ) – Skip Lists

This is a variant of the first solution, but with much less memory overhead.

A skip list is a linked list that contains not only a pointer to the next element, but also to more distant elements. This allows O(log n) search in an ordered skip list, similar to a binary search in an array. Skip lists can also be used for efficient indexing in linked lists, which is what we'll do here. Our “index” is actually the relative level of a node.

In our case, each child contains at least one link to the immediate parents, but possibly also to other ancestors. A link is a pair of a pointer to the target node and of an integer that tells us how many levels this link advances.

data Link(distance: Int, target: Node)

fun is_parent(c: Node, p: Node): Bool = {
  val skip_length = p.level - c.level
  if (skip_length <= 0)
    return c.id == p.id
  // Node.links stores links sorted in descending distance
  val link = c.links.first(link => link.distance <= skip_length)
  return is_parent(link.target, p)
}

Advantages: uses less memory than the other solutions.

Disadvantage: has O(n) worst case (when the skip list degrades to a simple linked list). This can be avoided by re-threading the skip list upon insertion.


答:
My question is this: when it call comes down to machine code, to 1s
  and 0s, to assembly instructions, should I be at all concerned that my
  class-separated code with variety of small-to-tiny functions generates
  too much extra overhead?

MY answer is yes, you should. Not because you have lots of little functions (once upon a time the overhead of calling functions was reasonably significant and you could slow your program down by making a million little calls in loops, but today compilers will inline them for you and what's left is taken care of by the CPU fancy prediction algorithms, so don't worry about that) but because you will introduce the concept of layering too much into your programs when the functionality is too small to sensibly grok in your head. If you have larger components you can be reasonably sure they are not performing the same work over and over, but you can make your program so minutely granular that you may find yourself unable to really understand the call paths, and in that end up with something that barely works (and is barely maintainable).

For example, I worked at a place that showed me a reference project for a web service with 1 method. The project comprised 32 .cs files - for a single web service! I figured this was way too much complexity, even though each part was tiny and easily understood by itself, when it came to describing the overall system, I quickly found myself having to trace through calls just to see what the hell it was doing (there were also too many abstractions involved,as you'd expect). My replacement webservice was 4 .cs files.

i didn't measure performance as I figure it would have been roughly the same all in all, but I can guarantee mine was significantly cheaper to maintain. When everyone talks of programmer time being more important than CPU time, then create complex monsters that cost lots of programmer time in both dev and maintenance you have to wonder that they are making excuses for bad behaviour.

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.

That is what CPUs do though, they move bits from memory to registers, add or subtract them, and then put them back into memory. All computing boils down to pretty much that. Mind you, I once had a very multi-threaded program that spent most of its time context switching (ie saving and restoring register state of threads) than it did working on the thread code. A simple lock in the wrong place truly screwed performance there, and it was such an innocuous bit of code too.

So my advice is : find a sensible middle ground between either extreme that make your code look good to other humans, and test the system to see if it performs well. Use the OS features to make sure its running as you'd expect with CPU, memory, disk and network IO.

Title: Did the gradual shift in methodology of writing code affect system performance? And Should I care?

Body:
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.


问:
How common is prototyping as the first stage of development?
I've been taking some software design courses in the past few semesters, and while I see the benefit in a lot of the formalism, I feel like it doesn't tell me anything about the program itself:

You can't tell how the program is going to operate from the Use Case spec, even though it discusses what the program can do.

You can't tell anything about the user experience from the requirements document, even though it can include quality requirements.

Sequence diagrams are a good description of how the software works as the call stack, but are very limited, and give a highly partial view of the overall system.

Class diagrams are great for describing how the system is built, but are utterly useless in helping you figure out what the software needs to be.

Where in all this formalism is the bottom line: how the program looks, operates, and what experience it gives? Doesn't it make more sense to design off of that? Isn't it better to figure out how the program should work via a prototype and strive to implement it for real?

I know that I'm probably suffering from being taught engineering by theoreticians, but I need to ask, do they do this in the industry? How do people figure out what the program actually is, not what it should conform to? Do people prototype a lot, or do they mostly use the formal tools like UML and I just didn't get the hang of using them yet?

答:
there are two kinds of prototyping - three, actually:

we build prototypes to refine the design and reduce risks before starting the "real" coding (Engineering)

we build the project as a series of refined prototypes (Agile)

we build a prototype and ship it as soon as it works (Cowboy)

ContentLicense: CC BY-SA 2.5


答:
If you want to determine the relative or absolute errors for a computation which is too complex to be estimated manually, you could try using interval arithmetic. This approach will help you to trace the error in each of your variables throughout the calculation process. Of course, you will typically have to implement something like Gauss elimination by yourself, since it will be unlikely to find a ready-made implementation using interval arithmetic for your requirements.

Try googling for "interval arithmetic [you favorite language]" to find a suitable library.

Title: how to carry a specific number of significant figures while computing?

Body:
How to carry more or less than six significant figures (4 , 5 , 7.. ) in the computation while running a program ?
i'm writing a program to solve a system of linear equations /using Gauss elimination method in the following example / . and i want to consider the relative errors happening , in this example , the result is very sensitive to the number of significant figures carried in the computation .


答:
Starting from Winston Ewart's answer, I figured out something that still uses only O(n) type instantiations, but also works when you have duplicate types in your parameter pack

```<code>// we want to get a different size if the types match
template <typename A, typename B> struct Same { char padding[3]; };
template <typename A> struct Same<A,A> { char padding[7]; };
template <typename T> struct Diff: public Same<int,bool> {};

#include <cstddef>
constexpr std::size_t SameSize = sizeof(Same<bool,bool>);       // size if really same
constexpr std::size_t DiffSize = SameSize - sizeof(Diff<bool>); // difference in size

// we instantiate only two flat tuples, hence O(n)
#include <tuple>
template <typename Needle, typename... Haystack>
struct SearchImpl {
    typedef std::tuple<Same<Needle,Haystack>...> SameTypes; // some may be matches
    typedef std::tuple<Diff<Haystack>...> DiffTypes;        // none will be matches

    static constexpr size_t matches = (sizeof(SameTypes)-sizeof(DiffTypes)) / DiffSize;
    static constexpr bool result = (matches > 0);
};

template <typename Needle, typename... Haystack>
struct Search: public std::integral_constant<bool, SearchImpl<Needle,Haystack...>::result>
{};
</code>```

Note that the tuple can't compress the members (they're never empty), so the size calc is correct and you get the number of matches as a bonus.

Title: How can I get better than O(N^2) space complexity for a type sequence search?

Body:
Suppose I have a type sequence through which I want to search:

```<code>template <typename...> struct TypeSequence { using type = TypeSequence; };
</code>```

I want to create a metafunction Search that returns true if a given type exists in my type sequence, or false otherwise, and I want it to have better than O(N^2) space-complexity!

Currently I basically have to iterate through each element and create a true_type if the first element matches, or continue with 1 of the types truncated until I reach the end.

In C++ that looks something like this:

```<code>template <typename Enable, typename Type, typename... T>
struct SearchImpl;

// empty type sequence
template <typename Type>
struct SearchImpl<void, Type> : std::false_type
{
};

// first element matches
template <typename Type, typename T1, typename... T>
struct SearchImpl<
    typename std::enable_if<std::is_same<Type, T1>::value>::type,
    Type, T1, T...>
:
    std::true_type
{
};

// first element doesn't match
template <typename Type, typename T1, typename... T>
struct SearchImpl<
    typename std::enable_if<!std::is_same<Type, T1>::value>::type,
    Type, T1, T...>
:
    SearchImpl<void, Type, T...>
{
};

// check if a type exists within a type list
template <typename TypeList, typename T>
struct Search;

template <template <typename...> class TypeList, typename T, typename... Types>
struct Search<TypeList<Types...>, T>
:
    SearchImpl<void, T, Types...>
{
};
</code>```

For a type sequence of length N with the matching type located at N/2, this search operation creates N/2 unique types with a length of order N each, equating to something in the order of O(N^2) space complexity at compile time.

Is there a way of performing such a search with lower complexity?

The following would be very cheap, but is illegal because it requires a variadic pack not at the end of the argument list:

```<code>template <typename T, typename... Types>
struct Has : std::false_type
{
};

template <typename T, typename... T1, typename... T2>
struct Has<T, T1..., T, T2...> : std::true_type // illegal!
{
};
</code>```

How can I better frame a solution to this problem to reduce the space-complexity (ie. number of types instantiated). I know I can reduce it by simply searching through larger blocks, but this doesn't reduce the complexity itself (ie. it doesn't scale well).

The answer can be in pseudo-code, as long as it writable in c++ template code.

Body:
Starting from Winston Ewart's answer, I figured out something that still uses only O(n) type instantiations, but also works when you have duplicate types in your parameter pack

// we want to get a different size if the types match
template <typename A, typename B> struct Same { char padding[3]; };
template <typename A> struct Same<A,A> { char padding[7]; };
template <typename T> struct Diff: public Same<int,bool> {};

#include <cstddef>
constexpr std::size_t SameSize = sizeof(Same<bool,bool>);       // size if really same
constexpr std::size_t DiffSize = SameSize - sizeof(Diff<bool>); // difference in size

// we instantiate only two flat tuples, hence O(n)
#include <tuple>
template <typename Needle, typename... Haystack>
struct SearchImpl {
    typedef std::tuple<Same<Needle,Haystack>...> SameTypes; // some may be matches
    typedef std::tuple<Diff<Haystack>...> DiffTypes;        // none will be matches

    static constexpr size_t matches = (sizeof(SameTypes)-sizeof(DiffTypes)) / DiffSize;
    static constexpr bool result = (matches > 0);
};

template <typename Needle, typename... Haystack>
struct Search: public std::integral_constant<bool, SearchImpl<Needle,Haystack...>::result>
{};

Note that the tuple can't compress the members (they're never empty), so the size calc is correct and you get the number of matches as a bonus.


问:
Publishing: Hows and Whos of Peer Reviews
So, I'm sitting here, chewing on a couple of novel data structures.  I'm thinking of coding them up, but I'ven't got any professional use for them at the moment.  Nonetheless, they solve interesting problems, and deserve reference implementations.  So, I'd like to publish them, ideally in a peer-reviewed journal, so there's at least an off-chance someone will run into them and get some use out of it.

But I can't for the life of me figure out how I'd even start to go about such a process, and none of my old professors seem to be in a position to help.  Can I get a primer on how to go about getting something published in a moderately reputable journal?

答:
research the market; see if it's been done before, and how your ideas are different. Part of this research will help you figure out what journals may be interested in the topic, based on similar things they've published in the past. Citeseerx is an awesome academic journal search tool.

if the project is still a go, write the paper in the style of the journal you've selected to target

send it to them

wait

edit as directed

???

Profit!


问:
Advantages of storing dependencies in repository management system vs. just VC
I just started a new job as a developer in an organizational unit which is responsible for development and maintenance of several small Java applications.  Just like most other Java apps out there, they use numerous dependency libraries.

In my previous job, we used Artifactory for dependency management and our Maven build infrastructure was picking up jars from there.  In this new job, they don't use a repository management system like Artifactory and all the dependency jars (on average 20-30 per application project) are actually checked into our Git repo.

I would like to see some feedback on the advantages of using a repo management system vs. simply putting your binary dependencies in VC.

See also:  Using Subversion as an artifact repository vs a specific artifact management tool

答:
Artifactory (and other Enterprise package managers) gives centralized control of which packages are used within a corporate development environment. For instance, if I want to avoid using say 4.3 of a given package, I can exclude it from my internal repository.

Also, it allows the company to make internally reusable packages available to other teams without exposing it to the public.

These are the primary advantages of using an enterprise repository over just checking dependencies into source control.


问:
Time limit on user input
I am trying to put a time limit on the user input, so if they take longer than 2 seconds to put type in an input then the program will terminate. I was wondering if there is a simple way to do this in C language?</p>

答: You can just use alarm() before calling the input functtion and write a signal handler for SIGALRM and terinate your program in the signal handler.</p>

Title: Time limit on user input


答:
What you are looking for is called the spec - you can read a description of that here in one of Joel's articles

http://www.joelonsoftware.com/articles/fog0000000035.html

Title: How common is prototyping as the first stage of development?

Body:
I've been taking some software design courses in the past few semesters, and while I see the benefit in a lot of the formalism, I feel like it doesn't tell me anything about the program itself:

You can't tell how the program is going to operate from the Use Case spec, even though it discusses what the program can do.

You can't tell anything about the user experience from the requirements document, even though it can include quality requirements.

Sequence diagrams are a good description of how the software works as the call stack, but are very limited, and give a highly partial view of the overall system.

Class diagrams are great for describing how the system is built, but are utterly useless in helping you figure out what the software needs to be.

Where in all this formalism is the bottom line: how the program looks, operates, and what experience it gives? Doesn't it make more sense to design off of that? Isn't it better to figure out how the program should work via a prototype and strive to implement it for real?

I know that I'm probably suffering from being taught engineering by theoreticians, but I need to ask, do they do this in the industry? How do people figure out what the program actually is, not what it should conform to? Do people prototype a lot, or do they mostly use the formal tools like UML and I just didn't get the hang of using them yet?


问:
Architecture - 3D Modeling Library
I'm writing a library to allow users to generate 3D models programatically.

User writes code (e.g. Square(4))

User views preview of 3D model (with built in visualizer)

User can "print" the model to a .obj file that can be read by other 3D modeling programs and visualizers

What is a good way to architect the data objects and the above functionality?

Lets assume a Square object subclasses a Polygon class.

A Polygon would have

vertices

a face

a transformation/translation

Eventually, I need to be able to print this polygon to the screen.  Some part of my program will need to know how render it using a graphics library that I will use.  However I don't want to add this functionality as part of the Polygon class because I would like the Polygon class to only have to worry about pure geometric considerations, not details of graphics libraries.  So, I could just create a Renderer object that can take Polygons and Circles and Curves and inspect them and then decide how to display them, but that didn't seem very Object Oriented.

So to summarize, I want to have

a bunch of different types of geometric objects (Polygons, Circles, Curves, etc)

a few different ways to "print" the objects (display to screen, write to file, etc)

And I'm not sure where to put all of this functionality so that it is well encapsulated, easy to maintain, and extensible.

答:
Visitor Pattern

Comedically, and with good fortune, I found the above Wikipedia article that precisely describes my situation (what are the odds?).

Consider the design of a 2D CAD system. At its core there are several types to represent basic geometric shapes like circles, lines and arcs...
  one could apply the Visitor pattern. The Visitor pattern encodes a logical operation on the whole hierarchy into a single class containing one method per type.

Title: Architecture - 3D Modeling Library


问:
What's the difference between "use case", "User Story" and "Usage Scenario"?
Is there an exact, but simple and understandable defintion of the distinction between "use case",  "User Story" and "Usage Scenario"?

there are quite a bunch of explanation, but right now, I see no one that explains the differences in a single sentence, or two...

(e.g. http://c2.com/cgi-bin/wiki?UserStoryAndUseCaseComparison very long and hard to get, full of discussion)

答:
"Use case" and "user story" are the same in the sense that they represent "requirements" of customer.

Use case is the way the system is used in each case, normally represented as an interaction between actor and system or between systems.

User story is the starting point in the journey to create a computer aided tool that will enable end-user to get something done, and normally begins with a simple sentence using who, what, why ("As a user closing the application, I want to be prompted to save anything that has changed since the last save so that I can preserve useful work and discard erroneous work."). That user story then needs to be cultivated into a use case that developers employ to build an application, and testers to conduct testing.

From the perspective of a QA Tester, they're not testing "user stories", but rather "use cases",  meaning they're testing software functionalities.

OwnerDisplayName: Henning


答: I can't think of a moderately reputable journal of programming science, the web seems to be the primary communication channel for such stuff. For peer review, you could for instance post your idea on Stack Overflow, you won't find a lot of other places with more qualified peers ready to burn their time.</p>

Title: Publishing: Hows and Whos of Peer Reviews

Body:
So, I'm sitting here, chewing on a couple of novel data structures.  I'm thinking of coding them up, but I'ven't got any professional use for them at the moment.  Nonetheless, they solve interesting problems, and deserve reference implementations.  So, I'd like to publish them, ideally in a peer-reviewed journal, so there's at least an off-chance someone will run into them and get some use out of it.

But I can't for the life of me figure out how I'd even start to go about such a process, and none of my old professors seem to be in a position to help.  Can I get a primer on how to go about getting something published in a moderately reputable journal?


问:
Min weight feedback edge set with DFS?
Exercise from The Algorithm Design Manual

6-10. [4] Let G = (V,E) be an undirected graph. A set F ⊆ E of edges
is called a feedback-edge set if every cycle of G has at least one
edge in F.

(b) Suppose that G is a weighted undirected graph with
positive edge weights. Design an efficient algorithm to find a
minimum-weight feedback-edge set.

My proposed solution for (b) is to run DFS with getting max weight as the tie breaker. Then every back edge will always be the lowest weighted edge in its cycle. I'm wondering if this is a valid solution.

答:
Actually, no, a counter example:

```<code>A --10-- B -- 10 -- C
          \        /
           6     4
            \   /
              D
</code>```

DFS will go like this:

A -> B -> C -> D

And the min feedback edge of that graph will become a tree edge.

Title: Min weight feedback edge set with DFS?

Body:
Actually, no, a counter example:

A --10-- B -- 10 -- C
          \        /
           6     4
            \   /
              D

DFS will go like this:

A -> B -> C -> D

And the min feedback edge of that graph will become a tree edge.


问:
"Implementing DDD" by Vernon: value object or not?
On page 382 of this book there is a passage talking about using value objects in aggregates, under the (entity) root. There is an example of Product that, besides other values, contains a Set<ProductBacklogItem> - collection of entities.

Now, Vernon tries to explain why ProductBacklogItem is an entity and not a value object:

There are good reasons why ProductBacklogItem is modeled as an Entity rather than a Value. As discussed in Value Objects (6), since the backing database is used via Hibernate, it must model collections of Values as database entities. Reordering any one of the elements could cause a significant number, even all, of the ProductBacklogItem instances to be deleted and replaced. That would tend to cause significant overhead in the infrastructure. As an Entity, it allows the ordering attribute to be changed across any and all collection elements as often as a product owner requires. However, if we were to switch from using Hibernate with MySQL to a key-value store, we could easily change ProductBacklogItem to be a Value type instead. When using a key- value or document store, Aggregate instances are typically serialized as one value representation for storage.

I don't understand why the Repository implementation determines if some model is going to be an Entity or Value Object? If we go to the key-value store, we still may have ordering he is talking about.

Do you think this make sense?

答:
The reason is that SQL databases store the objects in a relational way - items are stored in different table than aggregate root and they reference back to aggregate root by IDs. So using of MySQL requires to model items as entities that are persisted in separate table where they obtain primary id (with auto increment).

In key-value stores eg. MongoDB one can store the whole collection of items as part of the aggregate root. The items would not become separate entities (in its on table) and thus can be modelled as value objects.

Eg. Blog has Comments stored as collection within:

```<code>{
  _id: 1,
  title: 'Some title',
  body: 'Blog body',
  comments: [{
     person: 'John Smith',
     comment: 'First comment of the blog',
     created_at: new Date()
  },
  {
     person: 'Peter Jackson',
     comment: 'Second comment of the blog',
     created_at: new Date()
  }],
}
</code>```

Body:
The reason is that SQL databases store the objects in a relational way - items are stored in different table than aggregate root and they reference back to aggregate root by IDs. So using of MySQL requires to model items as entities that are persisted in separate table where they obtain primary id (with auto increment).

In key-value stores eg. MongoDB one can store the whole collection of items as part of the aggregate root. The items would not become separate entities (in its on table) and thus can be modelled as value objects.

Eg. Blog has Comments stored as collection within:

{
  _id: 1,
  title: 'Some title',
  body: 'Blog body',
  comments: [{
     person: 'John Smith',
     comment: 'First comment of the blog',
     created_at: new Date()
  },
  {
     person: 'Peter Jackson',
     comment: 'Second comment of the blog',
     created_at: new Date()
  }],
}


问:
graph implementation in PYthon
I have found the following implementation of a Flow algorithm in Python:

```<code>class Edge(object):
    def __init__(self, u, v, w):
        self.source = u
        self.sink = v
        self.capacity = w
    def __repr__(self):
        return "%s->%s:%s" % (self.source, self.sink, self.capacity)

lass FlowNetwork(object):
    def __init__(self):
        self.adj = {}
        self.flow = {}

    def add_vertex(self, vertex):
        self.adj[vertex] = []

    def get_edges(self, v):
        return self.adj[v]

    def add_edge(self, u, v, w=0):
        if u == v:
            raise ValueError("u == v")
        edge = Edge(u,v,w)
        redge = Edge(v,u,0)
        edge.redge = redge
        redge.redge = edge
        self.adj[u].append(edge)
        self.adj[v].append(redge)
        self.flow[edge] = 0
        self.flow[redge] = 0
</code>```

Which is tested with:

```<code>>>> g = FlowNetwork()
>>> for v in "sopqrt":
>>>   g.add_vertex(v)
>>> g.add_edge('s','o',3)
>>> g.add_edge('s','p',3)
</code>```

I was wondering what exactly this part:

```<code>        edge.redge = redge
        redge.redge = edge
</code>```

does in the add_edge function; it is like a sort of "recursive" call in which an edge its receiving the value of redge into one of his atributes, but why the last line of

redge.redge=edge?

Is it putting the edge in the attribute redge of redge?

For what I know of other OOP languages, when one put a point between two items it mostly indicates an object.atribute relationship, but I do not see how this is accomplished in that section.

Thanks

答:
"redge" is reverse edge. Each edge stores the reverse of itself. Read the following code statements as the following paragraph.

```<code>edge = Edge(u,v,w)
</code>```

Create the edge in question with weight "w".

```<code>redge = Edge(v,u,0)
</code>```

Create the reverse of the edge in question with weight "0".

```<code>edge.redge = redge
</code>```

The reverse edge  of "edge" becomes "redge".

```<code>redge.redge = edge
</code>```

The reverse edge of the reverse edge is the edge in question.

With the weights, you have a "capacity" of zero on the reverse edge. Therefore, as the programmer, you can follow the graph on the reverse edge, but you simulation will have "no capacity" in that direction in your simulation.

And yes, the semantics are object.attribute in this case.

Title: graph implementation in PYthon

Body:
"redge" is reverse edge. Each edge stores the reverse of itself. Read the following code statements as the following paragraph.

edge = Edge(u,v,w)

Create the edge in question with weight "w".

redge = Edge(v,u,0)

Create the reverse of the edge in question with weight "0".

edge.redge = redge

The reverse edge  of "edge" becomes "redge".

redge.redge = edge

The reverse edge of the reverse edge is the edge in question.

With the weights, you have a "capacity" of zero on the reverse edge. Therefore, as the programmer, you can follow the graph on the reverse edge, but you simulation will have "no capacity" in that direction in your simulation.

And yes, the semantics are object.attribute in this case.


问:
Why does a custom action filter need to inherit from both ActionFilterAttribute and IActionFilter?
I m first time creating a custom action filter and following this link http://www.asp.net/mvc/overview/older-versions/hands-on-labs/aspnet-mvc-4-custom-action-filters

They are saying to Extend ActionFilterAttribute class and also implement IActionFilter interface. ActionFilterAttribute already implement IActionFilter. I  m wondering why I need to implement Interface again in my attribute class. Is is something a must to do ? Will highly appreciate if you please can clear this ambiguity.

答:
You don't need to specify the interface again since the base class already implements it, it is redundant to add it again but it shouldn't harm anything either.

I also don't know why they are explicitly implementing the interface instead of overriding the existing virtual methods which already implement the interface.


问:
Proper use of typeclasses
I'm trying Haskell's Gloss module, and I found a a pattern of things required to properly display an object: Its position, dimensions, scale and Picture representation. This seemed like a good use case of typeclasses, so I wrote this up:

```<code>class Displayable d where

    toPicture :: d -> Picture

    getDims     :: d -> (Float,Float)
    getPos      :: d -> (Float,Float)
    getScale    :: d -> Float

    setDims     :: (Float,Float) -> d -> d
    setPos      :: (Float,Float) -> d -> d
    setScale    :: Float -> d -> d

    setDims _ d     = d
    setPos _ d      = d
    setScale _ d    = d

    getDims _   = (0,0)
    getPos _    = (0,0)
    getScale _  = 0
</code>```

I've never used customs typeclasses before though, so I have some questions about their use:

First and foremost, is this situation appropriate for a typeclass?

I noticed that I need a lot of methods for this to work (I'll probably be adding get/setRotation too, so it will grow). Is this typical? Is this a sign that I'm trying to encompass too much?

Should I be defining default definitions like I have? For certain scenarios, I may not need to define a particular characteristic, but would like the object to take advantage of the rest of the class (like needing to rotate a world, or get the dimensions of a "non-physical entity"). I realize though, that if the default definitions aren't accounted for down the road, it could lead to some odd results (like objects that have a 0 scale by default, which may render them invisible).

Are getters/setters the best way to achieve what I'm trying to do (a central interface for manipulating displayable objects)?

(I know that representations of data aren't thought of as objects in Haskell, but given I'm trying to represent something visual, I thought the term object would be appropriate)

Any thoughts would be appreciated.

答:
Usually in this sort of situation, you would just create a simple data type or perhaps a record to aggregate the different fields:

```<code>data Displayable = Displayable Picture (Float,Float) (Float,Float) Float
</code>```

Type classes are for when you need polymorphic dispatch to many implementations of the same function.  That's certainly not the case for scale and position, for which you'll only have one implementation.  Dimensions might have different ways to be calculated, such as based on the natural dimensions of a bitmap, but those differences can almost certainly be accounted for at construction time.

You might have a case for making toPicture part of a type class, but that can likely be mostly handled at construction time as well, then have one function that adds the appropriate transformations on top of a base Picture just before rendering it.

Another possible data structure might be a Picture and a list of transformation functions to apply to it:

```<code>data Displayable = Displayable Picture [Picture -> Picture]
</code>```

This makes it easier to add new kinds of transformations, like rotations or even complex combinations of transforms, but makes it more difficult to do operations like reset the scale back to the default.  Perhaps you could add a String description for each transformation.  Which is the best will depend on your application.  My point in including this example is to show that using function fields can often keep you from resorting to a type class.

It's not that type classes aren't useful.  Far from it.  It's just that the situations where creating a new one is the best fit are relatively rare.  When you do need to create them, they are generally very small and almost never change.  If you're thinking you might need to add a function to a type class later, that should make you think twice about using one.

It's okay to have lots of functions to manipulate the data type in more programmer-friendly ways, but you want them to be outside of type classes, if possible.  Every time you add a function to a type class, you have to add it to every single instance.

Title: Proper use of typeclasses

Body:
Usually in this sort of situation, you would just create a simple data type or perhaps a record to aggregate the different fields:

data Displayable = Displayable Picture (Float,Float) (Float,Float) Float

Type classes are for when you need polymorphic dispatch to many implementations of the same function.  That's certainly not the case for scale and position, for which you'll only have one implementation.  Dimensions might have different ways to be calculated, such as based on the natural dimensions of a bitmap, but those differences can almost certainly be accounted for at construction time.

You might have a case for making toPicture part of a type class, but that can likely be mostly handled at construction time as well, then have one function that adds the appropriate transformations on top of a base Picture just before rendering it.

Another possible data structure might be a Picture and a list of transformation functions to apply to it:

data Displayable = Displayable Picture [Picture -> Picture]

This makes it easier to add new kinds of transformations, like rotations or even complex combinations of transforms, but makes it more difficult to do operations like reset the scale back to the default.  Perhaps you could add a String description for each transformation.  Which is the best will depend on your application.  My point in including this example is to show that using function fields can often keep you from resorting to a type class.

It's not that type classes aren't useful.  Far from it.  It's just that the situations where creating a new one is the best fit are relatively rare.  When you do need to create them, they are generally very small and almost never change.  If you're thinking you might need to add a function to a type class later, that should make you think twice about using one.

It's okay to have lots of functions to manipulate the data type in more programmer-friendly ways, but you want them to be outside of type classes, if possible.  Every time you add a function to a type class, you have to add it to every single instance.


答:
It's usually a good idea avoid type classes unless it provides a specific benefit that cannot be gained by any other means.  This article provides a somewhat extreme view on this, so take it with a grain of salt, but it can help you understand why type classes can be troublesome.

The main issue type classes operate on the type level, which means that trying to do complicated things with type classes will typically require a plethora of Haskell extensions, and sometimes even impossible.  in contrast, operating on the value level is much simpler and you don't have to fight with the type checker and type inferencer regularly.

Getters and setters have their places in Haskell, but they are primarily for maintaining interface compatibility and using them excessively will cause a lot of boilerplate.  For simple, internal data structures, they might not be worth the extra effort.

In your example, it would be much simpler to implement Displayable as an ordinary data type (as shown in Karl Bielefeldt's example), with the added benefit that you can store all your Displayables in a container without funky extensions like ExistentialTypes.  Additionally, you can make use of pattern matching (or the record syntax) to deconstruct your Displayables.

On the issue of default definitions, they should be used cautiously.  Additionally, it's probably a bad idea to write defaults that don't work on every instance.  It's not a strict guideline, but it really helps to prevent silly mistakes like forgetting to write a function for an instance: without defaults, if you forget something, the compiler will give you a warning, or at worst cause a runtime error; that's not the case if it's defaulted, and if the default behavior is wrong, then your program might end up being subtly broken.

Addendum: a "record of methods" (or "instance dictionary" as it's often called) is actually what Haskell uses to implement type classes under the rug.  Such an approach would be something like:

```<code>data Displayable d = Displayable
  { display   :: d
  , toPicture :: d -> Picture
  , getDims   :: d -> (Float, Float)
  , getPos    :: d -> (Float, Float)
  , getScale  :: d -> Float
  , setDims   :: (Float,Float) -> d -> d
  , setPos    :: (Float,Float) -> d -> d
  , setScale  :: Float -> d -> d
  }
</code>```

Any type class can be transformed into this form: this a literal translation of the type class in your question.  You probably don't want to use in this exact form though: it's best if you can figure out which parts of Displayable really needs to be abstract, and which parts you can make concrete.  Too much flexibility can make the code more complex than it needs to be.

Title: Proper use of typeclasses

Body:
I'm trying Haskell's Gloss module, and I found a a pattern of things required to properly display an object: Its position, dimensions, scale and Picture representation. This seemed like a good use case of typeclasses, so I wrote this up:

```<code>class Displayable d where

    toPicture :: d -> Picture

    getDims     :: d -> (Float,Float)
    getPos      :: d -> (Float,Float)
    getScale    :: d -> Float

    setDims     :: (Float,Float) -> d -> d
    setPos      :: (Float,Float) -> d -> d
    setScale    :: Float -> d -> d

    setDims _ d     = d
    setPos _ d      = d
    setScale _ d    = d

    getDims _   = (0,0)
    getPos _    = (0,0)
    getScale _  = 0
</code>```

I've never used customs typeclasses before though, so I have some questions about their use:

First and foremost, is this situation appropriate for a typeclass?

I noticed that I need a lot of methods for this to work (I'll probably be adding get/setRotation too, so it will grow). Is this typical? Is this a sign that I'm trying to encompass too much?

Should I be defining default definitions like I have? For certain scenarios, I may not need to define a particular characteristic, but would like the object to take advantage of the rest of the class (like needing to rotate a world, or get the dimensions of a "non-physical entity"). I realize though, that if the default definitions aren't accounted for down the road, it could lead to some odd results (like objects that have a 0 scale by default, which may render them invisible).

Are getters/setters the best way to achieve what I'm trying to do (a central interface for manipulating displayable objects)?

(I know that representations of data aren't thought of as objects in Haskell, but given I'm trying to represent something visual, I thought the term object would be appropriate)

Any thoughts would be appreciated.

Body:
It's usually a good idea avoid type classes unless it provides a specific benefit that cannot be gained by any other means.  This article provides a somewhat extreme view on this, so take it with a grain of salt, but it can help you understand why type classes can be troublesome.

The main issue type classes operate on the type level, which means that trying to do complicated things with type classes will typically require a plethora of Haskell extensions, and sometimes even impossible.  in contrast, operating on the value level is much simpler and you don't have to fight with the type checker and type inferencer regularly.

Getters and setters have their places in Haskell, but they are primarily for maintaining interface compatibility and using them excessively will cause a lot of boilerplate.  For simple, internal data structures, they might not be worth the extra effort.

In your example, it would be much simpler to implement Displayable as an ordinary data type (as shown in Karl Bielefeldt's example), with the added benefit that you can store all your Displayables in a container without funky extensions like ExistentialTypes.  Additionally, you can make use of pattern matching (or the record syntax) to deconstruct your Displayables.

On the issue of default definitions, they should be used cautiously.  Additionally, it's probably a bad idea to write defaults that don't work on every instance.  It's not a strict guideline, but it really helps to prevent silly mistakes like forgetting to write a function for an instance: without defaults, if you forget something, the compiler will give you a warning, or at worst cause a runtime error; that's not the case if it's defaulted, and if the default behavior is wrong, then your program might end up being subtly broken.

Addendum: a "record of methods" (or "instance dictionary" as it's often called) is actually what Haskell uses to implement type classes under the rug.  Such an approach would be something like:

data Displayable d = Displayable
  { display   :: d
  , toPicture :: d -> Picture
  , getDims   :: d -> (Float, Float)
  , getPos    :: d -> (Float, Float)
  , getScale  :: d -> Float
  , setDims   :: (Float,Float) -> d -> d
  , setPos    :: (Float,Float) -> d -> d
  , setScale  :: Float -> d -> d
  }

Any type class can be transformed into this form: this a literal translation of the type class in your question.  You probably don't want to use in this exact form though: it's best if you can figure out which parts of Displayable really needs to be abstract, and which parts you can make concrete.  Too much flexibility can make the code more complex than it needs to be.


问:
Can tags be used as bookmarks under semantic versioning?
Shameless plug: this question is for StackMode – a StackExchange client for GNU Emacs 24+.

The product I'm working on, version-controlled with git, is a desktop application with an innately exposed API. Naturally, we want to adopt Semantic Versioning to the best of our ability. (Hopefully, perfectly and without error.)

As I understand it, semantic versions are implemented in git as tagged commits.  This is a convenient way to see all releases of a project, etc. etc.  However, we are still fairly early on in development.  Prototype functionality was implemented and committed that did not survive review (for reasons that are irrelevant here), but the functionality will almost certainly be requested in the future. We wish to bookmark the state of the repository at that time.

Are any patterns just ignored by semantic versioning tools? What patterns are allowed as these bookmarks, or is there a better way to achieve the same goal?

答:
Especially when using git I would suggest using different branches for implementing prototype functionality (feature branches).

The review process could then be executed on the different branches and in case the new prototype will be needed later in the master branch, it can easily be merged to the main development branch.

The main versioning would still only happen by tagging the master branch, while tagging the prototype branches could also be possible (in case a prototype would have different development stages).

The prototype branches could exist as long as the new features are either integrated in the master branch or thrown away.


问:
How to deal with no code reviews in my new place when I come from that practice?
The team in my new company does not have a code review process.

I come from companies with code review as a must culture and thus I don't feel comfortable committing my code without having it reviewed by someone.

I'm a firm believer that code review is a way to improve quality and save time because it catches potential problems earlier (note I am not talking about pair programming though).

How can I show that code review is not a time waster but a time saver?

Can code review be skipped if you have unit tests?

答:
Are there any studies and statistics showing code review is not a time waster but a time saver?

I don't know of any. It's also hard to conduct such studies, because you'd need two teams that have a task of equal and realistic complexity to accomplish, where one uses code reviews and the other one doesn't. You'd probably need to have them solve the same problem, which means throwing lots of money out the window. And you'd need to repeat the experiment often enough to get statistical relevance, which would increase that money throwing by orders of magnitude.

If you just measure the efficiency of companies using code reviews against companies that don't, it's not only unclear how to measure efficiency, but also what the actual cause is. Code reviews are part of a larger culture. Which part of it actually makes the team more efficient is hard to tell (and may very well depend on the nature of the team or the project). Or the presence of this culture may simply mean that the company is either smaller or younger, each of which has many effects. Or it may well just be that the willingness to submit to code reviews precludes or fosters a healthy distance to your ego ;)

But don't forget: you have your own experience to draw from. It's part of why they hired you. So if you truly believe you can increase efficiency (and your team actually suffers a lack thereof), then communicate that clearly.

Can code review be skipped if you have unit tests?

Nope. If you believe in the importance of tests, then actually your tests should be the first thing to be reviewed. What if they are nonsense? Or if coverage is lousy? Or if they test implementation rather than behavior?


问:
How to reuse common code between presenters
In my application there are 2 views both have 70% common fields like name, icon etc. One view is about list( contains 2-3 fields). On clicking the list  , the next view which is the details should be called.

Other functionality in both views is same. e.g while loading , presenter will be called to load data from the url. (The URL for both  views is different).
The common functionality includes
1. Load XML data from URL
2. Set the loading progress bar in activity
3. Removing the progress bar.
3. 50% methods for setting the activity views will be common.
4. Call the xml parser

The differences will be view specific:
1. The fields are only 50% common.
2. the action on button click

My doubt is shall I use 2 presenters or one presenter for both the views. Many methods are different , while many are same in the 2 presenters.

Which is the correct design strategy?:
1. Shall I use helper class
2. Shall both presenters have the same base class.
3. Shall i use the startegy pattern?
 What is the right way to do it in MVP? Or all are correct.

答: I would suggest starting off by writing your two presenters independently, then refactoring to remove duplication. This could be done either by moving code into one or more helper classes, or by introducing a new abstract ancester class for your presenters. Which of these is most appropriate will depend on details of your project that aren't in your question, but unless there are good reasons to favor inheritance I'd usually go for the former.</p>


问:
Should a getter throw an exception if its object has invalid state?
I often run into this problem, especially in Java, even if I think it's a general OOP issue. That is: raising an exception reveals a design problem.

Suppose that I have a class that has a String name field and a String surname field.

Then it uses those fields to compose the complete name of a person in order to display it on some sort of document, say an invoice.

```<code>public void String name;
public void String surname;

public String getCompleteName() {return name + " " + surname;}

public void displayCompleteNameOnInvoice() {
    String completeName = getCompleteName();
    //do something with it....
}
</code>```

Now I want to strengthen the behavior of my class by throwing an error if the displayCompleteNameOnInvoice is called before the name has been assigned. It seems a good idea, doesn't it?

I can add a exception-raising code to getCompleteName method.
But in this way I'm violating an 'implicit' contract with the class user; in general getters aren't supposed to throw exceptions if their values aren't set. Ok, this is not a standard getter since it does not return a single field, but from the user point of view the distinction may be too subtle to think about it.

Or I can throw the exception from inside the displayCompleteNameOnInvoice. But to do so I should test directly name or surname fields and doing so I would violate the abstraction represented by getCompleteName. It's this method responsibility to check and create the complete name. It could even decide, basing the decision on other data, that in some cases it is sufficient the surname.

So the only possibility seems to change the semantic of the method getCompleteName to composeCompleteName, that suggests a more 'active' behavior and, with it, the ability of throwing an exception.

Is this the better design solution? I'm always looking for the best balance between simplicity and correctness. Is there a design reference for this issue?

答:
You have the whole checking name thing upside down.

getCompleteName() does not have to know which functions will be utilizing it. Thus, not having a name when calling displayCompleteNameOnInvoice() is not getCompleteName()s responsibility.

But, name is a clear prerequisite for displayCompleteNameOnInvoice(). Thus, it should take the responsibility of checking the state (Or it should delegate the responsibility of checking to another method, if you prefer).


答:
There is no thumb rule for code reviews to be done on any software developed...it all depends on the scope of the application, client size and company size. For example if you are building an application where its a simple application where there may not be any further versions are being implemented in future, unit testing is sufficient there. But again code review comes into place when you talk about performance of the application where you need to review the code for any short falling of the code which could have been done in a better way to facilitate faster performance.

Code reviews are usually done where there is a team of more than 2 developers and a tech lead where tech lead wants to ensure the quality of the application and make sure the code standards are followed to scale the application for future enhancements and upgrade it for different upcoming versions.

For example we do have many CMS open source platforms now and these platforms release upgrades from time to time to enhance the platform features, imagine a developer using one of these platforms and has not followed the code standards like hard coding in core files, writing application code in template files, and if this code goes to production and later when client wants to upgrade the platform to new version it will never be upgraded unless the coding is redone as per the code standards for that platform. Here it becomes a serious issue for releasing the code to production without code review being done.

So i would say having code reviews done before release are a must for any professional software companies and the exceptions can only be for personal/very small scale applications where the developer is very seasoned programmer and carries experience with him.

Title: How to deal with no code reviews in my new place when I come from that practice?

Body:
The team in my new company does not have a code review process.

I come from companies with code review as a must culture and thus I don't feel comfortable committing my code without having it reviewed by someone.

I'm a firm believer that code review is a way to improve quality and save time because it catches potential problems earlier (note I am not talking about pair programming though).

How can I show that code review is not a time waster but a time saver?

Can code review be skipped if you have unit tests?


问:
Having many versions of an application
Basically the scenario is this:

There is one main version of an application, but it is modified for each client. The development is usually through the version that is currently worked on.

All the other versions should be updated after adding new features or bug fixes.

Application is written in ASP.NET MVC C#

Git is used for source control and there is one server version for each project. Branching is used mainly for working on different features.

Here are my thoughts on the problem:

Since the current modified version is the latest one, when I add a feature, I have to somehow add it to all of the other projects. Same goes for fixing bugs. Doing that manually is out of the question, so I guess I have to use some complex way of version control and merging?

Is this is even possible to pull off? I fear that at some point (20 versions) it will be impossible to keep up with what's where. The problem is, I don't see any other solution...

EDIT
(There aren't many propositions for solution in this or the other topic ):

As you guys said, it is a bad idea to have many versions, and it's best to have one body-of-code which can handle all of the scenarios, but there wasn't much said about how to accomplish this.

-Someone said that modular (plug-in) design would be good, but this really isn't the case, since there will be many modifications to existing code.

-using #if ?

-using config files ? How does this work exactly ? I wasn't able to find any examples.

答:
General suggestion : DO NOT USE VERSION CONTROL ! (for this kind of problem)

Either make it so the application has all features that can be turned on/off using config files.

Or make the application modular so each customer gets slightly different modules.

Title: Having many versions of an application


答:
Can code review be skipped if you have unit tests?

But why?

The primary role of peer review is not to catch out bugs.

Yes, you may identify some potential bugs and doubtful, bug-prone code, this often happens, but occasionally spotting some blunders doesn't mean that peer review is a reliable way of ruling out the presence of bugs. Far from that. It's not the right tool to verify the functional correctness of implementation.

Code review enforces code maintainability, though. I will demand that code is clean and understandable (not just for its author) before it goes into production.

The presence of unit tests is completely orthogonal to that. You can have 100% code coverage and all tests passing for totally incomprehensible code.

Code review also serves to familiarize other developers with your work so that they know what is what and are able to pick up from there, or handle bug reports while you're on holidays etc. Knowing what you've done straight away may help them do their job well - keep the codebase consistent (stick to similar patterns and conventions throughout the app), or avoid code duplication.

In broader scheme of things, one also learns and grows as a developer from reading other people's code.

Unit tests can hardly be a substitution for any of it. Yes, if they're well written, they read like documentation, and we should strive for this. But again this is not mutually exclusive with performing peer review, quite the contrary - all the advantages of peer review still hold true, the fact that your peers have some nice unit tests to look at will only make the reviewing process easier and even more beneficial rather than redundant.