问:
How do I learn Python from zero to web development?
I am looking into learning Python for web development.

Assuming I already have some basic web development experience with Java (JSP/Servlets), I'm already familiar with web design (HTML, CSS, JS), basic programming concepts and that I am completely new to Python, how do I go about learning Python in a structured manner that will eventually lead me to web development with Python and Django?

I'm not in a hurry to make web applications in Python so I really want to learn it thoroughly so as not to leave any gaps in my knowledge of the technologies involving web development in Python. Are there any books, resource or techniques to help me in my endeavor? In what order should I do/read them?

UPDATE:

When I say learning in a structured manner, I mean starting out from the basics then learning the advanced stuff without leaving some of the important details/features that Python has to offer. I want to know how to apply the things that I already know in programming to Python.

答:
Don't take this too seriously, but ...

create file name app.py with the following content:

```<code>from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()
</code>```

assuming you have pip (python package installer) installed do the following:

```<code>$ pip install Flask
$ python app.py
* Running on http://localhost:5000/
</code>```

Now you can visit your first web app under localhost, port 5000.

That would be your first python web application. Everything after that is "refinement" in application structure, functionality and appearance.

Body:
Don't take this too seriously, but ...

create file name app.py with the following content:

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()

assuming you have pip (python package installer) installed do the following:

$ pip install Flask
$ python app.py
* Running on http://localhost:5000/

Now you can visit your first web app under localhost, port 5000.

That would be your first python web application. Everything after that is "refinement" in application structure, functionality and appearance.


问:
Why C# doesn’t support multiple inheritance?
Even if it could be bad practices, I would say that there is time that it would fulfill its purpose.</p>

答:
https://stackoverflow.com/questions/995255/why-is-multiple-inheritance-not-allowed-in-java-or-c covers this question nicely.

My take on it is this: The designers probably wanted to make a language that promoted good design principles. Ok, so there are times that multiple inheritance is perfect. Those are the exception, rather than the rule, though, and can be abused very easily. So, the designers decided to make it impossible to do.

For those cases where it would be good, you need to use interfaces. Those work, albeit clumsily; but, you won't need them for that that much.

ContentLicense: CC BY-SA 2.5


问:
Why the name 'continue'
The 'continue' keyword in Java (and probably in many other programming languages) is used to skip further execution of the current iteration.

Why was the name 'continue' chosen? Why not something more straightforward like 'skip' ?

答:
I guess it might have to do with history of programming languages.

To ask why it is continue in Java is to ask why it is continue in C++, which is to ask why it is continue in C, Algol etc.

To my knowledge, Fortran was the first to have a CONTINUE statement, actually a no op. It was just there to make it possible to place a (numeric) label used in goto or other constructs like:

```<code>    DO 42 i=1,100
    A[i] = 0
42  CONTINUE
</code>```

The first line introduces a do loop that, when completed, continued execution at label 42.

ContentLicense: CC BY-SA 3.0

Title: Why the name 'continue'

Body:
I guess it might have to do with history of programming languages.

To ask why it is continue in Java is to ask why it is continue in C++, which is to ask why it is continue in C, Algol etc.

To my knowledge, Fortran was the first to have a CONTINUE statement, actually a no op. It was just there to make it possible to place a (numeric) label used in goto or other constructs like:

    DO 42 i=1,100
    A[i] = 0
42  CONTINUE

The first line introduces a do loop that, when completed, continued execution at label 42.


问:
Matrix Pattern Recognition Algorithm
I am designing a logic analyzer and I would like to implement some Matrix Algorithm.
I have several channels each one represented by a row in the matrix and every element in the column would be the state, for example:

```<code>Channel 1   1 0 0 1 0 1 1 0 1
Channel 2   1 1 0 1 1 0 0 1 1
Channel 3   0 1 0 1 1 0 1 0 0
</code>```

I would like to detect a pattern inside my matrix for example, detect ALL the matches of the bitmap inside the matrix:

```<code>1 0
1 1
</code>```

I think it can be accomplished testing element by element but I think there should be a better way of doing it. Is there any Java API or any way to do it ? If there is a API ARM optimized for NEON instructions would be great also but not mandatory.

They will be about 8 matrix of 3 or 2 rows by 20000 columns approximately, the matrix is not fixed, it change every time I scan it because I am constantly receiving data. I need to process them in 500mS or less. I am working on an ARM platform, dual core, 1.2GHz, 1Gb RAM, Android 4.1.2

Thank you very much in advance.

答:
EDIT: after you clarified things a bit, I see you are after some kind of different thing I was thinking of first. When your matrix changes for every search, creating some kind of lookup structure beforehand won't help you much - instead you probably may need some low-level optimized bitmap processing library (or write your own native code in C, analogous to this example). Even then, there is still the problem that you will have to convert your input data to the bitmap format used by that library, each time, for each single search. So you definitely will have to loop once over all the bits of your matrix.

For that reason, I doubt you can much improve the simple brute-force search which iterates over the whole matrix and just compares the values to the values of the given submatrix.

Title: Matrix Pattern Recognition Algorithm


问:
iOS - Unit tests for KVO/delegate codes
I am going to design a MVC pattern. It could be either designed as a delegate pattern, or a Key-Value-Observing(KVO), to notify the controller about changing models. The project requires certain quality control procedures to conform to those verification documents.

My questions:

Does delegate pattern fit better for unit testing than KVO?

If KVO fits better, would you please suggest some sample codes?

答:
I think this is the wrong question. Delegates, KVO, and notifications can all be unit-tested. That should not be the primary concern when picking how objects interact with each other.

Pick the pattern that is appropriate for the problem you are trying to solve. For example, Apple uses delegates to allow a UITableView to pull information from a controller. This feels appropriate. The table view knows what information it needs and pulls that information out of its delegates.

Apple could have chosen to have UITableView send notifications. There is no technical reason why a table view doesn't send a UITableViewCellForRowAtIndexPathNotification and expect a subscriber to set the cell at an index path included in the user info. They didn't do this because it's not appropriate.

Generally speaking, delegates are appropriate for pulling information from a source of truth. Views use this to gather details needed for display. Notification and KVO are appropriate pushing information out from a source of truth. Models use this to announce changes which the rest of the system may need to know about.

UPDATE

After reading your question again, it seems like you want to use KVO. As for code a unit test, here is some code to demonstrate how this can be done.

I assume you are looking to test a controller which is observing a change to a property of a model. When the change is observed, the controller will change the text of a view. Controller will have a properties named model and textView. Model will have a property name prop. TextView will have a property named text. The controller does KVO by calling [self addObserver:self forKeyPath:@"model.prop" options:0 context:NULL].

```<code>FakeModel *fakeModel = [[FakeModel alloc] init]; // FakeModel stubs out the needed functionality of Model.
FakeTextView *fakeTextView = [[FakeTextView alloc] init]; // FakeTextView stubs out the needed functionality of TextView.

Controller *controller = [storyboard instantiateViewControllerWithIdentifier:@"controller"]; // Or however you create your controller.
controller.textView = fakeTextView;
controller.model = fakeModel;

fakeModel.prop = @"new value"; // Change model.prop to kick off the KVO and change textview.text.

STAssertEqualObjects(fakeTextView.text, @"expected new text", @"Text should have matched");
</code>```

Of course, you can use OCMock for this, if you have it in your project.

Hope that helps.

Title: iOS - Unit tests for KVO/delegate codes

Body:
I think this is the wrong question. Delegates, KVO, and notifications can all be unit-tested. That should not be the primary concern when picking how objects interact with each other.

Pick the pattern that is appropriate for the problem you are trying to solve. For example, Apple uses delegates to allow a UITableView to pull information from a controller. This feels appropriate. The table view knows what information it needs and pulls that information out of its delegates.

Apple could have chosen to have UITableView send notifications. There is no technical reason why a table view doesn't send a UITableViewCellForRowAtIndexPathNotification and expect a subscriber to set the cell at an index path included in the user info. They didn't do this because it's not appropriate.

Generally speaking, delegates are appropriate for pulling information from a source of truth. Views use this to gather details needed for display. Notification and KVO are appropriate pushing information out from a source of truth. Models use this to announce changes which the rest of the system may need to know about.

UPDATE

After reading your question again, it seems like you want to use KVO. As for code a unit test, here is some code to demonstrate how this can be done.

I assume you are looking to test a controller which is observing a change to a property of a model. When the change is observed, the controller will change the text of a view. Controller will have a properties named model and textView. Model will have a property name prop. TextView will have a property named text. The controller does KVO by calling [self addObserver:self forKeyPath:@"model.prop" options:0 context:NULL].

FakeModel *fakeModel = [[FakeModel alloc] init]; // FakeModel stubs out the needed functionality of Model.
FakeTextView *fakeTextView = [[FakeTextView alloc] init]; // FakeTextView stubs out the needed functionality of TextView.

Controller *controller = [storyboard instantiateViewControllerWithIdentifier:@"controller"]; // Or however you create your controller.
controller.textView = fakeTextView;
controller.model = fakeModel;

fakeModel.prop = @"new value"; // Change model.prop to kick off the KVO and change textview.text.

STAssertEqualObjects(fakeTextView.text, @"expected new text", @"Text should have matched");

Of course, you can use OCMock for this, if you have it in your project.

Hope that helps.


问:
What is a *slightly* less extreme equivalent to being "fluent" in a language?
tl;dr: What is a less extreme (but still noticeable) alternative to the word "fluent", when saying e.g. "I am fluent in C++/Python/whatever?"

I think I can call myself "fluent" in C#, because I know the language and runtime very well, and I'm very familiar with the .NET framework's APIs and classes, etc.

I would like to claim the same thing for Python and C++.
But while I can program in Python (I did so for an entire summer, making a website with Django), for example, I would not call myself fluent because my code isn't always "Pythonic" (e.g. using map/filter vs. list comprehensions), and I'm not too intimate with some aspects of the language and standard library yet (e.g. the introspection API, etc.).

Is there a word or phrase I can use on e.g. a resume to describe what I know?

I can think of "very familiar with", but is there a better word/phrase I can use?

答: I'd say you are comfortable using the language. That does not imply you are an expert.


问:
Rendering design. How can I effectively deal with forward, deferred and transparent rendering?
I have many objects in my game world that all derive from one base class.

Each object will have different materials and will therefore be required to be drawn using various rendering techniques.

I currently use the following order for rendering my objects.

Deferred

Forward

Transparent (order independent)

Each object has a rendering flag that denotes which one of the above methods should be used.

The list of base objects in the scene are then iterated through and added to separate lists of deferred, forward or transparent objects based on their rendering flag value.

The individual lists are then iterated through and drawn using the order above.  Each list is cleared at the end of the frame.

This methods works fairly well but it requires different draw methods for each material type.

For example each object will require the following methods in order to be compatible with the possible flag settings.

```<code>object.DrawDeferred()
object.DrawForward()
object.DrawTransparent()
</code>```

It is also hard to see where methods outside of materials, such as rendering shadow maps, would fit using this "flag & method" design.

```<code>object.DrawShadow()
</code>```

I was hoping that someone may have some suggestions for improving this rendering process, possibly making it more generic and less verbose?

答:
I don't know what do the words "deferred" and "forward" mean in your case, but in my opinion, you should render the world in the following order:

Draw the world. If possible, draw the closest polygons first, so depth test can cull the polygons that are not going to be seen by the player. It's better to split the world into multiple segments, so you can do visibility and frustum culling to drastically reduce the amount of drawn polygons.

Draw the models. Because of depth testing, your graphics card won't render the polygons behind walls. Before rendering a model, check if it's in the view frustum, this is impotant because models usually consist of a lot of polygons.

Draw the farthest things such as sky box.

Enable blending and draw solid translucent objects.

Disable writing to Z buffer and draw sprites in far-to-near order.

Reenable writing to Z buffer and clear Z buffer to prevent close objects from going through the walls.

Draw close objects such as weapon model, legs and 3D HUD.


问:
Rails-API gem, Is there such thing as an API only application?
I've built a few API's using the complete rails stack. In each project there have been multiple uses for rails core features. Each of the API has had management screens for monitoring usage, managing authentication keys, etc. Is there such thing as an API without a management front end?</p>

答: All your data, including Users and authentication could be stored and handled in an enterprise resource planning application and you Rails App is only an interface that provides certain views on the database that can be used by mobile Apps, employees, desktop Apps or whatever.</p>


问:
is Microsoft LC random generator patented?
I need a very simple pseudo random generator (no any specific quality requirements) and I found Microsoft's variant of LCG algorithm used for rand() C runtime library function fit my needs (gcc's one seems too complex).

I found the algorithm here:

http://rosettacode.org/wiki/Linear_congruential_generator#C

However, I worry the algorithm (including its "magic numbers" i.e coefficients) may by patented or restricted for use in some another way.

Is it allowed to use this algorithm without any licence or patent restrictions or not?

I can't use library rand() because I need my results to be exactly reproducible on different platforms

答:
The code you reference is Free to use, but not necessarily free.  At the bottom of the page, you'll see:

```
    This page was last modified on 5 November 2012, at 23:58.
    Content is available under GNU Free Documentation License 1.2.
```

And it includes a link to the GNU Free Documentation License 1.2

Read the GNU documentation license to see what you need to do with attributing the code and providing any changes you may make.

In the US, design patents are only valid for 14 years after granting.  See this USPTO link.

The Wikipedia article on Linear congruential generator indicates a number of implementations and their coefficients.  It also includes a reference to Microsoft's implementation within Microsoft Visual/Quick C/C++.

Those compilers had their origins in 1983 or 1993, depending upon which you look at.  Either way, both are well past the 14 year limit for patents.

You also don't know that MS performed the research in order to discover those coefficients, nor that changing the coefficients would be sufficiently novel as to merit patent protection.  The LCG algorithm has been around for a long time.  Given that there are a number of sets of published coefficients, it's pretty safe to assume that they aren't protected through patents.

Body:
The code you reference is Free to use, but not necessarily free.  At the bottom of the page, you'll see:

    This page was last modified on 5 November 2012, at 23:58.
    Content is available under GNU Free Documentation License 1.2.

And it includes a link to the GNU Free Documentation License 1.2

Read the GNU documentation license to see what you need to do with attributing the code and providing any changes you may make.

In the US, design patents are only valid for 14 years after granting.  See this USPTO link.

The Wikipedia article on Linear congruential generator indicates a number of implementations and their coefficients.  It also includes a reference to Microsoft's implementation within Microsoft Visual/Quick C/C++.

Those compilers had their origins in 1983 or 1993, depending upon which you look at.  Either way, both are well past the 14 year limit for patents.

You also don't know that MS performed the research in order to discover those coefficients, nor that changing the coefficients would be sufficiently novel as to merit patent protection.  The LCG algorithm has been around for a long time.  Given that there are a number of sets of published coefficients, it's pretty safe to assume that they aren't protected through patents.


问:
How many types of programming languages are there?
Basically, I want to learn lots of programming languages to become a great programmer.  I know only a handful to depth and I was hoping someone could elaborate on how many classes or types of programming languages there are.  Like how you would lump them together if you had to learn them in groups.

Coming from a Java background, I'm familiar with static typing, but I know that in addition to dynamic typing there has to be such variety in available languages that I would love to see a categorical breakdown if possible.

答:
Assembly

Procedural

Basic

C

Object-Oriented

C#

Java

Declarative

Prolog

SQL

Functional

Lisp

Haskell

These are the main ones, but there's a lot of other paradigms out there, and there's plenty of overlap between them.


答:
if you are really worried you can find your own parameters for the LCG using the constrainst mentioned at http://en.wikipedia.org/wiki/Linear_congruential_generator#Period_length

or use one of the other examples given right below it (the a=1103515245 c=12345 varient is used by multiple open source projects so should (IANAL) be free to use)

Title: is Microsoft LC random generator patented?

Body:
I need a very simple pseudo random generator (no any specific quality requirements) and I found Microsoft's variant of LCG algorithm used for rand() C runtime library function fit my needs (gcc's one seems too complex).

I found the algorithm here:

http://rosettacode.org/wiki/Linear_congruential_generator#C

However, I worry the algorithm (including its "magic numbers" i.e coefficients) may by patented or restricted for use in some another way.

Is it allowed to use this algorithm without any licence or patent restrictions or not?

I can't use library rand() because I need my results to be exactly reproducible on different platforms


答:
The Mersenne twister prng is well known and implemented.

For an even simpler approach, Project Euler has used a pseudo random number generator:

S0 = seed

Sn+1 = Sn2 mod 50515093

If you want something close to 2^32, change the mod to 0xFFFFFFFB (the number 4,294,967,291 - the largest 32 bit prime)

The man page for rand has the following implementation from the POSIX.1-2001 specification:

```<code>static unsigned long next = 1;

/* RAND_MAX assumed to be 32767 */
int myrand(void) {
    next = next * 1103515245 + 12345;
    return((unsigned)(next/65536) % 32768);
}

void mysrand(unsigned seed) {
    next = seed;
}
</code>```

Look at the Art of Computer programming, volume 2 - it has a section dedicated to random number generation.

Body:
The Mersenne twister prng is well known and implemented.

For an even simpler approach, Project Euler has used a pseudo random number generator:

S0 = seed

Sn+1 = Sn2 mod 50515093

If you want something close to 2^32, change the mod to 0xFFFFFFFB (the number 4,294,967,291 - the largest 32 bit prime)

The man page for rand has the following implementation from the POSIX.1-2001 specification:

static unsigned long next = 1;

/* RAND_MAX assumed to be 32767 */
int myrand(void) {
    next = next * 1103515245 + 12345;
    return((unsigned)(next/65536) % 32768);
}

void mysrand(unsigned seed) {
    next = seed;
}

Look at the Art of Computer programming, volume 2 - it has a section dedicated to random number generation.


问:
Is asking for control totals on a file an outdated means of verifying a file?
I'm in a new position where I need to process a flat files on a regular basis.  The last time I did this was 5 or 6 years ago but as part of the file layout I received control totals.  It gave me simplistic information on the file like the total number of records as well as sums of the important fields.  This helped me during testing then also during production to verify the file arrived and has correct information.

I have asked for similar data for this new project and have hit a wall of no.

Is this no longer a standard practice?

Is there a better way?

答:
It depends on what you are trying to test.

If you are trying to verify that a file arrived intact and wasn't changed in transit, a checksum (or a digital signature) would be the gold standard.

If you are trying to verify that you have processed the file successfully, the aggregate information that you're looking for is exceptionally helpful.  Unfortunately, a large fraction of flat file based ETL processes are built with exceedingly little thought given to handling and preventing errors so lots of data sources have never been asked to provide this sort of header information, don't have the code to do so, and aren't terribly interested in writing the code on their side to generate the totals if few of their customers have any interest in using it.

What you're asking for sounds entirely reasonable.  If you are getting pushback from the data source, I would, within the realm of what is politically feasible in your environment, escalate the issue.  Presumably, if the data source is internal, you have much more leverage than if you are asking for a data feed from an external vendor.


问:
Should I use JSON just to use JSON
I'm building a blogging site for learning, with a PHP/MySQl back-end. All of the user input is handled with forms sent in POST requests.

Will using JSON somehow make it cleaner, or easier to maintain or add features? Or am I just adding an interchange format for no reason?

So essentially, what functionality would be best implemented by using JSON?

答:
JSON has a few advantages:

It's a structured format, which can be validated and parsed with existing, mature tools.

It can speak easily to JavaScript, which makes it very useful for AJAX communication.

It's extremely simple and lightweight.  Anything you'd want to use XML data interchange for, JSON is generally a better alternative.

My rule of thumb is, if you only need to return a single semantic element from a call, send it as plain text.  But if you need to return multiple pieces of information, use JSON.

Title: Should I use JSON just to use JSON


答: I don't think implementing JSON will inherently improve your site as is. JSON is JavaScript Object Notation; so unless you're starting to learn JavaScript as well, I don't see an inherent value in making sure everything is in JSON. </p>

Title: Should I use JSON just to use JSON

Body:
I'm building a blogging site for learning, with a PHP/MySQl back-end. All of the user input is handled with forms sent in POST requests.

Will using JSON somehow make it cleaner, or easier to maintain or add features? Or am I just adding an interchange format for no reason?

So essentially, what functionality would be best implemented by using JSON?


答:
Just to illustrate why not, multiple inheritance is supported by C++, but is strongly discouraged as you can accomplish most of the stuff with composition that you would with M.I., however in a much cleaner fashion. Unlike C++, C# is not a "hybrid" type OOP language, i.e. it didn't evolve from a previous language.

If you really need multiple inheritance, you can implement multiple interfaces.

Title: Why C# doesn’t support multiple inheritance?

Body: Even if it could be bad practices, I would say that there is time that it would fulfill its purpose.</p>


答:
While JSON is very extensible and well-structured, it's not the fastest one.

JSON is great for sending data from server to clients, because it resolves issues with encoding.

But on the server, you need maximum performance and minimum disc space consumption. So, for tables, you should use MySQL columns, and for non-tables a binary format is preferred.

To solve extensibility issues with binary files, you can tag your structures with a 4-character code for structure name and 1-2-byte number for version.

Title: Should I use JSON just to use JSON


问:
Why does Zend discourage "floating functions"?
Zend's Coding Standard Naming Convention says

Functions in the global scope (a.k.a "floating functions") are permitted but discouraged in most cases. Consider wrapping these functions in a static class.

The common wisdom in Python says practically the opposite:

Finally, use staticmethod sparingly! There are very few situations where static-methods are necessary in Python, and I've seen them used many times where a separate "top-level" function would have been clearer.

(Not only does the above StackOverflow answer warn against overuse of static methods, but more than one Python linter will warn the same.)

Is this something that can be generalized across programming languages, and if so, why does Python differ so from PHP? If it's not something that can be generalized, what is the basis for one approach or the other, and is there a way to immediately recognize in a language whether you should prefer bare functions or static methods?

答:
In general, it's a preference thing.  "Static" in this context is just another word for "global", so although either way will get you some evil looks (particularly if you're only using classes as namespaces), it works.

But:

PHP can very easily be set up to autoload classes, making it so that static functions aren't loaded in til you have need of them (or others in the same class).  It can't do the same for individual functions (yet), though.  I'm not sure whether Python has an equivalent for either one, but i haven't seen it yet.

Unlike global functions, static member functions can generally be made private, so it's easier to expose only the bits you intend for outsiders to use.  Well, except in Python, where you have to jump through some hoops to get private members.

PHP didn't have namespace support til recently, meaning every top-level function was crammed into the same namespace.  That's changed, but PHP namespaces are still rather hideous.  :P

It seems Python doesn't like making member functions static.  Other languages have a keyword for that purpose; in Python, apparently you need an annotation (excuse me, "decorator").


答:
the basic difference between php global functions and their python counterpart is in their scope:

python top-level functions are part of the module where they are defined.
when they are imported, they are called with defining_module.function_name()
therefore there is less risk of conflicting names.

php 'global' functions are really global, iirc, no matter from where they are called. thus they are much more likely to create naming problems, e.g. be overwritten by some third-party library, etc.

Title: Why does Zend discourage "floating functions"?

Body:
Zend's Coding Standard Naming Convention says

Functions in the global scope (a.k.a "floating functions") are permitted but discouraged in most cases. Consider wrapping these functions in a static class.

The common wisdom in Python says practically the opposite:

Finally, use staticmethod sparingly! There are very few situations where static-methods are necessary in Python, and I've seen them used many times where a separate "top-level" function would have been clearer.

(Not only does the above StackOverflow answer warn against overuse of static methods, but more than one Python linter will warn the same.)

Is this something that can be generalized across programming languages, and if so, why does Python differ so from PHP? If it's not something that can be generalized, what is the basis for one approach or the other, and is there a way to immediately recognize in a language whether you should prefer bare functions or static methods?


答: JSON is only useful if you intend to make a JavaScript heavy site that uses Ajax requests to pass data to the server/get data to display without doing a full post-back. If you have no intention of making use of that functionality using JSON is just wrapping your code in another layer that has to be serialized/deserialized to do anything useful.</p>

Title: Should I use JSON just to use JSON


答:
Python namespaces everything: Everything is in a module, and everything defined in a module has module scope rather than global scope (you have to go out of your way and do evil things to add something to "all" scopes). So name collisions aren't an issue. In PHP, on the other hand, if you just go ahead and define a function, you put it in the same scope everyone is using for global names. You either explicitly use a namespace to prevent that, or you use a class as "namespace" (though the class should probably be in a namespace itself). The added bonus is that classes benefit from autoloaders, whereas functions do not IIRC.

There are philosophical differences too. The Python community is (and long has been) very open to utilizing multiple paradigms. Classes, higher-order functions and simple procedural programming are all equally accepted ways of doing stuff, as long as they fit the problem. And module-level data + functions does just what, so unless you need polymorphism or want a strong association with a particular class, there's little benefit of attaching a non-method to a class.
In contrast, the PHP community (at least since the majority stopped screwing around and giving PHP the bad reputation it built up over the years) seems to be focused heavily on object-oriented programming. Free functions simply don't fit into this paradigm, whereas static is widely accepted. I don't quite get the logic behind that, but such is the convention.

Finally, note that staticmethod is not only eschewed because we don't like the concept of static methods. Sometimes we do want static methods, but then we usually prefer classmethod, which does basically the same thing but gives more power to the method (it receives the class object, and can thus there can be polymorphism among classmethods). staticmethod is sometimes considered to be entirely redundant.


答:
For what you describe - it sounds like a blogging platform where everything is submitted via forms - no, you dont need to convert it all to JSON.  PHP handles forms seamlessly for you.  There's no reason to introduce a new piece of complication in that situation.

Again, in your specific circumstance, JSON might be something you'd use if you needed to send semi-structured data back to the web brower.  On the browser side, the JSON would be very easy to parse out in javascript.

Title: Should I use JSON just to use JSON


问:
Is Software Testing Really Needed?
I'm a student working on my B.E(CS) and my question is the following:

Is testing in the software field needed?

If we create a software with great care, then why should we test?

After testing can we be sure that we have achieved this goal (the product/software works as intended) because we have done the testing for it? Is it possible?

My question: Is testing of software needed?

答:
To answer #3 of your question:

Having been a programmer and a software tester, yes, you can be sure you're meeting the requirements of the software during testing.

{putting QA hat on}

How? You can do this by tracing your tests from test code to acceptance criteria, acceptance criteria to features, and features to requirements. If you trace every single test up the design chain and they map to one or more requirements, you can be sure that your tests are being used to ensure code meets its requirements (although this brings up the notion of adequate test coverage, which is a another topic). If you can't trace a test up the design chain, then you're likely testing for things that aren't required, and this is a waste of time. Acceptance criteria can also include checking for undesired behaviors - you can test for those too, which gets you one step closer to a quality release.

{QA hat off}

No code is ever bug-free, just less costly over time when more effort is spent assessing its quality during development.

Title: Is Software Testing Really Needed?


问:
How can I avoid the engineering mistakes of PDT?
As a developer with enough experience to evaluate a tool, I may say that PDT is very huge in size and slow in performance for a PHP IDE.

It gets bigger by release and exponentially slower by the size of the projects. Add some extra syntax coloring rules and it literally crawls, code completion works randomly and building workspace takes like forever. Java black magic (-Xmx etc) eases the pain a little but that's it.

So my questions are:

Why is PDT like this? What design or engineering factors led to its poor performance?

How can I avoid making these same mistakes in my own products?

答:
There is actually no problem with Eclipse PDT. The reason some users have it very slow is that these users haven't done the important project configuration.

Every project has validators. Many of them can be safely disabled, other are relevant only for a small fraction of the project and irrelevant for the rest. For example, application framework shouldn't be scanned for TODO's, HTML syntax validity, XML syntax validity, PHP errors, and similar. Only the actual project should be scanned.

This needs to be configured per project. Rebuilding workspace then takes up to 5 seconds (if it's a large project).

Here is the suggested performance optimization:

Right click project

Select properties

Select validation

Check Enable Project specific settings

On any Validator row, click the '...' button

Select Exclude Group

Click Add rule

Select 'Folder or file name'

Click Next

Select files or folder which don't need any validation (i.e. 3rd-party files in your project).

Click Finish

Click OK

Click OK

Repeat the above for all current validators, or simply disable unwanted validators completely.

In addition, follow the Zend Studio performance optimization. It applies to PDT just as well:
http://kb.zend.com/index.php?View=entry&EntryID=480

Portions borrowed from https://stackoverflow.com/questions/783902/excluding-disabling-validation-in-eclipse

Since I believe there is no mistake in eclipse (and PDT), the question no. 2 is not applicable here. Note that PDT is not a PHP IDE. It is a plugin for Eclipse which adds PHP support. Eclipse is a development platform. It's robust, configurable, scalable.

Bottom end: users should be able to configure their projects to use only what they need.


问:
Does low latency code sometimes have to be "ugly"?
(This is mainly aimed at those who have specific knowledge of low latency systems, to avoid people just answering with unsubstantiated opinions).

Do you feel there is a trade-off between writing "nice" object orientated code and writing very fast low latency code? For instance, avoiding virtual functions in C++/the overhead of polymorphism etc- re-writing code which looks nasty, but is very fast etc?

It stands to reason- who cares if it looks ugly (so long as its maintainable)- if you need speed, you need speed?

I would be interested to hear from people who have worked in such areas.

答:
Do you feel there is a trade-off between writing "nice" object
  orientated code and writing very [sic] low latency code?

Yes.

That's why the phrase "premature optimization" exists.  It exists to force developers to measure their performance, and only optimize that code that will make a difference in performance, while sensibly designing their application architecture from the start so that it doesn't fall down under heavy load.

That way, to the maximum extent possible, you get to keep your pretty, well-architected,  object-oriented code, and only optimize with ugly code those small portions that matter.


答:
Yes sometimes code has to be "ugly" to make it work in the required time, all the code doesn't have to be ugly though. Performance should be tested and profiled before to find the bits of code that need to be "ugly" and those sections should be noted with a comment so future devs know what is purposefully ugly and what is just laziness. If someone is writing lots of poorly designed code claiming performance reasons, make them prove it.

Speed is just as important as any other requirement of a program, giving wrong corrections to a guided missile is equivalent to providing the right corrections after impact. Maintainability is always a secondary concern to working code.

Title: Does low latency code sometimes have to be "ugly"?

Body:
(This is mainly aimed at those who have specific knowledge of low latency systems, to avoid people just answering with unsubstantiated opinions).

Do you feel there is a trade-off between writing "nice" object orientated code and writing very fast low latency code? For instance, avoiding virtual functions in C++/the overhead of polymorphism etc- re-writing code which looks nasty, but is very fast etc?

It stands to reason- who cares if it looks ugly (so long as its maintainable)- if you need speed, you need speed?

I would be interested to hear from people who have worked in such areas.


答:
It depends on how you want to classify languages. Fundamentally, languages can be broken down into two types: imperative languages in which you instruct the computer how to do a task, and declarative languages in which you tell the computer what to do. Declarative languages can further be broken down into functional languages, in which a program is constructed by composing functions, and logic programming languages, in which a program is constructed through a set of logical connections. Imperative languages read more like a list of steps for solving a problem, kind of like a recipe. Imperative languages include C, C++, and Java; functional languages include Haskell; logic programming languages include Prolog.

Imperative languages are sometimes broken into two subgroups: procedural languages like C, and object-oriented languages. Object-oriented languages are a bit orthogonal to the groupings, though, as there are object-oriented functional languages (OCaml and Scala being examples).

You can also group languages by typing: static and dynamic. Statically-typed languages are ones in which typing is checked (and usually enforced) prior to running the program (typically during a compile phase); dynamically-typed languages defer type checking to runtime. C, C++, and Java are statically-typed languages; Python, Ruby, JavaScript, and Objective-C are dynamically-typed languages. There are also untyped languages, which include the Forth programming language.

You can also group languages by their typing discipline: weak typing, which supports implicit type conversions, and strong typing, which prohibits implicit type conversions. The lines between the two are a bit blurry: according to some definitions, C is a weakly-typed languages, while others consider it to be strongly-typed. Typing discipline isn't really a useful way to group languages, anyway.

Title: How many types of programming languages are there?

Body:
Basically, I want to learn lots of programming languages to become a great programmer.  I know only a handful to depth and I was hoping someone could elaborate on how many classes or types of programming languages there are.  Like how you would lump them together if you had to learn them in groups.

Coming from a Java background, I'm familiar with static typing, but I know that in addition to dynamic typing there has to be such variety in available languages that I would love to see a categorical breakdown if possible.


问:
How to add a new developer to the team
I run a small company composed of only 2 developers. We are building a very big application for one of our clients. Development on this project has gone on for 1.5 years.

Now this client has secured an important sponsorship, and they are organizing events related to this project. So now we have a deadline in 2 months and we can't miss it.

We are thinking of adding a new developer to the team, and I am wondering what we can do to help his integration.

This is the situation:

We are approaching the threshold of Brooks's law -- the point when adding new developers will be counter-productive.

The application is relatively well-designed, but the implementation is chaotic in some points (especially older code).

There are unit tests only for more recent code. When this project started, we didn't regularly conduct tests.

Documentation and comments are incomplete.

The application is both large and complex.

The client has written down almost every detail about his project, in a very clear and "programmer-friendly" way.

Is it a good idea to add a person now? If so, what can we do in order to help the new developer integrate into the team?

EDIT:

The sponsor is organizing an internet-based sport event for next spring. It must start on a specific day of the year. We can't change it.

What we developers (I am one of the two) need to do is:

Completing the existing application (about 25% of the work to do).

Creating a new module, essential for the organization of this event (about 75% of the work to do). This new module can't be developed without understanding the main program's API.

I can't do an exact time estimation, but we are in a risky situation.

答:
The date has already gone by, but for anyone reading this later.

The key thing to consider is that the client in this situation has much more to lose than you do.  They have already spent a lot of money, and they have a key event coming up that might make or break their business.  You already have their money, and losing a single client should not break your business.  If it does, then you have other serious business issues beyond terrible project management.

Your best bet is to negotiate an essential subset of functionality and then work overtime to get it done.  If you can't make a smaller subset happen or aren't willing to work overtime in that situation, you probably shouldn't be in business.  This may mean putting other clients on hold, however I'm guessing your other clients haven't paid for 3 man years worth of time, so put your resources where the money is.

If they aren't willing to negotiate scope down, then you are set to fail.

There is no chance of delivering this project completely in the timeframe.  If you think you have 25% left on a project that has taken 18 months to deliver so far, then you have at least 6 months left (of ~2 developers).  Adding another person will not change this significantly.

As has been pointed out, recruiting takes time.  My experience is that is takes a month at the bare minimum.  Then add training and your time has run out.

I hope this worked out for you.

Title: How to add a new developer to the team


问:
Multiple database accesses or one massive access?
What is a better approach when it comes to performance and optimal resource utilization: accessing a database multiple times through AJAX to only get the exact information needed when it is needed, or performing one access to retrieve an object that holds all information that might be needed, with a high probability that not all is actually needed?

I know how to benchmark the actual queries, but I don't know how to test what is best when it comes to database performance when thousands of users are accessing the database simultaneously and how connection pooling comes into play.

答:
Remember the first rule of optimization: measure, don't guess.  Try both, instrument them with some sort of stopwatch code, and see what takes longer.

And also bear in mind the old joke that "there are only two difficult problems in computer science: cache invalidation and naming things well."  If you pull everything from the DB at once and hold it in memory, you have a cache.  And now you have a new problem: anytime anything changes anywhere in the system, it has to make the same change in two places: the database, and the cache.  If you have more than one server talking to the DB, or multiple APIs to make the server modify data, this can become very tricky very quickly.


答: Getting everything at once will give you better performance, unless "everything" includes things like BLOBs or similarly large data objects.  The performance overhead to serialize everything, move it over the wire, then deserialize it on the other end is pretty significant, with network latency being a big chunk of it.  Memory is cheaper than network bandwidth, and will probably remain so for awhile yet.  Your only real answer will come from a benchmark, but if you're just trying to gauge one over the other, that's the way I'd lean.</p>

Title: Multiple database accesses or one massive access?

Body:
What is a better approach when it comes to performance and optimal resource utilization: accessing a database multiple times through AJAX to only get the exact information needed when it is needed, or performing one access to retrieve an object that holds all information that might be needed, with a high probability that not all is actually needed?

I know how to benchmark the actual queries, but I don't know how to test what is best when it comes to database performance when thousands of users are accessing the database simultaneously and how connection pooling comes into play.


答:
There is no one correct answer to this; like any optimization it depends heavily on context / usage.

However, consider the following as a rule of thumb:

```<code>x
+: Data is stable / static
-: Data is dynamic / volatile

y
+: Data is frequently used
-: Data is infrequently used

++: fetch large chunks in the fewest number of fetches
    and persist the data as long as possible within tolerances for staleness.

+-: do what is expedient to the logic & usage; if it is convenient to
    fetch / calc as needed do so, if it is convenient to pre-fetch and
    persist then do so. Seek to optimize only if absolutely necessary.

-+: fetch / calc as needed; but if optimization is required consider
    pre-fetching or pre-calculating if possible, or negotiate a tolerance
    for less than real time accuracy to reduce volatility.

--: fetch / calc as needed and don't worry about it further unless a
    specific case is unacceptably expensive; if so see -+.
</code>```

Body:
There is no one correct answer to this; like any optimization it depends heavily on context / usage.

However, consider the following as a rule of thumb:

x
+: Data is stable / static
-: Data is dynamic / volatile

y
+: Data is frequently used
-: Data is infrequently used

++: fetch large chunks in the fewest number of fetches
    and persist the data as long as possible within tolerances for staleness.

+-: do what is expedient to the logic & usage; if it is convenient to
    fetch / calc as needed do so, if it is convenient to pre-fetch and
    persist then do so. Seek to optimize only if absolutely necessary.

-+: fetch / calc as needed; but if optimization is required consider
    pre-fetching or pre-calculating if possible, or negotiate a tolerance
    for less than real time accuracy to reduce volatility.

--: fetch / calc as needed and don't worry about it further unless a
    specific case is unacceptably expensive; if so see -+.


问:
Should developers be responsible for tests other than unit tests, if so which ones are the most common?
I am currently working on a rather large project, and I have used JUnit and EasyMock to fairly extensively unit test functionality. I am now interested in what other types of testing I should worry about. As a developer is it my responsibility to worry about things like functional, or regression testing? Is there a good way to integrate these in a useable way in tools such as Maven/Ant/Gradle?  Are these better suited for a Tester or BA? Are there other useful types of testing that I am missing?</p>

答:
Functional test can be automated just like unit tests, and are very useful for testing how the different components of your project work together, and how well your system reflects the business rules.

Also, this automated test, serves as regression and acceptance test suite for any major (or minor) changes you have to do to the software (bug fix, refactor, business change, new functionality, etc). This gives the developers a lot more confidence to do so.

There are several frameworks for this kind of testing, we are using fitnesse with very good results. Has a very good library for testing web pages (we use it for testing our web app and our web services) and it integrates very well with Maven and Jenkins.

We also used to do "cross functional testing", between developers, but this kind of testing is not "repeatable", so its usefulness is limited...


问:
Why was Tanenbaum wrong in the Tanenbaum-Torvalds debates?
I was recently assigned reading from the Tanenbaum-Torvalds debates in my OS class. In the debates, Tanenbaum makes some predictions:

Microkernels are the future

x86 will die out and RISC architectures will dominate the market

(5 years from then) everyone will be running a free GNU OS

I was a one year old when the debates happened, so I lack historical intuition. Why have these predictions not panned out? It seems to me, that from Tanenbaum's perspective, they're pretty reasonable predictions of the future. What happened so that they didn't come to pass?

答:
I remember the time -- and the time that preceded it. Dunno about microkernals, but

2) The idea of RISC had two legs: that software optimizations could be done in software better than in the hardware, and that RISC chips could economically be made that were faster than CISC chips.

Both ideas turned out to be false in the short term. Intel could, and did, make CISC chips that clocked instructions faster than the competing RISC chips, at a competitive price. Intel could, and did, make CISC chips that did program optimization better in hardware than could be done in the compiler, or in the software runtime supervisor --and any software optimization could be added on top of that, just as it would with a RISC chip.

3) Computer Science, Programming, and Operations, have been completely re-invented 4 times in my career. From main frame to PC. From command line to GUI. From GUI to internet. From Internet to iPad. Revolution seems normal now, but WE DID NOT PREDICT THAT. Like all older programmers at the time, he was predicting the 'end of history'.

Very few people were running a GNU OS in five years, because the count restarted.

Perhaps it is still happening. 5 years ago you would have predicted that our Windows Server would be replaced by *nix servers (As I write, SAMBA has released an AD Domain Server, which was the missing piece of the puzzle). It's not going to happen where I work: we won't have any local servers.


答:
There is NO silver bullet solution to this question. I guess you need to  TRY the possible trade-offs and tune-up your server(s) to achieve the best out of it.

First point: before starting to do any improvements you need to SET your current performance benchmark, measuring it, and take it a baseline in comparison possible solutions to improve it.

The Second thing is, application usage needs to be tracked. The way how the application is utilized by end users. Cutting down on returned data raw numbers that is not needed to the end user(s) may save you a lot precious server resources. For example: there is no point in returning 5000 records while users are interested in first 50.

Third point: You have to understand the frequency of calls and possible implications. For example: if most calls are look-up value table queries, then you might probably would create an infrastructure to cache these calls. In another words, if your data is not changing frequently, consider the caching option. And of course, minimizing the number of calls always should help to boost performance.


问:
Should I implement an interface directly or have the superclass do it?
Is there a difference between

```<code>public class A extends AbstractB implements C
{...}
</code>```

versus...

```<code>public class A extends AbstractB
{...}
abstract class AbstractB implements C
{...}
</code>```

I understand that in both cases, class A will end up conforming to the interface. In the second case, AbstractB can provide implementation for interface methods in C. Is that the only difference?

If I do NOT want to provide an implementation for any of the interface methods in AbstractB, which style should I be using? Does using one or the other have some hidden 'documentation' purpose?

答:
It all depends on if AbstractB implements C semantically. I.e if it makes sense semantically for AbstractB to implement C, then go for it.

If we take concrete examples the semantic difference becomes clear.

If A = Dog , AbstractB = Animal, C = IBark

Only choice that makes sense is

```<code>class Dog extends Animal implements IBark{
</code>```

This makes no sense, since this would imply that all animals bark.

```<code>class Animal implements IBark{
</code>```

The other differences come into play if you have more than just class A inheriting from AbstractB. In #1 they need not implement C, in #2 they are all forced to implement C.

Body:
It all depends on if AbstractB implements C semantically. I.e if it makes sense semantically for AbstractB to implement C, then go for it.

If we take concrete examples the semantic difference becomes clear.

If A = Dog , AbstractB = Animal, C = IBark

Only choice that makes sense is

class Dog extends Animal implements IBark{

This makes no sense, since this would imply that all animals bark.

class Animal implements IBark{

The other differences come into play if you have more than just class A inheriting from AbstractB. In #1 they need not implement C, in #2 they are all forced to implement C.


答:
It's not a "hidden" documentation purpose.  It allows you to cast AbstractB and all of it's subclasses to C.  There are actually three styles.

```<code>public class A extends AbstractB implements C
public class AbstractB
</code>```

I'd use this one if AbstractB didn't logically implement C.  Even if it doesn't provide the methods, it could have meaning.  Such as Dog extends Animal implements Wag.  It doesn't make sense for all animals to Wag.  Note that this approach doesn't actually preclude AbstractB from providing the implementation.

```<code>public class A extends AbstractB
public AbstractB implements C
</code>```

I'd use this one if I wanted all subclasses to implement the interface AND it makes sense for all of them to do so.  Such as Beagle extends AbstractDog implements Wag.

```<code>public class A extends AbstractB implements C
public class AbstractB implements C
</code>```

This one is redundant but might add clarity.

Title: Should I implement an interface directly or have the superclass do it?

Body:
Is there a difference between

```<code>public class A extends AbstractB implements C
{...}
</code>```

versus...

```<code>public class A extends AbstractB
{...}
abstract class AbstractB implements C
{...}
</code>```

I understand that in both cases, class A will end up conforming to the interface. In the second case, AbstractB can provide implementation for interface methods in C. Is that the only difference?

If I do NOT want to provide an implementation for any of the interface methods in AbstractB, which style should I be using? Does using one or the other have some hidden 'documentation' purpose?

Body:
It's not a "hidden" documentation purpose.  It allows you to cast AbstractB and all of it's subclasses to C.  There are actually three styles.

public class A extends AbstractB implements C
public class AbstractB

I'd use this one if AbstractB didn't logically implement C.  Even if it doesn't provide the methods, it could have meaning.  Such as Dog extends Animal implements Wag.  It doesn't make sense for all animals to Wag.  Note that this approach doesn't actually preclude AbstractB from providing the implementation.

public class A extends AbstractB
public AbstractB implements C

I'd use this one if I wanted all subclasses to implement the interface AND it makes sense for all of them to do so.  Such as Beagle extends AbstractDog implements Wag.

public class A extends AbstractB implements C
public class AbstractB implements C

This one is redundant but might add clarity.


答:
Yes, the example I give is not C++ vs. Java but is Assembly vs. COBOL as it is what I know.

Both languages are very fast, but, even COBOL when compiled has many more instructions that are placed into the instruction set that do not necessarily need to be there vs writing those instructions yourself in Assembly.

The same idea can be applied directly to your question of writing "ugly looking code" vs. using inheritance/polymorphism in C++. I believe it is necessary to write ugly looking code, if the end-user needs sub-second transaction timeframes then it's our job as programmers to give them that no matter how it happens.

That being said, liberal use of comments increases programmer functionality & maintainability greatly, no matter how ugly the code is.


问:
What can I do with urllib?
I grasp that it can fetch internet resources, but I'm not really fully appreciating what that means. I was doing the challenges at pythonchallenge.com, and I got past the one that requires urllib to fetch the page and read the source, but I don't see how this is useful quite yet. And examples are kind of lacking in diversity.

What else can it do, or how can I use this to my advantage?

(Besides building a web browser...)

答:
Screen Scraping is one possible application

It is a technique that is commonly used to automate tasks that would normally involve a person opening a browser, browsing to a page and manually analysing a page.

Other more common uses might be to access and use web services, or any sort of communication where the server is accessible via a URL

Title: What can I do with urllib?


答:
Yes, a trade-off exist. By this, I mean that code that is faster and
uglier is not necessary better - the quantitative benefits from "fast
code" needs to be weighted against the maintenance complexity of the
code changes needed to achieve that speed.

The trade-off comes from business cost. Code that is more complex
requires more skilled programmers (and programmers with a more focused
skill set, such as ones with CPU architecture and design knowledge),
takes more time to read and understand the code and to fix bugs.
The business cost of developing and maintaining such code could be
in the range of 10x - 100x over normally-written code.

This maintenance cost is justifiable in some industries, in which
customers are willing to pay a very high premium for very fast software.

Some speed optimizations make better return-on-investment (ROI) than
others. Namely, some optimizations techniques can be applied with
lesser impact on code maintainability (preserving higher-level structure
and lower-level readability) compared to normally-written code.

Thus, a business owner should:

Look at the costs and benefits,

Make measurements and calculations

Have the programmer measure the program speed

Have the programmer estimate the development time needed for optimization

Make own estimate about the increased revenue from faster software

Have software architects or QA managers gauge qualitatively the drawbacks from reduced intuitiveness and readability of source code

And prioritize the low-hanging fruits of software optimization.

These trade-offs are highly specific to circumstances.

These cannot be optimally decided without the participation of managers and
product owners.

These are highly specific to platforms. For example, desktop and mobile
CPUs have different considerations. Server and client applications
also have different considerations.

Yes, it is generally true that faster code looks different from
normally-written code. Any code that is different will take more time
to read. Whether that implies ugliness is in the eyes of the beholder.

The techniques that I have some exposure with are: (without trying to
claim any level of expertise) short-vector optimization (SIMD),
fine-grained task parallelism, memory pre-allocation and object reuse.

SIMD typically has severe impacts on low-level readability, even though
it typically doesn't require higher-level structural changes (provided
that the API is designed with bottleneck-prevention in mind).

Some algorithms can be transformed into SIMD easily (the embarassingly-
vectorizable). Some algorithms require more computation rearrangements
in order to use SIMD. In extreme cases such as wavefront SIMD parallelism,
entirely new algorithms (and patentable implementations) have to be
written to to take advantage.

Fine-grained task parallelization requires rearranging algorithms into
data flow graphs, and repeatedly apply functional (computational)
decomposition to the algorithm until no further margin benefit can be
gained. Decomposed stages are typically chained with continuation-style,
a concept borrowed from functional programming.

By functional (computational) decomposition, algorithms which could
have been normally-written in a linear and conceptually clear sequence
(lines of code that are executable in the same order they are written)
have to be broken down into fragments, and distributed into multiple
functions or classes. (See algorithm objectification, below.) This
change will greatly impede fellow programmers who are not familiar
with the decomposition design process which gave rise to such code.

To make such code maintainable, the authors of such code must write
elaborate documentations of the algorithm - far beyond the kind of
code commenting or UML diagrams done for normally-written code.
This is similar to the way researchers write their academic papers.

No, fast code need not be in contradiction with object-orientedness.

Put in another way, it is possible to implement very fast software that
is still object-oriented. However, toward the lower-end of that
implementation (at the nuts-and-bolts level where the majority of
computation occurs), the object design may deviate significantly from
designs obtained from object-oriented design (OOD). The lower-level design
is geared toward algorithm-objectification.

A few benefits of object-oriented programming (OOP), such as
encapsulation, polymorphism, and composition, can still be reaped from
low-level algorithm-objectification. This is the main justification for
using OOP at this level.

Most benefits of object-oriented design (OOD) are lost. Most
importantly, there is no intuitiveness in the low-level design.
A fellow programmer cannot learn how to work with the lower-level
code without first fully understanding how the algorithm had been
transformed and decomposed in the first place, and this understanding
is not obtainable from the resulting code.


问:
Advantages and disadvantages of structuring all code via classes and compiling to classes (like Java)
Edit: my language allows for multiple inheritance, unlike Java.

I've started designing and developing my own programming language for educational, recreational, and potentially useful purposes.

At first, I've decided to base it off Java.

This implied that all the code would be written in form of classes, and that code compiles into classes, which are loaded by the VM.

However, I've excluded features such as interfaces and abstract classes, because I found no need for them. They seemed to be enforcing a paradigm, and I'd like my language not to do that. I wanted to keep the classes as the compilation unit though, because it seemed convenient to implement, familiar, and I just liked the idea.

Then I noticed that I'm basically left with a module system, where classes could be used either as "namespaces", providing constants and functions using the static directive, or as templates for objects that need to be instantiated ("actual" purpose of classes in other languages).

Now I'm left wondering: what are the upsides and the downsides of having classes as compilation units?

Also, any general commentary on my design would be much appreciated. An informative post on my language can be found here: http://www.yannbane.com/2012/12/kava.html.

答:
what are the benefits of having classes as compilation units?

It can reduce the complexity of the language. No need for different constructs, everything is treated the same. In certain designs (though not yours it seems), you benefit from not having statics and the design issues they tend to run into (initialization order issues, concurrency limitations, awkwardness with generics/type classes). It also allows some benefits of the module concept like isolated module instances for sandboxing or parallelization; and module typing where dependencies fit some interface and the entire module worth of implementation can be instantiated and dropped in.

That said, the concept tends to have more issues than not. Realistically, you can't treat everything the same, since 'top level' classes need special rules like having a default constructor (or else you run into odd issues spinning them up). Modularity of compilation units tends to get really awkward too. How does a class even reference others when they're just classes? How are those dependencies dealt with, and how do you determine the correct order for spinning up the classes? How do you make sure that duplicate class references are reused by different parts of the app (or how do you deal with duplicate instances if that's the semantics you want)?

Having looked into it, I ran into a lot of issues with dependencies, scoping things properly, and initialization concerns. You end up running into issues that make 'top level classes' special, and many limitations to make them work that ends up shaping them into simple namespaces.


答:
The easy way to determine the proper inheritance relationship is not to look at the classes themselves, but at the code that calls methods on those classes.  Somewhere in your code you have something like AbstractB b = new A(); or otherObject.addAbstractB(this);.  Either way, you later use that AbstractB reference to make various method calls.

In that situation, are you going to want to call methods of C?  If so, then AbstractB should implement C.  If not, it shouldn't.  If you don't have any situations like that, then you don't need inheritance, and should refactor to use composition instead because it is much looser coupled.


答:
I don't think this has already been covered - sorry if I missed it.

One issue is the efficient use of a developers time.

Developers often lack the skills to be good at certain types of testing. Partly, this is just natural. It's the same reason why authors have editors. It's very difficult to see the deficiencies in something if you're too close to it. But it's also about different skill-sets and different specialties.

That being the case, a developer spending time testing is poor in cost:benefit terms. That developer would be more productive doing other things, and a specialist tester would be more productive doing the testing.

Of course that's making various assumptions that aren't necessarily valid. In a small company, for example, it may not make sense to employ people who specialise in testing. Though it may make more sense to employ extra support staff and have them do some testing, or at least to get people testing code that they didn't write themselves.

Title: Should developers be responsible for tests other than unit tests, if so which ones are the most common?

Body: I am currently working on a rather large project, and I have used JUnit and EasyMock to fairly extensively unit test functionality. I am now interested in what other types of testing I should worry about. As a developer is it my responsibility to worry about things like functional, or regression testing? Is there a good way to integrate these in a useable way in tools such as Maven/Ant/Gradle?  Are these better suited for a Tester or BA? Are there other useful types of testing that I am missing?</p>


答:
If you're making architectural decision, then REST is one option. With REST, you always request for a resource multiple times, i.e. you don't send a request to get 2 objects because each object has its own url.
The performance concern with doing it this style will probably be solved when HTTP/2.0 come out. Otherwise, you just optimise to make it as fast as possible. A lot of companies are doing it this way.</p>


问:
What are the advantages of obfuscating release code?
The specific example I have in mind involves the currently-alpha game Minecraft, but this is a general question that I think warrants some conversation.

Minecraft is written in Java, and stack traces usually look like this (real example):

```<code>java.lang.NullPointerException
    at d.a(SourceFile:247)
    at gi.b(SourceFile:92)
    at bd.a(SourceFile:33)
    at bn.a(SourceFile:69)
    at bn.e(SourceFile:115)
    at bn.d(SourceFile:103)
    at net.minecraft.client.Minecraft.i(SourceFile:1007)
    at net.minecraft.client.Minecraft.run(SourceFile:596)
    at java.lang.Thread.run(Unknown Source)
</code>```

Obviously these are not the real package and method names that the developer uses when he writes.  Since he is in an alpha stage, it seems that the developer should like to be able to make sense of his stack traces, especially if someone is able to provide one for a bug report.  As this stands, it's mostly meaningless.

What advantage could one possibly hope to gain by obfuscating his code like this that overcomes the drawbacks of more difficult bug identification?

答:
We obfuscate our Java code too....

The advantage is that it makes it harder to reverse-engineer (if you are worried about someone stealing your code base and using it as a base to create a similar competing product, for example, etc).

You can get the original stack trace back: there are obfuscation tools out there which create special reference files which you can use to run the obfuscated stack traces through, and it comes out with the original source stack trace. These are generated by the obfuscation process itself, so you can't get the original stack trace back unless you have your hands on the reference file that you used to obfuscate the code in the first place.

This has no disadvantages really. :)


问:
Requesting quality analysis test cases up front of implementation/change
Recently I have been assigned to work on a major requirement that falls between a change request and an improvement. The previous implementation was done (badly) by a senior developer that left the company and did so without leaving a trace of documentation.

Here were my initial steps to approach this problem:

Considering that the release date was fast approaching and there was no time for slip-ups, I initially asked if the requirement was a "must have". Since the requirement helped the product significantly in terms of usability, the answer was "If possible, yes".

Knowing the wide-spread use and affects of this requirement, had it come to a point where the requirement could not be finished prior to release, I asked if it would be a viable option to thrash the current state and revert back to the state prior to the ex-senior implementation. The answer was "Most likely: no".

Understanding that the requirement was coming from the higher management, and due to the complexity of it, I asked all usability test cases to be written prior to the implementation (by QA) and given to me, to aid me in the comprehension of this task. This was a big no-no for the folks at the management as they failed to understand this approach. Knowing that I had to insist on my request and the responsibility of this requirement, I insisted and have fallen out of favor with some of the folks, leaving me in a state of "baffledness".

Basically, I was trying a test-driven approach to a high-risk, high-complexity and must-have requirement and trying to be safe rather than sorry. Is this approach wrong or have I approached it incorrectly?

P.S.: The change request/improvement was cancelled and the implementation was reverted back to the prior state due to the complexity of the problem and lack of time. This only happened after a 2 hour long meeting with other seniors in order to convince the aforementioned folks.

答:
Trying to do TDD out-of-blue on highly complex requirement is never good idea. TDD is meant as long-term approach and commitment. TDD won't make it easy to implement change requests and new features overnight.

Also, like Carl said, having answers as "if possible" and "maybe" only shows lack of understanding and commitment from side of management. If you properly explained all ups and downs of your implementation and what might happen if things stay the way they are now, they should have answered either yes or no. That is the key role of management. Deciding what to do based on what people under them say.


答:
Loads to be said about all that. Due to this being Programmers.SE I will ignore the aspect about falling out of favor with some folks and your "baffledness". If you want input on those, I suggest you pay workplace.SE a visit instead.

Apart from that, let's look at the technical issues here:

You are a developer (I assume here), that tells the QA how to do its job. Obviously, you should be well prepared to answer the following questions satisfactorily:

Why do you know better? They worked in some way before, now you want to change it, so you better give them a reason to.

Are you in a position to demand a change of the development process? QA probably has a process to adhere to and you asked them to screw it. Again, better have a good reason.

QA test cases are not supposed to be available to developers up front for a reason. TDD is one thing, but the whole point of QA is to have an independent verification. If you are biased by their test cases you undermine their whole system. Personally, if I was working in QA this would be my #1 reason for not giving you test cases.

You might have mixed up use-case/"usability" and "test-case" in your question. The difference is huge. As mentioned above, you have no rights to access QA test cases in advance, but you should get access to use-cases for the feature you are supposed to implement. Though, the use-cases are normally not maintained in QA anyways. You might even have to come up with them yourself in cooperation with a customer or product manager.

You said that you were "trying a test-driven approach", which causes an immediate question to jump to mind: Why trying? Is there a culture of TDD at your workplace or not? If there isn't then you have to tread very carefully and slowly (see the above questions, except that they will be asked by your co-developers instead of QA this time).

In essence, this might simply be a big misunderstanding and if you point it out as such you might be lucky to fix things with those other folks. We cannot tell here what exactly you said to them, but if you truly demanded from them to violate their processes, years of experience, and sacrifice the whole point of their verification work - just because of you - then you may want to approach them again in a much humbler way instead.

Title: Requesting quality analysis test cases up front of implementation/change

Body:
Recently I have been assigned to work on a major requirement that falls between a change request and an improvement. The previous implementation was done (badly) by a senior developer that left the company and did so without leaving a trace of documentation.

Here were my initial steps to approach this problem:

Considering that the release date was fast approaching and there was no time for slip-ups, I initially asked if the requirement was a "must have". Since the requirement helped the product significantly in terms of usability, the answer was "If possible, yes".

Knowing the wide-spread use and affects of this requirement, had it come to a point where the requirement could not be finished prior to release, I asked if it would be a viable option to thrash the current state and revert back to the state prior to the ex-senior implementation. The answer was "Most likely: no".

Understanding that the requirement was coming from the higher management, and due to the complexity of it, I asked all usability test cases to be written prior to the implementation (by QA) and given to me, to aid me in the comprehension of this task. This was a big no-no for the folks at the management as they failed to understand this approach. Knowing that I had to insist on my request and the responsibility of this requirement, I insisted and have fallen out of favor with some of the folks, leaving me in a state of "baffledness".

Basically, I was trying a test-driven approach to a high-risk, high-complexity and must-have requirement and trying to be safe rather than sorry. Is this approach wrong or have I approached it incorrectly?

P.S.: The change request/improvement was cancelled and the implementation was reverted back to the prior state due to the complexity of the problem and lack of time. This only happened after a 2 hour long meeting with other seniors in order to convince the aforementioned folks.


问:
Functional programming compared to OOP with classes
I have been interested in some of the concepts of functional programming lately. I have used OOP for some time now. I can see how I would build a fairly complex app in OOP. Each object would know how to do things that object does. Or anything it's parents class does as well. So I can simply tell Person().speak() to make the person talk.

But how do I do similar things in functional programming? I see how functions are first class items. But that function only does one specific thing. Would I simply have a say() method floating around and call it with an equivalent of Person() argument so I know what kind of thing is saying something?

So I can see the simple things, just how would I do the comparable of OOP and objects in functional programming, so I can modularize and organize my code base?

For reference, my primary experience with OOP is Python, PHP, and some C#. The languages that I am looking at that have functional features are Scala and Haskell. Though I am leaning towards Scala.

Basic Example (Python):

```<code>Animal(object):
    def say(self, what):
        print(what)

Dog(Animal):
    def say(self, what):
        super().say('dog barks: {0}'.format(what))

Cat(Animal):
    def say(self, what):
        super().say('cat meows: {0}'.format(what))

dog = Dog()
cat = Cat()
dog.say('ruff')
cat.say('purr')
</code>```

答:
In Haskell, the closest you have is "class". This class though  not as same as the class in Java and C++ , will work for what you want in this case.

In your case this is how your code will look.

```
class Animal a where
say :: String -> sound
```

Then you can have individual data types adapting these methods.

```
instance Animal Dog where
say s = "bark " ++ s
```

EDIT :-
Before you can specialize say for Dog you need to tell the system that Dog is animal.

```
data Dog =  \--something here --\ (deriving Animal)
```

EDIT :- For Wilq.

Now if you want to use say in a function say foo, you will have to tell haskell that foo can only work with Animal.

```
foo :: (Animal a) => a -> String -> String
foo a str = say a str
```

now if you call foo with dog it will bark, if you call with cat it will meow.

```
main = do
let d = dog (\--cstr parameters--\)
    c = cat
in show $ foo d "Hello World"
```

You now can not have any other definition of function say. If say is called with anything which is not animal, it will cause compile error.

Body:
In Haskell, the closest you have is "class". This class though  not as same as the class in Java and C++ , will work for what you want in this case.

In your case this is how your code will look.

class Animal a where
say :: String -> sound

Then you can have individual data types adapting these methods.

instance Animal Dog where
say s = "bark " ++ s

EDIT :-
Before you can specialize say for Dog you need to tell the system that Dog is animal.

data Dog =  \--something here --\ (deriving Animal)

EDIT :- For Wilq.

Now if you want to use say in a function say foo, you will have to tell haskell that foo can only work with Animal.

foo :: (Animal a) => a -> String -> String
foo a str = say a str

now if you call foo with dog it will bark, if you call with cat it will meow.

main = do
let d = dog (\--cstr parameters--\)
    c = cat
in show $ foo d "Hello World"

You now can not have any other definition of function say. If say is called with anything which is not animal, it will cause compile error.

ContentLicense: CC BY-SA 4.0


问:
Domain Model and Querying
I am new to DDD, having worked only in Transaction-Script apps with an anemic model, or just Big Balls of Mud, so please forgive any terminology I abuse.

I am trying to understand the proper separation between the domain model and the repository. What is the proper way to construct a domain object that is coming from a database, assuming the (incredibly simplified) need to query for objects by status (returns enumerable), or by ID.

Should a factory be building the objects, exposing methods for GetByStatus() and GetByID(), using a DIed repository?

Should a repository be called directly, knowing how to build a domain model from the DTO?

Should the domain model have a constructor for get by ID, using a DIed repoistory to load the initial state, using some other (?) method for the list?

I am not really sure what the best way would be, and this question has an answer advocating each one (these are certainly mutuallu exclusive).

答:
Repository is a service of domain model, that has responsibility of serving as layer between your domain and data store. It should have method to query entities and methods to save and update them.

To answer your question:

I would say no. I think if you use factories to create your domain object, it should be obvious that domain object comes from data store and is not created anew.

Yes, if you want to. I think this is pretty close to implementation detail and can be left on you.

Definitely not. Like I said, it should be obvious where the entity is coming from.

Also, if you are using an ORM framework, then this framework is already form of repository. Make full use of it and don't reinvent the wheel or add unnecessary layer of complexity over it.

Title: Domain Model and Querying


答:
Functional languages use 2 constructs to achieve polymorphism:

First order functions

Generics

Creating polymorphic code with those is completely different than how OOP uses inheritance and virtual methods. While both of those might be available in your favorite OOP language (like C#), most functional languages (like Haskell) kick it up to eleven. It is rare to function to be non-generic and most functions have functions as parameters.

It is hard to explain like this and it will require lot of your time to learn this new way. But to do this, you need to completely forget OOP, because that's not how it works in functional world.

Title: Functional programming compared to OOP with classes

Body:
I have been interested in some of the concepts of functional programming lately. I have used OOP for some time now. I can see how I would build a fairly complex app in OOP. Each object would know how to do things that object does. Or anything it's parents class does as well. So I can simply tell Person().speak() to make the person talk.

But how do I do similar things in functional programming? I see how functions are first class items. But that function only does one specific thing. Would I simply have a say() method floating around and call it with an equivalent of Person() argument so I know what kind of thing is saying something?

So I can see the simple things, just how would I do the comparable of OOP and objects in functional programming, so I can modularize and organize my code base?

For reference, my primary experience with OOP is Python, PHP, and some C#. The languages that I am looking at that have functional features are Scala and Haskell. Though I am leaning towards Scala.

Basic Example (Python):

```<code>Animal(object):
    def say(self, what):
        print(what)

Dog(Animal):
    def say(self, what):
        super().say('dog barks: {0}'.format(what))

Cat(Animal):
    def say(self, what):
        super().say('cat meows: {0}'.format(what))

dog = Dog()
cat = Cat()
dog.say('ruff')
cat.say('purr')
</code>```


答:
You could do something like this .. php</p>

```<code>    function say($whostosay)
    {
        if($whostosay == 'cat')
        {
             return 'purr';
        }elseif($whostosay == 'dog'){
             return 'bark';
        }else{
             //do something with errors....
        }
     }

     function speak($whostosay)
     {
          return $whostosay .'\'s '.say($whostosay);
     }
     echo speak('cat');
     >>>cat's purr
     echo speak('dog');
     >>>dogs's bark
</code>```

Body:
You could do something like this .. php

    function say($whostosay)
    {
        if($whostosay == 'cat')
        {
             return 'purr';
        }elseif($whostosay == 'dog'){
             return 'bark';
        }else{
             //do something with errors....
        }
     }

     function speak($whostosay)
     {
          return $whostosay .'\'s '.say($whostosay);
     }
     echo speak('cat');
     >>>cat's purr
     echo speak('dog');
     >>>dogs's bark


答:
This is not a direct answer, nor is it necessarily 100% accurate as I'm not a functional language expert. But in either case, I'll share with you my experience...

About a year ago I was in a similar boat as you. I've done C++ and C# and all of my designs were always very heavy on OOP. I've heard about FP languages, read some info online, flipped through F# book but still couldn't really grasp how can an FP language replace OOP or be useful in general as most examples I've seen were just too simple.

For me the "breakthrough" came when I decided to learn python. I downloaded python, then went to project euler homepage and just started doing one problem after another.  Python is not necessarily an FP language and you can certainly create classes in it, but compared to C++/Java/C#, it does have a lot more of FP constructs, so when I started playing with it, I made a conscious decision not to define a class unless I absolutely had to.

What I found interesting about Python was how easy and natural it was to take functions and "stitch" them to create more complex functions and in the end your problem was still solved by calling a single function.

You pointed out that when coding you should follow single responsibility principle and that is absolutely correct.  But just because function is responsible for a single task, doesn't mean it can only do the absolute bare minimum. In FP, you still have abstraction levels. So your higher-level functions can still do "one" thing but they can delegate to lower level functions to implement finer details of how that "one" thing is achieved.

The key with FP however is that you do not have side-effects. As long as you treat the application as simple data transformation with defined set of inputs and set of outputs, you can write FP code that would accomplish what you need. Obviously not every application will fit nicely into this mold, but once you start doing it, you'll be surprised how many applications do fit.  And this is where I think Python, F# or Scala shine because they give you FP constructs but when you do need to remember your state and "introduce side-effects" you can always fall back on true and tried OOP techniques.

Since then, I've written a whole bunch of python code as utilities and other helper scripts for internal work and some of them scaled out fairly far but by remembering basic SOLID principles, most of that code still came out very maintainable and flexible.  Just like in OOP your interface is a class and you move classes around as you refactor and/or add functionality, in FP you do exactly same thing with functions.

Last week I started coding in Java and since then, almost on daily basis I get reminded that when in OOP, I have to implement interfaces by declaring classes with methods that override functions, in some cases I could achieve the same thing in Python using a simple lambda expression, for example, 20-30 lines of code that I wrote to scan a directory, would've been 1-2 lines in Python and no classes.

FP themselves are higher level languages. In Python (sorry, my only FP experience) I could put together list comprehension inside another list comprehension with lambdas and other stuff thrown in and the whole thing would only be 3-4 lines of code.  In C++, I could absolutely accomplish the same thing, but because C++ is lower-level, I would have to write much more code than 3-4 lines and as the number of lines increases, my SRP training would kick in and I would start thinking about how to split up code into smaller pieces (i.e. more functions). But in the interests of maintainability and hiding implementation details, I would put all those functions into the same class and make them private.  And there you have it... I just created a class whereas in python I would have written "return (.... lambda x:.. ....)"


答:
What you are really asking about here is how to do Polymorphism in functional languages, i.e. how to create functions that behave differently based on their arguments.

Note the first argument to a function is typically equivalent to the "object" in OOP, but in functional languages you usually want to separate functions from data, so the "object" is likely to be a pure (immutable) data value.

Functional languages in general provide various options for achieving polymorphism:

Something like multimethods which call a different function based on examining the arguments provided. This can be done on the type of the first argument (which is effectively equal to the behaviour of most OOP languages), but could also be done on other attributes of the arguments.

Prototype / object-like data structures which contain first-class functions as members. So you could embed a "say" function inside your dog and cat data structures. Effectively you have made the code part of the data.

Pattern matching - where pattern matching logic is built into the function definition, and ensures different behaviours for different parameters. Common in Haskell.

Branching / conditions - equivalent to if / else clauses in OOP. Might not be highly extensible, but can still be appropriate in many cases when you have a limited set of possible values (e.g. was the function passed a number or a string or null?)

As an example, here's a Clojure implementation of your problem using multimethods:

```<code>;; define a multimethod, that dispatched on the ":type" keyword
(defmulti say :type)

;; define specific methods for each possible value of :type. You can add more later
(defmethod say :cat [animal what] (println (str "Car purrs: " what)))
(defmethod say :dog [animal what] (println (str "Dog barks: " what)))
(defmethod say :default [animal what] (println (str "Unknown noise: " what)))

(say {:type :dog} "ruff")
=> Dog barks: ruff

(say {:type :ape} "ook")
=> Unknown noise: ook
</code>```

Note that this behaviour doesn't require any explicit classes to be defined: regular maps work fine. The dispatch function (:type in this case) could be any arbitrary function of the arguments.

Body:
What you are really asking about here is how to do Polymorphism in functional languages, i.e. how to create functions that behave differently based on their arguments.

Note the first argument to a function is typically equivalent to the "object" in OOP, but in functional languages you usually want to separate functions from data, so the "object" is likely to be a pure (immutable) data value.

Functional languages in general provide various options for achieving polymorphism:

Something like multimethods which call a different function based on examining the arguments provided. This can be done on the type of the first argument (which is effectively equal to the behaviour of most OOP languages), but could also be done on other attributes of the arguments.

Prototype / object-like data structures which contain first-class functions as members. So you could embed a "say" function inside your dog and cat data structures. Effectively you have made the code part of the data.

Pattern matching - where pattern matching logic is built into the function definition, and ensures different behaviours for different parameters. Common in Haskell.

Branching / conditions - equivalent to if / else clauses in OOP. Might not be highly extensible, but can still be appropriate in many cases when you have a limited set of possible values (e.g. was the function passed a number or a string or null?)

As an example, here's a Clojure implementation of your problem using multimethods:

;; define a multimethod, that dispatched on the ":type" keyword
(defmulti say :type)

;; define specific methods for each possible value of :type. You can add more later
(defmethod say :cat [animal what] (println (str "Car purrs: " what)))
(defmethod say :dog [animal what] (println (str "Dog barks: " what)))
(defmethod say :default [animal what] (println (str "Unknown noise: " what)))

(say {:type :dog} "ruff")
=> Dog barks: ruff

(say {:type :ape} "ook")
=> Unknown noise: ook

Note that this behaviour doesn't require any explicit classes to be defined: regular maps work fine. The dispatch function (:type in this case) could be any arbitrary function of the arguments.


问:
Why C# doesn’t support multiple inheritance?
Even if it could be bad practices, I would say that there is time that it would fulfill its purpose.</p>

答: Multiple inheritance, if you use it a lot, results in very complex situations. Too much complexity with little benefit is why it was ruled out for both Java and C#.</p>


问:
Wiki/markup in enterprise as documentation
Why it is less common to use wiki/markup in enterprise as documentation?

They use Word document instead.

Wiki/markup are in text format, which is version control friendly.

答:
Two types of answer

Pessimistic view

Corporate ordinary employee is lazy, passive, lowbrow executor, not interested in quality work, only in quantity. If he know Office, he haven't interest to know and use more

Realistic view

Contrary to code, historical aspects of "active" documents have a lot less value - every time only "now state" make sense in workflow - thus "easy versioning", "less size", "light markup" is arguments and values of geeks, not casual personnel. Using non-standard a) markups b) tools will require learning cycle, re-education of users, (possible) changing of workflow... Without strong reasoning all these costs and losses are not being taken into account by the real business in the real world


问:
iOS - Unit tests for KVO/delegate codes
I am going to design a MVC pattern. It could be either designed as a delegate pattern, or a Key-Value-Observing(KVO), to notify the controller about changing models. The project requires certain quality control procedures to conform to those verification documents.

My questions:

Does delegate pattern fit better for unit testing than KVO?

If KVO fits better, would you please suggest some sample codes?

答:
Neither of your suggested approaches "fits better for unit testing". You could use a delegate, KVO, a callback block, notifications or some other scheme—any of these things could be tested.

The key to writing testable code in my experience is to write the tests first, as with Test-Driven Development and its red-green-refactor mantra. That way, you are constrained to write code that can be (easily) tested by the fact that the test already exists and you need to write code that integrates with it.

If you write the code first, then try to test it, you have the same problem as with any attempt to integrate existing code—albeit on a small scale. You have to work out where your test needs to interface with the class, then whether the class supplies that interface, then whether the class expects the interface to be used that way…a major aspect of TDD is that you write the interfaces you need when you need them, rather than trying to retrofit them.

Title: iOS - Unit tests for KVO/delegate codes