问:
One of my team members committed SQL injection-vulnerable code; should I report it to the manager?
One of my team members committed a huge mistake; a clear SQL injection-vulnerability. It obviously didn't pass my peer review and I made very clear that this is unacceptable. I never saw this programmer make this mistake before and I'm unaware of any other security holes this particular programmer committed. The problem is fixed and my explanation is understood.

My considerations:

The programmer is now aware of this mistake and probably won't do it again.

The problem however was huge and could have had major consequences when brought to production.

It's not a junior programmer (> 5 years experience).

Should I tell the manager?

答:
There are only two good reasons to report something like this to management: is if you believe that the coder who did this was malicious and attempting to sneak something through, or if you believe that the coder who did this is incompetent, which can be just as harmful as a malicious coder.

From the way you describe him, it sounds like you believe he's just a programmer who made a mistake.  I bet you've done that a time or two, even as an experienced developer.  It got caught in review before it ever made it to production, and you've talked to the guy and made him aware of the issue.

Personally, at this point, I'd file the whole incident under "no harm done, lesson learned" and let it go.  But keep an eye on this guy's commits for a while, just to be sure, and if you see a pattern emerge, then go to management.  But for the moment, there's no reason to go potentially screwing up someone's career over one mistake.


答:
This is the whole point of code review.

Mistake is written. Mistake is found and corrected in code review.

Do you want to tattle on your senior team member? This team member according to you has never made a similar mistake before.

Unless the code was intentionally written that way (and you can prove it) this is a really dumb idea to go to management with.

ContentLicense: CC BY-SA 3.0

Title: One of my team members committed SQL injection-vulnerable code; should I report it to the manager?

Body:
One of my team members committed a huge mistake; a clear SQL injection-vulnerability. It obviously didn't pass my peer review and I made very clear that this is unacceptable. I never saw this programmer make this mistake before and I'm unaware of any other security holes this particular programmer committed. The problem is fixed and my explanation is understood.

My considerations:

The programmer is now aware of this mistake and probably won't do it again.

The problem however was huge and could have had major consequences when brought to production.

It's not a junior programmer (> 5 years experience).

Should I tell the manager?


问:
Scaling locks in high concurrency web apps
Our web application has a certain resource type that is shared accross multiple users, and may thus be read and written by anyone at anytime. We resorted to the usual suspects, database transactions and software locks with expiration times, and with a low user base and low concurrency this worked well and prevented many race condition scenarios that would otherwise have happened.

We are now slowly starting to scale and are finding out that with a few hundred concurrent users, ocassionally (about once a day) a request fails due to either timing out waiting for a lock (which I assume happens when many attempt to get or are waiting for the same lock at the same time) or by database deadlocks. Today, this is only a minor annoyance, since it's still relatively infrequent and the affected user can reattempt the request and it will usually get through. But we are naturally concerned that this will not scale well.

How is this scenario typically addressed? I can only imagine it's a relatively common problem to have, but I'm not sure what specific techniques can be applied here without having to redesign the entire application. We're looking into lock-free designs currently, but at a first glance it would seem like rewritting our application to be lock-free would be a titanic task. Any sort of advice would be appreciated.

答:
Welcome to the deep, dark recesses of the Concurrency Jungle! This is where many app developers fear to tread--and fear it for good reason.

@kdgregory gets it exactly right: This is not one problem, but a very large, very sticky class of problems.

Most hard concurrency problems are addressable at scale, with sufficient effort and investment. None, however, are particularly simple, easy, or cheap. All of the world's high-concurrency solutions--e.g. the insides of operating systems and databases, high-scale message passing and trading systems, financial markets, travel booking systems, global web apps--have received enormous ongoing development efforts and investments, in most cases over years or decades. Most of them have required fundamental engine rewrites/roto-tilling to reach new scale plateaus.

It sounds as if you are at one of those plateaus. Your fear about "having to redesign the entire application" and "at a first glance it would seem [to] be a titanic task" are well-founded. If you aren't daunted at the effort involved in scaling up a highly-concurrent app, you just don't understand concurrency.

I would start by reconsidering the "certain resource type that is shared accross multiple users, and may thus be read and written by anyone at anytime." Is it truly possible for any and every user to share this resource / these resources? Or is it just that many users may share each? That's a slightly subtle distinction. If truly everyone may share (M:1), that's a genuine individual bottleneck. If it's more accurately M:N, and the users that can share each of the N can be grouped or partitioned, then it may be more readily addressed, for example by

Sharding Sharding would partition users onto different servers, along with their related critical resource(s). Organizing by shards/partitions isn't automagically easy, but it's easier than a lot of other concurrency strategies, given that it nicely strength reduces the problem into smaller sub-problems, each of which is more manageable and performant. If pure sharding isn't enough, it's sometimes possible to combine sharding with function or data shipping: that is, sharing for the common cases, then move shared computations to where the data is, or dynamically recognize users that could be better migrated to other shards, as what other resources they interact with are discovered. And/or if your central shared resource is read-mostly or read-more-often-than-write, it can possibly also can be replicated across shards.

Truly complete sharing problems are harder--especially if you have heavy updates to your critical shared resources.

Scale Up. For some scale ranges, this can be addressed with "scale up" servers--buying much bigger, shared-memory servers. The servers are a lot more expensive than traditional web gear, but the large memory complement and extremely high-speed system interconnect goes a long way to solving communication/coordination problems. Even if the gear is expensive, you don't have to worry so much about software rewrites, which can make them an economic win. ("Send in the mainframes!")

Parallel Scale Up. A fallback from there are logically scale-up data stores: parallel database and middleware engines (e.g. DB2, NonStop SQL, Teradata) that, while parallel internally, appear to your code as unified, less-parallel services. (Internally such servers often use InfiniBand or proprietary low-lantency system-to-system interconnects, making them a hybrid between full "scale up" and distributed servers.)

Many web apps, however, skip the various levels of "scale up" solutions and head directly for the final frontier:

Fully distributed. Rewrite to use middleware/services with exposed parallelism. Examples would be Hadoop, Amazon Web Services's
SimpleDB database and SQS queueing services, the parallelism models of many NoSQL databases, and the API semantics of
most high-scale web services (e.g. Twitter). To use these, developers must embrace much different and usually much weaker concurrency semantics than traditional databases offer (e.g. "eventual consistency") and must accept the responsibility for app-managed concurrency (also a weaker semantic and service level than app developers have been accustomed to).
This preference for exposed parallelism in web apps is often cultural, since so many web apps are "green
fields" and there
is a strong preference for scale-out strategies and "parallel
everything" (really, "distributed everything," since even scale-up
systems are highly parallel).

This final "entirely distributed, parallelism exposed" infrastructure is popular among the highest scale web apps (e.g. Google, Facebook, Twitter), but it's also where your "large rewrite effort" fear comes in most directly, because adopting these would likely change the level at which your app manages interactions/sharing. I'd suggest reviewing the opportunities for the more modest sharding and/or scale-up strategies before diving into the full "eventual consistency" and "rewrite for different sharing semantics" thickets.


问:
Why sacrificing good software engineering practices is typically the first choice for software development projects assuming "good enough" quality
I have observed a correlation between a customer ordering software of "good enough" quality and the same customer not willing to pay for good engineering practices (unit testing, code reviews and the like) that many times that I would call it causality. Still, I am having hard time coming up with any logical reasoning behind such thinking so I would appreciate some insights from the community here.

As I see it, the engineering practices mentioned above have effect on only two quality attributes: maintainability and, to a lesser degree, reliability. Except for throw-away prototypes, I can hardly imagine a customer in their right mind who would want to get software that

crashes every now and then (although I realize that MTBF expectations vary depending on the cost of error), and/or

incurs considerable maintenance costs down the road.

On the other hand, other quality attributes such as scalability or performance are not directly affected by the engineering practices (if we don't count architecture reviews which are kind of from another league). What's more interesting, relaxing one or more of these could lead to way more considerable cost reductions, while not following proper engineering practices might as well lead to increasing project costs due to so called "endless debugging / stabilization cycle"

I should be missing something important since the preference to "save" on not doing software development properly is so prevalent among customers.

Please enlighten me :)

答:
This really depends on the reaction of the customer when they get software they don't like. Very few will say, "Gee, you were right. We should have had tests." but most will feel like you should have been able to make those "simple" changes anyway.

If you continue to struggle with customers, you need to stop asking them if they want you to create tests. Provide quotes based on your expert opinion for doing quality work. Do you ask them if they want you to use and IDE that is more productive or if you should automate the build?

Customers need to understand they are assuming the risks when they create restrictions on a project. Instead of saying, "I told you so." you should get in the habit of saying, "No."


答:
I think your reasoning is flawed because you consider "best practices" as boolean.

However, it's not a question whether you apply them or not. It's "how much" you apply them.

For example testing: you can do a couple of manual tests, cover the basic tests automatically, make an extensive automated suite, test also all your libraries/dependencies, double-check it by third parties...

For example code quality: code as you go, take time for a clean design, refactor often, double check everything, triple check by third parties, formal proofs...

Everything has a cost. Basically, the more you want to ensure that you software is bug free, the more it costs. The testing suites and frequent refactoring can quickly be more than the development itself. Now, what's the cost of a bug? ...every client is somewhere on this price/bug curve.

Some people just want something basic and would prefer to live with a bug once in a while rather than pay the extra bucks. There are plenty of examples for this:

people prefering a free tool even if it's known to have several quirks

people just wanting a prototype

people wanting software quick/cheap because they need quick ROI to stay afloat

people who don't want to spend a lot on software

there are also other extremes. Software for aircrafts, aerospace financial and medical application are tested so thoroughly that even tiny changes quickly require millions because a lot of stuff has to be thoroughly verified. And don't even think of updating an open source library ...or even use "normal" hardware! ;)

Here, it is also frequent that the same module is implemented in parallel by independent teams. The modules are then run in parallel. If at some point their output differs, some kind of decision making takes place, like taking a "majority wins" approach if there are three modules available. ...so, are you ready to develop the same software by three different teams just to ensure it is reliable? ;)

Title: Why sacrificing good software engineering practices is typically the first choice for software development projects assuming "good enough" quality

Body:
I have observed a correlation between a customer ordering software of "good enough" quality and the same customer not willing to pay for good engineering practices (unit testing, code reviews and the like) that many times that I would call it causality. Still, I am having hard time coming up with any logical reasoning behind such thinking so I would appreciate some insights from the community here.

As I see it, the engineering practices mentioned above have effect on only two quality attributes: maintainability and, to a lesser degree, reliability. Except for throw-away prototypes, I can hardly imagine a customer in their right mind who would want to get software that

crashes every now and then (although I realize that MTBF expectations vary depending on the cost of error), and/or

incurs considerable maintenance costs down the road.

On the other hand, other quality attributes such as scalability or performance are not directly affected by the engineering practices (if we don't count architecture reviews which are kind of from another league). What's more interesting, relaxing one or more of these could lead to way more considerable cost reductions, while not following proper engineering practices might as well lead to increasing project costs due to so called "endless debugging / stabilization cycle"

I should be missing something important since the preference to "save" on not doing software development properly is so prevalent among customers.

Please enlighten me :)


答:
There are already several good answers.

I would add that sometimes time to market is one of the requirements.  For example, there are industries where a large fraction of sales are generated at trade shows; that means a hard deadline, and if you miss it, you've lost opportunity and probably market share.  In such a case, it's typically necessary to have your product ready for "the big expo" -- even if it has a few bugs or you had to incur some technical debt.


问:
How to add rigor to my testing?
I work on a small/medium sized Java application. Over time, I've tried to ensure that the tests which I write are "good" tests, and that there's plenty of them. Hence I've been looking into various, more rigorous, testing methodologies, such as boundary value analysis, combinatorial tests, and other testing methods.

However, most of these have examples that are very dry, and the examples don't map very well to my domain, as the examples are mostly functions of numerical data. My functions are almost never concerned with numerical data, they're about enforcing business rules.

The application is hibernate/spring, and my testing strategy is as follows:

Every single class gets a unit test. Collaborators of each class are entirely mocked away at this point, and as far as is reasonable, the contract of that class is exercised. Usually with hand-picked test cases. These tests often run in seconds.

A full spring context is fired up by TestNG. All of a class' collaborators are therefore present, and even the database access layer is active (with a real, on-disk database that is trashed at the end of the test). Once again, the system is exercised using hand-selected test-cases. The start up time for these tests often stretches into 20 - 30 seconds apiece, and there's enough of them to seriously impact the build time.

The system is booted up, usually against a blank database, and then a copy of an end-user database. A developer "clicks around" each booted system in an attempt to elicit a failure. This takes a while, easily over 30 minutes.

I worry that my testing regimen is insufficient, and that my tests are not as effective as their metrics would imply (it's quite easy to get close to 100% coverage with this scheme). There is no formal guidance on how to select test cases, aside from "what the developer thinks are good tests."

I've considered trying to express the behaviour of the system in something roughly like Z notation, and using that specification to drive test case production, but that is likely to be very costly in terms of time. Similarly, convincing my colleagues that there will be a reasonable return on investment of such an activity would be a very hard sell, and even I'm not convinced it's worth it for our system.

There have been discussions relating to randomised tests, but they've been vague and very general; and we rarely bump into run time errors/exceptions (NullPointerException, ArraysOutOfBounds, etc.), it's usually that the behaviour of the system is unacceptable to the client (i.e. in corner/degenerate cases, the system behaves in a counter intuitive manner, but which is completely consistent)

I would like to get the most "bang for my buck" with my tests; that is, how does one design test cases which are likely to exercise a defect in the systems similar to the one above?

答:
Further to class level unit tests, what's in my opinion perhaps a more grounded test and pragmatic approach is to execute all the critical/high value execution paths..

identify and create a metrics (of criticality) for your end user's minimum required critical functionality set - invoke these functions/operations at (increasingly) much higher level than at a class level. A state transition comparison against an expected state would be your test. For example state transition could be change in database table, addition in a message queue and so on - obviously that is the expected end result of the functionality under testing.

Unit tests are good, but they are also expensive. Writing and CERTAINLY maintaining one in a fast evolving product environment has very serious and significant cost. Developers can also go to extremes to test at unit level and in the process end up loosing the far sight.

100% coverage is a very subjective term as you already know.

Title: How to add rigor to my testing?


答:
Delivery Quality can be expressed as a function of cost and time.

Future cost of software for maintenance and enhancements can only be
  expressed  as function of current delivery quality.

"Good enough is fine" --> I can live with the occasional crashes, maintenance cost, increased future feature adding cost..what I need NOW is a good enough software.. not a bad business decision under given circumstances (of cost and time)..in such cases goes out of the window are extra (less) lines of codes, refactoring, unit tests to some degree, and so on..

"Good enough is fine" and "I am also not seeing the increased future cost for maintenance and enhancement" --> I am an idiot and you are an unfortunate soul happen to work for me.


问:
Can a class method be accessed both in an instance and statically?
I am relatively new to class design and I have a task that I'm not sure how best to complete, or whether my idea in general is a code smell.

I'm developing a RPG where people can own monsters, so each one is an object instance of the Monster class. Since the sprite of a monster changes depending on a few different factors, the Monster class has a method for drawing the sprite that I call which does all the checks and logic and displays the correct sprite using the object's properties and I just call it like:

```<code>$Monster->drawSprite();
</code>```

This method does checks using other class methods, such as

```<code>$this->isHoldingItem();
</code>```

which checks data from the database using a unique monster ID (a class property) and stored as object properties.

Now and then for the story and in other places, I want to draw a monster sprite that isn't actually owned by anyone, so has no database row or object instance. Rather than hardcode the image URL or duplicate my code, is there any way a method can be called both as part of an instance and statically and respond accordingly? Is this even a good idea?

So in my head I could do:

```<code> $Monster->drawSprite();
</code>```

This will use the instance properties to determine all the necessary logic to display the sprite, or I could do:

```<code>Monster::drawSprite();
</code>```

To draw a monster sprite without relying on class properties. Maybe I could pass an array as an argument for all the necessary object property checks the method usually relies on.

I imagine I could do something using func_get_args() or lots of conditionals but I could see that turning into spaghetti code quickly. Is this a good idea, or is it even possible? I'm specifically referring to PHP with this question.

答:
This isn't an answer to your question, but a solution to your problem.

The issue here is that $Monster->drawSprite() is a non-starter; having monsters know how to draw themselves is a violation of the Single Responsibility Principle. For that same reason it doesn't make sense to try to make a method pull "double duty" by being both an instance method and static method, since you don't want the instance method at all.

You should separate the game logic from I/O. More specifically, you should be able to run the game loop without any video/audio/input devices (and I don't mean providing no-op mock interfaces). A good solution would look something like this:

The Monster class only contains data relevant to the game logic.

There exists a mapping from monster types (and other game entity types) to their corresponding sprites (and sound effects, etc.) This may involve adding a new field to your game objects.

There exists a function to go from game world coordinates to screen coordinates. (This is again a matter of separation of concerns. Separating them has the benefit that your game logic won't be affected by graphical resolution.)

There exists a drawSprite function that takes a sprite and screen coordinates and just draws it.

During normal gameplay you iterate over all game entities, find the correct sprite, calculate its screen coordinates, figure out if it's even visible, and pass all the info to drawSprite. During scripted events you just call drawSprite directly.

This might seem like extra work but you'll be thankful you did it as your game grows. Keeping IO and logic separate means you can reason about them more easily, test them separately, makes it impossible for changes in the graphics code to break your game logic, and reduces the scope you need to look at when a bug creeps in.


答: Would it be possible to use an update log approach? That is, instead of directly updating the resource, code would simply write an update entry in a table/queue/whatever-makes-sense and a periodic task (or some other mechanism) applies the updates to the resource. Now you only have lock contention on the log, which should be significantly less than contention for your shared resource.</p>

Title: Scaling locks in high concurrency web apps

Body:
Our web application has a certain resource type that is shared accross multiple users, and may thus be read and written by anyone at anytime. We resorted to the usual suspects, database transactions and software locks with expiration times, and with a low user base and low concurrency this worked well and prevented many race condition scenarios that would otherwise have happened.

We are now slowly starting to scale and are finding out that with a few hundred concurrent users, ocassionally (about once a day) a request fails due to either timing out waiting for a lock (which I assume happens when many attempt to get or are waiting for the same lock at the same time) or by database deadlocks. Today, this is only a minor annoyance, since it's still relatively infrequent and the affected user can reattempt the request and it will usually get through. But we are naturally concerned that this will not scale well.

How is this scenario typically addressed? I can only imagine it's a relatively common problem to have, but I'm not sure what specific techniques can be applied here without having to redesign the entire application. We're looking into lock-free designs currently, but at a first glance it would seem like rewritting our application to be lock-free would be a titanic task. Any sort of advice would be appreciated.


问:
Can I include an LGPLv2.0-licensed XSLT stylesheet into my Apache v2.0-license nodejs package?
I am creating an open source tool which leverages some XSLT stylesheets in order to do its work, which is transforming XML to Java code. One of the stylesheets that I want to use is licensed under LGPL v2.0. My tool will be license under the Apache License v2.0.

I read somewhere that if you link your Apache-licensed program to an LGPL library dynamically, it's ok. I see the link between my program and the stylesheet as dynamic, since it only depends on a filename and could easily be replaced with a different stylesheet by replacing a single file.

Can I infer from this that it's OK to use LGPL XSLT stylesheets or am I making an error in judgement here?

The file would be included in the nodejs package project directory

the package would be distributed through npmjs.org.

my own source files would be in lib/ (e.g. lib/transform.js), licensed under ASLv2.0.

the stylesheet would be in xslt/' (e.g.xslt/java/xml-to-java.xslt`) licensed under its original license (in this case LGPLv2.0).

the program does not provide an interface to change the used stylesheet, but the user has to go into the filesystem, look for the install directory of my package and manually replace the file with another if so desired.

The file provides essential functionality to the program

my own stylesheets convert to a format that this stylesheet understands

without it, I would have to provide a stylesheet with the same behavior (same input format, same output format).

So basically my program delegates the last transformation phase that is part of my program's behaviour.

To be clear: the file that I am trying to include into my package may retain its original license, I am only interested in adding its functionality to my program, because without it, my program loses so much of its functionality that it becomes useless. The reason I'm asking this question is that I want to distribute the file along with my project, because I would like my tool to work out of the box, not have the user download the xslt separately from the developers website.

答:
To determine if copyleft applies, ask yourself:

Is the XSLT stylesheet an integral part of the application?  Will your application work without it?

Are you communicating with it at arms length (through a File/Open command, batch file or something similar)?

If the answer to either of those questions is no, the answer to your question is no.

Note that LGPL has a linking exception that makes it easier to incorporate libraries into your program without opening your own source, but it still requires you to distribute any changes you make to the library's source.


问:
Inject it or create a new instance
suppose i have an interface in some language with two simple methods

```<code>interface IConverter{
   String toString(Object o)
   Object fromString(String s)
}
</code>```

this interface is implemented by many classes and there is always just the implementation of those 2 methods nothing more.

my question is, does it make sense to use dependency injection and register the classes that implement this interface in an IoC container? or should i create a new instance in each class that requires this dependency?

note that i already use an IoC container for other things in this app

答:
It depends on the current situation and the size of the project. Registering the classes that implement this interface in the IoC container and then injecting specific implementations in the objects that depend on the interface might be the way to go in some cases but might be an overkill in others.

In small projects, I prefer the benefits of seeing dependencies and passing dependent objects as parameters and not using IoC container. In bigger projects using IoC container you can delegate the responsibility for managing objects life cycle to the container and avoid the need to write objects initialization code manually in all places where a specific dependent object is needed.

The more complex your dependency graph the more benefit you will get from a IoC/DI container.

Title: Inject it or create a new instance


答:
The LGPL effectively requires that it must be possible for the user of your program to replace the LGPL-licensed parts with versions of his own and still have a functioning program (provided that the new versions are interface-compatible).

If your program reads the LGPL XSLT stylesheet as an external file at runtime (as in, the XSLT file is distributed as a separate file), then the requirement of user-replaceability has been fulfilled.

Furthermore, if your program only requires that there exists a file "foo.xslt" in a certain folder, then it can even be argued that the XSLT stylesheet is not actually part of your program but just mere data. In that case, the application and stylesheet are considered to be unrelated for copyright purposes.

Distributing them together means just that you are distributing an aggregation of multiple independent works.

Title: Can I include an LGPLv2.0-licensed XSLT stylesheet into my Apache v2.0-license nodejs package?

Body:
I am creating an open source tool which leverages some XSLT stylesheets in order to do its work, which is transforming XML to Java code. One of the stylesheets that I want to use is licensed under LGPL v2.0. My tool will be license under the Apache License v2.0.

I read somewhere that if you link your Apache-licensed program to an LGPL library dynamically, it's ok. I see the link between my program and the stylesheet as dynamic, since it only depends on a filename and could easily be replaced with a different stylesheet by replacing a single file.

Can I infer from this that it's OK to use LGPL XSLT stylesheets or am I making an error in judgement here?

The file would be included in the nodejs package project directory

the package would be distributed through npmjs.org.

my own source files would be in lib/ (e.g. lib/transform.js), licensed under ASLv2.0.

the stylesheet would be in xslt/' (e.g.xslt/java/xml-to-java.xslt`) licensed under its original license (in this case LGPLv2.0).

the program does not provide an interface to change the used stylesheet, but the user has to go into the filesystem, look for the install directory of my package and manually replace the file with another if so desired.

The file provides essential functionality to the program

my own stylesheets convert to a format that this stylesheet understands

without it, I would have to provide a stylesheet with the same behavior (same input format, same output format).

So basically my program delegates the last transformation phase that is part of my program's behaviour.

To be clear: the file that I am trying to include into my package may retain its original license, I am only interested in adding its functionality to my program, because without it, my program loses so much of its functionality that it becomes useless. The reason I'm asking this question is that I want to distribute the file along with my project, because I would like my tool to work out of the box, not have the user download the xslt separately from the developers website.


问:
Does Object Orientation require the concept of inheritance?
I read Object-Oriented Analysis and Design with Applications Notes  written by Grady Booch. In the book there is a sentence:

There are three important parts to this definition: (1) Object-oriented programming uses objects, not algorithms, as its fundamental logical building blocks (the “part of” hierarchy we introduced in Chapter 1); (2) each object is an instance of some class; and (3) classes may be related to one another via inheritance relationships (the “is a” hierarchy we spoke of in Chapter 1). A program may appear to be object-oriented, but if any of these elements is missing, it is not an object-oriented program. Specifically, programming without inheritance is distinctly not objectoriented; that would merely be programming with abstract data types.

I want to know this is right?If we don't have inheritance' our program is not object oriented?

答:
If we don't have inheritance our program is not object oriented?

Umm, no.

I expect that a majority of programmers would still consider a program with traditional objects (bundles of related state and functions) as objected oriented, even if there is no inheritance. In the past handful of years, it has become widely accepted that inheritance of concrete objects is something to be used cautiously if not avoided outright.

Regardless, you're asking about terminology. There are no rules for what Object Oriented is really. It's a name used loosely to help communicate concepts; concepts that are decreasingly useful in helping programmers solve problems.

ContentLicense: CC BY-SA 4.0


答:
Most OO principles depend on inheritance,  abstraction and interfaces. So inheritance and interface implementation plays major role in object oriented software design.

You may want to read about SOLID and other object oriented design principles.

Of course it is possible to write programs in object oriented languages without using inheritance (and more specifically interfaces and specializations of those interfaces) but you will end up with more tightly coupled code.

Title: Does Object Orientation require the concept of inheritance?

Body:
I read Object-Oriented Analysis and Design with Applications Notes  written by Grady Booch. In the book there is a sentence:

There are three important parts to this definition: (1) Object-oriented programming uses objects, not algorithms, as its fundamental logical building blocks (the “part of” hierarchy we introduced in Chapter 1); (2) each object is an instance of some class; and (3) classes may be related to one another via inheritance relationships (the “is a” hierarchy we spoke of in Chapter 1). A program may appear to be object-oriented, but if any of these elements is missing, it is not an object-oriented program. Specifically, programming without inheritance is distinctly not objectoriented; that would merely be programming with abstract data types.

I want to know this is right?If we don't have inheritance' our program is not object oriented?


答:
Inheritance is another form of containment even if the inheritance is interface implementation. Without leveraging inheritance, you lose a lot of the strength of object-oriented programming.

Inheritance allows you to substitute implementations of a class without impacting the client of the class. Think of a UI framework (like MFC or WPF). A lot of the framework depends on the fact that a Button, TextBox, Label, and Combobox are all subclasses of the same base class Control. If there weren't this common interface or base class, there would be a huge proliferation of code to do the same thing for the specific instances of these classes.

In that case you might as well be using basic C.


问:
How to make significant technical decisions given very little time
I have got 2 days for making a very serious decision about the tools and platforms that my company is going to use in order to port its WPF application to Linux / Android / iOS whatnot.

Obviously I can point to my seniors that 2 days is hardly enough for reading about all possible options, and what about trying, making prototypes etc. I can say it, it won't help me a bit, I have got 2 days, and after 2 days the decision would be made. Period.

From one side I am frustrated, from other side I think there is a grain of truth in this approach, otherwise I can easily find myself buried under dozens of downloaded SDKs, frameworks,  APIs, blog articles etc etc doing bench-works, running samples and forgetting in the process what it all was for.

Still I am afraid that a wrong decision will cost the company dearly.
So what do you think is an "ideal" process for making such decisions?

答:
Make a list of the factors that should go into choosing, things like:
Performance
security
cost
ease of use
ability to do X
ability to do Y
developer familiarity
time to market
etc.

This should take less than an hour (actually it should take less than 15 minutes), then sit down with management and have them prioritize those factors. (The chances of their priorities and yours being the same are remote although you can guide thier choice somewhat with suggestions as to priorities.) Now you know what to evaluate about the technology.

Pick three or four common solutions to your problem based on an internet search.

Then read enough to make a good guess about how well each of the choices fits their top 3-4 priorities. Assign a numeric value to each choice.  Do the math by multiplyig the rating of each priority times as value set on that priority (10 for Number 1, 8 for number 2, 6 for number 3 4 for number 4 or what ever numeric you like). Now you have a numeric score for each possibility. Generally it will be obvious which best meets the assigned priorities.  Even better you now have something analytical to take to them to prove your choice. They will usually buy off on your choice because you have the numbers to support it. If the numbers don't support it then you need to ask yourself why you prefer the other one and either go with the best one numerically or revisit the assigned numbers.

By concentrating on what the real priroites of the choice are you can cut out a lot of research time. You can probably have a guess within a day and then have a day left to take the top 2 possibilities and download trial versions if need be and play a bit with them.


问:
Efficient method for finding closest point to a line segment from a set of points including line segment's vertices
Let's say I have a list of points (in my case, point objects in a Python implementation). I then have a line segment connecting two of these points.

I want to know if there's a way to efficiently find the point from the list that is closest to the line segment. I realize I could step through all of the points and check distances individually, then select the smallest distance, but I'm eventually hoping to scale the program up to deal with perhaps millions of points. So, you know, maybe something more efficient than that?

If it helps, in terms of CCW all the points being questioned should either be to the "left"/"below" or the "right"/"above" of the line segment; I don't think my implementation will involve checking points to both sides of the segment.

The points will be point objects with (x,y) coordinates and some other junk not directly relevant to this question. The line segments are currently implemented as objects containing references to two point objects (its vertices) and its length.

As I mentioned this is part of a Python implementation. I'm trying to design a way to find a concave hull to a set of points (given some predefined parameters of how to decide whether a point not on the convex hull is on the concave hull or not). I want to find the convex hull first, then for each line segment on the convex hull find the closest point to it, make a triangle with that point, then decide if that triangle bears "deleting such that the internal point is now on the hull.

I considered putting this in Mathematics, but I don't need a distance equation - I need help with an efficient algorithm for finding points closest to a line segment. Note also that I am not looking for the closest point on a line to an input point; I'm looking for the closest point from a set to an input line segment.

Thank you all!

答:
You're going to have to loop through all the points and calculate the distance. There is a great question on StackOverflow about how to calculate the distance: Shortest distance between a point and a line segment

Some of the work can be precalculated, given that you have to do this more than once for a given line segment. You also don't need to figure out the smallest distance, only the smallest distance squared (since squaring is strictly increasing). I converted the top voted answer in that question to a Java version that does this precalculation (in the constructor), and is easier to read and follow. Unfortunately I don't know Python well enough to give you Python code, but you should be able to figure it out.

```<code>import java.util.Arrays;
import java.util.List;

public class LineSegment {
    public static class Point {
        public final double x;
        public final double y;

        public Point(double x, double y) {
            this.x = x;
            this.y = y;
        }

        public String toString() {
            return "(" + x + "," + y + ")";
        }
    }

    public static void main(String[] args) {
        LineSegment segment = new LineSegment(new Point(0, 3), new Point(2, 0));
        List<Point> pointList =
                Arrays.asList(new Point[] { new Point(-5, 3), new Point(1, 1),
                        new Point(2, 3), new Point(0, 5) });

        Point answer = segment.closestPoint(pointList);
        System.out.println("The closest point is: " + answer);
    }

    private static double sqr(double x) {
        return x * x;
    }

    private static double distanceSquared(Point v, Point w) {
        return sqr(v.x - w.x) + sqr(v.y - w.y);
    }

    private final Point firstSegPoint;
    private final Point secondSegPoint;
    private final double segmentDistance;
    private double xDifference;
    private double yDifference;

    public LineSegment(Point firstSegPoint, Point secondSegPoint) {
        this.firstSegPoint = firstSegPoint;
        this.secondSegPoint = secondSegPoint;
        this.segmentDistance = distanceSquared(firstSegPoint, secondSegPoint);
        this.xDifference = secondSegPoint.x - firstSegPoint.x;
        this.yDifference = secondSegPoint.y - firstSegPoint.y;
    }

    public Point closestPoint(List<Point> pointList) {
        double minDistance = Double.POSITIVE_INFINITY;
        Point answer = null;

        for (Point point : pointList) {
            double distSquared = distToSegmentSquared(point);
            if (distSquared < minDistance) {
                answer = point;
                minDistance = distSquared;
            }
        }

        return answer;
    }

    private double distToSegmentSquared(Point input) {
        if (segmentDistance == 0)
            return distanceSquared(input, firstSegPoint);

        double xComponent = (input.x - firstSegPoint.x) * xDifference;
        double yComponent = (input.y - firstSegPoint.y) * yDifference;
        double t = (xComponent + yComponent) / segmentDistance;
        if (closestPointIsFirst(t))
            return distanceSquared(input, firstSegPoint);
        if (closestPointIsSecond(t))
            return distanceSquared(input, secondSegPoint);
        Point closestPointOnLine =
                new Point(firstSegPoint.x + t * xDifference, firstSegPoint.y
                        + t * yDifference);
        return distanceSquared(input, closestPointOnLine);
    }

    private boolean closestPointIsFirst(double t) {
        return t < 0;
    }

    private boolean closestPointIsSecond(double t) {
        return t > 1;
    }
}
</code>```

See the full implementation here: http://ideone.com/fBFwda

Body:
You're going to have to loop through all the points and calculate the distance. There is a great question on StackOverflow about how to calculate the distance: Shortest distance between a point and a line segment

Some of the work can be precalculated, given that you have to do this more than once for a given line segment. You also don't need to figure out the smallest distance, only the smallest distance squared (since squaring is strictly increasing). I converted the top voted answer in that question to a Java version that does this precalculation (in the constructor), and is easier to read and follow. Unfortunately I don't know Python well enough to give you Python code, but you should be able to figure it out.

import java.util.Arrays;
import java.util.List;

public class LineSegment {
    public static class Point {
        public final double x;
        public final double y;

        public Point(double x, double y) {
            this.x = x;
            this.y = y;
        }

        public String toString() {
            return "(" + x + "," + y + ")";
        }
    }

    public static void main(String[] args) {
        LineSegment segment = new LineSegment(new Point(0, 3), new Point(2, 0));
        List<Point> pointList =
                Arrays.asList(new Point[] { new Point(-5, 3), new Point(1, 1),
                        new Point(2, 3), new Point(0, 5) });

        Point answer = segment.closestPoint(pointList);
        System.out.println("The closest point is: " + answer);
    }

    private static double sqr(double x) {
        return x * x;
    }

    private static double distanceSquared(Point v, Point w) {
        return sqr(v.x - w.x) + sqr(v.y - w.y);
    }

    private final Point firstSegPoint;
    private final Point secondSegPoint;
    private final double segmentDistance;
    private double xDifference;
    private double yDifference;

    public LineSegment(Point firstSegPoint, Point secondSegPoint) {
        this.firstSegPoint = firstSegPoint;
        this.secondSegPoint = secondSegPoint;
        this.segmentDistance = distanceSquared(firstSegPoint, secondSegPoint);
        this.xDifference = secondSegPoint.x - firstSegPoint.x;
        this.yDifference = secondSegPoint.y - firstSegPoint.y;
    }

    public Point closestPoint(List<Point> pointList) {
        double minDistance = Double.POSITIVE_INFINITY;
        Point answer = null;

        for (Point point : pointList) {
            double distSquared = distToSegmentSquared(point);
            if (distSquared < minDistance) {
                answer = point;
                minDistance = distSquared;
            }
        }

        return answer;
    }

    private double distToSegmentSquared(Point input) {
        if (segmentDistance == 0)
            return distanceSquared(input, firstSegPoint);

        double xComponent = (input.x - firstSegPoint.x) * xDifference;
        double yComponent = (input.y - firstSegPoint.y) * yDifference;
        double t = (xComponent + yComponent) / segmentDistance;
        if (closestPointIsFirst(t))
            return distanceSquared(input, firstSegPoint);
        if (closestPointIsSecond(t))
            return distanceSquared(input, secondSegPoint);
        Point closestPointOnLine =
                new Point(firstSegPoint.x + t * xDifference, firstSegPoint.y
                        + t * yDifference);
        return distanceSquared(input, closestPointOnLine);
    }

    private boolean closestPointIsFirst(double t) {
        return t < 0;
    }

    private boolean closestPointIsSecond(double t) {
        return t > 1;
    }
}

See the full implementation here: http://ideone.com/fBFwda


问:
Create an AngularJS front end for a Microservices application
I want to create a Microservices application, in which every microservice is responsible for its own part of the front end. At the same time, I want to create the front end in AngularJS as a Single Page Application (SPA). When a new microservice gets deployed, the web front end would automatically pick up the new front end part and add it to the SPA. What would be the best way of realising this?

This is what I came up with. Each microservice could be responsible for its own Angular module. Then when the customer navigates to the application, a server component (ASP.NET or JSP) could see which microservices are online and create an html page which includes the angular modules from those microservices.

What the front end component can also do, is enable some microservices to some specific customers which have extended privileges, like admins or VIP customers.

Of course, for this to work, I need a nice structured way for each microservice to take up a part of the screen, without 'knowing' what other microservices are on the screen. A simple solution would be to create a tab for each microservice. On the tab, the microservice in charge can put its functionality on the page. The front end component would be responsible for general stuff like (angular-)routing and look-and-feel.

Is this the best way of realising this goal? Does anyone have experience with this?

答:
Disclaimer: I have not built an application with a microservices architecture, I'm simply using my intuition here, and what I consider being mostly common sense.

I believe that trying to manage this on the front-end is overkill. I would recommend that you build a backend for your single page application, which knows about which microservices are available or not (be it by checking user credentials like you mentioned, or the service being down for maintenance, etc), and that will orchestrate everything. I would call this the application layer, which glues everything together, and acts as a facade to access your different microservices.

Your SPA does not need to know that it's getting its data from microservices. It should definitely request the data from a single entry-point, which dispatches the queries to the appropriate services.


答:
Alan Kay, who coined the phrase object-oriented programming has remarked here and in other places, that object-oriented programming is more about messages than objects. The key is that programs are designed as a set of objects that communicate through messages (in many languages a message is referred to as a polymorphic method call).

In Smalltalk (the language Alan Kay was working on) when a message is sent to an object, the receiver of the object determines how the object will respond. In a class-based language, the typical behaviour is:

Check if the object has a method matching the message's signature, if so invoke that.

Otherwise, check (recursively) if any of the object's base classes contains a method matching the method signature. When a class inherits another class, it means that the methods of the base class are available for object's of the derived class, but may be overridden to provide different behaviour.

However, other languages such as Self and JavaScript, objects are not instance of classes. In place of inheritance, a pattern known as delegation is used. When a object receives a message it does not understand, it can delegate its response to another object known as a prototype.

In all the languages mentioned so far, unlike most mainstream languages such as Java, C++ and C#, any object can implement a message for any message. C++ derived a different (and more restrictive) model from Simula, where a message is defined on a base class and can be overridden by a derived class, but no other classes can respond to the method.

Self demonstrated, by including in images a Smalltalk subsystem, that using the prototype-based model a class-based model can be implemented as a pattern of programming, so in this sense the prototype-based model is more descriptive. The converse would require implementing a new object system from scratch (e.g. a class called PrototypicalObject, with behaviour entirely distinct from normal Smalltalk objects).

At its core, OOP is about objects and messages (method calls), where various objects can implement different responses to the same message. The details of inheritance and delegation can help create those objects, but are simply variants of the standard model.


问:
Is the use of DSLs in a state monad a good approach to building complex stateful computations?
First, sorry if that title makes no sense. I am a little out of my depth here with the terminology.

So, imagine that I'm writing a text editor in Haskell. For the purposes of this question, let's consider a toy text editor that only operates on a single line of text, and has three primitive operations:

Insert a character at the cursor (so all characters under and to the right of the cursor, if any, are moved to the right).

Move the cursor to the left (no effect if it's already at position zero)

Move the cursor to the right (no effect if it's already at the end of the line)

Obviously I am dealing with a state (the "buffer" of my text editor, and the position of its cursor) and some operations that can be applied in some sequence to modify the state. So, I'm going to implement this thing using a state monad that holds two lists, one for the characters behind the cursor and another for those after it. I will write three simple functions in the state monad to provide my three primitive operations:

```<code>data ListState a = ListState {
                     before :: [a],
                     after :: [a]
                   }

insert :: MonadState (ListState a) m => a -> m ()
insert x = do
  ListState bs as <- get
  put $ ListState bs (x:as)

moveForward :: MonadState (ListState a) m => m ()
moveForward = do
  ListState bs as <- get
  case as of
    (a:as') -> put $ ListState (a:bs) as'
    _       -> return ()

moveBackward :: MonadState (ListState a) m => m ()
moveBackward = do
  ListState bs as <- get
  case bs of
    (b:bs') -> put $ ListState bs' (b:as)
    _       -> return ()
</code>```

Cool! Now I can use these three primitives to do more complicated things:

```<code>insertList :: MonadState (ListState a) m => [a] -> m ()
insertList xs = forM_ (reverse xs) insert

foo :: MonadState (ListState Char) m => m ()
foo = do
  insertList "This is a idea!"
  replicateM_ 10 moveForward
  insertList "bad "
  replicateM_ 3 moveBackward
  insertList "n't"

main = let state = ListState "" ""
           state' = execState foo state
       in  putStrLn $ reverse (before state') ++ after state'
</code>```

Using my primitive DSL, I've defined a function using repeated calls to insert to insert a whole list at once, and another function foo that combines all these functions to circuitously build a string:

```<code>(mdunsmuir@altair) mdunsmuir/projects >> ./ToyDSL
This isn't a bad idea!
</code>```

I find myself following this pattern a lot: define some data type to hold a state that I want to apply a sequence of operations to, and then build out a DSL starting with the most basic atomic operations and with more complex operations defined as combinations of those primitives.

My question is pretty open-ended: For this sort of problem (imagine a more realistic text editor implemented in the same way), is this a generally valid approach? What other approaches might one use? The primary thing that I find concerning about this approach is that if you don't take a disciplined approach to the design of your DSL, you can run into a lot of unpleasant issues that I associate with imperative programming.

答:
Although this can be a good idea at one level, you want to avoid passing monads around all over the place if you can.  It's easier to read, write, compose, and reuse if you write your functions normally, then modify them into a monadic context as needed:</p>

```<code>insert x (Buffer before after) = Buffer (x:before) after

insertList xs (Buffer before after) = Buffer (reverse xs ++ before) after

moveForward (Buffer before (x:after)) = Buffer (x:before) after

moveBackward (Buffer (x:before) after) = Buffer before (x:after)

modify2 f a = do {x <- get; put (f a x) }

insertM = modify2 insert
insertListM = modify2 insertList
moveForwardM = modify moveForward
moveBackwardM = modify moveBackward
</code>```

Body:
Although this can be a good idea at one level, you want to avoid passing monads around all over the place if you can.  It's easier to read, write, compose, and reuse if you write your functions normally, then modify them into a monadic context as needed:

insert x (Buffer before after) = Buffer (x:before) after

insertList xs (Buffer before after) = Buffer (reverse xs ++ before) after

moveForward (Buffer before (x:after)) = Buffer (x:before) after

moveBackward (Buffer (x:before) after) = Buffer before (x:after)

modify2 f a = do {x <- get; put (f a x) }

insertM = modify2 insert
insertListM = modify2 insertList
moveForwardM = modify moveForward
moveBackwardM = modify moveBackward


问:
Multiple users using the same script for their websites
I'm working on a project, I have a question regarding the architecture:

Say I have a many python scripts on my server and there's main.py
which contains all the classes. And there's a script called
copymain.py

A user named alex signs up and the url of his site is stored in
mariadb

copymain.py checks if a user has signed up every 5 min using cron

when copymain.py detects that alex has signed up, it creates a copy of main.py rename it to alex.py, moves alex.py to scriptFolder, and writes the url of alex's site to alex.py

Cron or Celery (haven't decided yet) will run all the .py files inside scriptFolder every lets say 15 mins

Why I picked this design?

This design will let me get rid of many stack and queues and
threading in my script and make it simpler, it is a simple solution, and it works perfectly. If I need to edit main.py, all I have to do is edit the modules imported, so I don't need to edit individual copies.

I think that by copying the files, I could easily deploy it on many
servers. Move some .py files to this server, others to that and I'm
done. These are the two main reasons.

Say you have to generate RSS for websites, for some reason there's a user called fred that has a problem, there's an issue that needs a special script, because we all know that every website has its own design and many errors occur when scrapping and dealing with html, you can go to fred.py and edit your script for that user.

Is it the most efficient architecture? Or should I use one file, get the users from database? My script currently does that, but I prefer to copy for the reasons stated above, a simple scheduling would do. I need to make sure that no matter how many users I have, the website of every user will be processed at exactly the time I promised when they signed up, when there's too many of them and I notice it's being slow, I just buy upgrade or buy another server. I'm afraid of creating too many threads and having to worry about it as it scales. Copying seems the simplest solution, Linux uses cron all the  time for entire directories.

Edit

Please forget about the scrapping part, say you have to do some task for each user in your database, like sending him a message, or whatever, is my solution as good as queuing and threading, in terms of time spent on the process and in terms of being lightweight on the server? Is there a better solution that I have not considered?

答:
Disclaimer: I'm not entirely sure I understand what you're actually trying to accomplish here, so my answer is going to be somewhat vague.

Cron or Celery (haven't decided yet) will run all the .py files inside scriptFolder every lets say 15 mins

Let's be optimistic and suppose you have millions of users some day.  Will Cron/Celery be able to get through all those scripts in a reasonable period of time?  How long does each script take to run?

If your scripts are sufficiently complex, you will probably have difficulty scaling to millions of users.  If they are not sufficiently complex, you can probably get by with a simpler design, perhaps using multiprocessing.


问:
Is checking count/size/length less than 0 necessary in modern languages?
Is checking count/size/length less than 0 necessary in modern languages anymore? For instance, in C# I quote often will check if a collection's count is less than or equal to 0.

I assume that this was done in older languages, like C, where you could potentially have a size of less than 0.

Is there ever a case where you can have the size/length/count of an object or primitive type be less than 0?

答: You can use Any which will return as soon as if there is an item in the collection, whereas using Length will actually iterate through the whole collection and count it, which is a bad idea. So Any is lazy, Length is eager. Most of the cases, Any is sufficient.


问:
Where does the Liskov Substitution Principle lie in a subclass passing extra arguments to similar, tightly-related callbacks?
Take the following examples, which have been abbreviated:

BasicButton:

```<code>public class BasicButton
{
    private var m_fOnClick:Function;

    public function BasicButton(pOnClick:Function)
    {
        m_fOnClick = pOnClick;
    }

    .
    .
    .
        // when the button has been clicked:
        m_fOnClick();
    .
    .
    .
}
</code>```

DirectionalButton:

```<code>public final class DirectionalButton extends BasicButton
{
    private var m_eDirection:int;

    private var m_fOnClick:Function;

    public function DirectionalButton(pDirection:int, pOnClick:Function)
    {
        m_eDirection = pDirection;
        m_fOnClick = pOnClick;
        super(onClick);
    }

    private function onClick():void
    {
        m_fOnClick(m_eDirection);
    }
}
</code>```

Is messing with the callback's parameter list like this a violation of the Liskov Substitution Principle?  I know the constructors don't violate it, according to the way the industry generally interprets that principle, but whether messing with the callback's parameter list constitutes a mutation of a common output or whatever seems to be a little less clear.

On the one hand, both classes use a function called pOnClick that is called each time they're clicked on, and the instantiating code is able to pass in whichever function it wants to be referred to by pOnClick.  On the other hand, since constructors tend to be abstracted from LSP, these two pOnClick parameters in the two constructors could be interpreted as referring to very different things.

Even if the two pOnClick parameters are interpreted as two separate inputs, there's still some ambiguity as to how much the subclasses's pOnClick effectively overwrites or destroys the superclass's (in a strictly virtual, publicly exposed sense), and how much it instead simply passes - in a very virtual sense - the equivalent of null to the superclass's still existent pOnClick.

It's a little tough to find the exact words for what I'm describing, but in general, where does LSP lie in this?  Is this a violation?  If so, can it be remedied by simply rewriting DirectionalButton.onClick as follows?

```<code>private function onClick():void
{
    try
    {
        m_fOnClick(m_eDirection);
    }
    catch (e:Error)
    {
        m_fOnClick(); // This is not how I would set this up in real life.
    }
}
</code>```

答:
The test is whether you can take code written to interact with the base class, and without modification, get it to work with an instance of the derived class instead.  That means in most circumstances, your example would violate LSP.

However, in some circumstances it might not.  If you're using a language like JavaScript that essentially ignores extra parameters, and that parameter is not semantically crucial, you could make a case that it doesn't violate LSP.

In a dynamically-typed language, you could make a case that your proposed fallback remedy doesn't violate LSP.  However, I don't believe you could get something like that to compile in most statically-typed languages.

One remedy that would work in any language is to just change the base class to add the optional parameter.  That feels kind of icky, though.

The easiest way to not accidentally break inheritance design principles is to not use inheritance.  You could have your directional button class contain a basic button instead of inheriting from it, and forward any events with the parameter added.  This is a good option if you never have to put a directional button into code that was originally designed to interact with a basic one.

Another very flexible option to pass arbitrary data back to a callback is to pass in a closure to the constructor instead.


问:
What are the benefits of using new over closures
I've been programming in JS for over a year now, mainly in angularJS. And I can honestly say I've never made a function use prototypical inheritance. When ever i need a class like object that has private data, I use the factory pattern and closures to create classes. I can honestly say I've never needed to use the this key word.

I'm trying to learn node, and it uses prototypical inheritance pretty heavily so it seems. So there has to be a pretty big benefit of using it over closures.  Can someone explain the main advantages of using prototypes and what not?

答:
Aside from being more familiar to C++/Java programmers, the only advantage I can think of is that prototypes and constructors have arguably better support for traditional OOP-style inheritance.

Imagine you have class A with method foo(), and class B with method bar() that calls foo(). We want class B to be derived from A, so that it can simply call foo() directly and everything works. With constructors and prototypes, this is easy:

```<code>var A = function() {
    this.x = 42;
};
A.prototype.foo = function() {
    return this.x;
};

var B = function() {
    this.y = 7;
};
B.prototype = new A;
B.prototype.constructor = B;

B.prototype.bar = function() {
    return this.x * this.y;
};

var a = new A;
var b = new B;
console.log(a.foo()); // 42
console.log(b.foo()); // 42
console.log(b.bar()); // 294
</code>```

With closures, you can use the "mixin" approach for public members and methods, but for privates you're basically stuck.

```<code>var A = function() {
    var x = 42;
    return {
        foo: function() {
            return x;
        }
    };
};

var B = function() {
    var y = 7;
    var obj = {
        bar: function() {
            return x * y;
        }
    };

    // mix in A's public members
    var a = A();
    Object.keys(a).forEach(function(key) {
        obj[key] = a[key];
    });
    return obj;
};

var a = A();
var b = B();
console.log(a.foo()); // 42
console.log(b.foo()); // 42
console.log(b.bar()); // Uncaught ReferenceError: x is not defined
</code>```

As far as I can tell, the only way to make this snippet work is to make x public and use "this.x", at which point it might as well not be using closures anymore. Closures can implement "private" access, but not "protected" access, so if you want to do traditional inheritance you have to leave everything public anyway.

Of course, if you don't do very much inheritance, this is a non-issue. At my job we hardly ever inherit from anything, so we also use closures by default.

Body:
Aside from being more familiar to C++/Java programmers, the only advantage I can think of is that prototypes and constructors have arguably better support for traditional OOP-style inheritance.

Imagine you have class A with method foo(), and class B with method bar() that calls foo(). We want class B to be derived from A, so that it can simply call foo() directly and everything works. With constructors and prototypes, this is easy:

var A = function() {
    this.x = 42;
};
A.prototype.foo = function() {
    return this.x;
};

var B = function() {
    this.y = 7;
};
B.prototype = new A;
B.prototype.constructor = B;

B.prototype.bar = function() {
    return this.x * this.y;
};

var a = new A;
var b = new B;
console.log(a.foo()); // 42
console.log(b.foo()); // 42
console.log(b.bar()); // 294

With closures, you can use the "mixin" approach for public members and methods, but for privates you're basically stuck.

var A = function() {
    var x = 42;
    return {
        foo: function() {
            return x;
        }
    };
};

var B = function() {
    var y = 7;
    var obj = {
        bar: function() {
            return x * y;
        }
    };

    // mix in A's public members
    var a = A();
    Object.keys(a).forEach(function(key) {
        obj[key] = a[key];
    });
    return obj;
};

var a = A();
var b = B();
console.log(a.foo()); // 42
console.log(b.foo()); // 42
console.log(b.bar()); // Uncaught ReferenceError: x is not defined

As far as I can tell, the only way to make this snippet work is to make x public and use "this.x", at which point it might as well not be using closures anymore. Closures can implement "private" access, but not "protected" access, so if you want to do traditional inheritance you have to leave everything public anyway.

Of course, if you don't do very much inheritance, this is a non-issue. At my job we hardly ever inherit from anything, so we also use closures by default.


问:
Sharing constructor code between classes that do not inherit from each other
There is a PHP library of classes (generated from a WSDL) that cannot be changed. These look like the below for simplicity.

```<code>class System extends \SoapClient
{
    public function __construct(array $options = array(), $wsdl = 'http://example.com/system?wsdl')
    {
       // Do configuration and include required classes.

       parent::__construct($wsdl, $options);
    }
}

class Report extends \SoapClient
{
    public function __construct(array $options = array(), $wsdl = 'http://example.com/report?wsdl')
    {
       // Do configuration and include required classes.

       parent::__construct($wsdl, $options);
    }
}
</code>```

Custom code needs to do some configuration (e.g. setting some SOAP headers and the SOAP version) whenever a System or Report object is required. The current implementation is as below.

```<code>class mySystem extends System
{
  public function __construct($wsdl, $configuration) {

    $options = array(
      'soap_version' => SOAP_1_2,
    );

    // Do more stuff here.

    parent::__construct($options, $wsdl);
  }
}

class myReport extends mySystem
{
  public function __construct($wsdl, $configuration) {
    parent::__construct($options, $wsdl);
  }
}
</code>```

The above works but my IDE is screaming at me every time I do anything on myReport (cannot find method etc.) and I think it only works because PHP doesn't care about type very much, and any actual methods are passed to the SoapClient->__doRequest() method. Any over, more concrete, thoughts on why this is bad are welcome.

I want to refactor this to a better design. The first thing is that mySystem correctly extends System but myReport should also extend Report. This means that the constructor code needs to be duplicated in mySystem and myReport. Is there a way around this?

My thoughts so far:

Have a "setup" trait that both mySystem and myReport use and call the appropriate "setup" method in their constructors. The major blocker here is PHP version on some systems is 5.3 although there are plans to upgrade these.

Have a factory method that can instantiate the required classes. Not 100% sure how this would look though.

答:
Personally I would be using factory methods to create each of these objects and would forget about the additional inheritance you have designed.

The form of this would be a ReportFactory class and a SystemFactory class that would have their own creation methods.  In the creation methods you would instantiate the required class, and then perform the initialisation specific to the object within the factory method.

Where there is commonality in the configuration requirements (most likely at the SOAP level) then that work can be farmed off to a common class for handling that part of the configuration.

It would appear that the additional level of inheritance you have added provides no real value, and there is no distinction between the inherited value and the base class, apart from the differing initialisation semantics.  Therefore I think that approach would need to be justified more than it currently is if you were to continue down that path.


问:
Which language has most advanced support for proof based programming?
By proof based programming, I mean, you can somehow prove the correctness of your program without testing.

I heard that Ada has a feature called contract, I also heard that, if you can pass Haskell's type checker, your program probably is right.

Can I write correct program without a single line of test code in these two language? Is there other language that supports this kind of feature?

答:
Some thoughts:

The proof doesn't know what you want to accomplish with your code.  That's the domain of  well-written software requirements.

Tests (when used as a description of requirements, as in TDD) are proof of the software requirements, not the software itself.

The proof can, and often does, exceed the complexity of the actual program.  Proofs, unlike tests, must account for all possible edge cases.

Some things you can't prove or predict.  Things like the customer saying "This isn't what I actually wanted."

All that said, Haskell is probably the closest thing to "programming by proof."

Rather than asking for an iron-clad guarantee, good language designers (as well as good programmers) seek to make software more reliable by reducing complexity as much as possible.  This reduces (but does not eliminate) the number of edge-cases, which is what we're really after.


问:
Most efficient way to generate all descendents of all nodes in a tree
I'm looking for the most efficient algorithm to take a tree (stored as either a list of edges; OR as a list of mappings from parent node to a list of child nodes); and produce, for EVERY node, a list of all nodes descended from it (leaf level and non-leaf level).

The implementation must be via loops instead of recusion, due to scale; and should ideally be O(N).

This SO question covers a standard reasonably obvious solution for finding the answer for ONE node in a tree. But obviously, repeating that algorithm on every tree node is highly inefficient ( off the top of my head, O(NlogN) to O(N^2) ).

The tree root is known. The tree is of absolutely arbitrary shape (e.g. not N-nary, not balanced in any way, shape or form, not uniform depth) - some nodes have 1-2 children, some have 30K children.

On a practical level (though it shouldn't affect the algorithm) the tree has ~100K-200K nodes.

答:
This short algorithm should do it,
Have a look at the code public void TestTreeNodeChildrenListing()

The algorithm actually goes through the nodes of the tree in sequence, and keeping the list of parents of the current node. As per your requirement current node is a child of each parent node it's added to each and every one of them as a child.

Final result is stored in the dictionary.

```<code>    [TestFixture]
    public class TreeNodeChildrenListing
    {
        private TreeNode _root;

        [SetUp]
        public void SetUp()
        {
            _root = new TreeNode("root");
            int rootCount = 0;
            for (int i = 0; i < 2; i++)
            {
                int iCount = 0;
                var iNode = new TreeNode("i:" + i);
                _root.Children.Add(iNode);
                rootCount++;
                for (int j = 0; j < 2; j++)
                {
                    int jCount = 0;
                    var jNode = new TreeNode(iNode.Value + "_j:" + j);
                    iCount++;
                    rootCount++;
                    iNode.Children.Add(jNode);
                    for (int k = 0; k < 2; k++)
                    {
                        var kNode = new TreeNode(jNode.Value + "_k:" + k);
                        jNode.Children.Add(kNode);
                        iCount++;
                        rootCount++;
                        jCount++;

                    }
                    jNode.Value += " ChildCount:" + jCount;
                }
                iNode.Value += " ChildCount:" + iCount;
            }
            _root.Value += " ChildCount:" + rootCount;
        }

        [Test]
        public void TestTreeNodeChildrenListing()
        {
            var iteration = new Stack<TreeNode>();
            var parents = new List<TreeNode>();
            var dic = new Dictionary<TreeNode, IList<TreeNode>>();

            TreeNode node = _root;
            while (node != null)
            {
                if (node.Children.Count > 0)
                {
                    if (!dic.ContainsKey(node))
                        dic.Add(node,new List<TreeNode>());

                    parents.Add(node);
                    foreach (var child in node.Children)
                    {
                        foreach (var parent in parents)
                        {
                            dic[parent].Add(child);
                        }
                        iteration.Push(child);
                    }
                }

                if (iteration.Count > 0)
                    node = iteration.Pop();
                else
                    node = null;

                bool removeParents = true;
                while (removeParents)
                {
                    var lastParent = parents[parents.Count - 1];
                    if (!lastParent.Children.Contains(node)
                        && node != _root && lastParent != _root)
                    {
                        parents.Remove(lastParent);
                    }
                    else
                    {
                        removeParents = false;
                    }
                }
            }
        }
    }

    internal class TreeNode
    {
        private IList<TreeNode> _children;
        public string Value { get; set; }

        public TreeNode(string value)
        {
            _children = new List<TreeNode>();
            Value = value;
        }

        public IList<TreeNode> Children
        {
            get { return _children; }
        }
    }
}
</code>```

Body:
This short algorithm should do it,
Have a look at the code public void TestTreeNodeChildrenListing()

The algorithm actually goes through the nodes of the tree in sequence, and keeping the list of parents of the current node. As per your requirement current node is a child of each parent node it's added to each and every one of them as a child.

Final result is stored in the dictionary.

    [TestFixture]
    public class TreeNodeChildrenListing
    {
        private TreeNode _root;

        [SetUp]
        public void SetUp()
        {
            _root = new TreeNode("root");
            int rootCount = 0;
            for (int i = 0; i < 2; i++)
            {
                int iCount = 0;
                var iNode = new TreeNode("i:" + i);
                _root.Children.Add(iNode);
                rootCount++;
                for (int j = 0; j < 2; j++)
                {
                    int jCount = 0;
                    var jNode = new TreeNode(iNode.Value + "_j:" + j);
                    iCount++;
                    rootCount++;
                    iNode.Children.Add(jNode);
                    for (int k = 0; k < 2; k++)
                    {
                        var kNode = new TreeNode(jNode.Value + "_k:" + k);
                        jNode.Children.Add(kNode);
                        iCount++;
                        rootCount++;
                        jCount++;

                    }
                    jNode.Value += " ChildCount:" + jCount;
                }
                iNode.Value += " ChildCount:" + iCount;
            }
            _root.Value += " ChildCount:" + rootCount;
        }

        [Test]
        public void TestTreeNodeChildrenListing()
        {
            var iteration = new Stack<TreeNode>();
            var parents = new List<TreeNode>();
            var dic = new Dictionary<TreeNode, IList<TreeNode>>();

            TreeNode node = _root;
            while (node != null)
            {
                if (node.Children.Count > 0)
                {
                    if (!dic.ContainsKey(node))
                        dic.Add(node,new List<TreeNode>());

                    parents.Add(node);
                    foreach (var child in node.Children)
                    {
                        foreach (var parent in parents)
                        {
                            dic[parent].Add(child);
                        }
                        iteration.Push(child);
                    }
                }

                if (iteration.Count > 0)
                    node = iteration.Pop();
                else
                    node = null;

                bool removeParents = true;
                while (removeParents)
                {
                    var lastParent = parents[parents.Count - 1];
                    if (!lastParent.Children.Contains(node)
                        && node != _root && lastParent != _root)
                    {
                        parents.Remove(lastParent);
                    }
                    else
                    {
                        removeParents = false;
                    }
                }
            }
        }
    }

    internal class TreeNode
    {
        private IList<TreeNode> _children;
        public string Value { get; set; }

        public TreeNode(string value)
        {
            _children = new List<TreeNode>();
            Value = value;
        }

        public IList<TreeNode> Children
        {
            get { return _children; }
        }
    }
}


答:
It's not exactly clear what you are asking.

You can always prove a program correct, if you want. This is independent of the language.

The question is, can you get the computer to do the proof for you, or at least check a proof given by you? And the answer is: Yes!

In fact, the Curry-Howard-Isomorphism states that there is an isomorphism between logic and programming, between proofs and programs, between theorems and types. Every type is a theorem (and vice versa), every program is a proof (and vice versa). So, in some sense, every statically typed language does this; every type checker is a theorem prover!

However, there is a limit to what you can express in a type. Haskell lets you express more than, say, Java, but there is even more. In a dependently-typed language, static types may depend on runtime values. For example, there could be a type List<n> which is a list with n elements, where n is a value that is only determined at runtime.

Now, in order to type-check such a program, the type checker needs to be able to statically prove properties about runtime values, but we all know that this lets us run quickly into the Halting Problem. Well, dependently-typed languages have a simple solution: they don't allow non-termination, they are total, i.e. they always terminate, therefore the Halting Problem doesn't apply.

Obviously, that means that they aren't Turing-complete, but that sounds scarier than it actually is. Firstly, there are many languages that aren't Turing-complete, yet still useful: regex, SQL (before 2003), HTML+CSS (before HTML5+CSS3), and many others. In fact, since the C spec requires that I can take the address of any object and the size of any object, and both of those have to fit into a finite sized integer, C is technically not Turing-complete, because it doesn't have infinite memory. Likewise, our computers aren't Turing-complete either, in fact, it is physically impossible to build a Turing-complete computing machine.

But that's hair-splitting, there are much more practical considerations. For example, one might think that an operating system, a web server, or really anything with an event loop can't be built with a language that isn't Turing-complete. But it turns out that instead of modeling, say, an operating system as an infinite loop (or rather infinite recursion) over data, we can also model it using finite co-recursion over co-data! And in fact, there are many such patterns for problems that at first glance might require an infinite loop or non-terminating recursion.

Dependently-typed languages fall into three broad camps:

(Interactive) Proof Assistants: these are programs that are primarily designed for computer-assisted proofs. The fact that one can also program in them is rather incidental.

Dependently-typed languages: these are primarily intended as programming languages, the language itself typically doesn't offer any tools to ease the "proof"-part.

Integrated approaches, where the IDE for the language contains an interactive proof assistant that helps you with constructing the proof(s) while you are constructing the program, similarly to how a modern IDE with visual interactive debugging, profiling etc. helps you with constructing programs.

Some of those languages/proof systems are (in no particular order):

Agda

ATS

Coq

Epigram2

Guru

Idris

Isabelle/HOL

Matita

NuPRL

Twelf

Of those, Coq is the most mature. It was, however, clearly not designed for programming. When viewed as a programming language, it isn't actually a very nice one.

OTOH, Idris is somewhat new, but it is clearly designed as programming language. It is very much like Haskell. You could think of it as Haskell-with-dependent-types.

ATS is unlike the others. It is not a full dependent-typed language / proof assistant. Rather it is being designed as a systems programming language, as a replacement for C, C++, D, Java, C# and similar languages with performance comparable to C, and "just enough dependent typing to prove some interesting properties". ATS is not geared towards being able to prove everything but rather specific safety properties of software systems such as operating systems, compilers, servers, etc.

Title: Which language has most advanced support for proof based programming?

Body:
By proof based programming, I mean, you can somehow prove the correctness of your program without testing.

I heard that Ada has a feature called contract, I also heard that, if you can pass Haskell's type checker, your program probably is right.

Can I write correct program without a single line of test code in these two language? Is there other language that supports this kind of feature?


问:
Is my application vulnerable to SQL injection if I don't specify each type in Doctrine2?
I thought Doctrine 2 DBAL prepared statements were safe from SQLi. But I found this confusing bit in the docs:

By default the Doctrine DBAL does no escaping. Escaping is a very
  tricky business to do automatically, therefore there is none by
  default. When you use the Doctrine DBAL as standalone, you have to
  take care of this yourself.

What does that mean exactly? If someone tries to inject malicious code, will the query fail (as opposed to insert escaped) because the RDBMS protects me? Or I'm not protected at all?

I'm using PostgreSQL as my RDBMS.

答:
I'd wondered as well.
Googling a lot I found the answer posted by Benjamin Eberlei himself (Doctrine Project Lead and Contributor):

Hello,

of course DBAL uses PDO internally and escapes parameters such as in
  your example. I think the docs are messed up here. The Paragraph
  relates to the two subparagraphs about quote() and quoteIdentifier()
  and should mention quoting INSIDE sql strings (prepared statements are
  secure of course!). sorry for the confusion, i should update the docs
  to be more clear on this.

greetings, Benjamin

On Sat, 1 Jan 2011 15:12:28 -0800 (PST)


问:
Initialize physical resources in constructor
Is it an acceptable practice to initialize physical/external resources from a constructor when the resource is needed for the object to do it's work?

For instance, let's say I wanted to create an object that proxies a durable message queue and that the message queue is a physical database table.

Would that make sense to create an idempotent constructor which physically create the table if it doesn't exist yet?

E.g.

```<code>IMessageQueue queue = new SQLTableMessageQueue('table_name', dataSource);
</code>```

Perhaps a static factory method would be more appropriate? In that case, the table creation would occur in the factory method and the constructor would be free of such behavior.

```<code>IMessageQueue queue = SQLTableMessageQueue.create('table_name', dataSource);
</code>```

I'm not too sure what would be an appropriate approach? Another idea I had was to use the Repository Pattern.

答:
Usually constructors are not used to initialize external resources, there are few reasons,

Testability - It would be very hard to create unit tests

To be in compliance with SRP

You could always pass the message queue to the constructor where you use it.

```<code>class QueueProcessor
{
    private IMessageQueue _queue;

    public QueueProcessor(IMessageQueue queue)
    {
        _queue = queue;
    }
}
</code>```

Yes, you can use a factory to create the queue

```<code>class QueueFactory
{
    public IMessageQueue CreateMessageQueue
    {
        return new SQLTableMessageQueue('table_name', dataSource);
    }
}
</code>```

With this approach you can easily mock the message queue for testing, and also it does comply with the SRP compared to constructing the queue within the constructor.

Body:
Usually constructors are not used to initialize external resources, there are few reasons,

Testability - It would be very hard to create unit tests

To be in compliance with SRP

You could always pass the message queue to the constructor where you use it.

class QueueProcessor
{
    private IMessageQueue _queue;

    public QueueProcessor(IMessageQueue queue)
    {
        _queue = queue;
    }
}

Yes, you can use a factory to create the queue

class QueueFactory
{
    public IMessageQueue CreateMessageQueue
    {
        return new SQLTableMessageQueue('table_name', dataSource);
    }
}

With this approach you can easily mock the message queue for testing, and also it does comply with the SRP compared to constructing the queue within the constructor.


问:
Factors for choosing between using a wrapper library or issuing command line process from my web application
I have a Java web application that makes use of certain libraries for example: Ghost Script for converting PDFs to TIFFs and Tesseract for OCR. There are java wrappers for both of these: Ghost4J and Tess4J.

What are some things I should think about when deciding whether to use the libraries or issue a command line process from my web application?

Off the bat what I'm noticing is that command line operations are slightly faster and don't take a toll on my application. For example 100 users sending PDFs that need to be converted to TIFFs using Ghost4j makes Java run at more that 100% CPU which makes the entire web application unresponsive.

答:
The following factors should be considered:

portability

the command line interface will be different per environment,

and also the configuration

performance

re-usability

maintainability

scaleability

If possible consider creating the conversion component as a separate service running in it's own JVM (possibly multiple) and forwarding conversion requests to this service (reusability).

This allows you to use the wrapper libraries (allowing the code to be portable) + (maintainability).

It also allows you to scale the number of conversion component processes to deal with system scaling (scaleability), and also allows you to potentially host on different hardware when the existing hardware resources are at a limit. (performance)

A simple web-service interface or equivalent is simple to implement between two components to provide this functionality, which then allows you to separate your web interface behaviour from the grunt work of performing document conversion.


问:
Can I include an LGPLv2.0-licensed XSLT stylesheet into my Apache v2.0-license nodejs package?
I am creating an open source tool which leverages some XSLT stylesheets in order to do its work, which is transforming XML to Java code. One of the stylesheets that I want to use is licensed under LGPL v2.0. My tool will be license under the Apache License v2.0.

I read somewhere that if you link your Apache-licensed program to an LGPL library dynamically, it's ok. I see the link between my program and the stylesheet as dynamic, since it only depends on a filename and could easily be replaced with a different stylesheet by replacing a single file.

Can I infer from this that it's OK to use LGPL XSLT stylesheets or am I making an error in judgement here?

The file would be included in the nodejs package project directory

the package would be distributed through npmjs.org.

my own source files would be in lib/ (e.g. lib/transform.js), licensed under ASLv2.0.

the stylesheet would be in xslt/' (e.g.xslt/java/xml-to-java.xslt`) licensed under its original license (in this case LGPLv2.0).

the program does not provide an interface to change the used stylesheet, but the user has to go into the filesystem, look for the install directory of my package and manually replace the file with another if so desired.

The file provides essential functionality to the program

my own stylesheets convert to a format that this stylesheet understands

without it, I would have to provide a stylesheet with the same behavior (same input format, same output format).

So basically my program delegates the last transformation phase that is part of my program's behaviour.

To be clear: the file that I am trying to include into my package may retain its original license, I am only interested in adding its functionality to my program, because without it, my program loses so much of its functionality that it becomes useless. The reason I'm asking this question is that I want to distribute the file along with my project, because I would like my tool to work out of the box, not have the user download the xslt separately from the developers website.

答:
I am not a lawyer. You should get one, if you are concerned about possible legal issues.

It’s absolutely irrelevant what that stylesheet does and where it is stored in a package. The important question is what you mean by including something covered by GNU LGPL into a package covered by the Apache License v2.

Do you mean, that the whole package, including that XSLT, should be under ASLv2? Then no, that’s absolutely impossible regardless of how parts are combined: statically, dynamically, even if they do not interact at all but just packaged together by some reason. You basically want to grant more rights to your licensees than you obtained.

Or you are just want to assign ASLv2 to your work, that incorporates someone else's work under a GNU licence? Then I do not understand, why you are looking for problems from nothing: definitely yes, you can do that even if that GNU licence would be ordinary GPL, not Lesser.

Copyleft of GNU (L)GPL protects free/libre software from being bound with additional restrictions and becoming proprietary, not the opposite; if you want to, you are free to apply to your own part of work alone any of GNU GPL-compatible licences, which are actually either ① more permissive ones that does not prohibit sub-licensing or ② ones that explicitly allows re-licensing under GNU (L)GPL; ASLv2 is in the former category.

Now about issues, specific to certain licence’s versions. You stated that the stylesheet is under GNU LGPLv2.0. Though GNU licences allow limiting upper bound of their version when applying them, there are actually few who do it. But suppose that you did not overlook ‘or any later version’ clause in the copyright notice; that makes question more interesting, since ASLv2 is not compatible with obsolete GNU GPLv2, only with modern GPLv3.

However, GNU Library/Lesser GPL 2.x do allow re-licensing (re-, not sub-) to ordinary GNU GPL of the same or any later version regardless of whether it is allowed to bump a version of LGPL.

So, what you definitely may do is to take the stylesheet and change its copyright notice, so that it refers to GNU GPLv3+ instead of GNU LGPLv2.0=; then combine it with your your work, which is under ASLv2. But the only answer to a question ‘What terms this package as a whole is?’ would be ‘GNU GPLv3+’¹.

¹ By the way, that is not something specific to GNU (L)GPL or copyleft. For example, if you would combine software covered by 3-clause BSDL and Apache License and would want to distribute it as a whole under a single licence, you should do actually the same – choose the less permissive of them, i. e. Apache License.