问:
Interfaces on an abstract class
My coworker and I have different opinions on the relationship between base classes and interfaces.  I'm of the belief that a class should not implement an interface unless that class can be used when an implementation of the interface is required.  In other words, I like to see code like this:

```<code>interface IFooWorker { void Work(); }

abstract class BaseWorker {
    ... base class behaviors ...
    public abstract void Work() { }
    protected string CleanData(string data) { ... }
}

class DbWorker : BaseWorker, IFooWorker {
    public void Work() {
        Repository.AddCleanData(base.CleanData(UI.GetDirtyData()));
    }
}
</code>```

The DbWorker is what gets the IFooWorker interface, because it is an instantiatable implementation of the interface.  It completely fulfills the contract.  My coworker prefers the nearly identical:

```<code>interface IFooWorker { void Work(); }

abstract class BaseWorker : IFooWorker {
    ... base class behaviors ...
    public abstract void Work() { }
    protected string CleanData(string data) { ... }
}

class DbWorker : BaseWorker {
    public void Work() {
        Repository.AddCleanData(base.CleanData(UI.GetDirtyData()));
    }
}
</code>```

Where the base class gets the interface, and by virtue of this all inheritors of the base class are of that interface as well.  This bugs me but I can't come up with concrete reasons why, outside of "the base class cannot stand on its own as an implementation of the interface".

What are the pros & cons of his method vs. mine, and why should one be used over another?

答:
I am still years away from fully grasping the distinction between an abstract class and an interface. Every time I think I get a handle on the basic concepts, I go looking on stackexchange and I'm two steps back. But a few thoughts on the topic and the OPs question:

First:

There are two common explanations of an interface:

An interface is a list of methods and properties that any class can implement, and by implementing an interface, a class guarantees those methods (and their signatures) and those properties (and their types) will be available when "interfacing" with that class or an object of that class. An interface is a contract.

Interfaces are abstract classes that don't/can't do anything. They're useful because you can implement more than one, unlike those mean parent classes. Like, I could be an object of class BananaBread, and inherit from BaseBread, but that doesn't mean I can't also implement both the IWithNuts and the ITastesYummy interfaces. I could even implement the IDoesTheDishes interface, because I'm not just bread, yknow?

There are two common explanations of an abstract class:

An abstract class is, yknow, the thing not what the thing can do. It's like, the essence, not really a real thing at all. Hang on, this will help. A boat is an abstract class, but a sexy Playboy Yacht would be a sub class of BaseBoat.

I read a book on abstract classes, and maybe you should read that book, because you probably don't get it and will do it wrong if you haven't read that book.

By the way, the book Citers always seem impressive, even if I still walk away confused.

Second:

On SO, someone asked a simpler version of this question, the classic, "why use interfaces? What's the difference? What am I missing?" And one answer used an air force pilot as a simple example. It didn't quite land, but it sparked some great comments, one of which mentioned the IFlyable interface having methods like takeOff, pilotEject, etc. And this really clicked for me as a real-world example of why interfaces are not just useful, but crucial. An interface makes an object/class intuitive, or at least gives the sense that it is. An interface isn't for the benefit of the object or the data, but for something that needs to interact with that object. The classic Fruit->Apple->Fuji or Shape->Triangle->Equilateral examples of inheritance are a great model for taxonomically understanding a given object based on its descendants. It informs the consumer and the processors about its general qualities, behaviors, whether the object is a group of things, will hose your system if you put it in the wrong place, or describes sensory data, a connector to a specific data store, or financial data needed to make payroll.

A specific Plane object may or may not have a method for an emergency landing, but I'm going to be pissed off if I assume its emergencyLand like every other flyable object only to wake up covered in DumbPlane and learn that the developers went with quickLand because they thought that it was all the same.  Just like how I would be frustrated if every screw manufacturer had their own interpretation of righty tighty or if my TV didn't have the volume increase button above the volume decrease button.

Abstract classes are the model that establishes what any descendent object must have to qualifiy as that class. If you don't have all the qualities of a duck, it doesn't matter that you have the IQuack interface implemented, your just a weird penguin.  Interfaces are the things that make sense even when you can't be sure of anything else. Jeff Goldblum and Starbuck were both able to fly alien spaceships because the interface was reliably similar.

Third:

I agree with your coworker, because sometimes you need to enforce certain methods at the very start. If you're creating an Active Record ORM, it needs a save method. This isn't up to the subclass that can be instantiated. And if the ICRUD interface is portable enough to not be exclusively coupled to the one abstract class, it can be implemented by other classes to make them reliable and intuitive for anyone already familiar with any of the descendant classes of that abstract class.

On the other hand, there was a great example earlier of when to not jump to tying an interface to the abstract class, because not all list types will (or should) implement a queue interface. You said this scenario happens half the time, which means you and your coworker are both wrong half the time, and thus the best thing to do is argue, debate, consider, and if they turn out to be right, acknowledge and accept the coupling. But don't become a developer who follows a philosophy even when it isn't not the best one for the job at hand.

Title: Interfaces on an abstract class


问:
Using session managed application environment vs no protection
First of all sorry for the title, I didn't know how to explain it. So here comes the story;

We are bunch of coders, front-end and back-end, and we are going to create this new system, based on micro-service architecture for our company. So we already have couple of micro-services in place and our current central application (symfony 1.4 based) is communicating with them, however we want to get rid of this old central application and build a new one. We basically decided to create it with one of the famous JS frameworks without doing much HTML coding. Here are the details about upcoming/planned system

Each micro-service is secured with OAuth2

Central application is of course responsible for logging in and managing token and requests to this micro-services.

So you may ask, OK this looks good but what is the problem? The problem is this,

(BE represents Backend Developers, FE represents Frontend Developers)

BE says, 'OK guys, we don't need to put your frontend code in a container (Lets say Spring MVC) and we don't need to manage sessions etc. because you FE guys will log this user in via our awesome OAuth2 service, you'll keep the token with you and whenever you want to hit those micro-service endpoints just append that token to your request and micro-service will provide you the response you want'

FE says, 'OK BE guys, why don't we do like this, we put our JS code in your Spring MVC environments which will do the session management and logging in and act as a ROUTER, router means this, our JS code just knows one endpoint in Sprint MVC and send all the requests to that endpoint and then that endpoint acts as a router and he redirects the requests to certain micro-service endpoints by appending token, so JS doesn't have to care about all this stuff'

So BE guys say, our approach will give us some certain benefits like,

We don't need to manage session for different machines, because there is load balancer in front of the servers and multiple machines behind we always have to keep sessions synced between them

Since we don't have to put your JS code in a container we don't need a running physical server on the cloud, we can just out your code on S3 in a bucket and no auto-scaling and no server costs

Since you want use to create a router endpoint for your JS calls that would cause to a 'Single point of failure', that means if this router end point doesn't work the complete system will not work at all, but if we use pure static JS even if one micro-service fails other will still work.'

FE guys take their chance and responds,

First of all your approach will make all our source code public

Your approach will make our micro-services visible for all, we know those endpoints are secured via oauth2 but that wouldn't stop DDOS attacks

This would probably end up in a more complex authentication flow

Here is also the way both teams suggests as a diagram. Which way would you guys go and the most important question is WHY?
Thank for your suggestions.

答:
It's hard to answer.

Both approaches seem valid. most of the arguments seem weak. And you can make both of the architectures mimic the other's intended interface.

I'm mostly a ""server side"" developer, and i pretty much prefer the first (FE) approach, just because it'll give me more control, and i could offer the client a simple clear interface with less effort. I would of course want the "router" to run as several physical instances for scalability and redundancy.

Also I think it makes more sense to do session management on the server side.

On the other hand it really depends on the specifics of what you are building... If you have a "fat" client with a lot of Business Logic in it, the second architecture makes more sense...

ContentLicense: CC BY-SA 3.0


问:
Unit-testing on higher levels of architecture
tl;dr: Libraries and classes I use as client are well tested. How I can use that knowledge to reduce amount of testing?

Elaboration: Let's assume for theoretical purposes that we're implementing function which does something fairly simple, say, creating an array of sin(x) of consecutive integers.
(That's Ruby, but choice of the language was arbitrary)

```<code>def arr_of_sins(num)
  Array.new(num){|i| Math.sin(i) }
end
</code>```

We have here the use of 2 well-tested methods, of which we're perfectly confident: Array.new and Math.sin.

Question: how would you test our #arr_of_sins to minimize retesting of dependencies, but to be still confident enough to use it somewhere else?

Bonus question: which tests of those you came out with answering previous question you(as developers) would leave as automated ones?

答:
I would make a single unit test that provides some input and checks that the output is correct. Maybe 1-3 others for bad (negative, null, zero) input. And I would leave them all automated since this sort of this is tailor made for unit testing.

I don't particularly care (in this case) that I'm retesting sin and Array.new. For one, I shouldn't know/care about the unit of work's implementation details. For another, everything builds on something else; to exclude all dependencies sets yourself up for insanity.


答:
for simple scenarios

In your example of arr_of_sins, it has two dependencies: Math.sin and Array.new, however, both of these are used statically and thus to be confident in your tests you must treat it as you wrote the Math.sin and Array.new methods yourself in the class your testing.

This sounds completely ridiculous, but this is the problem of static dependencies that you cannot determine how your logic uses them.

For your particular case, sin can be safely and easily used in any context, so for your test you could call sin itself to see if the result of your class matches up with the expected outcome, however, you will soon find that your unit test will look exactly like your production code, which is pointless.

I would follow @Telastyn's answer and do the cases to get a good approximation of the range of outputs you can expect.

for complex scenarios

The problem arises when you get into more complex scenarios where you're testing code which relies on other systems / sub-systems.  This is where patterns like dependency injection and mockism can help with making your unit tests robust.

For example, if you're testing some code which relies on getting data from another system, say you need to build a report in CSV format from a query on a database.

If a CSV formatter and a repository are dependencies of your report generator, then you can mock both those dependencies out and all you end up testing is that your class uses the dependencies in a way you expect and not that they go to the database to execute query xyz.

to summarize

You write unit tests to ensure that the content of the methods your testing are correct, if you assume that sin behaves as expected that's fine, but you still need to ensure that the unit you're testing is in fact calling sin, and in the example above, the only way to do that is to verify the output.

This is fine for smaller units where the static dependencies have no dependencies of their own, but for more complex cases you need to have a different strategy to ensure the unit your testing is correct.

Title: Unit-testing on higher levels of architecture

Body:
tl;dr: Libraries and classes I use as client are well tested. How I can use that knowledge to reduce amount of testing?

Elaboration: Let's assume for theoretical purposes that we're implementing function which does something fairly simple, say, creating an array of sin(x) of consecutive integers.
(That's Ruby, but choice of the language was arbitrary)

```<code>def arr_of_sins(num)
  Array.new(num){|i| Math.sin(i) }
end
</code>```

We have here the use of 2 well-tested methods, of which we're perfectly confident: Array.new and Math.sin.

Question: how would you test our #arr_of_sins to minimize retesting of dependencies, but to be still confident enough to use it somewhere else?

Bonus question: which tests of those you came out with answering previous question you(as developers) would leave as automated ones?


答:
I would test this as a black box. That means, I would only test the "interface" of a function, like I've never seen it's implementation, which I consider a subject to change. For a given example, I may check:

Resulting array length

... bounds (I assume they are 0..num-1)

Behavior in case of argument is zero (empty array as a result)

... is negative

... is null

If contents are actually results of Math.sin, and not some other random function

Types of argument/result, if it is significant part of API or otherwise "exposed"

Some of those tests definitely may overlap with test from the standard library (e.g. bounds checking), but if someone would change the implementation later, then tests would show the difference, preventing regression, which is a desired property of a test suite.


答:
Ask yourself what the purpose of this function is. Write your tests based on that.

That you are using a well tested library is an implementation detail.

Should you decide to reduce the number of tests because that implementation detail allows you to do so, then you have to make sure that there is a test that would warn you about the implementation changing in such a way that your decision to reduce the number of test is no longer appropriate and should be re-evaluated.

In other words: I am with @Telastyn on this.

If you really want to reduce the number of tests given that you are calling a library you trust, pick a couple of essential tests to keep as part of your own automated test set. In addition to that I would add one or more tests to show that the proper library is used.


问:
URL routing for master detail pattern
Are there any best practices for URL routing in a master detail application?

Let's say the master is a list of fruits. And the master can be filtered based on user security (not all users have access to banana, client side filters (only show green fruits), etc.

The URL route for an apple cannot be as simple as /apple, because there is no guarantee that apple is currently in the master list.

Or would it make sense to handle detail items that are not in the master? You could update the master list to ensure that apple is there, or leave the master list as is, without apple.

Or would you handle routing differently than /apple?

答:
I would keep your routing as simple as possible - /apple seems perfectly valid.

If the user is not allowed to view /apple then show them an error message, if they are allowed to but apple is currently hidden by filters, I'd remove those filters and show them the apple.

Basically - routes should refer to distinct resources and not be clouded by other concerns.

Title: URL routing for master detail pattern


答:
What I'd use:

/fruit or just / — allows to select a master which the user is allowed to see.

/apple, /banana, etc — access a particular master and show available details. If the user is not allowed, responds with a 403.

/apple/seed — access to a detail record; again, is access-controlled and give 403 if the user is not allowed to access either a particular detail or a particular master.

/anything-else — returns 403 (not 404) to prevent a user from checking which fruits exist and which don't.

Upsides: utter simplicity, easy-to-remember links.

Downsides: need to check for master access on every detail page.

Title: URL routing for master detail pattern

Body:
Are there any best practices for URL routing in a master detail application?

Let's say the master is a list of fruits. And the master can be filtered based on user security (not all users have access to banana, client side filters (only show green fruits), etc.

The URL route for an apple cannot be as simple as /apple, because there is no guarantee that apple is currently in the master list.

Or would it make sense to handle detail items that are not in the master? You could update the master list to ensure that apple is there, or leave the master list as is, without apple.

Or would you handle routing differently than /apple?


问:
How do personal assistants typically generate sentences?
This is sort of a follow up to this question about NLG research directions in the linguistics field.

How do personal assistant tools such as Siri, Google Now, or Cortana perform Natural Language Generation (NLG)? Specifically, the sentence text generation part. I am not interested in the text-to-speech part, just the text generation part.

I'm not looking for exactly how each one does it, as that information is probably not available.

I am wondering what setup is required to implement sentence generation of that quality?

What kind of data would you need in a database (at a high level)?

Does it require having a dictionary of every possible word and it's meaning, along with many books/corpora annotated and statistically analyzed added to it?

Does it require actually recording people talk in a natural way (such as from TV shows or podcasts), transcribing them to text, and then adding that somehow to their "system"? (to get really "human"-like sentences)

Or are there just simple syntax-based sentence patterns they are using, with no gigantic semantic "meaning" database? Where someone just wrote a bunch of regular expressions type thing..

What are the algorithms that are used for such naturally written human-like sentences?

One reason for asking is, it seems like the NLG field is very far from being able to do what Siri and Google Now and others are accomplishing. So what kind of stuff are they doing? (Just for the sentence text generation part).

答:
Siri typically doesn't "generate" sentences. She parses what you say and 'recognizes' certain keywords, sure, and for common responses, she will use a template, such as I found [N] restaurants fairly close to you or I couldn't find [X] in your music, [Username].

But most of her responses are canned, depending on her interpretation of your speech, in addition to a random number generator to choose a creative answer to a flippant question. Simply asking Siri "How much wood can a wood chuck chuck?" or "What is the meaning of life?" will generate any of a variety of answers. There are numerous cultural references and jokes built-in (and repeated verbatim) that prove with relative certainty that Siri is not just spontaneously generating most of her text, but pulling it from a database of some sort. It's likely that incoming questions are saved to a central server, where new responses to those questions can be created by Apple employees, allowing Siri to "learn".

Her text-to-speech part is good enough, however, that it sometimes makes it seem as though the answers are being generated...

OwnerDisplayName: Lance Pollard


答:
You say the sin function is well tested an you trust it. You're probably right that it is well tested. So sin (0) is 0, sin (90) = 1, sin (180) = 0, sin (270) = -1 and so on, right? You see, even if the function does 100% correctly what it is supposed to do, it doesn't mean it does what you think it should do.

But in your unit test, do you care whether the array new and the sine function work? You don't, not in your unit test. What you care about is that the function that you wrote returns the right values, and that's what you should test. What do you gain by having a unit test for the sine function? If the unit tests for your function work, the sine function unit test doesn't gain you anything.

If the unit test for your function breaks, you have to decide whether your code was wrong, or whether the sine or the array code is bad. So you won't have a colleague telling you "guess what, the sine function is broken" and then you say "well, that explains why my unit test fails". But that wouldn't happen anyway, because the sine function isn't broken. So just good old fashioned debugging.


问:
What makes functional programming languages declarative as opposed to Imperative?
On many articles, describing the benefits of functional programming, I have seen functional programming languages, such as Haskell, ML, Scala or Clojure, referred to as "declarative languages" distinct from imperative languages such as C/C++/C#/Java. My question is what makes functional programming languages declarative as opposed to imperative.

An often encountered explanation describing the differences between Declarative and Imperative programming is that in Imperative programming you tell the computer "How to do something" as opposed to "What to do" in declarative languages. The problem I have with this explanation is that you are constantly doing both in all programming languages. Even if you go down to the lowest level assembly you are still telling the computer "What to do", you tell the CPU to add two numbers, you don't instruct it on how to perform the addition. If we go to the other end of the spectrum, a high level pure functional language like Haskell, you are in fact telling the computer how to achieve a specific task, that is what your program is a sequence of instructions to achieve a specific task which the computer does not know how to achieve alone. I understand that languages such as Haskell, Clojure, etc. are obviously higher level than C/C++/C#/Java and offer features such as lazy evaluation, immutable data structures, anonymous functions, currying, persistent data structures, etc. all which make functional programming possible and efficient, but I wouldn't classify them as declarative languages.

A pure declarative languages for me would be one which is comprised entirely of declarations only, an example of such a languages would be CSS (Yes I know CSS would technically not be a programming language). CSS just contains style declarations which are used by the HTML and Javascript of the page. CSS cannot do anything else besides make declarations, it cannot create class functions, i.e. functions which determine the style to display based on some parameter, you cannot execute CSS scripts, etc. That for me describes a declarative language (notice I did not say declarative programming language).

Update:

I've been playing around with Prolog recently and to me, Prolog is the closest programming language to a fully declarative language (At least in my opinion), if it is not the only fully declarative programming language. To elaborate programming in Prolog is done by making declarations which state either a fact (a predicate function which returns true for a specific input) or a rule (a predicate function which returns true for a given condition/pattern based on the inputs), rules are defined using a pattern matching technique. To do anything in prolog you query the knowledge base by substituting one or more of the inputs of a predicate with a variable and prolog tries to find values for the variable(s) for which the predicate succeeds.

My point is in prolog there are no imperative instructions, you basically telling (declaring) the computer what it knows and then asking (querying) about about the knowledge.  In functional programming languages you are still giving instructions i.e. take a value, call function X and add 1 to it, etc, even if you are not directly manipulating memory locations or writing out computation step by step. I wouldn't say that programming in Haskell, ML, Scala or Clojure is declarative in this sense, though I may be wrong. Is proper, true, pure functional programming declarative in the sense that I described above.

答:
The real defining characteristic that separates declarative from imperative programming is in declarative style you are not giving sequenced instructions; at the lower level yes the CPU operates this way, but that's a concern of the compiler.

You suggest CSS is a "declarative language", I wouldn't call it a language at all. It's a data structure format, like JSON, XML, CSV, or INI, just a format for defining data that's known to an interpreter of some nature.

Some interesting side effects happen when you take the assignment operator out of a language, and this is the real cause for losing all those step1-step2-step3 imperative instructions in declarative languages.

What do you do with the assignment operator in a function? You create intermediate steps. That's the crux of it, the assignment operator is used to alter data in a step-by-step fashion. As soon as you can no longer alter data, you lose all of those steps and end up with:

Every function has only one statement, this statement being the single declaration

Now there are many ways to make a single statement look like many statement, but that's just trickery, for instance: 1 + 3 + (2*4) + 8 - (7 / (8*3)) this is clearly a single statement, but if you write it as...

```<code>1 +
3 +
(
  2*4
) +
8 -
(
  7 / (8*3)
)
</code>```

It can take on the appearance of a sequence of operations which can be easier for the brain to recognize the desired decomposition the author was intending. I often do this in C# with code like..

```<code>people
  .Where(person => person.MiddleName != null)
  .Select(person => person.MiddleName)
  .Distinct();
</code>```

This is a single statement, but shows the appearance of being decomposed into many - notice there are no assignments.

Also note, in both above methods - the way the code is actually executed is not in the order you immediately read it in; because this code says what to do, but it does not dictate how. Note the simple arithmetic above is obviously not going to be executed in the sequence it's written left to right, and in the C# example above those 3 methods are actually all re-entrant and not executed to completion in sequence, the compiler in fact generates code that will do what that statement wants, but not necessarily how you assume.

I believe getting used to this no-intermediate-steps approach of declarative coding is really the most difficult part of it all; and why Haskell is so tricky because few languages truly disallow it like Haskell does. You have to start doing some interesting gymnastics to accomplish some things that you would typically do with the aid of intermediate variables, such as summation.

In a declarative language, if you want an intermediate variable to do something with - it means passing it as a parameter to a function which does that thing. This is why recursion becomes so important.

sum xs = (head xs) + sum (tail xs)

You can't create a resultSum variable and add to it as you loop through xs, you have to simply take the first value, and add it to whatever the sum is of everything else - and to access everything else you have to pass xs to a function tail because you can't just create a variable for xs and pop the head off which would be an imperative approach. (Yes I know you could use destructuring but this example is meant to be illustrative)

Body:
The real defining characteristic that separates declarative from imperative programming is in declarative style you are not giving sequenced instructions; at the lower level yes the CPU operates this way, but that's a concern of the compiler.

You suggest CSS is a "declarative language", I wouldn't call it a language at all. It's a data structure format, like JSON, XML, CSV, or INI, just a format for defining data that's known to an interpreter of some nature.

Some interesting side effects happen when you take the assignment operator out of a language, and this is the real cause for losing all those step1-step2-step3 imperative instructions in declarative languages.

What do you do with the assignment operator in a function? You create intermediate steps. That's the crux of it, the assignment operator is used to alter data in a step-by-step fashion. As soon as you can no longer alter data, you lose all of those steps and end up with:

Every function has only one statement, this statement being the single declaration

Now there are many ways to make a single statement look like many statement, but that's just trickery, for instance: 1 + 3 + (2*4) + 8 - (7 / (8*3)) this is clearly a single statement, but if you write it as...

1 +
3 +
(
  2*4
) +
8 -
(
  7 / (8*3)
)

It can take on the appearance of a sequence of operations which can be easier for the brain to recognize the desired decomposition the author was intending. I often do this in C# with code like..

people
  .Where(person => person.MiddleName != null)
  .Select(person => person.MiddleName)
  .Distinct();

This is a single statement, but shows the appearance of being decomposed into many - notice there are no assignments.

Also note, in both above methods - the way the code is actually executed is not in the order you immediately read it in; because this code says what to do, but it does not dictate how. Note the simple arithmetic above is obviously not going to be executed in the sequence it's written left to right, and in the C# example above those 3 methods are actually all re-entrant and not executed to completion in sequence, the compiler in fact generates code that will do what that statement wants, but not necessarily how you assume.

I believe getting used to this no-intermediate-steps approach of declarative coding is really the most difficult part of it all; and why Haskell is so tricky because few languages truly disallow it like Haskell does. You have to start doing some interesting gymnastics to accomplish some things that you would typically do with the aid of intermediate variables, such as summation.

In a declarative language, if you want an intermediate variable to do something with - it means passing it as a parameter to a function which does that thing. This is why recursion becomes so important.

sum xs = (head xs) + sum (tail xs)

You can't create a resultSum variable and add to it as you loop through xs, you have to simply take the first value, and add it to whatever the sum is of everything else - and to access everything else you have to pass xs to a function tail because you can't just create a variable for xs and pop the head off which would be an imperative approach. (Yes I know you could use destructuring but this example is meant to be illustrative)


问:
Is it a good idea to install more libraries than you need?
I decided to try Anaconda, it seems that too many large companies are using it. I was amazed by the number of libraries included by default

```<code>installing: python-2.7.9-2 ...
installing: conda-3.10.0-py27_0 ...
installing: conda-build-1.11.0-py27_0 ...
installing: conda-env-2.1.3-py27_0 ...
installing: _license-1.1-py27_0 ...
installing: abstract-rendering-0.5.1-np19py27_0 ...
installing: argcomplete-0.8.4-py27_0 ...
installing: astropy-1.0.1-np19py27_0 ...
installing: bcolz-0.8.1-np19py27_0 ...
installing: beautiful-soup-4.3.2-py27_0 ...
installing: binstar-0.10.1-py27_3 ...
installing: bitarray-0.8.1-py27_0 ...
installing: blaze-core-0.7.3-np19py27_0 ...
installing: blz-0.6.2-np19py27_0 ...
installing: bokeh-0.8.1-np19py27_1 ...
installing: boto-2.36.0-py27_0 ...
installing: cairo-1.12.18-1 ...
installing: cdecimal-2.3-py27_0 ...
installing: certifi-14.05.14-py27_0 ...
installing: cffi-0.9.2-py27_0 ...
installing: clyent-0.3.4-py27_0 ...
installing: colorama-0.3.3-py27_0 ...
installing: configobj-5.0.6-py27_0 ...
installing: cryptography-0.8-py27_0 ...
installing: curl-7.38.0-0 ...
installing: cython-0.22-py27_0 ...
installing: cytoolz-0.7.2-py27_0 ...
installing: datashape-0.4.4-np19py27_1 ...
installing: decorator-3.4.0-py27_0 ...
installing: docutils-0.12-py27_0 ...
installing: dynd-python-0.6.5-np19py27_0 ...
installing: enum34-1.0.4-py27_0 ...
installing: fastcache-1.0.2-py27_0 ...
installing: flask-0.10.1-py27_1 ...
installing: fontconfig-2.11.1-2 ...
installing: freetype-2.5.2-0 ...
installing: funcsigs-0.4-py27_0 ...
installing: futures-2.2.0-py27_0 ...
installing: gevent-1.0.1-py27_0 ...
installing: gevent-websocket-0.9.3-py27_0 ...
installing: greenlet-0.4.5-py27_0 ...
installing: grin-1.2.1-py27_1 ...
installing: h5py-2.4.0-np19py27_0 ...
installing: hdf5-1.8.14-0 ...
installing: ipython-3.0.0-py27_0 ...
installing: ipython-notebook-3.0.0-py27_1 ...
installing: ipython-qtconsole-3.0.0-py27_0 ...
installing: itsdangerous-0.24-py27_0 ...
installing: jdcal-1.0-py27_0 ...
installing: jedi-0.8.1-py27_0 ...
installing: jinja2-2.7.3-py27_1 ...
installing: jpeg-8d-0 ...
installing: jsonschema-2.4.0-py27_0 ...
installing: libdynd-0.6.5-0 ...
installing: libffi-3.0.13-0 ...
installing: libpng-1.5.13-1 ...
installing: libsodium-0.4.5-0 ...
installing: libtiff-4.0.2-1 ...
installing: libxml2-2.9.0-0 ...
installing: libxslt-1.1.28-0 ...
installing: llvmlite-0.2.2-py27_1 ...
installing: lxml-3.4.2-py27_0 ...
installing: markupsafe-0.23-py27_0 ...
installing: matplotlib-1.4.3-np19py27_1 ...
installing: mistune-0.5.1-py27_0 ...
installing: mock-1.0.1-py27_0 ...
installing: multipledispatch-0.4.7-py27_0 ...
installing: networkx-1.9.1-py27_0 ...
installing: nltk-3.0.2-np19py27_0 ...
installing: nose-1.3.4-py27_1 ...
installing: numba-0.17.0-np19py27_0 ...
installing: numexpr-2.3.1-np19py27_0 ...
installing: numpy-1.9.2-py27_0 ...
installing: odo-0.3.1-np19py27_0 ...
installing: openpyxl-1.8.5-py27_0 ...
installing: openssl-1.0.1k-1 ...
installing: pandas-0.15.2-np19py27_1 ...
installing: patsy-0.3.0-np19py27_0 ...
installing: pep8-1.6.2-py27_0 ...
installing: pillow-2.7.0-py27_1 ...
installing: pip-6.0.8-py27_0 ...
installing: pixman-0.26.2-0 ...
installing: ply-3.4-py27_0 ...
installing: psutil-2.2.1-py27_0 ...
installing: ptyprocess-0.4-py27_0 ...
installing: py-1.4.26-py27_0 ...
installing: py2cairo-1.10.0-py27_2 ...
installing: pyasn1-0.1.7-py27_0 ...
installing: pycosat-0.6.1-py27_0 ...
installing: pycparser-2.10-py27_0 ...
installing: pycrypto-2.6.1-py27_0 ...
installing: pycurl-7.19.5.1-py27_0 ...
installing: pyflakes-0.8.1-py27_0 ...
installing: pygments-2.0.2-py27_0 ...
installing: pyopenssl-0.14-py27_0 ...
installing: pyparsing-2.0.3-py27_0 ...
installing: pyqt-4.11.3-py27_0 ...
installing: pytables-3.1.1-np19py27_2 ...
installing: pytest-2.6.4-py27_0 ...
installing: python-dateutil-2.4.1-py27_0 ...
installing: pytz-2015.2-py27_0 ...
installing: pyyaml-3.11-py27_0 ...
installing: pyzmq-14.5.0-py27_0 ...
installing: qt-4.8.6-0 ...
installing: readline-6.2-2 ...
installing: redis-2.6.9-0 ...
installing: redis-py-2.10.3-py27_0 ...
installing: requests-2.6.0-py27_0 ...
installing: rope-0.9.4-py27_1 ...
installing: runipy-0.1.3-py27_0 ...
installing: scikit-image-0.11.2-np19py27_0 ...
installing: scikit-learn-0.15.2-np19py27_0 ...
installing: scipy-0.15.1-np19py27_0 ...
installing: setuptools-14.3-py27_0 ...
installing: sip-4.16.5-py27_0 ...
installing: six-1.9.0-py27_0 ...
installing: sockjs-tornado-1.0.1-py27_0 ...
installing: sphinx-1.2.3-py27_0 ...
installing: spyder-2.3.4-py27_1 ...
installing: spyder-app-2.3.4-py27_0 ...
installing: sqlalchemy-0.9.9-py27_0 ...
installing: sqlite-3.8.4.1-1 ...
installing: ssl_match_hostname-3.4.0.2-py27_0 ...
installing: statsmodels-0.6.1-np19py27_0 ...
installing: sympy-0.7.6-py27_0 ...
installing: system-5.8-2 ...
installing: terminado-0.5-py27_0 ...
installing: theano-0.6.0-np19py27_0 ...
installing: tk-8.5.18-0 ...
installing: toolz-0.7.1-py27_0 ...
installing: tornado-4.1-py27_0 ...
installing: ujson-1.33-py27_0 ...
installing: unicodecsv-0.9.4-py27_0 ...
installing: util-linux-2.21-0 ...
installing: werkzeug-0.10.1-py27_0 ...
installing: xlrd-0.9.3-py27_0 ...
installing: xlsxwriter-0.6.7-py27_0 ...
installing: xlwt-0.7.5-py27_0 ...
installing: yaml-0.1.4-0 ...
installing: zeromq-4.0.4-0 ...
installing: zlib-1.2.8-0 ...
installing: anaconda-2.2.0-np19py27_0 ...
installing: _cache-0.0-x0 ...
</code>```

I need many of them, it makes deployment so I easy, it has a cloning option, too many good options, but there are libraries I don't need, like PyQt and others.

So when it comes to deployment, is it a good idea to buy time and make your job easier by bloating the servers?

答:
Contractors from various fields typically bring their entire toolbox to a job. Sometimes, they even bring tools that they're not entirely familiar with, on the off chance that they might find them necessary... But also, probably because those tools came in a set, and that set was made in a 'one-size-fits-all' fashion, as it seems has been done here.

You may not need bits to remove hex or torx screws, for instance, but they're in your kit, and you take your kit wherever you go. On the off chance that you do find one, you'll be ready to use it!

Contractors that work in the field of malware removal, as another example, keep all sorts of removal software on their discs and keys. It is often justified.

If you don't feel justified using the bandwidth or drive space, see if there's a way to do a custom install, or if removing the libraries by hand will remedy the situation. Or you could always learn to use them all! ;)


问:
Complex data structure in python: just dict, etc, or some classes?
Consider a web service API that returns a complex Json object. Using the stock Python tools for the job, this will read in from the web service as a dict which contains, in turn, a mixture of arrays, dicts, strings, and numbers.

I confess: this data is born in Java. In Java, there's a data model for this data. My question is, would dyed-in-the-wool Python programmers desire a Python class data model that adds some notational niceness, or would they expect to just be handed the situation described in the first paragraph.

In code terms, what's the value of:

```<code> text.tokens[3].part_of_speech
</code>```

as opposed to:

```<code> text['tokens'][3]['part_of_speech']
</code>```

?

Based on some comments, I want to expand this a little. What I wrote above is all about consuming a complex data structure that arrives in Python as Json, and I can see that 'sugaring' it with a pile of classes with @property markers is not very helpful.

Another side of the coin is assembling one of these. As, admittedly, a person who has spent a lot more time in Java, C++, C (and Lisp?) than in Python, I would tend to see value in some API that helps me remember the names of all the bits and pieces. So maybe that suggests simply providing constants that provide the defined keys?

答:
I would use built-in lists for any lists (uniform variable-length sequences of objects).

I would use namedtuple-derived classes to store data with known fixed sets of named fields. It's like objects, but immutable.

So you'd have your text.tokens[3].part_of_speech == NOUN, but won't have text.tokens[3].part_of_speech = NOUN. Immutability is often useful at preventing a whole class of errors, though.

E.g.

```<code>from collection import namedtuple

Token = namedtuple('Token', ['part_of_speech', 'whatnot'])
Text = namedtuple('Text', ['tokens', 'metainfo', 'stats'])

# ...

json_doc = json.load(...)
tokens = []
for json_token in json_doc['tokens']:
  t = Token(json_token['part_of_speech'], json_token['whatnot'])
  # or even t = Token(**json_token)
  tokens.append(t)
...
return Text(tokens, ...)
</code>```

Body:
I would use built-in lists for any lists (uniform variable-length sequences of objects).

I would use namedtuple-derived classes to store data with known fixed sets of named fields. It's like objects, but immutable.

So you'd have your text.tokens[3].part_of_speech == NOUN, but won't have text.tokens[3].part_of_speech = NOUN. Immutability is often useful at preventing a whole class of errors, though.

E.g.

from collection import namedtuple

Token = namedtuple('Token', ['part_of_speech', 'whatnot'])
Text = namedtuple('Text', ['tokens', 'metainfo', 'stats'])

# ...

json_doc = json.load(...)
tokens = []
for json_token in json_doc['tokens']:
  t = Token(json_token['part_of_speech'], json_token['whatnot'])
  # or even t = Token(**json_token)
  tokens.append(t)
...
return Text(tokens, ...)


问:
Is it possible to make a printable 'template' document?
I'm writing a piece of software to generate and print nametags. The issue I'm having is that nametags need to be formatted the same, but have different values (ie. different names, titles), and can be on different sizes of paper.

So I need an efficient way to store a sort of 'template' that has certain formatting info (alignment, size and location relative to document's dimensions) and has placeholders for values to be substituted in. Then, at runtime, I need to be able to provide the dimensions of the nametag and the field values, to return a printable document.

My current approach is to have a bunch of pre-written HTML documents which have tables and different sizes, and then substituting the cell values with the given information. The problem with this is that HTML tables are really limited on positioning and sizing of elements. Plus, I end up needing to write javascript to resize and translate elements to handle different sizes of paper and really long field values, which limits code reusability as everyone needs to have the same JS or the files will produce different nametags.

Is there a better way to do this? Is there a printable document type that uses relative sizing and positioning for elements, such that if the values are edited the formatting will be preserved?

I would write my own file type (probably an XML structure) but then anyone using these files would have to use additional code to read my document and turn it into something printable.

答: Another PDF-leveraging option could be to use a PDF form: this can be filled in via a code process (there are both software libraries and web APIs that do this) and then 'flattened' into a printable PDF.</p>


问:
How to represent a Model with a 1:N relation?
I have a task to associate 1:N documents to a record in my hardware table. This file could be a warranty, or whatever. In SQLServer I set up a FileStream group and made a table for only the file and the other required columns (id, internal id (a guid), and a varbinary(MAX) column). I have another table that will store the file information (name, size, mime type), and the file's id in from the files table. I call this table Document_Info. Is this a good name? Describing the relationship between my hardware table and the Document_Info table I'm struggling with.

I'm considering storing the hardware's id in the Document_Info table and create another column representing what this document is related to. That would help me integrate other future tables that also need to relate 1:1 or 1:N if they need to store files as well. I just specify a new type and I'm good. id's can be the same as long as their id type is different.

How this all relates to my hardware model is, by principle, it doesn't because a model's fields represents a table's columns. Yet, I have to store this hardware's documents somewhere, but the question is where?

答:
Is this your basic model, sorry, not sure if I understand your text:

Hardware_table(Id, GUID, Description, etc) this holds your primary object one of each
Document_info_table(Id, HId,  Name, size, mime type) this holds documents related to primary object

Using SQL you would have to link Hardware_Table to Document_Info_table by inserting the PK from the first into each related record into the latter table.  Names of tables don't really matter since these are shielded from end users by your programming interface.

I would not store the actual documents into the SQL tables unless you really have a need do do that, I dont like reading and writing blob data into SQL.  BEtter to store in the file system and store the pointers in the SQL databas, better use of DB storage and read/write efficiency.


问:
How do I determine if customers have already received a newsletter?
The problem: When we were sending newsletters to customers, there was no way to confirm if the customer already received the mail. We have come up with two different approaches:

(Boss's Idea) Each time mail was being sent, do an INSERT in a db with the title of the newsletter being sent and the email address which is receving the email address. To ensure that any email address does not receive the same email twice, do a SELECT in the table and find the title of the newsletter being sent:

```<code>if (title of newsletter is found)
{
  check to see of the email we are sending mail to is already present. if it does, do not send mail
}
else
{
  send mail
}
</code>```

(My idea) create a column called unique and mark it as UNIQUE. Each time mail was being sent, concatenate email + newsletter id and record it in the UNIQUE row. The next time we do a "mysql_affected_rows" check to see if our INSERT was successful, we send the mail, else, there is already a duplicate and no need to send it.

Is either approach objectively superior? If yes, which one and why?

答:
Your boss's solution is the better of the two.

But you're actually both wrong. :-)

Each mailing (ie, title) should have a unique id.  So you need a table that tracks that.  Never rely on a title being unique like that.

Then you need a 'working' table that includes the mailing id, the email address, and a flag for whether the message is sent (integer, 0 or 1).  Before you start mailing, do a mass insert into that table of all the addresses you intend to send to.

Then, your mailer will operate against that table, flipping the sent flag as it processes each message.  This way a mailing can easily be resumed if the server is interupted for some reason by simply querying those rows that do not have their sent flag set.  It also never hurts to track a timestamp of each sent email.

In addition, you can insert the working table's row id as part of an unsubscribe link included in each mailer, so you'll know which mailings caused people to unsubscribe.

This approach allows you to handle multiple mailings (if you have multiple newsletters for example) and maintain a very detailed log of who got what email and when.

ContentLicense: CC BY-SA 2.5


问:
Is it bad practice to make a subclass in name only for readability?
I have three sensors in a single package that all need to be calibrated which I will call sens1, sens2, and sens3. The calibration for sens1 and sens2 are identical, but the calibration for sens3 requires an extra parameter. My question is, "What is the best way to deal with three near-identical objects while still maintaining readability?"

My first thought, of course, was to use polymorphism. I would setup a generic Sensor object with a .calibrate(Parameters params) method where the Parameters class allows me to vary the number of parameters based on the calibration that I am doing. However, this leads to the following:

```<code>Sensor sens1 = new Sensor();
Sensor sens2 = new Sensor();
Sensor3 sens3 = new Sensor3();
</code>```

So that future people will need to know that one sensor is fundamentally different than the other two, but very very similar, it seems to me that the best thing to do is to subclass Sens1 and Sens2 in name only. In other words, make two sublcasses that don't modify or extend any behavior in order to have more logical class names. Remember, all three of these sensors are in the same package, so this data very often goes together. This changes the above code to:

```<code>Sensor1 sens1 = new Sensor1();
Sensor2 sens2 = new Sensor2();
Sensor3 sens3 = new Sensor3();
</code>```

where

```<code>Sensor1 extends Sensor {
}

Sensor2 extends Sensor {
}

Sensor3 extends Sensor {
    @Override
    calibrated(Parameters params) {
        \\ Code
    }
}
</code>```

Am I crazy for thinking this is a good idea? Is there a cleaner pattern I'm completely missing here?

答:
Not if the best descriptive names for these sensors are Sensor1, Sensor2 and Sensor3.  The numbers do not indicate any distinguishing characteristics between the sensors.

If the different classes denote different types of sensors, then different classes may be warranted.  This is why we sometimes refer to classes as types, though the word "type" itself has a broader meaning.

```<code>PressureSensor extends Sensor
TemperatureSensor extends Sensor
</code>```

Body:
Not if the best descriptive names for these sensors are Sensor1, Sensor2 and Sensor3.  The numbers do not indicate any distinguishing characteristics between the sensors.

If the different classes denote different types of sensors, then different classes may be warranted.  This is why we sometimes refer to classes as types, though the word "type" itself has a broader meaning.

PressureSensor extends Sensor
TemperatureSensor extends Sensor


答:
As written (which may be oversimplified) it sounds like the Sensors are all the same in general behavior, but the Parameters for calibration are different.

If this were the only difference, and you are using a language with generics, such as Java (used below), you could generify the class by the Parameters, something like:

```<code>abstract class Sensor<CalibrationParameters> {
   // constructor, getters, setters, etc...

   abstract public void calibrated(CalibrationParameters parameters);
}
</code>```

then a bunch of

```<code>public class SensorN extends Sensor<CalibrationParametersForSensorN> {

   public void calibrated(CalibrationParametersForSensorN parameters) {
      ...
   }

}
</code>```

Caveat: typed without an IDE so there may be typos or errors...

p.s. Agree with Robert that better names would be, er, better.  So a better concrete implementation would be:

```<code>public class Thermometer extends Sensor<ThermometerCalibration> {

    public void calibrated(ThermometerCalibration parameters) {
       ...
    }

}
</code>```

Title: Is it bad practice to make a subclass in name only for readability?

Body:
I have three sensors in a single package that all need to be calibrated which I will call sens1, sens2, and sens3. The calibration for sens1 and sens2 are identical, but the calibration for sens3 requires an extra parameter. My question is, "What is the best way to deal with three near-identical objects while still maintaining readability?"

My first thought, of course, was to use polymorphism. I would setup a generic Sensor object with a .calibrate(Parameters params) method where the Parameters class allows me to vary the number of parameters based on the calibration that I am doing. However, this leads to the following:

```<code>Sensor sens1 = new Sensor();
Sensor sens2 = new Sensor();
Sensor3 sens3 = new Sensor3();
</code>```

So that future people will need to know that one sensor is fundamentally different than the other two, but very very similar, it seems to me that the best thing to do is to subclass Sens1 and Sens2 in name only. In other words, make two sublcasses that don't modify or extend any behavior in order to have more logical class names. Remember, all three of these sensors are in the same package, so this data very often goes together. This changes the above code to:

```<code>Sensor1 sens1 = new Sensor1();
Sensor2 sens2 = new Sensor2();
Sensor3 sens3 = new Sensor3();
</code>```

where

```<code>Sensor1 extends Sensor {
}

Sensor2 extends Sensor {
}

Sensor3 extends Sensor {
    @Override
    calibrated(Parameters params) {
        \\ Code
    }
}
</code>```

Am I crazy for thinking this is a good idea? Is there a cleaner pattern I'm completely missing here?

Body:
As written (which may be oversimplified) it sounds like the Sensors are all the same in general behavior, but the Parameters for calibration are different.

If this were the only difference, and you are using a language with generics, such as Java (used below), you could generify the class by the Parameters, something like:

abstract class Sensor<CalibrationParameters> {
   // constructor, getters, setters, etc...

   abstract public void calibrated(CalibrationParameters parameters);
}

then a bunch of

public class SensorN extends Sensor<CalibrationParametersForSensorN> {

   public void calibrated(CalibrationParametersForSensorN parameters) {
      ...
   }

}

Caveat: typed without an IDE so there may be typos or errors...

p.s. Agree with Robert that better names would be, er, better.  So a better concrete implementation would be:

public class Thermometer extends Sensor<ThermometerCalibration> {

    public void calibrated(ThermometerCalibration parameters) {
       ...
    }

}


问:
How does a browser remember the scroll state?
For example you are visiting a page and scrolled down half way through and then you refresh the page the browser remembers your scroll state and loads the page at exactly the same spot where you were viewing it.

I think the same thing happens when you hit the back button.

答:
The scroll bar has a numeric position associated with it.  More specifically, it's a get/set property on the scroll bar object.  When you navigate to another page, the browser stores the number corresponding to the current scroll bar position with the page URL.  When you navigate back to that page, the browser recalls the scroll bar position.  That's all.

This technique is not unique to browsers; generally you can do the same thing in any UI framework that has windows and scroll bars.


问:
What layer would an Audio Player Service fall under in a an MVP system?
I'm trying to completely overhaul an app I wrote a while back that plays audio, and I'm learning how the MVP pattern of organization works, but I'm not sure how/where an audio playback service would fit in this design pattern, or how I could break out of this pattern without disrupting the benefits that come with it.

I'm working off of these tutorials/examples to get my head around the topic:
first example|second example

I realize that the MVP pattern is not a complete system architecture, but I'm struggling to figure out how I can continue with the good practices set out in this patter with things like an audio play service. Or a download service, sense neither of those fall strictly under what I would think of data or presentation. If someone could point me in the right direction on this I would be very grateful.

答: The purpose of the MV* patterns is primarily to provide separation of concerns between the UI and the rest of the system.  Your Audio Player Service, if it also includes the player, uses the entire pattern.  If it's just streaming data, it's the model.


问:
Updating particular properties of EF objects every X amount of days in MVC
I'm building an MVC ASP.NET IMDb-like website which presents various information about movies to users, relying on 3rd party APIs to (initially) fetch movie info.

The IDs representing each movie on the website are identical to IMDb's (ID tt1234567 points to the same movie on both websites).

The way movie info are fetched (and subsequently stored on SQL server) is as follows:

User requests movie with id tt1234567

MVC checks if movie with id tt1234567 exists in the database.

If not, it queries external APIs to fetch movie information and stores it in the database.

If yes, it fetches the information directly from the database.

This works fine and I'm at the point where I'm implementing caching. There are some particular columns for each row in the Movie table which change every certain amount of days (e.g. overall rating and number of votes for that movie in IMDb). As such, I need to implement a function where relevant columns of the row are updated after certain amount of time (e.g. every 10 days).

What would be the correct approach to do this? Should I implement a scheduled task which runs every 10 days and updates the needed columns in the DB, or should I somehow add caching into the mix?

答:
if you go the task route write the task to run every 10 minutes, select movies which are out of date and update them. otherwise you will end up with a massive task every ten days.

But I would suggest you just run this check when a movies is retrieved from the db instead. If its not found OR out of date, goto imdb and update


问:
Is there a detriment to using SQLite over a pList for persistence?
I'm making a fairly simple application and I've got a settings menu that stores times and some boolean values. I have the application storing and retrieving data already but I started to wonder if SQLite was a bad choice.

I am assuming the answer is that I should've probably just used a pList for such few values. But if I'm comfortable with CoreData (and it's already in place) is there a detriment to using SQLite over pList?

Also for sake of argument, lets say this database will hold a total of 20 items and at the most 2 tables.

答:
Database migrations between core data models is difficult.  Setting up a core data model (or any sql-like database) is like getting a tattoo.

The core data API is good but even seasoned veterans still struggle with it.

I am in no way suggesting core data is bad and it shouldn't be used. I am just suggesting that in your case, you could easily avoid it, so you should.

Another thing to consider is that data retrieval from a pList is slower than core data fetches but I doubt this will impact you.


问:
How wrong it is to have multiple associations between classes?
I'm modeling a college process, in which I have three classes: Student, Subject and Degree

Degrees have their own subjects, students have a list of subjects they have passed, and also students should belong to a single degree plan.

From a design perspective, how should I associate a student with his/her degree?

If student has a reference to his relevant Degree object, then it suddenly could have a lot more responsibility, and I want to manage Separation of concerns properly.

Is there a better alternative?

答:
Asking this question shows that you find your current model not intuitive and I think this is a good feeling.
Let me explain an alternative to having only Student, Subject and Degree to you that hopefully feels more intuitive.

While a student might seem to know everything about his degrees, he doesn't. Let's illustrate this with a real world example: Consider a student got a degree for some course. However, the university staff found out and can prove that the student cheated in the final tests. His degree is therefore immediatly declared invalid before he probably even gets to know about that.

The question is: who is responsible for telling if some students degree is existing and also valid?

They are the ones having the responsibility of knowing which student has which (valid) degrees. This could e.g. be an examination office, but it might depend on the university/country.[1]

As you see, we have to model another party in regards of separation of concerns. And same goes for your single degree plan. There certainly is another authority responsible for administration of the students degree plans to make sure every student has only one plan and that this plan is valid.

In a nutshell, students and their degrees are only connected indirect through differend kind of authorities. The students usually know the authorities that are responsible for them (e.g. in code that means they have a reference to this object).

[1]: Just a note of caution: even though there might only be one authority of this kind, don't model this with some singleton pattern. Instead, model it as if there could be more than one authorities and in your actual program only create one instance.


问:
Module based project vs Normal project
I am writing code on top an established Enterprise application. I see that the application has 4 modules as shown below.

```<code>-Srk
-SrkEJB
-SrkUtils
-SrkWeb
</code>```

I have gone through the code and I see that some modules are tiny for example: SrkEJB module has got just 2 EJBS. I don't see any reason to create a separate module for 2 Java classes.

I have simplified the above approach and is shown below.

```<code>Srk
 - com.srk.utils
 - com.srk.ejb
 - com.srk.web
</code>```

How is the first module based architecture different from the second from an architectural stand point? Generally, which is the followed mostly, when creating an application from scratch? If not, What could be the trade-offs of each of the approaches? I believe this is a not specific to Java alone.

答:
Generally speaking, there is no right way to organize classes. There is only the way that best meets the projects requirements for clarity. The size of the modules is probably the least important organizing principle.

–  Robert Harvey

Title: Module based project vs Normal project


答:
Modular design is about separation of concerns, NOT about splitting something up into smaller sections (though it tends to have that effect).

It's perfectly acceptable (and even very good practice) to have a separate EJB module, web module, etc.. Each is its own deliverable after all within the JEE landscape, with the EJB module creating an EJB jar, the web module a WAR, and the utils module a jar file referenced by both.

So your environment is suggesting the modules, enforcing it even through most build tools.

Title: Module based project vs Normal project

Body:
I am writing code on top an established Enterprise application. I see that the application has 4 modules as shown below.

```<code>-Srk
-SrkEJB
-SrkUtils
-SrkWeb
</code>```

I have gone through the code and I see that some modules are tiny for example: SrkEJB module has got just 2 EJBS. I don't see any reason to create a separate module for 2 Java classes.

I have simplified the above approach and is shown below.

```<code>Srk
 - com.srk.utils
 - com.srk.ejb
 - com.srk.web
</code>```

How is the first module based architecture different from the second from an architectural stand point? Generally, which is the followed mostly, when creating an application from scratch? If not, What could be the trade-offs of each of the approaches? I believe this is a not specific to Java alone.


答:
If you want to associate a Student with a Degree, but keep them separate from each other, you can express that relationship with a data structure like a HashMap.

something like (untested, treat this as pseudo code):

```<code>HashMap<Student, Degree> enrolment = new HashMap<Student, Degree>();
Student dave = new Student();
Degree masterOfScience = new Degree();
enrolment.put(dave, masterOfScience);
</code>```

Title: How wrong it is to have multiple associations between classes?

Body:
I'm modeling a college process, in which I have three classes: Student, Subject and Degree

Degrees have their own subjects, students have a list of subjects they have passed, and also students should belong to a single degree plan.

From a design perspective, how should I associate a student with his/her degree?

If student has a reference to his relevant Degree object, then it suddenly could have a lot more responsibility, and I want to manage Separation of concerns properly.

Is there a better alternative?

Body:
If you want to associate a Student with a Degree, but keep them separate from each other, you can express that relationship with a data structure like a HashMap.

something like (untested, treat this as pseudo code):

HashMap<Student, Degree> enrolment = new HashMap<Student, Degree>();
Student dave = new Student();
Degree masterOfScience = new Degree();
enrolment.put(dave, masterOfScience);


问:
How do I override the Type of members in a base class from the derived class?
I have two classes that know each other in a many-to-many relationship. Now I want to have two additional classes that inherit from the existing classes. The association between the inherited classes should stay.

Example:

Say you have a Vehicle

public class Vehicle{ }

And you have Tires

public class Tire { }

Now you want the Vehicle to have many Tires

```<code>public class Vehicle
{
    public Tire[] Tires { get; set; }
}
</code>```

That's great! But a Trucks Tires are significantly different than other Vehicles.. They're larger, have spikes (big metal Ramones studs!), are made of space age polymers (plausibly from outer-space) and filled with novel gases (Isn't Neon cool?).

public class TruckTire : Tire { }

But here's the rub... my Truck now only has normal Tires if it inherits from Vehicle...

public class Truck : Vehicle { }

Crux of the problem & question:

So... How do I make it so when people access Truck.Tires they get back something that's cast as TruckTire[] instead of just regular old Tire[] when the Tires property/field is defined in the base class with a type of Tire[] not TruckTire[]? Yes the instances at runtime could be TruckTires, but that would require a cast to utilize as such...

答:
TruckTire is a Tire all right so inheritance is appropriate here. Truck however cannot use Tires, only TruckTires. This we can achieve by introducing some elementary generics. If the program would need additional types, say Tractor and TractorTire, the solution could easily be extended to this.

public class Vehicle<T extends Tire> {

    private T[] tires;

    public T[] getTires() {
        return tires;
    }

    public void setTires(T[] tires) {
        this.tires = tires;
    }

    @Override
    public String toString() {
        if (tires == null || tires.length <= 0) {
            return String.format("%s has no tires", this.getClass().getSimpleName());
        } else {
            return String.format("%s has %d tires of type %s", this.getClass().getSimpleName(),
                    tires.length, tires[0].toString());
        }
    }
}

public class Truck<T extends TruckTire> extends Vehicle<T> {
}

public class Tire {

    @Override
    public String toString() {
        return this.getClass().getSimpleName();
    }
}

public class TruckTire extends Tire {
}

public class App {

    public static void main(String[] args) {
        // vehicle
        Vehicle<Tire> vehicle = new Vehicle<>();
        System.out.println(vehicle);
        Tire[] tires = {new Tire(), new Tire(), new Tire(), new Tire()};
        vehicle.setTires(tires);
        System.out.println(vehicle);

        // truck
        Truck<TruckTire> truck = new Truck<>();
        System.out.println(truck);
        TruckTire[] truckTires = {new TruckTire(), new TruckTire(), new TruckTire(), new TruckTire()};
        truck.setTires(truckTires);
        System.out.println(truck);
    }
}
```

<p><strong>Console ouput:</strong></p>

```Vehicle has no tires
Vehicle has 4 tires of type Tire
Truck has no tires
Truck has 4 tires of type TruckTire
```

Body:
TruckTire is a Tire all right so inheritance is appropriate here. Truck however cannot use Tires, only TruckTires. This we can achieve by introducing some elementary generics. If the program would need additional types, say Tractor and TractorTire, the solution could easily be extended to this.

public class Vehicle<T extends Tire> {

    private T[] tires;

    public T[] getTires() {
        return tires;
    }

    public void setTires(T[] tires) {
        this.tires = tires;
    }

    @Override
    public String toString() {
        if (tires == null || tires.length <= 0) {
            return String.format("%s has no tires", this.getClass().getSimpleName());
        } else {
            return String.format("%s has %d tires of type %s", this.getClass().getSimpleName(),
                    tires.length, tires[0].toString());
        }
    }
}

public class Truck<T extends TruckTire> extends Vehicle<T> {
}

public class Tire {

    @Override
    public String toString() {
        return this.getClass().getSimpleName();
    }
}

public class TruckTire extends Tire {
}

public class App {

    public static void main(String[] args) {
        // vehicle
        Vehicle<Tire> vehicle = new Vehicle<>();
        System.out.println(vehicle);
        Tire[] tires = {new Tire(), new Tire(), new Tire(), new Tire()};
        vehicle.setTires(tires);
        System.out.println(vehicle);

        // truck
        Truck<TruckTire> truck = new Truck<>();
        System.out.println(truck);
        TruckTire[] truckTires = {new TruckTire(), new TruckTire(), new TruckTire(), new TruckTire()};
        truck.setTires(truckTires);
        System.out.println(truck);
    }
}

Console ouput:

Vehicle has no tires
Vehicle has 4 tires of type Tire
Truck has no tires
Truck has 4 tires of type TruckTire


问:
Are static methods of a class part of its type?
As far as I understand it, classes –as they are supported in OOP languages such as C++, Java, and Scala – define the type of each object I can instantiate with that class.

Not all features of a class are relevant to the type of its instances: Private methods, the constructor, the destructor (in C++), and the methods' implementations.

My question: Are the static methods of a class part of the instances' type?

Related: Is there a distinct type of a class (calling new to get an instance, calling its static methods) and the type of the class' instances (calling the public methods).

I'm happy for all suggestions and corrections of any invalid assumptions I have made.

答:
Any field/method that a user of the class can access is part of the type, because all code using that type has to know it exists, whether it's static, how many arguments it takes and so on in order for code using it to compile properly. For instance, you'd have no way of knowing if Foo::field was valid code unless static int field (or something similar) was part of Foo's class definition. So the short answer to your question is yes, static methods are part of the type (at least in C++).

It sounds like your confusion stems from the fact that a static field/method is not contained within or carried around by every individual instance of a class. Of course, the code implementing the class' methods is also not carried around by every individual instance of a class, so this property is not unique to statics.

In general, a class can and usually does tell you a lot more about its objects/instances than just the data each instance contains. That's a big part of what makes OOP so powerful.

I'm not sure I understand your related question, but I believe the answer is: The class is the type of the instances. The type of a class would be a type of a type, which is the sort of thing we don't normally talk about in C++ since it has no real meaning in the language (with the very debatable exception of derived/base classes).


答:
Not all features of a class are relevant to the type of its instances: Private methods, the constructor, the destructor (in C++), and the methods' implementations.

This is not usually true. In a nominative type system, nothing about the type matters but the name (and where it exists in the hierarchy if you have subtyping). As the compiler goes through your code, it matches the type name to the type name of parameters to make sure the code is well formed. The type checker does not care what functions are on the type. The type checker does not care what fields are on the type.

Earlier parts of the compiler, where it uses the symbol table to resolve identifiers does. In semantic analysis, where the compiler makes sure you're doing function invocation on a function rather than an int does. But those parts don't deal with types beyond "is A equal to, or a subtype of B?".

Structural type systems on the other hand do care about the guts of a class. Since their definition of subtyping is "is A's fields/functions compatible with the fields/functions of B?", fields and functions are part of the type definition. But here, statics don't count since they're not part of the instance type. I guess that a language could have a type for the singleton instance of the statics, but I know of none that actually do.

Title: Are static methods of a class part of its type?

Body:
As far as I understand it, classes –as they are supported in OOP languages such as C++, Java, and Scala – define the type of each object I can instantiate with that class.

Not all features of a class are relevant to the type of its instances: Private methods, the constructor, the destructor (in C++), and the methods' implementations.

My question: Are the static methods of a class part of the instances' type?

Related: Is there a distinct type of a class (calling new to get an instance, calling its static methods) and the type of the class' instances (calling the public methods).

I'm happy for all suggestions and corrections of any invalid assumptions I have made.


答:
First: What is the program supposed to do? You cannot make decision about architecture without knowing the purpose of the program. Also, ignore advice from people whom you haven't told the purpose of the program :)

Second: Unless you are writing an actual simulation of a college, you probably don't want objects like Student, Subject etc. to have behavior and responsibilities at all. In eg. an administrative program for a college, entities like students and degrees are the data that the system acts upon, not the objects that act in the system. For data entities you should not think about responsibilities, but about what data you need to keep track of in order for the system to fulfill its tasks.

Don't fall into the trap to think that the objects acting in the system should somehow represent real-world objects. This is only the case in simulation software, which is very specific niche. In most software, the objects with behavior (being subject to principles like separation of concerns and single-responsibility) will be things like 'DatabaseConnection', 'UI Control', 'Report Scheduler' etc. which have no correspondence to real-world objects but rather corresponds to the tasks the application is designed to do.


问:
"Control enters method a" What does control mean in this context?
From this page (Java Monitors Are Reentrant) there's a sentence that says:

Reentrant contains two synchronized methods: a and b. The first
  synchronized method, a, calls the other synchronized method, b.

When control enters method a, the current thread acquires the monitor
  for the Reentrant object.

What does the "control" refer to in the sentence "control enters method a"?

答:
Control is "The place where the next instruction is going to be executed."  If you are familiar with Assembly Language, you can think of it as the value contained in the Program Counter register.

The term comes from the notion "Flow of Control," the specific order in which statements are executed to produce a computing result.

So when someone says that "Control enters method A," it means that method A is about to be executed.  Or, more specifically, the instructions or statements in method A are about to be executed.


答: I'm not sure if the calibration should be the responsibility of the sensor... I would consider creating 2 new classes. Something like SensorCalibratorBase, SensorCalibratorAdavanced. Then, I would create a specific instance of the calibrator based on the app state and feed the sensor instance to it's Calibrate function. Each calibrator would get  the needed params as the constructor arguments.</p>


答: Student, Subject and Degree are not directly related. A StudentDegree would have the knowledge and reach to know about students, subjects and their degree. A subject should not track what each student scored. A StudentSubject should. A student should have one StudentDegree. A StudentDegree has a Student, and many StudentSubjects and  Degree. Now you've got the proper relationships so that behavior can be centralized for a student's degree program.</p>


问:
Why static methods can't call non-static methods directly?
I don't understand why most programming language don't allow developers/users to call non-static method from static method directly? What is the reason behind it?

p.s. I know, you can create object and call non-static method from static method.

答:
Because a static field/method--by definition--is not tied to any single object/instance of the class, while a non-static field/method always refers to an actual object/instance in some way.

Since that probably sounded too vague/abstract to answer the question, and this kind of confusion usually stems from a misunderstanding of what static actually means, let's make this concrete with some C++-like pseudocode:

```<code>class Foo {
public:
    static int a() { return 2; }
    int b()        { return d_x; }
    Foo(int x)     { d_x = x; }
private:
    int d_x;
}
</code>```

The static method a is not tied to any particular instance of Foo, meaning it can be called from anywhere, whether or not you have an actual Foo object. In C++ you'd simply write Foo::a(), and it would always return 2.

The non-static method b is tied to a single instance of Foo. Because it simply returns the int inside a given Foo object, it doesn't make any sense to try calling b() without a specific Foo object. What would you expect it to return if it didn't have a Foo? So Foo f; f.b(); makes sense but Foo::b() does not.

If I tried to make a() call b(), then whenever I called a() without an actual instance of Foo, I'd also be calling b() without an actual instance of Foo, so now a() doesn't make sense either.

Essentially, the two methods are implemented something like this:

```<code>namespace Foo {
    int a() {
        return 2;
    }
    int b(Foo* this) {
        return this->x;
    }
};
</code>```

When you look at the methods this way, it's fairly obvious why b() can call a() but not the other way around: a() simply doesn't have a Foo* lying around to give to b().

Incidentally, you can "work around" this limitation by writing a static method that takes an actual Foo object and then calls non-static methods on that Foo object. But that's usually a code smell indicating that you have static methods which shouldn't be static or non-static method that should be static, or a class that's trying to do too many things at once.

Body:
Because a static field/method--by definition--is not tied to any single object/instance of the class, while a non-static field/method always refers to an actual object/instance in some way.

Since that probably sounded too vague/abstract to answer the question, and this kind of confusion usually stems from a misunderstanding of what static actually means, let's make this concrete with some C++-like pseudocode:

class Foo {
public:
    static int a() { return 2; }
    int b()        { return d_x; }
    Foo(int x)     { d_x = x; }
private:
    int d_x;
}

The static method a is not tied to any particular instance of Foo, meaning it can be called from anywhere, whether or not you have an actual Foo object. In C++ you'd simply write Foo::a(), and it would always return 2.

The non-static method b is tied to a single instance of Foo. Because it simply returns the int inside a given Foo object, it doesn't make any sense to try calling b() without a specific Foo object. What would you expect it to return if it didn't have a Foo? So Foo f; f.b(); makes sense but Foo::b() does not.

If I tried to make a() call b(), then whenever I called a() without an actual instance of Foo, I'd also be calling b() without an actual instance of Foo, so now a() doesn't make sense either.

Essentially, the two methods are implemented something like this:

namespace Foo {
    int a() {
        return 2;
    }
    int b(Foo* this) {
        return this->x;
    }
};

When you look at the methods this way, it's fairly obvious why b() can call a() but not the other way around: a() simply doesn't have a Foo* lying around to give to b().

Incidentally, you can "work around" this limitation by writing a static method that takes an actual Foo object and then calls non-static methods on that Foo object. But that's usually a code smell indicating that you have static methods which shouldn't be static or non-static method that should be static, or a class that's trying to do too many things at once.


答:
Because all static things are not related to any object, but they are related to a class. So all objects of same class will access same static methods.

On the other hand, non static methods are attached to a particular object of a class.

You can call static methods without creating any object of a class, but that is not the case with non static methods.

Title: Why static methods can't call non-static methods directly?

Body:
I don't understand why most programming language don't allow developers/users to call non-static method from static method directly? What is the reason behind it?

p.s. I know, you can create object and call non-static method from static method.


答:
Somewhat Tongue-in-cheek... Or at least this is the functional perspective on methods...

There is no such thing called "method"

```<code>class Apple
{
 ...
public void Eat()
{
    this.weight --;
}
public static Apple ChangeColor(Apple apple)
{
    apple.color = Color.GetRandomColor();
}
}
</code>```

The example above defines a class with two methods one static and one isn't.
The second is actually a function that receives a single parameter of the Apple type and changes it's color. The first is also a function that implicitly receives a parameter called this and decreases it's weight.

That's basically the idea behind a 'member function' / 'member method'. It receives an implicit first parameter of the type of the class.

so doing this: Apple.Eat() doesn't make sense, there are too few parameters (Apple is the class name here).

while this does:

```<code>Apple x = new Apple();
x.eat()
</code>```

That 'implicit first parameter' of 'member methods' in OOP languages also has a special feature around it. If a member method is virtual (language specific) then the method will be dynamically invoked based on the type of that parameter.

Dynamic dispatch or dynamic invocation, is something similar to method overloads - that is deciding which method to call based on compile time type, except it happens at runtime.

Some programming languages allow doing this on all parameters of a function - this is called  Multiple dispatch

Though most OOP languages allow this only for the 'first implicit parameter' of 'member methods' - this is called virtual methods, Polymorphism and single dispatch.

By the way...
There is a whole design pattern called Visitor solely to allow some sort of Multiple dispatch to languages that don't have the feature

Body:
Somewhat Tongue-in-cheek... Or at least this is the functional perspective on methods...

There is no such thing called "method"

class Apple
{
 ...
public void Eat()
{
    this.weight --;
}
public static Apple ChangeColor(Apple apple)
{
    apple.color = Color.GetRandomColor();
}
}

The example above defines a class with two methods one static and one isn't.
The second is actually a function that receives a single parameter of the Apple type and changes it's color. The first is also a function that implicitly receives a parameter called this and decreases it's weight.

That's basically the idea behind a 'member function' / 'member method'. It receives an implicit first parameter of the type of the class.

so doing this: Apple.Eat() doesn't make sense, there are too few parameters (Apple is the class name here).

while this does:

Apple x = new Apple();
x.eat()

That 'implicit first parameter' of 'member methods' in OOP languages also has a special feature around it. If a member method is virtual (language specific) then the method will be dynamically invoked based on the type of that parameter.

Dynamic dispatch or dynamic invocation, is something similar to method overloads - that is deciding which method to call based on compile time type, except it happens at runtime.

Some programming languages allow doing this on all parameters of a function - this is called  Multiple dispatch

Though most OOP languages allow this only for the 'first implicit parameter' of 'member methods' - this is called virtual methods, Polymorphism and single dispatch.

By the way...
There is a whole design pattern called Visitor solely to allow some sort of Multiple dispatch to languages that don't have the feature


答:
Based on your update from 2015-05-18.

TruckTire should be a private subclass of Tire. Tire should contain the interface other client classes (Truck, Car) use, and TruckTire encapsulates the behavior. The Truck's interface to TruckTire is the same as Car's interface is to CarTire. They all know them as Tires. Use the Strategy pattern for Tire.

Title: How do I override the Type of members in a base class from the derived class?

Body:
I have two classes that know each other in a many-to-many relationship. Now I want to have two additional classes that inherit from the existing classes. The association between the inherited classes should stay.

Example:

Say you have a Vehicle

public class Vehicle{ }

And you have Tires

public class Tire { }

Now you want the Vehicle to have many Tires

```<code>public class Vehicle
{
    public Tire[] Tires { get; set; }
}
</code>```

That's great! But a Trucks Tires are significantly different than other Vehicles.. They're larger, have spikes (big metal Ramones studs!), are made of space age polymers (plausibly from outer-space) and filled with novel gases (Isn't Neon cool?).

public class TruckTire : Tire { }

But here's the rub... my Truck now only has normal Tires if it inherits from Vehicle...

public class Truck : Vehicle { }

Crux of the problem & question:

So... How do I make it so when people access Truck.Tires they get back something that's cast as TruckTire[] instead of just regular old Tire[] when the Tires property/field is defined in the base class with a type of Tire[] not TruckTire[]? Yes the instances at runtime could be TruckTires, but that would require a cast to utilize as such...


问:
What defines robust code?
My professor keeps referring to this Java example when he speaks of "robust" code:

```<code>if (var == true) {
    ...
} else if (var == false) {
    ...
} else {
    ...
}
</code>```

He claims that "robust code" means that your program takes into account all possibilities, and that there is no such thing as an error - all situations are handled by the code and result in valid state, hence the "else".

I am doubtful, however. If the variable is a boolean, what is the point of checking a third state when a third state is logically impossible?

"Having no such thing as an error" seems ridiculous as well; even Google applications show errors directly to the user instead of swallowing them up silently or somehow considering them as valid state. And it's good - I like knowing when something goes wrong. And it seems quite the claim to say an application would never have any errors.

So what is the actual definition of "robust code"?

答:
Your professor's approach is totally misguided.

A function, or just a bit of code, should have a spec that says what it does, which should cover every possible input. And the code should be written so that its behaviour is guaranteed to match the spec. In the example, I would write the spec quite simple like this:

```<code>Spec: If var is false then the function does "this", otherwise it does "that".
</code>```

Then you write the function:

```<code>if (var == false) dothis; else dothat;
</code>```

and the code meets the spec. So your professor says: What if var == 42? Look at the spec: It says the function should do "that". Look at the code: The function does "that". The function meets the spec.

Where your professor's code makes things totally unrobust is the fact that with his approach, when var is neither true nor false, it will execute code that has never been called before and that is completely untested, with utterly unpredictable results.

Title: What defines robust code?

Body:
Your professor's approach is totally misguided.

A function, or just a bit of code, should have a spec that says what it does, which should cover every possible input. And the code should be written so that its behaviour is guaranteed to match the spec. In the example, I would write the spec quite simple like this:

Spec: If var is false then the function does "this", otherwise it does "that".

Then you write the function:

if (var == false) dothis; else dothat;

and the code meets the spec. So your professor says: What if var == 42? Look at the spec: It says the function should do "that". Look at the code: The function does "that". The function meets the spec.

Where your professor's code makes things totally unrobust is the fact that with his approach, when var is neither true nor false, it will execute code that has never been called before and that is completely untested, with utterly unpredictable results.


问:
Does a Completely Full-Featured Intermediate Language Exist?
Often when translating between languages (whether with program translation or compiling) it's a one-way, destructive translation.  The functionality of the "port" isn't lost, but some of the intent and expression is.

For instance, porting a program from Java to C is possible, but you lose the notion of classes and methods.  If that program were to be ported back to Java you'd need to infer the intent of what would be considered an object to get back to the original state.  And that's something that a computer isn't good at doing.  As such you'd end up with a Java program that looked more like a C program with data structures and a big collection of static functions.

Also consider a compiler.  Once a language has been compiled down to assembler or even to say CIL or JVM, concepts such as if statements are lost as they are turned into branches.

On a higher level, source to source translators exist, but some languages have features (i.e. delegates in C#) which don't exist in other languages (like Java not having delegates).  The translation can happen, but is mildly destructive (i.e. Java would need a wrapper class to simulate delegates).

So, having said all that, is there a language who's goal is to be structurally compatible with all other languages by supporting all language features of all languages?

I'm not so concerned with being able to fully translate between languages as I am with being able to express each language's code in the common language.  So the goal would be translating to the common language and back again to the source language without losing anything.  Like: Java->Common->Java or LISP->Common->LISP

答:
Once a language has been compiled down to assembler or even to say CIL or JVM, concepts such as if statements are lost as they are turned into branches.

Not particularly in practice. If you look at a tool like Reflector, it will happily turn CIL back into pretty accurate C# code, ifs and all.

So, having said all that, is there a language who's goal is to be structurally compatible with all other languages by supporting all language features of all languages?

No, because at that point we wouldn't need compilers or source translators since we have the One True Language. Sarcasm aside, this is effectively asking why we have different languages in the first place. Language features are not things that live in isolation. Providing one often hinders (or breaks) others. If there was a language that could provide the features of others without loss, why would we be using the others?


问:
How is multi-threading different in a Java based Web Application vs Stand-alone Java Application
I am fairly new to Java and my experience is limited to Web Based Applications running on a Web Container (Jboss in my case).

Am I correct in saying that for Web Applications the web container takes care of multi-threading? If so, can I introduce new treads in a Web Based applications? Is there any advantage in doing so and in what scenario one would need to do that?

答:
Well this is a nice question and I think most of the developers who work in web application development don't use multithreading explicitly. The reason is quite obvious since you are using a application server to deploy your application, the application server internally manages a thread pool for incoming requests.

Then why use multithreading explicitly? What is need a web application developer expose himself to multithreading?

When you work on a large scale application where you have to server many request concurrently it is difficult to serve every kind of request synchronously because particular kind of request could have been doing a lot processing which could bring down the performance your application.

Lets take an example where a web application after serving particular kind of request has to notify users through email and SMS. Doing it synchronously with the request thread could bring down the performance of your web application. So here comes the role of mutlithreading. In such cases it is advisable to develop a stand alone multithreaded application over the network which is responsible for sending email and SMS only.


问:
Parent class using methods defined in child
I am working on a large program (more than 10k lines of code).

Below is a (hopefully not over-simplified) example of a problem I sometimes face:

```<code>class MyClass1(object):

    def func_1(self):
        return self.func_2() * 2

class MyClass6(MyClass1):

    def func_2(self):
        return 10

a = MyClass6().func_1()
print(a)  # Prints 20
</code>```

I need to use in MyClass1 a method that is defined later on in MyClass6.

Using this code as is, works fine. I get quite a visible warning:

and I can add a comment so that I know what is going on in the future in case I need to debug it. However, I can't use options in my IDE like Find usages, Rename etc.

Alternatively, I can use @abstractmethod to make it explicit that funct_2 is defined in a child class and my IDE options would work fine:

```<code>import abc

class MyClass1(metaclass=abc.ABCMeta):

    @abc.abstractmethod
    def func_2(self):
        return 'zzzz'

    def func_1(self):
        return self.func_2() * 2

class MyClass5(MyClass1):

    def func_2(self):
        return 10

a = MyClass5().func_1()
print(a)    # Prints 20
</code>```

... but I think this is not the way to go. For example I get weak warnings from my IDE for classes inbetween MyClass1 and MyClass5 (e.g. "MyClass4 has to implement abstract method...").

Question:

What is the right way to deal with a parent class using a method that is defined in a child class?

Edit:

Some extra details:
MyClass1 is never called on its own. Also func_2() has to be defined in MyClass6 because everything it needs is defined there as well.

答:
If func_2 in MyClass1 doesn't contain any logic and is expected to be declared by child classes (and MyClass1 is never used directly), then making the class abstract like you did is a reasonable approach and makes the code self-documenting and explicit.

If:

func_2 in MyClass1 contains logic (eventually overwritten in child classes),

Or MyClass1 may be used as-is without any inheritance,

Or a child should not be forced to implement func_2,

then declare func_2 in MyClass1, containing the default logic (this is similar to virtual methods in other languages such as C#). In your case, it will return the default value. For methods which don't return anything, you may use pass keyword:

```<code>def func_2():
    pass
</code>```

Finally, you may always rely on a dynamic nature of Python and let children deal with the declaration of func_2, expecting errors during runtime if the method is missing.

Body:
If func_2 in MyClass1 doesn't contain any logic and is expected to be declared by child classes (and MyClass1 is never used directly), then making the class abstract like you did is a reasonable approach and makes the code self-documenting and explicit.

If:

func_2 in MyClass1 contains logic (eventually overwritten in child classes),

Or MyClass1 may be used as-is without any inheritance,

Or a child should not be forced to implement func_2,

then declare func_2 in MyClass1, containing the default logic (this is similar to virtual methods in other languages such as C#). In your case, it will return the default value. For methods which don't return anything, you may use pass keyword:

def func_2():
    pass

Finally, you may always rely on a dynamic nature of Python and let children deal with the declaration of func_2, expecting errors during runtime if the method is missing.