问:
How to store satellite data in C data structures
I've been reading through Introduction To Algorithms 3rd Ed, and I am having difficulty in implementing some practical situations. It's not the theory, or implementing the internals of the data structures themselves, but rather how to design a good interface that makes the data structures useful for storing real data (as opposed to just the keys).

Specifically, I'm told that C has a very "trust the programmer" type philosophy. I just don't know how much trust is too much trust:

As an example, many data structures can be implemented as linked structures with similar nodes having a key, satellite data, and pointers to other nodes in the ds, ex:

```<code>typedef struct {
    int key;
    void *data;
    node_t *prev;
    node_t *next;
} node_t;
</code>```

To what extent should I be encapsulating my implementations? For most structures, you have both:
(a) a data structure type, and (b) a type that can be inserted/deleted from the data structure. Should they both be hidden? Clearly if I expose a some node_t with the intention someone only alters key and *data.. theres the possibility prev or next is altered, thus destroying the data structure. A similar risk exists if I expose the data structure type and someone messes around with the root..

How should the keys be stored/accessed/compared? Presumably, the keys depend on the satellite data, but if you go the approach as above, you've decoupled the key from the data itself. What would happen if a user updates the data but forgets to update the key (or worse, they update the key, but don't remove/reinsert it into the ds)? For something like a binary tree which uses only comparisons, I could design the interface to accept comparators that accept pointers to the satellite data? This makes the structure more generalized, but all the defreferencing has to have an impact on speed. Alternatively, (and would be needed for structures like hashes which need a concrete key), I could accept a pointer to a int toKey(void *data)function..

I'm unclear on how good software should be designed for use in the real world.

答: Provide methods for manipulating your data structure such as Add() and Remove(), so that your consumers don't have to touch the nodes directly.


问:
Entity Framework with no direct table access
There are some similar questions I've found here, but none of them fully answer the question I'm asking. Similar questions: here and here

In my company, I develop C# .NET applications and our Server Admins in IT don't allow direct table access so we're required to use stored procedures to insert, update, and delete from a table. In the past I've been using DataSets and TableAdapters to access the tables of a database, but I'm starting to realize that everything is starting to use Entity Framework.

Herein lies my issue. There is another developer here that uses the Entity Framework, but he doesn't actually use entities. He uses Entity Models that have no tables or views, only stored procedures. Doesn't this defeat the purpose of the Entity Framework, or am I crazy?

Also, I realize that you can map the insert, update, and delete functionality to stored procedures and this article mentions some interesting ways of implementing that, but creating views for every table would be a major pain. Are there any more practical or easily implemented alternatives?

答:
It depends on ones background and preferences.

Some people came up using stored procedures and are very comfortable with them.  They love T-SQL and can do a lot with it.  They tend to write the SPs first and then use a minimal wrapper to use the SP.  Note some people prefer their SPs a lot of the logic such as validation, business rules, data transformations, etc.

Other people are more comfortable with object oriented programming and prefer to write classes and then serialize those classes to and from a database.  In these cases the logic tends to be in the classes.

Entity framework supports both types of development.  It is mostly agnostic of development style and not overly opinionated.

But in your situation you and your team need to devise what the standard is.  You need to make a decision about how many EF features you are going to use and you style of database development.

I personally lean toward using everything the EF can provide, so I let it generate all of the entities.  Then I use Linq to Objects to move data to and from the entities, and let EF deal with the database I/O.  I find doing this allows me to create nice tight code that is reusable and testable, and most importantly, understandable.

OwnerDisplayName: austincrft

ContentLicense: CC BY-SA 3.0


问:
Choosing a diff program for Mercurial
I decided to try to contribute Firefox development, and they use Mercurial for source control. In the documentation about using Mercurial it was advised to choose a diff program and to do it before you start coding. They list a bunch of options, one of which appears to be the standard Unix/Linux diff program, which I'm somewhat familiar with via basic use. </p>

<p>The thing is, I hadn't realized that the diff program can even be an issue and I have a feeling that I won't know how to pick one until I pick the wrong one and get screwed by it somehow. So to skip this unnecessary hurdle, I'd like to ask what should I look at when choosing a diff program, and in what cases is the choice important (and in what way)? </p>

答:
You want a program that can display differences and navigate between them quickly and easily.  If you're using it with a VCS, especially a DVCS like Mercurial, you'll want built-in merge support as well.

I'd recommend Beyond Compare.  It's intuitive and easy to use, they've got versions for Windows and Linux, and the Pro version (which doesn't cost all that much) has a very useful three-way merge feature.

ContentLicense: CC BY-SA 2.5

Title: Choosing a diff program for Mercurial


问:
Is this looping solution possible with recursion?
Eventually, I would like to generalize this solutions to work with a Tuple of any length. I think recursion is required for that, but I haven't been able to do it.

```<code>def combineRanges(maxValues) :
    for x in range(0, maxValues[0]) :
        for y in range(0, maxValues[1]) :
            for z in range(0, maxValues[2]) :
                print (str(x) + '-' + str(y) + '-' + str(z));

m = (6,9,20);
combineRanges(m);
</code>```

http://repl.it/WiZ

答:
Recursion is not required, but it's one of the clearest ways to do unknown levels of nested loops.  You will only use one level of stack per element in your input tuple, so you have a fair bit of breathing room.

For a recursive function you need a base case and a recursive case.  The base case is when you have zero elements in your tuple, which is where you print your result.  The recursive case is where you do each nested loop and append the results to the level below.

def combineRanges(maxValues, result=()):
  if len(maxValues) is 0:
    print("-".join(result))
    return

  for x in range(0, maxValues[0]):
    combineRanges(maxValues[1:], result + (str(x),))
```

Each recursive call pulls one element off the front of maxValues and adds one result to the result tuple, until maxValues is empty.  This type of recursion is a little trickier because you are accumulating the result in an argument, but this pattern is very useful and comes up a lot, so it is worth learning.  Also, python's lists aren't immutable, which is why I use a tuple to hold the result.

Body:
Recursion is not required, but it's one of the clearest ways to do unknown levels of nested loops.  You will only use one level of stack per element in your input tuple, so you have a fair bit of breathing room.

For a recursive function you need a base case and a recursive case.  The base case is when you have zero elements in your tuple, which is where you print your result.  The recursive case is where you do each nested loop and append the results to the level below.

def combineRanges(maxValues, result=()):
  if len(maxValues) is 0:
    print("-".join(result))
    return

  for x in range(0, maxValues[0]):
    combineRanges(maxValues[1:], result + (str(x),))

Each recursive call pulls one element off the front of maxValues and adds one result to the result tuple, until maxValues is empty.  This type of recursion is a little trickier because you are accumulating the result in an argument, but this pattern is very useful and comes up a lot, so it is worth learning.  Also, python's lists aren't immutable, which is why I use a tuple to hold the result.


问:
Has there really not been one thing in the past 20 years that provided huge software development gains?
In No Silver Bullet, Fred Brooks makes a variety of predictions about the future of software engineering, best summed up by:

There is no single development, in either technology or in management technique, that by itself promises even one order-of-magnitude improvement in productivity, in reliability, in simplicity.

His argument is very convincing. Brooks was writing in 1986: was he right? Do developers in 2014 produce software at a rate less than 10x faster than their counterparts in 1986? By some appropriate metric -- how large has the gain in productivity actually been?

答:
Technology has advanced very much and now we have all the things Robert Harvey enumerates in his answer, but:

The problem seems to be changing requirements. The client knows that there will not be waste of materials when changing the requirements of a software project, so they do. That kind of requirement changes almost never happen once a physical-world project like a building, is half done.

Another important aspect is that programming continues to be highly handiwork. Rarely if ever, RAD-generated code goes into production without being modified by hand first.

Code continues to be highly complex, and that complexity doesn't seem to decrease with new technologies.

The rate of deadlines not met or budgets exceeded continues to be greater that those in other disciplines, and often times technical debt is incurred in order to meet them, generating hidden costs.

Something that have, without a doubt, happened is that compartmentalization has ocurred. The sheer ammount of technologies one has to know is so that programmers have had to specialized a small number of technologies in order to become really good at them, requiring different kinds of experts to complete a large project.

One thing that talks about software complexity is that whereas there are literally hundreds of car makers in the world, the list of companies capable of creating and maintaning an operating system, (desktop, mobile, embedded or otherwise), can be counted with the fingers of your hands.

All the above has created a situation in which there are not enough people studying to be programmers, so that governments have created campaigns in order to motivate more students into taking that career path.

One taste of the maturity of the software industry is that software licenses continue to state "<companyX> makes no representations about the suitability of this software for any particular purpose.  It is provided "as is" without express or implied warranty." Imagine a hardware maker stating that their product is not suitable for any particular purpose. That's the state of the art right now.


问:
Why are inheritance, encapsulation and polymorphism not the pillars of OOP?
One day I went to a Stack Overflow chat and saw a phrase, that was stating that inheritance, encapsulation, and polymorphism are the pillars of OOP (in the sense that they are fundamental, a construction sole).

Also, there's a similar question, that I have been asked very often on college exams and job interviews, and the right answer always was the statement pronounced in the title of the question ("Yes, inheritance, encapsulation, and polymorphism are the pillars of OOP).

But in the Stack Overflow chat I was severely ridiculed, participants strongly disagreed with such a statement. So, what's wrong with this statement?

Do programmers seem to be trained in different things in post-Soviet and United States colleges?

Are inheritance, encapsulation, and polymorphism not considered to be the pillars of OOP by US/UK programmers?

答:
Are inheritance, encapsulation and polymorphism are not considered to be the pillars of OOP by US/UK programmers?

They are considered to be pillars by many programmers, and many colleges teach OO that way.

Unfortunately, it is also a shortsighted view.

Inheritance is but one mechanism used to implement OOP and can be abused to not do OOP.

Encapsulation is a concept, useful for programming of all sorts, OOP and not.

Polymorphism is a... trait(?) to describe how computation behaves. There are many ways to achieve polymorphism, not all of which are OO specific.

OOP has very little foundation, since in reality, it's very conceptual: "Approach the design of your program by thinking of things as objects - cohesive bundles of data and functionality."

And while modern program design takes a poor view of doing things in a "purely OO fashion", most skilled programmers will agree that the SOLID principles (or some subset) are better candidates for the "pillars of Object Oriented Programming" (even though they apply well to non-OOP). These don't work with these terms at all. Instead they use the concepts of software entities (of which, objects are one), interfaces (of which, a C#/Java/etc. interface is one), abstraction and sub-typing (of which, inheritance is one form).

ContentLicense: CC BY-SA 4.0


问:
Designing module interfaces
I'm studying software engineering and one thing I'm really trying to improve is my skill in software architecture. My question is quite broad, so I'll try to explain it with an example.

Suppose you have a model layer and a service layer. The model manages various entities (such as users, products, orders, campains etc.). The services provide features, such as evaluating the efficency of a campaign, and use several modules of the model layer to access the required data.

How and when do you specify those dependencies? I see the following possibilities:

Allow general access to all models. This is the approach taken in many MVC frameworks, where the controllers can access any model classes.

Pro: You don't have to specify the dependencies, the developer writing the controller is very flexible.

Contra: If you want to test a service, you don't really know which model you have to mock because the service could use everything. These implicit dependencies can also make maintainance a pain.

The services specify the required models explicitly. Dependency management systems like requirejs or CommonJS require work this way.

Pro: No implicit dependencies simplifies maintanance

Contra: Mocking is impossible. When designing the module, you have to know exactly what the module will need. If you later notice that you need another interface, you have to change the architecture.

Specify explicit interfaces that will be provided to the service. Anyone instancing the service will have to provide implementations of the interfaces. I think dependency injection works this way, although the injection is automated there.

Pro: No implicit dependencies simplifies maintanance, Testing is simplified, because you know exactly what to mock.

Contra: When designing the module, you have to know exactly what the module will need. If you later notice that you need another interface, you have to change the architecture.

In theory, dependency injection seems like the best way. But is it practical to specify each requirement? How fine-grained should it be? Per entity? Group them? Or one dependency per "thing you can do with an entity"?

There are simply too many possibilities, and I'd like to get some real-world advice.

答:
A truly independent module would expose API to create objects that it exposes and every such object would expose an interface that is clear to what the object is supposed to do.

Instead of any one gigantic API somewhere.
For example jQuery - one object because it does one thing.
jQueryUI is not one object but offers individual objects as widgets.

So from a client (code) from of view what the module does is well documented.
Complex steps to create the objects is simplified.

How and when do you specify those dependencies?

The client code should be only adding the module as a dependency.
If module has other dependencies they need to be resolved as the module dependency is resolved. (RequireJS, Maven Dependencies)

Dependency Injection

This is different than the code dependency as you have noted. Model should be injected in the Module interface. Your service objects can also be injected here but in that case it is your services which will inject the Model and the service objects could be created only from your MyModuleFactory(Impl).

The client code you inject the MyModuleFactory. The injection chain will be resolved down the path.

Specific point About Model and Services - non Anemic model

Services may seem like an nice idea but it becomes a problem down the line.
Checkout cases against this.

Anemic Domain Model

Title: Designing module interfaces


答:
A great deal of what we have learned in software engineering practice in the past 30+ years is of the form "technology X can speed up initial development of new software, but if you don't spend as much or more time thinking about how and when to use it as you saved by using it, in the long run it will turn your application into a sucking swamp of technical debt, costing you orders of magnitude more time and effort in maintenance."

Technologies that fall under this razor include: hand-coded assembly language, compilers, interpreters, procedure libraries, imperative programming, functional programming, object-oriented programming, manual memory allocation, garbage collection, static types, dynamic types, lexical scope, dynamic scope, "safe" pointers, "unsafe" pointers, the absence of pointers as a language concept, binary file formats, structured-markup file formats, macros, templates, avoidance of macros and templates, shared memory, message passing, threads, coroutines, asynchronous event loops, centralized remote services, distributed services, locally installed software, arrays, linked lists, hash tables, and trees.

The fact that many of the items in the above list come in groups which together exhaust the known solution space is very much intentional, and should in and of itself tell you something.  One could argue that the only unambiguous, across-the-board improvements in praxis we've had since they first switched on the Z3 are block-structured programming (as opposed to spaghetti code) and memory protection (boy, do I ever not miss the days when a typo could take down my entire computer).

Title: Has there really not been one thing in the past 20 years that provided huge software development gains?

Body:
In No Silver Bullet, Fred Brooks makes a variety of predictions about the future of software engineering, best summed up by:

There is no single development, in either technology or in management technique, that by itself promises even one order-of-magnitude improvement in productivity, in reliability, in simplicity.

His argument is very convincing. Brooks was writing in 1986: was he right? Do developers in 2014 produce software at a rate less than 10x faster than their counterparts in 1986? By some appropriate metric -- how large has the gain in productivity actually been?


问:
What is the point of writing WCF Interceptors, compared to using a helper method?
For those of you who don't know, WCF allows you to attach interceptors to methods in the service contract.  The interceptor is capable of performing custom logic before and after a method call, and is (as far as I know) used mainly for validating parameters and doing custom authorization schemes.

But what's the point of using them if you can just write a helper method to do the same thing?

答:
MSDN has a good example of using Interceptors for implementing user security:</p>

```<code>// Define a query interceptor for the Orders entity set.
[QueryInterceptor("Orders")]
public Expression<Func<Order, bool>> OnQueryOrders()
{
    // Filter the returned orders to only orders
    // that belong to a customer that is the current user.
    return o => o.Customer.ContactName ==
        HttpContext.Current.User.Identity.Name;
}
</code>```

Body:
MSDN has a good example of using Interceptors for implementing user security:

// Define a query interceptor for the Orders entity set.
[QueryInterceptor("Orders")]
public Expression<Func<Order, bool>> OnQueryOrders()
{
    // Filter the returned orders to only orders
    // that belong to a customer that is the current user.
    return o => o.Customer.ContactName ==
        HttpContext.Current.User.Identity.Name;
}


问:
What's the most absurd myth about programming issues?
To put it another way... What is the most commonly held and frustrating misunderstanding about programming, you have encountered?

Which widespread and longstanding myths/misconceptions do you find hard for programmers to dispel/correct.

Please, explain why this is a myth.

答: That a manager knows jack-squat about the code that his/her developers are writing.</p>


问:
The nature of callbacks in Node.js
In the plain javaScript world I've learned that nested functions can be problematic because the inner function is "re-created" every time the outer function is called:

```<code>function outer(a) {
    function inner(arg1,arg2){
        return arg1 + arg2;
    }
    return inner(a, 6);
}
myVar = outer(4);
</code>```

Apparently the inner function is garbage collected and the constant re-creation of it has a cost on performance. This could be re-factored as:

```<code>function inner(arg1, arg2) {
    return arg1 + arg2;
}

function outer(a) {
    return inner(a, 6);
}

myVar = outer(4);
</code>```

If I am correct it seems that the tradeoff lies in the changing scope of inner; the fact that function inner no longer has access to outer's own variables. If I am correct so far, lets move to Node.JS. Node is heavy on callbacks, and my question is, are asynchronous callback functions typical in Node also "re-created" every time they are fired? Take the following common Node construct:

```<code>http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
</code>```

In reality the function can get pretty large; it can encompass a lot of functionality. Is the above callback "re-created" every time a client GETs or POSTs the server? If so, would it be better to always de-couple the callbacks as in the plain javaScript example:

```<code>function handleGET(req, res) {
   res.writeHead(200, {'Content-Type': 'text/plain'});
   res.end('Hello World\n');
}

http.createServer(handleGET).listen(1337, '127.0.0.1');
</code>```

as a related bonus question, are event functions re-created too? Would they benefit from prior  declaration?

```<code>myObj.on('someEvent', function someFunction() {...});
</code>```

vs.

```<code>function someFunction() {...}
myObj.on('someEvent', someFunction);
</code>```

答:
Note that a modern JavaScript implementation will only create individual function objects for different instances of the same function, these objects can easily share the code.

Both of your first two examples should, at least in V8, have the inner function inlined by the optimizer, thus effectively removing the overhead of having a second function at all. I'll try to make time for some benchmarks, but for now I note that the first example could potentially be faster because it can be verified by simple static analysis that the inner function will never change. The second example has to be able to deal with the possibility that the global variable inner changes value.

You give the example code:

```<code>http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
</code>```

Note that this is not an example of multiple instances of the same function, createServer is called once and is in this process given the only instance of the anonymous function that is ever created. It is likely to call the anonymous function multiple times, but that is a different matter.

Title: The nature of callbacks in Node.js

Body:
Note that a modern JavaScript implementation will only create individual function objects for different instances of the same function, these objects can easily share the code.

Both of your first two examples should, at least in V8, have the inner function inlined by the optimizer, thus effectively removing the overhead of having a second function at all. I'll try to make time for some benchmarks, but for now I note that the first example could potentially be faster because it can be verified by simple static analysis that the inner function will never change. The second example has to be able to deal with the possibility that the global variable inner changes value.

You give the example code:

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(1337, '127.0.0.1');

Note that this is not an example of multiple instances of the same function, createServer is called once and is in this process given the only instance of the anonymous function that is ever created. It is likely to call the anonymous function multiple times, but that is a different matter.


问:
What is your approach to debugging a transient problem
I am working on a system that controls a label printer and occasionally the label printer will print the same label 2,3,...,10 times.  The error is transient, occurring once per 3000-4000 (once a month) or so labels.

I am adding tracing to a log file to see what commands are being sent to the printer and state of the printer (we have a state machine defining allowable commands). But since this is a transient problem that may tell me that we had an error, but not why we had the error so I can fix the problem.

I am also trying to get the print job files for the errant jobs so that I can emulate the job in my test environment.  Hopefully with these I can reliably make the error occur

I am curious how other might approach diagnosing this type of transient error.

答:
I would look for a way to detect the duplicates inside your code, check it at various levels of abstraction, and log when it occurs.  You could require a sequence number be submitted with each job, or attach a timestamp to a job, or check a hash.  That way if you detect a duplicate at layer 3, but not layer 2, you've narrowed down your search criteria.

The other benefit to this approach is you can often work around the symptom even before you know the cause.  Assuming you can tell the difference between user-initiated duplicates and bug duplicates, you can just suppress the duplicates when they are detected after the fact.  This isn't an ideal solution, but it's better than leaving the problem for months or years, especially if the duplicates now are only being caught by manual inspection.


答: For me personally, I've used two different programs, kdiff3 and p4merge.  I believe they both run off the unix diff.  In my limited experience, you can't really go wrong with either of these diff programs as they have always produced identical results for me.  The main factor is personal preference.  The program kdiff3 is more configurable, but I prefer p4merge when I am actually merging files (kdiff3 requires an additional step to start merging).  p4merge has a little bit better looking interface.

Title: Choosing a diff program for Mercurial

Body:
I decided to try to contribute Firefox development, and they use Mercurial for source control. In the documentation about using Mercurial it was advised to choose a diff program and to do it before you start coding. They list a bunch of options, one of which appears to be the standard Unix/Linux diff program, which I'm somewhat familiar with via basic use. </p>

<p>The thing is, I hadn't realized that the diff program can even be an issue and I have a feeling that I won't know how to pick one until I pick the wrong one and get screwed by it somehow. So to skip this unnecessary hurdle, I'd like to ask what should I look at when choosing a diff program, and in what cases is the choice important (and in what way)? </p>


答:
It enables the open/closed principle, which is the 'O' in SOLID.  It states that modules should be open for extension, but closed for modification.  Essentially, interceptors allow you to extend the behavior of a method call by adding new code, instead of by changing existing code, as you would have to do to add a call to a helper method.

A lot of very smart people have written in detail about why this is beneficial, but the bottom line is it makes your program less prone to breaking old features when you add new features.

Title: What is the point of writing WCF Interceptors, compared to using a helper method?

Body:
For those of you who don't know, WCF allows you to attach interceptors to methods in the service contract.  The interceptor is capable of performing custom logic before and after a method call, and is (as far as I know) used mainly for validating parameters and doing custom authorization schemes.

But what's the point of using them if you can just write a helper method to do the same thing?


答:
tl;dr: You can have inheritance without OO, you can have encapsulation without OO, you can have polymorphism without OO, you can even have all three at once without OO. On the flipside, you can have OO without inheritance. Plus, there are different kinds of encapsulation (ADT-oriented and OO), IOW not all encapsulation is OO.

Long version:

The term "Object-Oriented Programming" was invented by Alan Kay, so he gets to decide what it means. And he defines it this way:

OOP to me means only messaging, local retention and protection and hiding of state-process, and extreme late-binding of all things.

Implementation-wise, messaging is a late-bound procedure call, and if procedure calls are late-bound, then you cannot know at design time what you are going to call, so you cannot make any assumptions about the concrete representation of state. So, really it is about messaging, late-binding is an implementation of messaging and encapsulation is a consequence of it.

He later on clarified that "The big idea is 'messaging'", and regrets having called it "object-oriented" instead of "message-oriented", because the term "object-oriented" puts the focus on the unimportant thing (objects) and distracts from what is really important (messaging):

Just a gentle reminder that I took some pains at the last OOPSLA to try to remind everyone that Smalltalk is not only NOT its syntax or the class library, it is not even about classes. I'm sorry that I long ago coined the term "objects" for this topic because it gets many people to focus on the lesser idea.

The big idea is "messaging" -- that is what the kernal of Smalltalk/Squeak is all about (and it's something that was never quite completed in our Xerox PARC phase). The Japanese have a small word -- ma -- for "that which is in between" -- perhaps the nearest English equivalent is "interstitial". The key in making great and growable systems is much more to design how its modules communicate rather than what their internal properties and behaviors should be. Think of the internet -- to live, it (a) has to allow many different kinds of ideas and realizations that are beyond any single standard and (b) to allow varying degrees of safe interoperability between these ideas.

(Of course, today, most people don't even focus on objects but on classes, which is even more wrong.)

Messaging is fundamental to OO, both as metaphor and as a mechanism.

If you send someone a message, you don't know what they do with it. The only thing you can observe, is their response. You don't know whether they processed the message themselves (i.e. if the object has a method), if they forwarded the message to someone else (delegation / proxying), if they even understood it. That's what encapsulation is all about, that's what OO is all about. You cannot even distinguish a proxy from the real thing, as long as it responds how you expect it to.

A more "modern" term for "messaging" is "dynamic method dispatch" or "virtual method call", but that loses the metaphor and focuses on the mechanism.

Similar points are also made in On Understanding Data Abstraction, Revisited by William R. Cook and also his Proposal for Simplified, Modern Definitions of "Object" and "Object Oriented".

Dynamic dispatch of operations is the essential characteristic of objects. It means that the operation to be invoked is a dynamic property of the object itself. Operations cannot be identified statically, and there is no way in general to exactly what operation will executed in response to a given request, except by running it. This is exactly the same as with first-class functions, which are always dynamically dispatched.

In Smalltalk-72, there weren't even any objects! There were only message streams that got parsed, rewritten and rerouted. First came methods (standard ways to parse and reroute the message streams), later came objects (groupings of methods that share some private state). Inheritance came much later, and classes were only introduced as a way to support inheritance. Had Kay's research group already known about prototypes, they probably would have never introduced classes in the first place.

Every programmer should read On Understanding Data Abstraction, Revisited. It explains in detail what exactly the difference is between Objects and Abstract Data Types. He gives examples using Java, and that is extremely relevant to this question, because in both the ADT examples and the Object examples he uses inheritance, encapsulation and polymorphism, but only one of the examples is object-oriented! In other words: you can have inheritance, encapsulation and polymorphism, you can even have all three at once and still not have OO.

On the other hand, you can have OO without inheritance. Like I hinted at above: the original versions of Smalltalk (the language designed by Alan Kay, the inventor of the term "Object-Oriented Programming") didn't have inheritance.

Last, but certainly not least, The Treaty of Orlando discusses delegation as an alternative to inheritance and how different forms of delegation and inheritance lead to different design points within the design space of object-oiented languages. (Note that actually even in languages that support inheritance, like Java, people are actually taught to avoid it, again indicating that it is not necessary for OO.)

Title: Why are inheritance, encapsulation and polymorphism not the pillars of OOP?

Body:
One day I went to a Stack Overflow chat and saw a phrase, that was stating that inheritance, encapsulation, and polymorphism are the pillars of OOP (in the sense that they are fundamental, a construction sole).

Also, there's a similar question, that I have been asked very often on college exams and job interviews, and the right answer always was the statement pronounced in the title of the question ("Yes, inheritance, encapsulation, and polymorphism are the pillars of OOP).

But in the Stack Overflow chat I was severely ridiculed, participants strongly disagreed with such a statement. So, what's wrong with this statement?

Do programmers seem to be trained in different things in post-Soviet and United States colleges?

Are inheritance, encapsulation, and polymorphism not considered to be the pillars of OOP by US/UK programmers?


问:
Has anyone nailed dependency management?
I've used various dependency management tools for installing software: homebrew, cabal, rubygems, etc.  Invariably, despite someone's simple instructions for installing their package, there are times when dependencies don't get worked out by the package manager and the installation fails.  This is more common than it ought be.  And frustrating!  You end up trying to troubleshoot the installation process which I feel is something users (even if they are developers) shouldn't have to do.

This is one reason people knock Linux (which I love!) as compared to Windows: installations can be associated with complications.  Windows users aren't tasked with compiling source.

Is someone aware of a dependency management tool (or dependency management strategies) that has been especially successful at eliminating the bumps associated with installs?  Clearly some package managers must be better than others.  Or does this remain an unsolved problem?

答:
Package managers fail to install some software because of the intrinsic problem of releasing software in the wild: it can be installed anywhere, and should accommodate itself to different machines, different hardware, different versions of OS, different configuration, different side-by-side software and different problems.

You test your software on all Debian, Ubuntu, Fedora, Red Hat and SUSE distributions released since 2008, your Continuous Integration server deploys more than 150 VMs of different versions and variants of OSes with different configurations at every commit.

Then, when your product is finally released, it appears that it fails miserably on Joe's machine, because Joe has a custom-compiled Debian in Romanian, lacks a few packages that you assumed are always installed, has a hard drive which hangs for 30 seconds from time to time, doesn't have a mouse and has an antivirus which is popular in Romania and only there.

And now, he posts a message on a popular forum, telling that your software crashes, because, indeed, you had no idea that you should have had in your CI a Romanian VM with a custom-compiled Debian with an emulation of a dying hard disk, no mouse and some unknown antivirus.

Dependency management tools such as apt-get for Debian-type distributions, npm for Node.js or pip for Python work great as systems. The fact that sometimes, you install packages through them and it doesn't work is not the fault of those systems, but more the fault of developers who made the packages (and the installer). Don't blame the dependency management tools for the failures of individual packages.

Could the installation be less error prone? Yes. There are things you can do to make your life easier. All those points are crucial.

Use officially supported OSes and upgrade often (but don't be the guy who jumps to the newest pre-Alpha). The fact that you can install some software on Windows 2000 doesn't mean you should.

Use recent hardware and up-to-date drivers. The number of issues from old motherboards or old GPUs or outdated drivers is huge. When I started using Ubuntu, I hated Chromium: it crashed several times per day, often forcing the whole system to crash. Updating the GPU driver solved the problem.

Don't try to install every package you find on your system. I mean, if your corporate server serves as domain controller, DNS and DHCP and has on it Sharepoint Services, IIS (preferably two versions of it hacked side by side, with the support for PHP and Python as well), SQL Server (which surprisingly takes all the RAM), SMTP and a dozen of other services, you should start by firing your system administrator.

Set up security. Nobody should access your corporate server through Remote Desktop to "tweak a little thing".

Get your configuration under version control. You should be able to create a replica of any machine in an unattended way from a bunch of scripts in a matter of minutes. If you have to install this, then that, then configure this thing and move this file in that folder, you'll make mistakes which will cost a lot (unless you can afford a downtime of your entire infrastructure for a week).

Test third-party software before pushing it in production. The version 3.0 of the proxy server is released? Great. Let's configure it in staging, run automated tests on exact replicas of production servers, and see that everything works as expected. It does? We can now upgrade our production servers.

Virtualize severely. A VM is much easier to handle and replicate. "You can bootstrap a VM in less than a minute", which makes it very easy to deploy something for testing purposes, see if it works, experiment with it or throw the VM if it failed.

Real, non-virtual machines are great when you need the cutting edge performance and the VM abstraction becomes the bottleneck. But installing a distribution on a real machine trough PXE may take fifteen minutes, sometimes even longer. This makes experimentation much more difficult.

Compartmentalize severely. If you have a DNS service and an SMTP server, run two VMs. If you host two Python applications and they are too small to deserve a dedicated VM each, virtualenv is your friend.

Automate severely. VMs should be deployed automatically. Software should be pushed on VMs automatically. Software and infrastructure should be tested automatically. Anything done by hand will introduce random, difficult to track and reproduce mistakes, and slow processes down.

Snapshots help. Installing something in production and don't have time to test everything thoughtfully? Don't forget to create a snapshot of your disks in order to be able to revert to a working version within seconds if anything goes wrong.

Side note unrelated to the question: your second paragraph is more your personal opinion than a fact. The reason I knocked Windows is because it's sooo easier to apt-get install something (given that it works most of the time) compared to the time I spent on Windows searching for the software website, searching for the download button (mostly hidden for an unknown reason), then trying to install the software and finally spend an hour configuring it because the default configuration is surprisingly unusable for any one.


问:
Is there anything groundbreaking about NoSQL?
I am a very solid Relational Database guy and understand all the way to 3rd normal form, appreciate the algebraic set theory roots of SQL, and can probably relationalize a broken heart (or not).

I haven't figured out a relational database structure FOR date nights with my wife, but I HAVE thought about relational database projects ON date nights with my wife..

Now I'm hearing about NoSQL, and researching it.  Cutting to the chase, is there anything about NoSQL that is ground breaking, mathematically novel, or a "hey you don't even really need to organize your data relationally, this is so much easier" type of approach?

Is NoSQL like a super shell to the data structure? In my mind, data must ultimately have structure to be retrieved and the retrieval must be defined in a language of some sort.

答:
NoSQL is more evolutionary than revolutionary. It essentially combines the existing ideas of "external database storage" with "using familiar data structures, not relational tables."

There are more types of databases than relational, for example hierarchical databases. While archaic by today's standards, it meshed really well with the data structures of its data (e.g. COBOL records). The point is, the data in the database was modeled closely to how records were laid out in the programming languages that used them.

Fast forward to the invention of relational databases, where finally the database separated concerns and, when properly normalized, is a great way to visualize most types of data and relationships between data. It is really easy to understand compared to other types of databases. What it utterly fails at, however, is storing data in a way that mirrors objects and classes in a program. Hence, the invention of object-relational mapping. In other words, the design of the database is actually a hindrance to the design of the program that uses it, which is why we need ORM libraries such as Hibernate. While clean and consistent, there is always that nagging doubt in the back of my mind that something is not quite right there.

This gave rise to two more types of databases, object databases and NoSQL.

Both attempt to solve the issues introduced by relational databases while not exposing us to the mind-bending horrors of hierarchical databases. Data is still laid out in repositories that vaguely resemble tables, but in actuality are more like programming data structures than relational tables. While object databases follow mostly well-defined rules, my understanding is that NoSQL is rather arbitrary. For example, a table might be visualized as a hash table or an array. There is not an easy, well-defined way to query them using an arbitrary tool analogous to Oracle SQL Developer or SQL Server Management Studio.

The idea is that one may define data structures that are easily searched in code, rather than piecing together SQL queries that are better-suited to a SQL database engine rather than expressing the query one desires. For example, fuzzy or partial matches are more difficult and perform worse in a relational database, while a NoSQL database may have a structure that is optimized for such a search and completes in a fraction of the time.

There are languages for querying NoSQL. However, there is no universal language such as what SQL is for relational databases.

Late Edit:

While I am familiar enough with NoSQL databases, this question was the impetus for me to buy a quality book on the topic and to start reading it with the eventual goal of being a real expert on the topic. The remaining comments are based on NoSQL Distilled: a Brief Guide to the Emerging World of Polyglot Persistence by Pramod Sadalage and Martin Fowler.

The authors state that relational databases do not scale well to clusters capable of serving the data needed for sites such as Amazon and Google: NoSQL was developed to fit this niche, relaxing the concurrency and durability in ACID in order to server large number of queries that largely use static data (hence, ACID transactions are not as important).

Furthermore, they posit that NoSQL databases operate without a schema (page 10) which allows NoSQL databases to modify the structure of data more easily. I am not sure that the presence or absence of a formal schema matters in this regard, since SQL databases allow modifying schemas as well. Regardless, the two renowned authors make the claim so it is worth examining.

I believe that both of these main points serve only to enforce my primary point that NoSQL is evolutionary, not revolutionary. They still store data, and make incremental improvements to the scale and modifiability. They also make the point that NoSQL does not seek to usurp relational databases as the king of data storage, only to provide an alternative means of data storage for the types of data that need to scale and morph in a way that (they believe) relational databases do not support well enough.


问:
What to do about "stopping point syndrome"?
I have noticed a behavior in myself that I call "stopping point syndrome"... it means I cannot stop working until I reach a "stopping point" (or I become exhausted).  In other words, if I am in the zone working on getting a feature completed, I won't stop until I get it done.   If it's a bug I'm working on, this effect is even more pronounced... I won't stop until it's fixed, or at the very least, understood.  Even though I work from a laptop and have VPN and could easily go home and pick up on the work later that evening, that fact does not help me leave work... it's like I'm afraid I will die before I find the bug.

I have a very hard time explaining this to family members who can't figure out why I never come home from work at the same time and sometimes come home at 11 pm.  Even managers have been mystified by this, and I've noticed that most of my colleagues have no trouble working the same hours every day.

Does anyone else have this problem?  Should I be worried about this and/or try to change it?  If so how?

答: I think it's the programmer's nature. Sometimes you may have to leave early before you start work on a new problem. With all the extra time you've put in, no need to feel guilty. Then you have to be careful not to think about it too much.  Be prepared to tackle it first thing the next morning. </p>


问:
Level order sorted binary tree from a binary tree
Lets suppose we have a binary tree . Tree node structure is as

```<code>struct node
{
   int val ;
   struct node *left , *right ;
}
</code>```

Now we have to sort the tree in level order manner . For example lets suppose we have original tree like this

```<code>root = 6
root->left = 1
root->right = 9
root->left->left = 8
root->right->right = 2
</code>```

Then after applying level order sorting , our tree will be

```<code>root = 1
root->left = 2
root->right = 6
root->left->left = 8
root->right->right = 9
</code>```

One way of doing this problem is just take all the values in a array and apply any of the standard sorting algorithm and then put back the values in tree in level order traversal manner. This solution is not efficient in term of space and time both.

What algorithm can I use to decrease operations and memory usage from my proposed plan?  Is there a more efficient algorithm to do this without the use of a sorted array?

Level order sorting :

Level order sorting means if you do level order traversal of the tree then you should get a sorted non-decreasing sequence .

Constraint :

Shape of the tree should not alter that is if in original tree left child of the root does not have right child (as in my example) then after sorting too, it should not has right child .

答:
Sounds like you need a type of heap with some modified properties. First, use a min-heap instead of a max-heap: every node is less than the values of its children, and add a constraint that a node is greater than its siblings to the left.

One of the neat features of a heap is that it is a balanced binary tree: the depth of all leaf nodes vary by at most 1. Furthermore, leaf nodes are populated left to right. While this is not quite the same representation as you have, it makes the whole thing a ton easier.

If you take a tree with these properties and perform a level-order traversal, you can easily convert it to and from an array:

```<code>root = 6
root->left = 1
root->right = 9
root->left->left = 8
root->left->right = 2
</code>```

Level-order traversal gives the following: 6, 1, 9, 8, 2.

Note how each level takes 2^n elements in that array, where n is the depth of the nodes at that level. The root node has depth 0, so it takes 2^0 = 1 element. Next level has depth 1, so it takes 2^1 = 2 elements. This property means there is a direct correlation between a specific element in the tree and its array position.

Now perform an efficient sort on that array, and you get: 1, 2, 6, 8, 9.

Perform the reverse of the first transformation. Element 0 is the root, Elements 1 and 2 are the next level, elements 3, 4, (and 5, 6 if present) are the next level.

```<code>root = 1
root->left = 2
root->right = 6
root->left->left = 8
root->left->right = 9
</code>```

If you need to maintain the fact that leaves are not populated left to right, or the tree is not balanced, you can add gaps by saying certain nodes are null and modify a sort algorithm to leave null values in-place. Not ideal, but it can allow you to leverage the properties of a heap to do this. Level-order sorting pretty much has to be done using a heap as far as I am aware (made it through a B.S. and M.S. in computer science without ever hearing or seeing another way to do this, and you know the real world doesn't care).

OwnerDisplayName: sdream

Body:
Sounds like you need a type of heap with some modified properties. First, use a min-heap instead of a max-heap: every node is less than the values of its children, and add a constraint that a node is greater than its siblings to the left.

One of the neat features of a heap is that it is a balanced binary tree: the depth of all leaf nodes vary by at most 1. Furthermore, leaf nodes are populated left to right. While this is not quite the same representation as you have, it makes the whole thing a ton easier.

If you take a tree with these properties and perform a level-order traversal, you can easily convert it to and from an array:

root = 6
root->left = 1
root->right = 9
root->left->left = 8
root->left->right = 2

Level-order traversal gives the following: 6, 1, 9, 8, 2.

Note how each level takes 2^n elements in that array, where n is the depth of the nodes at that level. The root node has depth 0, so it takes 2^0 = 1 element. Next level has depth 1, so it takes 2^1 = 2 elements. This property means there is a direct correlation between a specific element in the tree and its array position.

Now perform an efficient sort on that array, and you get: 1, 2, 6, 8, 9.

Perform the reverse of the first transformation. Element 0 is the root, Elements 1 and 2 are the next level, elements 3, 4, (and 5, 6 if present) are the next level.

root = 1
root->left = 2
root->right = 6
root->left->left = 8
root->left->right = 9

If you need to maintain the fact that leaves are not populated left to right, or the tree is not balanced, you can add gaps by saying certain nodes are null and modify a sort algorithm to leave null values in-place. Not ideal, but it can allow you to leverage the properties of a heap to do this. Level-order sorting pretty much has to be done using a heap as far as I am aware (made it through a B.S. and M.S. in computer science without ever hearing or seeing another way to do this, and you know the real world doesn't care).


问:
How to collect industry usage of data persistence technologies?
In our organization, we are using various data access/persistence technologies in different projects. The ones used till now are Hibernate, JPA, Spring Data JPA, JDBC, Spring JDBC, MyBatis, and QueryDSL.

How do I find out what is the industry usage of these technologies? i.e. which is used more widely than others - or even a pie chart showing the distribution of such technologies.

Also curious to know which technologies are being used by major players - like big silicon valley companies, or prominent investment firms. Do you know a way to find this data?

Can the firms like Forrester or Gartner would have such a data?

Thanks in advance.

答: I guess most of this information is not freely available on the internet. So the best approach is probably to make a survey, call or email 100 top IT companies and just ask them. However, if you don't have a name like "Forrester" or "Gartner" on your business card, it is likely you won't get much response. Alternatively, you could charge someone from the big research companies to collect this information for you (note, you did not ask for a cheap solution).


问:
Property-level value transformation for indirect object casting
Does any programming language exist to support the explicit, property-level object copy?

For example, assume this code:

public class Student
{
    public string Name { get; set; }

    public string Code { get; set; }

    public List<string> Interests { get; set; }
}

public class Item
{
    public string Name { get; set; }

    public string Code { get; set; }
}
```

<p>I wonder if there is a compiler (or a language) out there that can indirectly cast two objects to each other, based on property-level matching and a lossy transformation algorithm?</p>

<ol>
<li>Create an instance of the target class</li>
<li>Using reflection, find all properties of the target class</li>
<li>For each property, try to find a match in the source class, using name and type</li>
<li>If found, transfer the value</li>
<li>Otherwise, initialize to the default value</li>
</ol>

<p>Of course, this should be done <strong>explicitly</strong> with the full intention of the developer. For example, a C# pseudo-syntax might look like:</p>

<pre class="lang-cs prettyprint-override"><code>Student student = new Student();
student.Name = "Saeed";
student.Code = "513223";
Item item = copy student; // assume "copy" to be a keyword
// Here, item's name is "Saeed" and its code is "513223"
</code>```

答:
I don't think any language would explicitly support such operation on language level. The major problem is it's complexity. It might look simple in your example, but if you look at something like Automapper, you will notice there is tons of complexity the user of such function would want/need. And the more complex a language feature is, the more use for it there should be, so it is profitable to implement it. And while I did find few cases where such feature would be nice, it is not a common programming requirement. Also, it becomes even less useful to implement a language feature, when you can do same thing without it, see Automapper for C#.

On the other side, if you consider only map of method binding/interface instead of deep copy, then what you are looking for is called Structural typing and languages, that support it do exist, like OCaml or Go.


问:
Should I place functions that are only used in one other function, within that function?
Specifically, I'm writing in JavaScript.

Let's say my primary function is Function A. If Function A makes several calls to Function B, but Function B is not used anywhere else, then should I just place Function B within Function A?

Is that good practice? Or should I still put Function B at the same scope as Function A?

答: Since function B isn't used anywhere else you might as well just make it an inside funtion within function A because that's the only reason why it exists.</p>


答:
I think one reason why this isn't widespread has to do with the meaning of names within a programming language. The fact that a class A has a field x and a class B also has a field x does not prove that these two fields are in any way comparable - one might be a value in a 2-D coordinate system and the other a dependent variable in a statistical modelling problem. (The standard example for this in the literature is that both a Tree class and a Dog class might have a member bark, but they will probably be very different.)

As long as you deal only with A objects, you have a certain kind of assurance that one object's x is like another object's x, only of greater or smaller value. Between classes, all bets are off. And if all the fields with similar names are comparable in the way you want, then it's more likely that the classes should be related to begin with, so you can achieve what you want via normal Object slicing.

Title: Property-level value transformation for indirect object casting

Body:
Does any programming language exist to support the explicit, property-level object copy?

For example, assume this code:

public class Student
{
    public string Name { get; set; }

    public string Code { get; set; }

    public List<string> Interests { get; set; }
}

public class Item
{
    public string Name { get; set; }

    public string Code { get; set; }
}
```

<p>I wonder if there is a compiler (or a language) out there that can indirectly cast two objects to each other, based on property-level matching and a lossy transformation algorithm?</p>

<ol>
<li>Create an instance of the target class</li>
<li>Using reflection, find all properties of the target class</li>
<li>For each property, try to find a match in the source class, using name and type</li>
<li>If found, transfer the value</li>
<li>Otherwise, initialize to the default value</li>
</ol>

<p>Of course, this should be done <strong>explicitly</strong> with the full intention of the developer. For example, a C# pseudo-syntax might look like:</p>

<pre class="lang-cs prettyprint-override"><code>Student student = new Student();
student.Name = "Saeed";
student.Code = "513223";
Item item = copy student; // assume "copy" to be a keyword
// Here, item's name is "Saeed" and its code is "513223"
</code>```


答:
I think you'd definitely like to look at this paper by Erik Meijer & Gavin Bierman, titled "Contrary to popular belief, SQL and NoSQL are really just two sides of the same coin". In short, it claims that mathematically speaking both approaches base on the same theory, but with some differences.

Couple of interesting differences are, from my opinion, the following: the direction of cross-type dependencies (FK in SQL) are the opposite in SQL and NoSQL and collections type is not limited to set in NoSQL (and therefore some set-theoretical operations might not apply in NoSQL world anymore, but some others are still valid). Yet another interesting point from the article is the single query language proposed for querying both SQL and NoSQL databases. It's called LINQ, and if you think you might've heard this name before, you're correct: that's the Microsoft's querying language from C#.

Title: Is there anything groundbreaking about NoSQL?

Body:
I am a very solid Relational Database guy and understand all the way to 3rd normal form, appreciate the algebraic set theory roots of SQL, and can probably relationalize a broken heart (or not).

I haven't figured out a relational database structure FOR date nights with my wife, but I HAVE thought about relational database projects ON date nights with my wife..

Now I'm hearing about NoSQL, and researching it.  Cutting to the chase, is there anything about NoSQL that is ground breaking, mathematically novel, or a "hey you don't even really need to organize your data relationally, this is so much easier" type of approach?

Is NoSQL like a super shell to the data structure? In my mind, data must ultimately have structure to be retrieved and the retrieval must be defined in a language of some sort.


问:
Ideal & idomatic javascript interface for RESTful API
I am trying to write an angular service to interface with a RESTful API.
For sake of simplicity, lets assume the API is

```<code>+ Company
|___+ Department
|   |____ Person
|
|____ Person
</code>```

Notice how person can be under Company > Department or directly underCompany.
  Each of the entities (Company, Department and Person) support add, edit, list and get_by_id.

Which of the following interfaces is more idiomatic?

Option 1:

```<code>// In all cases, get(), put() return $http promise

companyApi().get() // List all companies
companyApi(1).get() // Get company with ID 1
companyApi(1).departments().get() // List all departments
companyApi(1).departments(2).get() // Get department with ID 2
companyApi(1).departments(2).persons().get() // List all persons
companyApi(1).departments(2).persons().put(p) //Add a new person in department 2
companyApi(1).persons().put(p) //Add a new person in company 1
companyApi(1).persons(3).put(p) //Edit person with ID=3 in company 1
companyApi(1).persons(1).remove(p) // Delete a person
</code>```

Option 2:

```<code>// In all cases, get(), put() return $http promise

// List all companies
companyApi({
    type: 'company'
}).get();

// Get company with ID=1
companyApi({
    type: 'company',
    companyId: 1
}).get();

// Get department with ID=2 under company 1
companyApi({
    type: 'department',
    companyId: 1,
    departmentId: 2
}).get();

// List persons under department with ID=2 under company 1
companyApi({
    type: 'person',
    companyId: 1,
    departmentId: 2
}).get();

// Get person with ID=3 under department with ID=2 under company 1
companyApi({
    type: 'person',
    companyId: 1,
    departmentId: 2,
    personId: 3
}).get();

// Get person with ID=3 under department with ID=2 under company 1
companyApi({
    type: 'person',
    companyId: 1,
    departmentId: 2,
    personId: 3
}).get();

// Add person under department with ID=2 under company 1
companyApi({
    type: 'person',
    companyId: 1,
    departmentId: 2,
}).put(personObj);

//Edit person with ID=3 in company 1
companyApi({
    type: 'person',
    companyId: 1,
    departmentId: 2,
    personId: 3
}).put(personObj);

// Add person under directly under company 1
companyApi({
    type: 'person',
    companyId: 1
}).put(personObj);
</code>```

答:
First of all, whatever you do, please use unique ids. In your current scheme you can only reference an entity through the exact path through the tree, that is generally annoying to work with. What happens if a person is moved from one department to another? Or if there is a department restructure? Nothing will retain its handle.

Second, don't make entities that basically work the same way different. Company, department and any other organisation entity is just a container in your data model, there is no reason to distinguish between them in your basic data model.

The simplest way of implementing a tree structure is to make a data table with the fields id and parentId and have the parentId of any row be the id of its parent.

You can of course make a host of different functions to interface this data, you could start out with something like:

```<code>get(id)
getChildren(id)
getChildrenIds(id)
getDescendants(id)
create(parentId, ...)
move(id,newParentId)
</code>```

Body:
First of all, whatever you do, please use unique ids. In your current scheme you can only reference an entity through the exact path through the tree, that is generally annoying to work with. What happens if a person is moved from one department to another? Or if there is a department restructure? Nothing will retain its handle.

Second, don't make entities that basically work the same way different. Company, department and any other organisation entity is just a container in your data model, there is no reason to distinguish between them in your basic data model.

The simplest way of implementing a tree structure is to make a data table with the fields id and parentId and have the parentId of any row be the id of its parent.

You can of course make a host of different functions to interface this data, you could start out with something like:

get(id)
getChildren(id)
getChildrenIds(id)
getDescendants(id)
create(parentId, ...)
move(id,newParentId)


问:
Log within try-catch or after?
Should one log success of an operation within a try-catch-block, or after it?

Example:

```<code>try
    do x
    log('successful')
catch
    log('fail')
end
</code>```

or is this better:

```<code>try
    do x
catch
    log('fail')
end
log('successful')
</code>```

I would say that a logger should never fail, but what if, for some reason, it does anyway?

In this specific case, I  had a logfile on a network drive which disconnected due to actions of do(x), which however did not fail -- obviously my try failed, but my operation worked.
However, I find the latter example harder to read, and I try to keep my code as tight as possible for readability.

答: To answer your question you really need to answer the following: would you treat a log call failure as a failure of the whole try block? If yes, then it belongs in there. Otherwise, it should be placed outside. The bigger idea is to manage granularity of the try blocks, so that you catch right set of exceptions.

Title: Log within try-catch or after?


问:
Doctrine 2 and Concrete table inheritance
I use Doctrine 2 and I've read some articles on inheritance strategies' mapping with ORM.
I've seen three main strategies : "Class table inheritance", "Concrete table inheritance" and "Single table inheritance".

With Doctrine 2, I managed an install of "Class Table Inheritance" (CTI) and "Single Table Inheritance" (STI).

In some cases, I think use the "Concrete Table Inheritance" is most appropriate, but i didn't find any documentation which show this strategy in Doctrine 2.

Why there is no "Concrete Table Inheritance" with Doctrine 2 ?

Is it for performance ? What is the reason ?

答:
Concrete table inheritance is a problematic inheritance form as it requires the ORM to update multiple tables if a field in a supertype changes. The upside is that it doesn't require joins with supertype tables in many cases but it comes, as said, with the downside that it denormalizes your model. Not many ORMs support it (Hibernate/NHibernate does, but warns against it).

It's solely an optimization option, there's no logical 'need' for it as in 'it fits my application better', as the only difference with other inheritance forms is that it is stored differently in the DB.

If possible, stay away from inheritance mappings in ORMs btw. Only use it if there is clear entity inheritance in your domain. Don't use it for mapping pure OO structural aspects to the DB, e.g. avoid things like a supertype which has only fields like 'CreatedBy' and 'UpdatedOn' and is then inherited by all entities.


问:
Entity Framework with no direct table access
There are some similar questions I've found here, but none of them fully answer the question I'm asking. Similar questions: here and here

In my company, I develop C# .NET applications and our Server Admins in IT don't allow direct table access so we're required to use stored procedures to insert, update, and delete from a table. In the past I've been using DataSets and TableAdapters to access the tables of a database, but I'm starting to realize that everything is starting to use Entity Framework.

Herein lies my issue. There is another developer here that uses the Entity Framework, but he doesn't actually use entities. He uses Entity Models that have no tables or views, only stored procedures. Doesn't this defeat the purpose of the Entity Framework, or am I crazy?

Also, I realize that you can map the insert, update, and delete functionality to stored procedures and this article mentions some interesting ways of implementing that, but creating views for every table would be a major pain. Are there any more practical or easily implemented alternatives?

答:
I think you are on the right track with the EF stored procedures support. I would disagree with your pov about it would be pain to create stored proc and views.

Views:
One View per table

Stored procedures:
You will need at most three stored procedures

```<code>Create
Update
Delete
</code>```

And most of it is boiler plate code.

If the database is too big try using some sort of code generator tool. Or at its very simple have a template for your stored procedures in Visual Studio's SSDT project.

Once you have above four things in place considering you use some sort of Generic repository pattern, it would be quire easy to write your Business Services code.

```<code>public class MyBusinessService : IMyBusinessService
{
    public void InsertData(DataDTO dto)
    {
         ...
         _repo.Add(data);
         _repo.SaveChanges();
    }
}
</code>```

If you think about it , the amount of time you spend writing custom stored procedures for each operations, is large compare to one off three stored procedures and one view. In addition all your services code can be unit testable.

The thing you will need to consider when using EF (and is true for any ORM) is that its generating SQL for you from your C# code, so needs to pay attention about how you write your EF to Linq queries.

Body:
I think you are on the right track with the EF stored procedures support. I would disagree with your pov about it would be pain to create stored proc and views.

Views:
One View per table

Stored procedures:
You will need at most three stored procedures

Create
Update
Delete

And most of it is boiler plate code.

If the database is too big try using some sort of code generator tool. Or at its very simple have a template for your stored procedures in Visual Studio's SSDT project.

Once you have above four things in place considering you use some sort of Generic repository pattern, it would be quire easy to write your Business Services code.

public class MyBusinessService : IMyBusinessService
{
    public void InsertData(DataDTO dto)
    {
         ...
         _repo.Add(data);
         _repo.SaveChanges();
    }
}

If you think about it , the amount of time you spend writing custom stored procedures for each operations, is large compare to one off three stored procedures and one view. In addition all your services code can be unit testable.

The thing you will need to consider when using EF (and is true for any ORM) is that its generating SQL for you from your C# code, so needs to pay attention about how you write your EF to Linq queries.


答:
First of all, you have to ensure that logging never throws any exceptions. It's better not to log one message than breaking program logic by it.

Besides that, your second code in case of a success would log:

```<code>"successful"
</code>```

but an error would log 2 messages:

```<code>"fail"
"successful"
</code>```

I think it's not what you want, so a first example is the way to go.

Title: Log within try-catch or after?

Body:
Should one log success of an operation within a try-catch-block, or after it?

Example:

```<code>try
    do x
    log('successful')
catch
    log('fail')
end
</code>```

or is this better:

```<code>try
    do x
catch
    log('fail')
end
log('successful')
</code>```

I would say that a logger should never fail, but what if, for some reason, it does anyway?

In this specific case, I  had a logfile on a network drive which disconnected due to actions of do(x), which however did not fail -- obviously my try failed, but my operation worked.
However, I find the latter example harder to read, and I try to keep my code as tight as possible for readability.

Body:
First of all, you have to ensure that logging never throws any exceptions. It's better not to log one message than breaking program logic by it.

Besides that, your second code in case of a success would log:

"successful"

but an error would log 2 messages:

"fail"
"successful"

I think it's not what you want, so a first example is the way to go.


答:
Note that there are so many package managers; people keep thinking that it's an easy task and reinventing the wheel. The underlying problem is that software can interact in unexpected ways.

Most packaging systems which have versioned dependencies start off with "greater than or equal":

```<code>progX v2.8 requires libfoo >= v1.1
</code>```

Then someone releases libfoo2.0 which changes the interface and breaks progX. So now the developer of progX decides to use exact dependencies:

```<code>progX v2.9 requires libfoo == v2.0
</code>```

Then a security hole is discovered in libfoo, and everyone should urgently upgrade! But the exact dependency prevents this; either the package manager uninstalls progX or refuses to upgrade.

You might think you can avoid this by having libfoo1.1, libfoo2.0 and libfoo2.1 installed all at once. This mostly works, provided they can all be kept in distinct directories, you don't mind the disk space consumption, and they don't have to put files in some common location. But if libraries can depend on other libraries, this will fail: very few languages/systems will let you link libfoo1.1 and libfoo2.0 into the same program.

The other solution is to just bundle all the dependencies into progX. This is the approach taken by Windows, Android and iOS. You don't have external dependencies other than the operating system and its libraries. Hardly perfect ("this app won't work on your phone because it requires newer Android and your manufacturer won't upgrade", plus no automatic security upgrades), but you have basically reduced the number of points of failure to one.

I'm not familiar with cabal that you mention, but it seems to be the same basic problem: https://www.fpcomplete.com/user/simonmichael/how-to-cabal-install & https://hackage.haskell.org/package/cabal-nirvana imply that it's due to packages requiring incompatible versions of other packages.

This may require a social solution, of co-ordinating package releases to avoid this problem. Apt works because Debian's politics of coordination and release make sure it does, and Ubuntu build on this with a small team of smart people under a single employer.

(I'm disappointed that the functional programming community have bad dependency resolution, as it's the sort of mathematical graph problem that FP people and tools ought to excel on. They should look at apt/dpkg and see how it handles this.)

Title: Has anyone nailed dependency management?

Body:
I've used various dependency management tools for installing software: homebrew, cabal, rubygems, etc.  Invariably, despite someone's simple instructions for installing their package, there are times when dependencies don't get worked out by the package manager and the installation fails.  This is more common than it ought be.  And frustrating!  You end up trying to troubleshoot the installation process which I feel is something users (even if they are developers) shouldn't have to do.

This is one reason people knock Linux (which I love!) as compared to Windows: installations can be associated with complications.  Windows users aren't tasked with compiling source.

Is someone aware of a dependency management tool (or dependency management strategies) that has been especially successful at eliminating the bumps associated with installs?  Clearly some package managers must be better than others.  Or does this remain an unsolved problem?

Body:
Note that there are so many package managers; people keep thinking that it's an easy task and reinventing the wheel. The underlying problem is that software can interact in unexpected ways.

Most packaging systems which have versioned dependencies start off with "greater than or equal":

progX v2.8 requires libfoo >= v1.1

Then someone releases libfoo2.0 which changes the interface and breaks progX. So now the developer of progX decides to use exact dependencies:

progX v2.9 requires libfoo == v2.0

Then a security hole is discovered in libfoo, and everyone should urgently upgrade! But the exact dependency prevents this; either the package manager uninstalls progX or refuses to upgrade.

You might think you can avoid this by having libfoo1.1, libfoo2.0 and libfoo2.1 installed all at once. This mostly works, provided they can all be kept in distinct directories, you don't mind the disk space consumption, and they don't have to put files in some common location. But if libraries can depend on other libraries, this will fail: very few languages/systems will let you link libfoo1.1 and libfoo2.0 into the same program.

The other solution is to just bundle all the dependencies into progX. This is the approach taken by Windows, Android and iOS. You don't have external dependencies other than the operating system and its libraries. Hardly perfect ("this app won't work on your phone because it requires newer Android and your manufacturer won't upgrade", plus no automatic security upgrades), but you have basically reduced the number of points of failure to one.

I'm not familiar with cabal that you mention, but it seems to be the same basic problem: https://www.fpcomplete.com/user/simonmichael/how-to-cabal-install & https://hackage.haskell.org/package/cabal-nirvana imply that it's due to packages requiring incompatible versions of other packages.

This may require a social solution, of co-ordinating package releases to avoid this problem. Apt works because Debian's politics of coordination and release make sure it does, and Ubuntu build on this with a small team of smart people under a single employer.

(I'm disappointed that the functional programming community have bad dependency resolution, as it's the sort of mathematical graph problem that FP people and tools ought to excel on. They should look at apt/dpkg and see how it handles this.)


问:
In plain English, what is recursion?
The idea of recursion is not very common in real world. So, it seems a bit confusing to the novice programmers. Though, I guess, they become used to the concept gradually. So, what can be a nice explanation for them to grasp the idea easily?</p>

答:
I like to use this one:

How do you walk to the store?

If you're at the entrance to the store, simply go through it.
Otherwise, take one step, then walk the rest of the way to the store.

It's critical to include three aspects:

A trivial base case

Solving a small piece of the problem

Solving the rest of the problem recursively

We actually use recursion a lot in daily life; we just don't think of it that way.

Title: In plain English, what is recursion?


问:
Design Pattern: A single class with multiple purposes, or multiple extended classes each with their own purpose in PHP
I'm working on a PHP framework called Carbon CMS. This framework will be used as base to build larger web applications on top of it. This framework should provide all kinds of interfaces such as database access, caching and so on.

Currently I'm working on the IO and file handling part of the framework. This question will be about the design pattern I should use, whether I should use a single, or multiple classes that extend each other. In this case, the question will be asked with file systems in mind, because this applies to the problem I'm having, and should make it easier to understand the question itself because an example is given. So keep in mind, that this design-pattern question also applies to other cases.

My idea is to built a class, or multiple classes that reference to a file, directory or symbolic link on the file system by it's path. Then, these class(es) should also provide an interface to read/write files, to list directories and so on. Think of the File class in Java, or the File, Dir classes in Qt.

The question I'm having is what kind of structure or design pattern I should use in this case. I could create a single File class that has all the functionality included, not just for files, but also for directories and symbolic link. But I could also create multiple classes, such as Path, File, Directory and SymbolicLink. So, there are two possible ways I can think of:

Using a single File class. This class holds the reference (path) to a file system entry such as a file or directory. This class includes functionality both for files, directories and symbolic links, such as reading/writing files or listing directory contents.

Using multiple classes, which extend each other. A Path class (or something similar) holds the reference (path) to the file system entry such as a file or directory. And only contains the basic functionality which could be used on all three different file system entry types (files, directories and symbolic links). Think of features such as Path::isFile(), Path::getPath() or Path::exists(). Then three other classes are used for the different file system entry types called File, Directory and SymbolicLink, all of these classes extend the Path class to implement it's basic functionality and the path reference. These three classes contain the functionality for that specific entry type. So, methods to read and write files would be found in the File class; File::getContents();, and a method to list the contents of a directory would be placed in the Directory class; Directory::list();.

So, to clarify my question. Should I go for the first option, and create a single File class which handles everything regarding IO and file handling. Or should I go with the second option and create multiple classes. Where each class is for a specific type of file system entry (except the Path class, which will be used for all three types).

Now, if going for the first option. Functions such as listContents() (to list directory contents) could easily be called on a path that references a file. It would be impossible to list the directory contents of a file, thus calls like this would return null, or something similar indicating the directory couldn't be listed. When using the second option, this would be a bit different. The listContents() method would only be available for Directory instances, and these instances should reference to a directory anyway. Of course, it would be possible that the referenced path doesn't exist, but that could be the case with both options.

There are a few pro's and con's for both options. Here are some I can think of:

Going for the first option, with a single class:

Casting instances isn't required to use entry specific operations when using File's.

Creates one huge interface for everything, which makes it messier and allows certain operations to be used on incompatible file system entry types, such as listing directory contents on a file.

Going for the second option, with multiple classes:

Casting instances, and instance type checking is required to use entry specific operations when using Path's.

Creates a separate interface for each file system entry type, which makes it less messy, and also prevents the use of most operations on incompatible file system entry types.

The framework will be open to the public and will be used by multiple people, thus I'm looking for the option that is the easiest to use, doesn't have a performance impact if possible and the option that suits this ground the best.

Here's some sample code, to show off the very basic structure of both options.

When using a single class, with option one:

```<code>class File {
    private $path;

    public function __construct($path) {
        $this->path = $path;
    }

    public function getPath() {
        return $this->path;
    }

    public function getContents() {
        // Return the contents of a file
    }

    public function listContents() {
        // Return the contents of a directory
    }
}
</code>```

When using multiple classes, with option two:

```<code>class Path {
    private $path;

    public function __construct($path) {
        $this->path = $path;
    }

    public function getPath() {
        return $this->path;
    }
}

class File extends Path {
    public function getContents() {
        // Return the contents of a file
    }
}

class Directory extends Path {
    public function listContents() {
        // Return the contents of a directory
    }
}
</code>```

I should note that all the methods noted in this question, such as Path::getPath(); or Directory::listContents(); are non-static and have to be called on the instance of the class.

Java uses a single File class, which would be similar to first option I gave with a single class. There are some classes available such as a DirectoryIterator but classes like this would be created anyway, and don't depend on the first or second option. On the other hand, Qt uses something similar to the second option I gave, as far as I know.

So finally; What would be the best option, and why?

答:
I think you are touching two often discussed topics here:

Monolithic classes vs small components

Composition vs inheritance

The following is a conclusion from what I've read and learned when I had similar problems to solve.

Monolithic vs components

Usually you should go for components that provide a model of the reality instead of building big monolithic blocks. Small components are easier to test and debug and harder to break.

Composition vs Inheritance

If you can go without inheritance you should.
In your case the only common piece of File and Directory is that it has a path.
Note the HAS A relation here. In fact the path is a property.
Neither a directory nor a file is a path.

So - what you should go for is composition instead of inheritance.
Please see http://en.wikipedia.org/wiki/Composition_over_inheritance for an introduction.

How to hold things together

Look for the factory pattern for returning a file or a directory depending on the type of file system object

Use an interface to define methods that both File and Path need to implement.

If both need the same functionality define a class for it. Usually the methods in this class are static. A trivial example would be a class FilesystemPermission that provides a method ::show($file_or_directory_object)

By the way - reading 'The Pragmatic Programmer' (look it up in the bookstore of your choice) covers such problems in depth - go for it if you haven't read it yet (every programmer should!).


问:
Hardware-control on one computer. But how about several?
For a while I have been pondering the question of, given a standard interface specification, whether there is a way to allow multiple programs to control multiple hardware devices across the network. The program I am working with is the standard implementation of the ASCOM standard.

In short, the principle is that any program can call another known program or driver and expect it (computer-wise) to implement certain standard interfaces, allowing the calling program to control hardware. Currently we only use COM and .NET to do this.

This allows many different hardware and software manufacturers to all build software and drivers that all work together. By now it is becoming quite standard, including standard telescope companies providing drivers.

Within the ASCOM group, we have discussed how to do this across the network, but since we are more of a user group with a couple core devs, we have never been able to really decide what's a good way to do this. In order to understand the situation better, since I have already made a proof of concept system that works, here are several questions.

What transports/pipes/interops are available that most or all languages support across OSs? Or is the transport OS specific? I mean, for instance, the COM interop is on windows. Is there an equivalent on Linux, for instance, that would work the same and the language could use interchangeably? Most languages support network IO. Do we have to use that for interprocess communication or are there other options?

To make something truly platform and language agnostic, it would almost need to be dealing with text strings, not binary objects. What standard formats are there, and what are the pros and cons of each.

What are your thoughts on getting multiple languages to work together on one computer? Can it work well? Inter-process or intra-process as well?

Is something like ASCOM done in any other field of computing? Or are astronomers the only people who connect various software programs and hardware devices together to get one working system?

If you need more information, feel free to ask. The ASCOM standards home page is short and hopefully might help illustrate things a bit, but I don't expect you to crawl all over the site before you can answer. :D

答:
I assume the common underlying technology is TC/IP packets, and some kind of packet protocol layered on top. The question is which?

If the performance requirements are extreme and you have a willingness to write low level code then you will probably use something based on UDP. This is a connectionless protocol suitable for peer-to-peer communications, but you will have to write quite a bit of protocol code on top. Protocol buffers (as mentioned by @mattnz) provides a way to generate the structures and conventions required to support low-level binary protocols across a wide variety of different languages and architecture.

If the performance requirements are moderate and you have to support a lot of very low level devices, then you will probably use something based on TCP sockets. The natural approach is to write host servers and device clients, and again protocol buffers could be the way to go. You might use this for a camera data feed, but not so much for just sending instructions to position a telescope.

If the performance requirements are less demanding and the devices are all programmed with high-level languages, then you might well choose something based on HTTP. It is quite easy to write a sophisticated server on the host side supporting such things as SOAP, XML, JSON and REST. A simple client need only assemble a string and send it via a socket. There are libraries available in multiple languages to support these technologies, and in many ways they are the natural successor to the COM/DCOM you are already using. This would be well-suited to sending command strings and receiving responses, but perhaps less so for large batches of binary data.

Hopefully one or more of these will suit what you need.


问:
How do processes communicate?
What transports/pipes/interops are available that most or all languages support across OSs? Not necessarily, network, but interprocess. Or is interprocess communication OS specific? I mean, for instance, the COM interop is on windows. Is there an equivalent on Linux, for instance, that would work the same and a programming language could use interchangeably? I know most languages support network IO. Do we have to use that for interprocess communication or are there other options?</p>

答: Inter-process communication is always mediated by the operating system. Generic options for communication include (but are not limited to) files (you'll have to lock them to avoid race conditions), using standard in and standard out, or network sockets. Which one works best depends on your application's needs. Of course, you'll need a way to structure the data, since all 3 mechanisms operate at the byte level. JSON, YAML, and XML are all common formats for structuring and passing around data as strings.</p>

Title: How do processes communicate?


问:
How come centralized source control solutions don't do branching in place
With centralized source control like Perforce and SVN, when they create a branch, they create a whole new directory. However, git and other distributed source control solutions, in my experience, are able to update the branch in place as it were. That is, they apply the differences between the two branches to the files.

This seems to me to be the far superior option as it saves huge amount of duplication for large projects, quicker to switch branches etc...

What is the reason for this? I can't see any reason why there being a centralized authority affects the clients ability to diff the two branches and modify the changes.

答:
It's a snowball effect.

SVN has been around a long, long time, and duplicating a directory was the easy-to-code solution. It was good enough because branching was rare. But then DVCS were invented partly to overcome perceived weaknesses in SVN, and they had great, efficient branching support. That lead to people using much more branching than ever, which made it even more important that branching be cheap, so now it's unthinkable ever to go back to the easy-to-code solution.

So the reason is historical accident rather than the development model - it's more or less a coincidence that Linus introduced improved branching and distributed storage at the same time (via git). Certainly you could program efficient branching storage into any VCS if you wanted to.


问:
How do you guard against hidden overflows
consider the following:

```<code>(i+j)/2
</code>```

i and j are both 32 bit integers and the result should also be.
But in the little equation, there's a hidden overflow, i+j could become larger then a 32 bit integer even though the result would always be a 32 bit integer.

```<code>public class Sum{
     public static void main(String []args){
        int i = 2147483647;
        int j = 2147483647;
        System.out.println((i + j)/2);
     }
}
</code>```

Gives me -1 as a result.

How do you guard against situations that can overflow but are not always obvious.
Is there a pattern that describes this?

(apart from declaring everything long)

I'm looking for a general answer, the java example is just to  provide an example, my Delphi does the same.

答:
You can define your own arithmetic operators, for example like this.</p>

```<code>int operator + (int a, int b) {
    int res = a + b;
    if(a > 0 && b > 0 && res < 0) {
        throw new ArithmeticOverflowException();
    } else if(a < 0 && b < 0 && res > 0) {
        throw new ArithmeticUnderflowException();
    }
    return res;
}
</code>```

Body:
You can define your own arithmetic operators, for example like this.

int operator + (int a, int b) {
    int res = a + b;
    if(a > 0 && b > 0 && res < 0) {
        throw new ArithmeticOverflowException();
    } else if(a < 0 && b < 0 && res > 0) {
        throw new ArithmeticUnderflowException();
    }
    return res;
}


问:
Doesn't an event bus affect global state?
"Minimize mutable global state" is a more or less accepted program design principle. The reason often cited is that having global state can affect two components that don't are seemingly unrelated. In other words, a component mutating global state would have no idea who else it is effecting since it doesn't know what other component has a dependency on that global state.

Tangentially, a pattern that is often recommended for building decoupled software is the event bus pattern where a component capable of generating events broadcasts it over a bus and components interested in certain events subscribe on the same bus to receive said events.

My question is - doesn't the argument that holds for global state hold in the case of event bus too? After all, when broadcasting an event, I have no idea who else I am breaking since I have no way to know what other components are listening for it. Further, just as in the case with global state, reading the code might not make the dependencies of components on a certain even clear at the site of broadcast either.

The only difference between the two that I can think of is that an event is a transient state versus global state in the form of static variables or shared objects, that might be persistent.

答:
Yes, it's global state, but it's appropriately controlled global state. With the event bus, a given receiver can usually register for just the events it wants to see, and a given sender will only send a very small selection of the possible events. The ordering of event handling is often in some way defined by the event bus (as opposed to everyone polling a global willy-nilly). In an event bus, the only way things change is if everyone gets NOTIFIED that they changed.

Your problem is that you're taking the idea 'global state==bad' too literally. Unmanaged global state is bad. Global state that can change without notice is bad. Well controlled, properly isolated global state lets you get the job done.