问:
Talking about Front End Web Development frameworks from a designer's perspective
I am a Web Developer working at a company where the fronted framework we have selected is Angular JS. I am now in the position where I am the 'resident expert' whatever that may mean. I have been tasked with teaching/explaining everything that our Designers need to know about Angular JS. Unfortunately my knowledge/understanding of design begins and ends with the color wheel. Therefore I have the following question:

What, if anything would a designer need to know about a front end javascript framework in general/Angular JS in particular in order to streamline their productivity? What kind of things are irrelevant? What kind of things are important?

答:
When I was working with Android, here is what our designer wanted to know:

what is possible (compared to other technologies)

what is impossible (compared to other technologies)

what is generally accepted and "traditional"

what is more convenient (in our specific case it was button sizes or different keypads for different cases)

most recent samples with exceptional quality of UI (you or the designer need to follow the market and get new applications not to miss the latest tendencies)

resolution issues (though I doubt you will need this with JS framework)

any specific requirements for the resources, like images, icons, etc.

After all these points were covered, the cases when the designer asked for something impossible or needed any additional information were very rare.


问:
What skills to master to become a better ASP.net developer?
I've been an ASP.net web developer for about 2.5 years now.

I would describe my technical training before that as being "classical" C++.

It seemed like it took an eternity to get up to speed with ASP.net.  I kept wanting to think of programming in VB.net and C#.net as if it were C++ programming, which of course, it isn't.  Even my supervisor admitted that at the beginning he had doubts about "keeping me on board", but I made it.  I've now been working on a project of my own for about a year.

Here are some concepts and technologies I've picked up some skill with along the way.

class inheritance

separation of concerns

LINQ

SQL

Session State

JavaScript

jQuery

AJAX

CSS

The first two that I mentioned are essential for keeping the code organized.  LINQ is very nice to have to avoid having to write for loops over and over.  JavaScript seems to have become the backbone of web programming in spite of its shortcomings and jQuery seems to couple it very tightly with CSS.

I've been making a big effort to learn to write better JavaScript; mainly by reading on Douglas Crockford's web site.

I would like to know, from more experienced web developers, besides what I mentioned here, what are the most important tools to have in your toolbox to write great web applications?

答:
Asp.Net

C#

Sql server

Linq

Css

Html

Wcf

Mvc

Javascript

Jquery

Web services

All these are important for a good .Net Developer. If you have achieved all these technologies, then you move to anywhere in the .NET platform.

ContentLicense: CC BY-SA 3.0


答:
As a short answer, consider looking for some certification from Microsoft. This both shows off your commitment and is a good learning path to have a more complete understanding of the ASP.NET stack, based on what you already have.

The certifications suitable for you are probably the MCSD or the older MCTS (expecially for WebForms)

Title: What skills to master to become a better ASP.net developer?

Body:
I've been an ASP.net web developer for about 2.5 years now.

I would describe my technical training before that as being "classical" C++.

It seemed like it took an eternity to get up to speed with ASP.net.  I kept wanting to think of programming in VB.net and C#.net as if it were C++ programming, which of course, it isn't.  Even my supervisor admitted that at the beginning he had doubts about "keeping me on board", but I made it.  I've now been working on a project of my own for about a year.

Here are some concepts and technologies I've picked up some skill with along the way.

class inheritance

separation of concerns

LINQ

SQL

Session State

JavaScript

jQuery

AJAX

CSS

The first two that I mentioned are essential for keeping the code organized.  LINQ is very nice to have to avoid having to write for loops over and over.  JavaScript seems to have become the backbone of web programming in spite of its shortcomings and jQuery seems to couple it very tightly with CSS.

I've been making a big effort to learn to write better JavaScript; mainly by reading on Douglas Crockford's web site.

I would like to know, from more experienced web developers, besides what I mentioned here, what are the most important tools to have in your toolbox to write great web applications?


问:
What mistakes in managing software products must be avoided to keep people from hating the vendor?
A previous question about why people hate Microsoft was closed. This is an attempt at a somewhat more constructive question along the same general line. This one is both broader and narrower though. It's more general by being about software vendors in general, not just Microsoft. It's narrower by dealing only with management of software products.

So, what steps should be taken (and/or avoided) in managing individual software products to assure that not only the individual products, but the company as a whole is respected/liked/seen in a positive light?

答:
Some ways to be hated:

When marketing and selling your business product, aim for people with purchasing authority who won't have to use it.  Then you don't have to worry about usability.

Ideally, pricing should be confusing and irrational.  Have multiple versions with functionality that's not clearly differentiated.  Ideally, have one or two particularly desirable features high up on the price scale, so people get the feeling they have to pay big for a lot of things they won't use.

If you have enough power, make later versions of your software not quite compatible with their predecessors, and don't offer upgrade discounts.  For extra points, remove functionality that people might be used to.

Advertise features that don't really work.  If you've got sufficient control of the product, remove some of them with more or less forced upgrades.

Leave some bugs in, preferably intermittent bugs.  Come up with reasons why, if something happens, it isn't your fault.  Stonewall your complaining customers.  Alternatively, come up with a fix that actually makes the product less usable.

Quality control is for companies that want customer satisfaction.  You've got a lot of potential beta testers out there:  use them.  You'll get reports even if you don't give them any feedback.  You can fix a lot of them in the next version (see above about slight incompatibilities, no upgrade pricing, and removing functionality).

Mess up the users' computers.  DRM is great here, particularly if you don't tell anybody about it ahead of time (and particularly if they won't expect DRM on something like your product).

Anti-piracy measures are great.  Make sure your detection algorithms have plenty of false positives.  It isn't necessary to have convenient or easy ways to correct the false positives.

Long confusing EULAs that claim ridiculous things are commonplace nowadays.  To get hated over them, you have to bury something onerous in there and enforce it afterward.

Documentation is for wimps.  Make sure it's virtually impossible to figure out how to do a few important things from the docs.  (Unfortunately, this has become too common over time to be really effective.)

Rebates that require awkward documentation and application procedures are good.  Remember that many receipts nowadays are printed in a way that fades over time, so you can save a lot of money by requiring the original receipt and taking long enough to process them.

Arrogance and well-publicized anti-competitive practices are always useful here.

(No points for guessing which suggestions I wrote with companies in mind, or even which ones, or which I've suffered through personally.)

ContentLicense: CC BY-SA 2.5


问:
What is the proper way to store an object with many attributes in Objective-C?
I have an object that I am downloading over HTTP, that has approximately 50 attributes. What is the proper way to store this information in Objective-C? Should I have an NSObject with a property for each attribute (if so, what would be a good way to initialize this object?)? Should I use an NSDictionary with 50 key-value pairs?</p>

答:
As i think its better to create a class object and use properties to store attributes because that can store even NULL values instead of NSDictionary.

In NSDictionary you must have to check for NULL value before insert in it.

Class object is much cleaner, more understandable and easier to debug values during debug time.

Class objects differentiate b/w each property data type.

OwnerDisplayName: Lenny K


问:
How fast should a Python factoring script be?
Just how efficient is "good enough" for all intents and purposes? I wrote a script to simply list off all numbers that divide into an input, x, as pairs (i, n//i) and was just curious how efficient I should be going for? what is the acceptable rate at which the script starts to lose its efficiency? This is my code (although advice is appreciated, I just want to give an idea as to how it works).

```<code>import time
print('''This program determines all basic factors of a given number, x, as ordered            pairs, (a, b) where ab=x.
Type "quit" to exit.''')

timer = input('Would you like a timer? (y/n) ')
while  1:
    try:
        x =(input('x = '))
        T0 = time.time()
        b = []
        n = int(x)**0.5
        ran = list(range(1, int(n)+1))
        if int(x) % 2 == 1:
            ran = ran[::2]
        for i in ran:
            if int(x) % i == 0:
                m = (i, int(x)//i)
                b.append(m)
        else:
            pass
    except ValueError as error_1:
        if x == 'quit':
            break
        else:
            print(error_1)
    except EOFError as error_2:
        print(error_2)
    except OverflowError as error_3:
        print(error_3)
    except MemoryError as error_4:
        print(error_4)
    T1 = time.time()
    total = T1-T0
    print(b)
    print(str(len(b)) + ' pairs.')
    if timer == 'y':
    print("%.5f" % total + ' seconds.')
</code>```

some of the results are:

```<code>x = 9
[(1, 9), (3, 3)]
2 pairs.
0.00000 seconds.

x = 8234324543
[(1, 8234324543)]
1 pairs.
0.07404 seconds.

x = 438756349875
[(1, 438756349875), (3, 146252116625), (5, 87751269975), (15, 29250423325), (25,         17550253995), (75, 5850084665), (125, 3510050799), (375, 1170016933), (557, 787713375),   (1671, 262571125), (2785, 157542675), (8355, 52514225), (13925, 31508535), (41775,   10502845), (69625, 6301707), (208875, 2100569)]
16 pairs.
0.88859 seconds.
</code>```

So this program can be pretty quick, but then the speed drops rather rapidly once you get up to higher numbers. Anyways, ya, I was just wondering what is considered acceptable by todays standards?

答:
So this program can be pretty quick, but then the speed drops rather rapidly once you get up to higher numbers

This is normal. Doing the factorization of a large number is an highly time consuming tasks.
Indeed many cryptography algorithms (like the widely used RSA) rely on the difficulty of factoring large integers.


问:
How to handle divide by zero in a language that doesn't support exceptions?
I'm in the middle of developing a new programming language to solve some business requirements, and this language is targeted at novice users. So there is no support for exception handling in the language, and I wouldn't expect them to use it even if I added it.

I've reached the point where I have to implement the divide operator, and I'm wondering how to best handle a divide by zero error?

I seem to have only three possible ways to handle this case.

Ignore the error and produce 0 as the result. Logging a warning if possible.

Add NaN as a possible value for numbers, but that raises questions about how to handle NaN values in other areas of the language.

Terminate the execution of the program and report to the user a severe error occurred.

Option #1 seems the only reasonable solution. Option #3 is not practical as this language will be used to run logic as a nightly cron.

What are my alternatives to handling a divide by zero error, and what are the risks with going with option #1.

答:
3. Terminate the execution of the program and report to the user a severe error occurred.

[This option] is not practical…

Of course it is practical: It is the programmers' responsibility to write a program that actually makes sense. Dividing by 0 does not make any sense. Therefore, if the programmer is performing a division, it is also his/her responsibility to verify beforehand that the divisor is not equal to 0. If the programmer fails to perform that validation check, then s/he should realize that mistake as soon as possible, and denormalized (NaN) or incorrect (0) computation results simply won't help in that respect.

Option 3 happens to be the one I would have recommended to you, btw, for being the most straightforward, honest, and mathematically correct one.


问:
Is it good practice to create convenience delegate methods?
Suppose I have design like this:

```<code>class Corpus:
    def something1(self):
        pass
    def something2(self):
        pass
    def serialize_to_stream(self, stream):
        _CorpusJsonSerializer().serialize(self, stream)

class _CorpusJsonSerializer:
    def serialize(self, corpus, stream):
        .
        .
        .
    .
    .
    .
</code>```

I think that the serialization process should be in a separate class for various reasons. That makes the method serialize_to_stream in Corpus unnecessary. I would however like to have it there because I think it makes it easier for the users of the Corpus, because they do not have to know anything about another class CorpusJsonSerializer.

Do you think it is reasonable? Or shall I just expose the CorpusJsonSerializer and let the user do the work?

答:
This is a trade-off between ease-of-use and decoupling.

Having a serialize-method part of your Corpus class may make it easier to use, but this way your Corpus class depends on _CorpusJsonSerializer and vice versa, which means you have a cyclic dependency. This is often a sign of bad design, since it makes Corpus harder to test, harder to reuse in a different context, harder to extent etc.

In most cases, I would avoid solutions with cyclic dependencies. Even better would be a design where you don't need a special _CorpusJsonSerializer, but only a general JsonSerializer which takes an arbitrary object (for example, of type Corpus) and determines its type and the serializable attributes of that type at run time. This way, you would eliminate all of the current dependencies.

Another design option, which is not so generic but avoids cyclic dependency, is to inject the dependency from outside. Means, in the Corpus constructor provide a parameter for a "serializer" object which is stored in your Corpus object and used in the serialize_to_stream method. You can pass here an object of _CorpusJsonSerializer in most cases, but also a completely different object following the same interface conventions (i.e. providing a serialize method). This way, when for testing purposes you don't need a serializer, you don't have to provide one; or if you need a different kind of serializer, you can easily exchange it. Of course, this option will imply that _CorpusJsonSerializer is exposed to the user, but you can keep the convenience method in Corpus without the drawbacks of cyclic dependencies.


问:
Could I GPL this code?
I'm working on reviving a C++ codebase that hasn't been touched since '97.

It's academic software for text analysis, and originally it was non-functional, it wouldn't even compile.

I fixed the code so that it works, and added some new functionality of my own.

I'm doing this privately for someone else, and they will pay me over a student contract. I signed nothing with them, so ultimately, my work belongs to me. Given that they agree (I don't want to be rude), would I be able to relicense this code under GPL, and post it on a site like GitHub?

The current license is as follows:

Copyright (C) 1997, Carnegie Mellon University.  All rights reserved.
  This software is made available for research purposes only.  It may be
  redistributed freely for this purpose, in full or in part, provided
  that this entire copyright notice is included on any copies of this
  software and applications and derivations thereof.

This software is provided on an "as is" basis, without warranty of any
  kind, either expressed or implied, as to any matter including, but not
  limited to warranty of fitness of purpose, or merchantability, or
  results obtained from use of this software.

Seems like I would have to include that notice as well.

答:
IANAL! The License of the code is incompatible with the provisions of the GPL, so you cannot put the GPL on it.

Or rather you can put the GPL on your code but users would still be bound by the stricter provisions of the original License, making the legal situation a real mess.

The only option if you want to relicense the code is to get permission from the original authors of the code (in writing).

Title: Could I GPL this code?


问:
Methods to identify and resolve memory leaks in the JVM
As the data is migrated via the object level, there has been a slow upwards trend in memory usage. I can see the periodic gc activity, but the memory trend is still going up slowly.  I have currently for my application set the starting and max heap at 14GB in production, however if we might need a large data set, my concern is the we will eventually hit the limit and then the application will slow down (which was what happened).

What are some effective ways and proving strategies to help identify and remedy a potential memory leak in a running Java process?

答:
There are generally two ways to approach this problem.

1.) Use a GC Log analyser for post mortem analysis of a log. There are range of options from free to commercial for these.

You'll need to make sure your JVM starts with the flags -XX:+PrintGCDetails -XX:+PrintTenuringDistribution and -loggc:[name of your gc log]

When you analyse the log you want to look at what happens after full GC's.  Is the memory consumption dropping back to a fairly flat level?  If not then you have a possible memory leak.

If it's falling back fairly flat then you simply just have a big resident set size problem, up the heap size or split the work into batches.

2.) Fire up Visual VM (comes with Java) and then sample your object usage (profiler) Visual VM tells you how many generations the objects are living in.  Suspicious memory leaks tend to live in all of the generations (look for the big number, it'll be the big red bar at the top).  Typically this is some sort of base Java class byte[] or String or whatever, but that's not the leak, the leak is your code that's creating those and not letting go.

So next step is to follow the method profile down to the bit of code that's doing the creating and look at the source code as to why you're not releasing.


问:
Would copyrights drop if I re-write open source project into another language?
I have re-written an open source project from java to haxe, then from haxe compiled to javascript, with totally different UI

So, the question is, is the code considered to be mine after rewriting it to another language in a closed source project? can I use it freely with no worries about original copyrights?

答:
No. It is derived from the original open-source project, thus a so-called derivative work, still protected by the original copyright.

In copyright law, a derivative work is an expressive creation that includes major, copyright-protected elements of an original, previously created first work (the underlying work)...

For copyright protection to attach to a later, allegedly derivative work, it must display some originality of its own. It cannot be a rote, uncreative variation on the earlier, underlying work. The latter work must contain sufficient new expression, over and above that embodied in the earlier work for the latter work to satisfy copyright law’s requirement of originality...


答:
I am not a lawyer, and cannot give legal advice, which is what you are asking for. I do, however completely agree with @chirlu: it is a derivative work.

The completely proper thing to do is ask the original owner(s). If you think that they will assert their copyright then you have answered you own question.

In such situations it is better by far to be cautious.

Title: Would copyrights drop if I re-write open source project into another language?

Body:
I have re-written an open source project from java to haxe, then from haxe compiled to javascript, with totally different UI

So, the question is, is the code considered to be mine after rewriting it to another language in a closed source project? can I use it freely with no worries about original copyrights?


答:
IANAL either. I think that it all depends on how you do the "rewrite."

If you just look at the original source code and rewrite that into a different language, then I would say it is a derivative work covered by the existing copyright.

However, if you do not look at any of the source and you only look at the applications output and screens and behaviours, then I believe your work will not be derivative work.

That said, this is really a question for a lawyer.


问:
Is it a good idea to use Twitter Bootstrap 3 for production?
So in the past few weeks I was introduced to Bootstrap 3-RC1. I made some web sites using it, and I actually enjoyed it. Then, recently, I discovered Twitter Bootstrap has already released version 3-RC2. It makes me wonder if it's okay for me to use Bootstrap RC2 for production now? Is it wise if I used it considering it still in RC phase or should I just wait for the official, completed version 3?</p>

答:
Release candidates are usually well tested, with no major bugs.

Really it comes down to your specific company or project and their attitude to risk and where you are in your projects release cycle.

6 months before your release and you're probably going to be able fit in an upgrade to the full v3 release, but if you only have a week to go maybe you wouldn't want to risk it.


问:
Maintaining code-style conventions for large projects
For a while I've been maintaining an ad-hoc script to check code style against our project's guidelines.

I'm aware of AStyle/Uncrustify and have used them, but they are best for once-off code-style cleanups, but impractical to just run all code through some automatic process after every commit.

To explain the issue a little more, yes - we have code-style documentation, but devs don't always follow exactly, and it's not really great to give them personal mail every time they make some tiny change that goes against some convention.

So I took the approach to deal with this like compiler warnings, report inconsistencies but leave it up to the developer to resolve (some of you may be familiar with Python's pep8 style checker). Once every so often we do style cleanups.

In general I'm very happy with the outcome (unlike most style checking tools), you get to get a lot of flexibility - so you can choose where to be strict and where to be relaxed about conventions (avoid too many false positives is important too).

Currently I'm using Python and Pygments to parse C source code (some C++ also but mainly C) and then my own script to check the tokenized results meet our conventions. This works fairly well, I don't need the full AST you can get with GCC or Clang for example, simply knowing if text is a comment, string, punctuation, preprocessor... etc. is enough (what you would get from syntax highlighting, or a source tokenizer).

But I did end up having to write quite a few utility functions for the source:

extract the body of a block between brackets.

find matching brackets.

identify casts.

inspecting whitespace around punctuation.

... nothing really advanced.

The exact conventions are probably not so important, but for an example here are some checks:

Placement of braces for 'if' statement checks broken into multiple lines.

Placement of break in a switch statement.

Spaces around operators, braces, function calls, after commas.

Indentation for multi-line if statements.

Indentation consistency.

At this point I would be interested to move away from my own utility functions but still have a script which checks code-style, if there is something else well maintained solving similar problems.

I'd be surprised if there is not some other people doing similar projects to maintain consistent source style in this way, so I'm interested to know of any alternatives available.

Question:

Considering the workflow I have described, how can projects successfully maintain code-style?

答:
Depending on the languages, static analysis tools may exist or not. For example, for C#, there is StyleCop and its automatic integration within Visual Studio, letting to check the style errors in one click (actually two clicks, but there is a keyboard shortcut too). Using third-party tools, it can also be integrated into many version control systems, meaning that only compliant code may be committed.

For C and C++, see A free tool to check C/C++ source code against a set of coding standards? I haven't used it, so I don't know how well it is and whether it is possible to integrate it into a version control.

In all cases, version control integration is a must have, for two reasons:

If there is no such integration, there is no enough pressure on the developers to respect the style rules. Doing it during code review is a waste of time: code reviews are not for that. Finally, constantly reminding to the developers to check their style will inevitably decrease the quality of your relations with your colleagues.

Because one can commit for a few days without being recalled to check the style, it's much harder to enforce hundred rules after ten days of work than ten rules every day. The process should be as frequent as possible: the best technique would be to move the burden of style rules to the IDE, but actually, IDEs are quite shy when it comes to enforcing a style (including when they asked to do it, for example through the auto-formatting feature).

ContentLicense: CC BY-SA 4.0


问:
Is an atomic action supposed to be deterministic?
I was reading about the at most once property that defines what an atomic action is and I've been curios about this example:

```<code>x = 0, y = 0
x = y + 1 || y = y + 1
</code>```

If we use the 'at most once' definition, we can say that, indeed, x = y + 1 is atomic because

y is only referenced in an another thread and

x is not being read by any thread

But the result of this action is not deterministic, it could be 1 or 2 depending on which operation is being computed first.

I might be wrong from the start, isn't atomicity suppose to grant some kind of determinism?

答:
Deterministic is not part of the definition of Atomic, in Computer Science.  It is that simple.  This is a good thing; separation of concerns is as important in CS definitions as in software design.

Why would you want to dictate that all atomic actions be deterministic?  Very few applications can be entirely deterministic, and while it is good practice to isolate the non-deterministic functions, what would you gain by not allowing them to be atomic?


问:
How to update an existing excel file using java program?
I've made a file browser in java that opens and read already been made excel files. (using Apache poi 3.9 library)
program read those files perfectly but i want to update some of those files. how can i be able to update those files through my program.
is there is any library or function/class that might be helpful, or also any other language that can support that feature (among c/c++, python)..???</p>

答:
There are a bunch of examples on the Apachi POI library site on how to change and save Excel files. Here are a couple of pages to get you started:

Apache POI Spreadsheet HOWTO - The New Halloween Document

Apache POI Spreadsheet Quick Guide - Busy Developers' Guide to HSSF and XSSF Features

E.g. workbook objects in the library have a write(…) method if you want to save the contents of it to a file using an appropriate OutputStream:

```<code>// Save a workbook (wb)
FileOutputStream out = new FileOutputStream("my_workbook.xls");
wb.write(out);
out.close();
</code>```

If you want to open the files in Excel you can, according to this answer, try using Desktop which is available in JDK6.

```<code>Desktop.getDesktop().open(new File("c:\\file.xls"));
</code>```

Body:
There are a bunch of examples on the Apachi POI library site on how to change and save Excel files. Here are a couple of pages to get you started:

Apache POI Spreadsheet HOWTO - The New Halloween Document

Apache POI Spreadsheet Quick Guide - Busy Developers' Guide to HSSF and XSSF Features

E.g. workbook objects in the library have a write(…) method if you want to save the contents of it to a file using an appropriate OutputStream:

// Save a workbook (wb)
FileOutputStream out = new FileOutputStream("my_workbook.xls");
wb.write(out);
out.close();

If you want to open the files in Excel you can, according to this answer, try using Desktop which is available in JDK6.

Desktop.getDesktop().open(new File("c:\\file.xls"));


答:
If POI is not sufficient for any kind of reasons, you may have to utilize Excel by using COM Automation for such a task. Read this SO post for more information how to do this in Java. But beware, this will have some drawbacks:

platform-dependent (will only work on Windows)

won't work well for a server-side application

slow (compared to direct access by POI)

Title: How to update an existing excel file using java program?

Body:
I've made a file browser in java that opens and read already been made excel files. (using Apache poi 3.9 library)
program read those files perfectly but i want to update some of those files. how can i be able to update those files through my program.
is there is any library or function/class that might be helpful, or also any other language that can support that feature (among c/c++, python)..???</p>


问:
Architecture for REST consumer
Are there any good samples of web applications that consume restful web services?

I am developing a webapp with spring, and have come to the point of reading lists of elements and element details from a RESTful JSON api. I started developing as though I was using a database, creating services, model elements plus DAOS, but now I'm stuck on how to do a proper design here.

Should model objects hold a fromJson/toJson method and encapsulate themselves the serialization info? What should DAO objects do? Where should I keep WS specific info (urls, api keys, item names, etc.)?

Any good opensource apps would be nice.

答:
Many companies which develop APIs also develop clients using different programming languages. For example, Twilio list of client libraries is quite impressive. Recaptcha libraries is another good example.

Many of those libraries being open sourced, you can see how they are accessing the API. It won't give you all the answers (since their role is very limited), but still would be a good starting point. For example, they would show how to reduce code duplication and boilerplate code when calling the RESTful API with different options.

For now, I can't remember any open sourced application which uses RESTful APIs. If I recall one, I'll edit my answer.

Title: Architecture for REST consumer


问:
When should I write integration tests?
According to rules of TDD unit tests are written before production code, but what about Integration tests that exercises interaction between concrete (non mocks) wired objects?

Should they be written before unit tests or after production code just to test the "wiring" ?

Note that I'm not talking about Acceptance or functional tests but Lower level integration tests.

答:
Real project showed to me that it's not possible to write unit tests and then integration and even opposite direction is wrong :-) So, I usually write unit tests together with integration ones.

Why? Let me to write how I see both kinds of tests:

Unit tests - In addition to Wikipedia and all know information, unit tests help you to narrow your design, improve your model, relations. The flow is simple: once you start to type new project/new component, most of time you are making some kind of PoC. When you are done, you always have long methods, long classes, non-coherent methods and classes, etc.

Unit tests help you to remove these issues as when you do real unit testing using mocks (w/o dependency on other component) classes described above are un-testable. Basic sign of untestable code is large mocking part of tests because you are forced to mock many dependencies (or situations)

Integration tests - correct and working tests say to you that your new component (or components) work together or with other components - this is usual definition. I've found that integration tests mostly help you to define flow how to use your component from consumer side.

This is really important as it sometimes says to you that your API does not make sense from outside.

Well, what happen once I wrote unit tests and integration tests later?

I got nice classes, clear design, good constructor, short and coherent methods, IoC ready etc. Once I give my class/API to some consumer, e.g. developer from integration or GUI team, he was unable to use my API as it seems unlogic, weird. He was just confused. So I repaired API according to his point of view but it also required to rewrite many tests because I was pushed to change methods and sometimes even the flow how to use the API.

Well, what happen once I wrote integration tests and unit tests later?

I got exact flow, good usability. What I also have are large classes, non-coherent code, no logging, long methods. Spaghetti code

What's my advice?

I've learned following flow:

Develop basic skeleton of your code

Write integration tests that say whether it make sense from consumer point of view. Basic use-case is enough for now. The test obviously does not work.

Write code along with unit tests for each class.

Write the rest/missing of integration tests. It would be better to implement these test within #3 how you are improving your code.

Note that I've made small presentation about unit/integration testing, see slide #21 where the skeleton is described.

Title: When should I write integration tests?


问:
Is big-O really that relevant when working in industry?
In every interview I have been in, I have been quizzed on mathematical analysis of complexity, including big-O notation.

How relevant is big-O analysis to development in industry? How often do you really use it, and how necessary is it to have a honed mindset for the problem?

答:
Not really. Basically the only time I ever think about it is when accessing the database.  I'll usually look at code and say "That's doing n+1 queries, you should change it to do just 1 or 2"

Because all of my data is being read from a database and shown to the user, I try to minimize the amount of data I'm working with to the point where the difference between a linear and an O(n^2) algorithm is pretty negligible.

If there's a problem, we'll profile and fix it later.


问:
Python web application frontend for equipment diagnostics and interaction
My goal is to have a Python application that runs a web server which hosts the user interface, and based on interactions from a user in their browser, long running tasks get kicked off and through some process, feed status information back to the web server and subsequently back to the browser.

The application will not need to be used by more than 1 person at a time, and if 2 or more users are accessing the URL, the state should essentially be shared across all instances.  That is, each user does not have unique login session.

The main purpose of the application will be to maintain a list of devices it discovers automatically on the network, and poll those devices every 30-60 seconds and update the UI if it is being used.  In addition, the user can select one or more of those devices and issue commands or upgrade their software.  In the instance of the software upgrade, I would like to have it responsive enough where I could show real time progress bars for each device showing what % of the firmware has been uploaded.

My initial thought is something like web.py or Cherrypy for the GUI, now I'm just stuck on the best method to kick off those processes from the web server and how to feed the info back.  I was thinking of having some daemon listen for commands on a socket which the web app would send, and it would use sockets to pass state back and forth between the daemon and the web.  Then I still need to get that information smoothly from web to client so I was thinking of websockets for that.

I'm just looking for recommendations on some good practices for having the web interface communicate back and forth between the actual workers and then how to get the data from worker to web server to client browser.

The driving forces behind using the browser based approach is that the system itself must run on low cost hardware running Linux on x86 (not arm) with small amounts of memory.  It could be a GUI app which we VNC into a machine to use but the headless method seemed better to me.  I'm not 100% tied to this idea if anyone can suggest better alternatives.

答:
'GUI' or web fronted

You can choose between several very easy and fancy web frameworks to build the frontend (you already mentioned web.py and Cherrypy). Personally I prefer Flask, which is actively maintained, widely used, easy to learn, very lightweight and has great docs/community.

'Backend' or asynchronous tasks

Celery is a good library to have tasks running asynchronously in background (e.g. checking your devices or whatnot) and sending data back to your application via a DB like Redis.

In summary you can set up a very simple Flask app in minutes and have it 'call' Celery workers. The only non-pythonic thing you will need is Redis allowing Workers/Flask app to communicate, but this is described in the Celery docs.


问:
Is it a row or a record (or a tuple)

If I look at a database table for editing - is it made up of rows or records?

If I write some sql and then look at the result is this made up of the same elements as the answer to 1.?

Is it the case that they are all rows but in very specific circumstances they are also records?

EDIT

A recent article by Itzik Ben-Gan prompted my question and I see quite a discussion on dba.stackexchange.

In that article Aaron Bertrand brought up the same Itzik quote from his "Training Kit (Exam 70-461): Querying Microsoft SQL Server 2012"

As an example of incorrect terms in T-SQL, people often use the terms
  “field” and “record” to refer to what T-SQL calls “column” and “row,”
  respectively. Fields and records are physical. Fields are what you
  have in user interfaces in client applications, and records are what
  you have in files and cursors. Tables are logical, and they have
  logical rows and columns.

答:
row=record in relational databases, those are just two terms for the same thing

"SELECT" statements (not all SQL statements) deliver a result set consisting of rows or records, whatever term you prefer.

Next time you intend to ask such a question, have a look into Wikipedia first.

Title: Is it a row or a record (or a tuple)


问:
Can I use a dual license in my commercial Website
I have set up a web application which is of commercial use. This application had to make use of the plugin(which is not downloaded from http://plugins.jquery.com)
I downloaded this plugin from http://jquery.malsup.com/cycle2

Kindly, let me know if I could use this plugin in my commercial website.
If I do, would it cause any consequences in future?
Though, I could see few answers here, I would like to Insist upon itself on this as of critical importance.

Licensing Terms

答:
Your question is missing important information: what are the licensing terms for the Cycle2 plugin? The answer is that it is available under dual license, MIT and GPL. Which makes this question a duplicate of this one.

Brief answer: there's no problem using an MIT library in a commercial web website, or any other commercial program.

Therefore there is no problem using a dual licensed library, where one of the options is MIT, in a commercial website. "Dual licensing" means you, as the user, can choose which license to use. You simply make this choice in your own mind, you don't need to tell the library author. Simply say to yourself "I am using MIT", and you're fine.


问:
many include files vs one large include file
The company I work for is in the process of completely overhauling our current intranet site by moving it onto a Drupal framework. One area I am questioning is the number of include files we have. As it exists right now, every single .php page has a corresponding .inc page. There are .inc pages that provide certain functionality, but aren't tied to a specific page. However, each .php page includes multiple files - at a minimum, it will load the .inc page corresponding to it, and a few general scripts. This makes trying to find a function definition a nightmare when debugging.

My options right now seem to be the following:

1)Keep using this same system, but make it part of our convention to include a commented line stating where the function is defined
2) Consolidate all the include files into one large file. This would include class definitions, function definitions, everything. My concern here is that this file would get monolithic in a real big hurry. However, it would have the advantage of keeping all function definitions in one place.

I don't like either option to be honest. My goal is to reduce dependencies and make our code readable and easy to navigate. What is our best method to handle this problem?

I should also state that this is very much legacy code - it hasn't been refactored since it was created in 2003-2004. Just to give you an idea what I'm working with, there is a lot of php echoing html:

```<code>printf("<center>\n");
printf("<table>\n");
printf("<tr>\n");
printf("<td align=left>Select Division:</td>\n");
printf("<td><select name=\"div\">\n");
printf("  <option value=1 \"selected\">Division1\n");
printf("  <option value=2>Division2\n");
printf("</select></td>\n");
printf("</tr>\n");
printf("<tr>\n");
printf("<td align=center colspan=2><input type=\"submit\" value=\"Next->\"></td>\n");
printf("</tr>\n");
printf("</table>\n");
printf("</center>\n");
</code>```

答:
tl;dr it's not many include files vs one large file, it's the Drupal way.

Since you want to move onto Drupal, I'd suggest you go with it for real. Here is how Drupal works.

First, in Drupal, the only folder you can touch is sites/.

In sites/default, basically you only touch the settings.php file. Most of your time will be spent in sites/all/. In this folder, there are 2: themes and modules. Your theme will be where you guess it, and the modules (contributed, or yours) will be where you guess it too.

I won't write a tutorial about how to write themes. Basically, you have all your templates in your theme, and the modules use these templates. The big advantage is that you can override the templates used by other modules (which you shouldn't touch either) including the core ones.

Drupal separates modules by features. You, for your own website, usually separate your modules by business features.

I'm not going to write a tutorial about how to write modules, but here is how it basically works:

Your module needs a .module file. Let's say your module is foo. So you have in folder in sites/all/modules/foo/. In there, you have a file named foo.info (with basic information), and another file named foo.module. In the foo.module file, you have this kind of stuff:

```<code>function foo_menu() {
    $items['bar'] = array(
        'title' => 'Some title',
        'page callback' => 'foo_answer_bar',
    );
    return $items;
}

function foo_answer_bar() {
    return 'Baz';
}
</code>```

The principle is to have functions starting with your module name, and ending with specific names, such as _menu. These functions are picked up by Drupal and it handles them. In this example, the returned array tells Drupal to handle the /bar URL, and to display what the foo_answer_bar returns, in the layout.

Anyway. I'm not going further in this example, but what I'm saying is that if you go with Drupal, go with the Drupal way. It will be a little hard in the beginning, but a lot less painful in the long way. Try to keep many small modules rather one big module. The same rules as OOP apply there (SOLID, KISS, DRY).

Body:
tl;dr it's not many include files vs one large file, it's the Drupal way.

Since you want to move onto Drupal, I'd suggest you go with it for real. Here is how Drupal works.

First, in Drupal, the only folder you can touch is sites/.

In sites/default, basically you only touch the settings.php file. Most of your time will be spent in sites/all/. In this folder, there are 2: themes and modules. Your theme will be where you guess it, and the modules (contributed, or yours) will be where you guess it too.

I won't write a tutorial about how to write themes. Basically, you have all your templates in your theme, and the modules use these templates. The big advantage is that you can override the templates used by other modules (which you shouldn't touch either) including the core ones.

Drupal separates modules by features. You, for your own website, usually separate your modules by business features.

I'm not going to write a tutorial about how to write modules, but here is how it basically works:

Your module needs a .module file. Let's say your module is foo. So you have in folder in sites/all/modules/foo/. In there, you have a file named foo.info (with basic information), and another file named foo.module. In the foo.module file, you have this kind of stuff:

function foo_menu() {
    $items['bar'] = array(
        'title' => 'Some title',
        'page callback' => 'foo_answer_bar',
    );
    return $items;
}

function foo_answer_bar() {
    return 'Baz';
}

The principle is to have functions starting with your module name, and ending with specific names, such as _menu. These functions are picked up by Drupal and it handles them. In this example, the returned array tells Drupal to handle the /bar URL, and to display what the foo_answer_bar returns, in the layout.

Anyway. I'm not going further in this example, but what I'm saying is that if you go with Drupal, go with the Drupal way. It will be a little hard in the beginning, but a lot less painful in the long way. Try to keep many small modules rather one big module. The same rules as OOP apply there (SOLID, KISS, DRY).


答:
Because you're using Drupal, you cannot do things the PHP Way, which is probably more correct than the Drupal Way.

Drupal has conventions and limitations. It can make life very difficult if you do not follow those conventions, but if you do follow those conventions then it can be an okay system.

My recommendations are as follows:

Ditch Drupal if you can. There are far better systems out there, without all the incredible limitations that Drupal has. Drupal is a great system for people who aren't very good programmers, but for people used to writing OOP applications in PHP it will make them tear their hair out.

If you can't ditch Drupal, then do things the way Drupal wants you to. In particular, Drupal likes files separated into the directories where it expects to find them - theming, library, database access, and logic files all have a place. In addition, this will make your life much easier when you decide you may want to add namespaces, or if you want to be able to have more discerning includes later in because the include-everything paradigm is making your site slow.

Title: many include files vs one large include file

Body:
The company I work for is in the process of completely overhauling our current intranet site by moving it onto a Drupal framework. One area I am questioning is the number of include files we have. As it exists right now, every single .php page has a corresponding .inc page. There are .inc pages that provide certain functionality, but aren't tied to a specific page. However, each .php page includes multiple files - at a minimum, it will load the .inc page corresponding to it, and a few general scripts. This makes trying to find a function definition a nightmare when debugging.

My options right now seem to be the following:

1)Keep using this same system, but make it part of our convention to include a commented line stating where the function is defined
2) Consolidate all the include files into one large file. This would include class definitions, function definitions, everything. My concern here is that this file would get monolithic in a real big hurry. However, it would have the advantage of keeping all function definitions in one place.

I don't like either option to be honest. My goal is to reduce dependencies and make our code readable and easy to navigate. What is our best method to handle this problem?

I should also state that this is very much legacy code - it hasn't been refactored since it was created in 2003-2004. Just to give you an idea what I'm working with, there is a lot of php echoing html:

```<code>printf("<center>\n");
printf("<table>\n");
printf("<tr>\n");
printf("<td align=left>Select Division:</td>\n");
printf("<td><select name=\"div\">\n");
printf("  <option value=1 \"selected\">Division1\n");
printf("  <option value=2>Division2\n");
printf("</select></td>\n");
printf("</tr>\n");
printf("<tr>\n");
printf("<td align=center colspan=2><input type=\"submit\" value=\"Next->\"></td>\n");
printf("</tr>\n");
printf("</table>\n");
printf("</center>\n");
</code>```


问:
Could applications build in Xamarin possibly be banned from App Store by Apple?
Consider having restricted man resources and thinking about using Xamarin Studio for building cross platform application. Will you be afraid of Apple trying to ban all applications NOT developed by xCode? I mean in future. It is obviously not banned now.  </p>

<p>I am just asking this because I heard this on a meeting today as argument of not using Xamarin studio. I am not an expert in this area but very curious because it sounds odd. The application should be banned because of some kind of generated code which is always there when building app using Xamarin.  </p>

答:
Apple is not gonna ban an application if the application was developed outside of Xcode, however apple is gonna ban an app that doesn't follow the guidelines so if the tool you are using to develop applications creates code that comply with the apple guidelines you are pretty much safe.

https://developer.apple.com/appstore/guidelines.html

Check them if you are registered as a developer.


答:
No, this is not true. Apple will not ban Apps for compiling in Xamarin.

This is a myth that might have been spurred by Apple's history to revoke HTML5 Apps when the store first opened. Since then Apple is now accepting those types of Apps, and has been for a long time. Keep in mind that Facebook (one of the stores most popular apps) was once written in HTML5.

Anyone who is advising you that Xamarin is not an option because it will get banned by Apple has no clue what the app requires are for the store.

Follow Apple's Guidelines and you'll be fine.

https://developer.apple.com/appstore/guidelines.html

Title: Could applications build in Xamarin possibly be banned from App Store by Apple?

Body:
Consider having restricted man resources and thinking about using Xamarin Studio for building cross platform application. Will you be afraid of Apple trying to ban all applications NOT developed by xCode? I mean in future. It is obviously not banned now.  </p>

<p>I am just asking this because I heard this on a meeting today as argument of not using Xamarin studio. I am not an expert in this area but very curious because it sounds odd. The application should be banned because of some kind of generated code which is always there when building app using Xamarin.  </p>


问:
MVVM ViewModel and Commands
I need a bit of help to understand the relationship between a viewmodel and a command, and the responsibility of the viewmodel.

I'll try to give an example (using Caliburn Micro).

I have a viewmodel class, a command class and a view with a Save button.

```<code>public class EditViewModel : Screen
{
    public bool CanSave
    {
        get { return IsDirty; }
    }

    public void Save()
    {
        var command = new SaveCommand(this); // command gets reference to VM
        command.Execute();
    }
}

public class SaveCommand
{
    private readonly EditViewModel _viewModel;

    public SaveCommand(EditViewModel viewModel)
    {
        _viewModel = viewModel;
    }

    public void Execute()
    {
       var work = _viewModel.Work;
       ..
       _viewModel.IsDirty = false;
    }
}
</code>```

When the user click Save. Save() method is called and spins up a command that saves the work.

Now my question is, should the command have a reference to the viewmodel?

No) The viewmodel will have to pass the work to the command, which will have to pass the save result back to the viewmodel, which will update itself.

Yes) The command needs a reference to the viewmodel and properties needs to be public set-able.

No seems like the cleanest way, but also requires extra work, when the work or result aren't a simple bool or similar.

I guess the root it all is. What is the relationship between a viewmodel and it's command and the responsibility of the viewmodel ?

Is there a strong 1:1 "friend" relationship between the view-model and it's command, where code has just been moved to another class. So there is nothing wrong with the command having direct access to the viewmodel.

Another understanding, the viewmodel is a very simple class, almost only with properties and contains little logic. So the logic should be in the command.

Or the viewmodel is pretty smart and should contain application-logic. Commands are really only needed when there are either too many in one viewmodel or they are a bit complicated otherwise the command code can stay in the viewmodel.

I'm just rambling I guess, please help me out to understand the viewmodel and what it's responsibility is?

答:
MVVM inherits directly from the original Smalltalk MVC pattern as defined by Trygve Reenskaug. Just like MVC is highly misunderstood, MVVM is as well. In the original definition, MVC consisted of an conceptual model (which we refer to nowadays as a Domain Model) that contains the data and logic that powers an application, a View which provides a visual representation of that conceptual model, and a Controller which listens to events on the view and handles them as operations within the Model.

What people forget is that the Smalltalk environment was practically the first GUI in existence. This is the very project at Xerox that Jobs "emulated" for the Lisa (and which Microsoft later leveraged for Windows). Smalltalk had a very low-level user interface system, similar to programming the Win32 API directly. The controller was responsible for listening to the message pump and converting the messages that came to the UI into logical operations. There were no widget libraries when the MVC pattern was first conceived.

Fast forward a few years and Smalltalk is a commercial product (VisualWorks) with widgets and a new pattern has emerged: MMVC, this is MVC with two models: the Domain Model which is what we understand it to be; and the Application Model which more or less is a model specifically for the application itself, containing concepts that are important to the application but not to the domain.

Let me point to an interesting point in the C2 Wiki topic on MMVC (emphasis mine):

So what, you say. Well, here's what. As a point of general principle, people who talk about MVC architecture (such as people in the J2EE and JSP communities) should take it upon themselves to understand the historical meaning and implications of the terms they use, so as to eliminate confusion about WhatsaControllerAnyway, and to be aware that ModelViewController often means ModelModelViewController in the original Smalltalk implementation of the paradigm. In fact, a case could probably be made that many of the responsibilities allocated to the "controller" (in the Jacobsonian connotation of the term) were probably allocated to ApplicationModels in ModelModelViewController architecture.

The MMVC architecture gave the application model responsibilities that were normally assigned to the controller. Because of the introduction of widgets in VisualWorks that knew things like "I'm a button and someone clicked me". Controllers did not need to contain as much logic that they used to. The dispatch of operations gravitated toward the Application Model and away from the Controller.

MVVM is MMVC without a separate controller. The ViewModel should contain logic within it, but only enough to interpret a command and dispatch it to the Model for further handling. As I mentioned before, Caliburn does a lot of wiring for you by convention. So instead of having to register a relay command and have it resolve to the method, Caliburn looks for a method on your ViewModel called Save and wires up a command for you that is registered against the Button with an X:Name of Save, pointing it to your Save method.

Title: MVVM ViewModel and Commands


问:
What is it called when a website URL replaces WWW with something else, and what purpose does it serve?
What is it called when a website has another word in place of where www usually goes? For example, images.google.com vs google.com/images. I know the latter is a file on the server that the browser downloads, but what exactly is the purpose of the former? It would be helpful to know what this is called.

答:
This is is called a subdomain.

Subdomains can be routed via the cname entry to a different server so that when the user types in foo.bar.com, the nameserver for bar.com is examined, which reveals the IP address for the foo subdomain.


答:
Merging the PHP files into one will only provide a minor performance improvement, if any, especially with APC installed or with PHP 5.5's optimizer.  Drupal's primary PHP performance flaw is its global functional layout and the fact that hundreds or thousands of function calls are required for each page.  I recall Zend or another organization did a thorough analysis a while back.

If you're using Drupal, do not modify the core by merging PHP files or any other changes.  That would make future upgrades and patches incredibly difficult.  Instead write your modules as efficiently as possible and focus on other performance improvements, like caching and page rendering.


答:
The host name www is a host name.  It makes it convenient for people to know where to go for a given service, and as a convention, just entering the domain name (for example google) in many browsers, the browser will go to www.domain.com.

However, this points to a host (load balanced it may be), but it points to one server (-ish, yes, there's dns round robin too).  This can cause significant traffic to one server, which can be a bad thing.

It is a standard approach to split the dynamic content and static content into two parts and host the static content on a CDN (Content Delivery Network).  This requires pointing dns to a different server.  As such, the host name for the dynamic content cannot be the same as the static content.

Title: What is it called when a website URL replaces WWW with something else, and what purpose does it serve?

Body: What is it called when a website has another word in place of where www usually goes? For example, images.google.com vs google.com/images. I know the latter is a file on the server that the browser downloads, but what exactly is the purpose of the former? It would be helpful to know what this is called.


答:
This is usuall accomplished by a url redirect. No page is ever downloaded. Your browser requests the /images resource from the web server (sitting at google.com). The webserver responds saying "this is not the resource you're looking for" and points your browser to images.google.com (like the Bugs Bunny cartoon where Elmer Fudd asks "the park ranger" which way the wascally wabbit went and "the park ranger" says he went thataway).

Your browser then goes to images.google.com and says gimme what you got (or "get /"). The server responds with the appropriate resource.


答: There was wording in the Developers Agreement for a while to the effect that Apple has the right to reject any code not developed using XCode...but that was targeted specifically at Flash. Xamarin code compiles to native iOS binaries where as Adobe's solution with flash used an interpreter which was slow. That was the meat of the problem.</p>


答:
As Keldon said, subdomain is the term you are looking for.

The purpose is generally/originally was to allow someone to control their own mappings of the names to various IP addresses / servers by providing a domain name server themselves rather than registering a bunch of separate domains.

These days there are a fair number of people that use subdomains on the same IP address to do things with cookie/script scope, or to allow their networking hardware to decide where to route the traffic.

For example, resources embedded withing my pages like photos might be referred to at a subdomain like http://staticresource.xyzcompany.com and in my load balancer I could route those through a cache appliance even though they live on the main http://xyzcomapny.com domain.  This lowers the load on my actual web server and speeds up page loads to the clients without be having to do separate deploys and maintain separate actual servers.

I can also use it as it was originally used and assign a separate subdomain to a separate  IP address on a separate server to http://scaryadmintools.xyzcompany.com then put different rules and settings on that server to increase security while isolating that overhead from the general marketing site at the main domain.


问:
Drawbacks of using pure html in webforms?
I'm maintaining an ASP.NET Webforms 4.5 application for a few months and frankly i'm fed up with server controls. So i switched to pure HTML and Javascript for front end, when creating new content (or fixing the old, assuming there was enough time). Almost (for reusability reasons) all new requests to the server are done via ajax calls.

I'm happy, designers are happy, coworkers prefer it and the client seems to like the new ajax functionality very much.

Are there any drawbacks i should be aware of while doing so?

答:
Overhead

If nothing in your app is going to use the webforms model you are generating a lot of business with events, control/view states and what not that is just in the way and sucking cycles.

Also, if you are doing this now, why ajax and not json?  it is smaller, moves across frameworks better and is supported by more platform agnostic scripts.

If you are doing this in a section of the app, and the rest of the app is more traditional webforms then 100% you can do this, but if you are rebuilding the app with no webforms features then I would consider getting off the webform project type.


答:
Back before the world wide web was invented, servers used the convention of using different host names to access different services. So, for example, if "Example Corporation" had a public server, it was named "example.com". If they provided public ftp access, it would be accessible through the hostname "ftp.example.com". The "ftp" part identified an actual server machine on the subdomain "example.com".

Likewise, if "example.com" provided a public smtp server, it would be "smtp.example.com". If they provided a gopher server, it would be "gopher.example.com". When web servers were invented, pretty much everyone stuck to this convention and named their websites with "www" (eg: www.example.com).

This is simply a convention. Once websites started to proliferate, sites started using their corporate hostname as the main website to make it easier for people to get to the website, so instead of "www.example.com", the simpler "example.com" would be routed to the web server. As traffic increased, they could have multiple servers, with a load balancer sitting between "example.com" and the various servers that power it.


问:
What mistakes in managing software products must be avoided to keep people from hating the vendor?
A previous question about why people hate Microsoft was closed. This is an attempt at a somewhat more constructive question along the same general line. This one is both broader and narrower though. It's more general by being about software vendors in general, not just Microsoft. It's narrower by dealing only with management of software products.

So, what steps should be taken (and/or avoided) in managing individual software products to assure that not only the individual products, but the company as a whole is respected/liked/seen in a positive light?

答:
Poor Documentation and No Desire to Improve It - I'm currently working with a software vendor who is not able to give me any database definitions or diagrams. They actually recommended just calling one of their developers since they are the "walking data dictionaries". Now I'll know why they're not improving he application or fixing bugs; they're too busy explaining what is in the customer table.

EDIT: Now I know why they didn't document this database:

There is a naming convention for field names based on the type: dt=date, s = string/varchar, d=float

There are NO primary keys only unique clustered indexes.

No constraints on any tables.

Most of of the Stored Procedures contain: Select *

All Key fields are string types (least of the problems)

Cursors galore!

They did comment and version number their patches, but that's about it.


问:
Passing an object into a method which changes the object, is it a common (anti-) pattern?
I am reading about common code smells in Martin Fowler's Refactoring book. In that context, I was wondering about a pattern I am seeing in a code base, and wether one could objectively consider it an anti-pattern.

The pattern is one where a object is passed as an argument to one or more methods, all of which change the object's state, but none of which return the object. So it is relying on the pass by reference nature of (in this case) C#/.NET.

```<code>var something = new Thing();
// ...
Foo(something);
int result = Bar(something, 42);
Baz(something);
</code>```

I find that (especially when methods are not named appropriately) I need to look into such methods to understand if the object's state has changed. It makes code comprehension more complex, since I need to track multiple levels of the call-stack.

I'd like to propose to improve such code to return another (cloned) object with the new state, or anything that is needed to change the object at the call-site.

```<code>var something1 =  new Thing();
// ...

// Let's return a new instance of Thing
var something2 = Foo(something1);

// Let's use out param to 'return' other info about the operation
int result;
var something3 = Bar(something2, out result);

// If necessary, let's capture and make explicit complex changes
var changes = Baz(something3)
something3.Apply(changes);
</code>```

To me it seems the first pattern is chosen on the assumptions

that it is less work, or requires less lines of code

that it allows us to both change the object, and return some other piece of information

that it is more efficient since we have less instances of Thing.

I illustrate an alternative, but to propose it, one needs to have arguments against the original solution. What, if any, arguments can be made to make the case that the original solution is an anti-pattern?

And what, if anything, is wrong with my alternative solution?

答:
Yes, the original solution is an anti-pattern for the reasons you describe: it makes it hard to reason about what is going on, the object is not responsible for its own state/implementation (breaking encapsulation). I would also add that all of those state changes are implicit contracts of the method, making that method fragile in the face of changing requirements.

That said, your solution has some of its own downsides, the most obvious of which is that cloning objects isn't great. It can be slow for large objects. It can lead to errors where other parts of the code hold on to the old references (which is likely the case in the codebase you describe). Making those objects explicitly immutable solves at least a few of these issues, but is a more drastic change.

Unless the objects are small and somewhat transient (which makes them good candidates for immutability), I would be inclined to simply move more of the state transition into the objects themselves. That lets you hide the implementation details of these transitions and set stronger requirements around who/what/where those state transitions occur.


答:
Yes, see https://weblogs.asp.net/podwysocki/side-effecting-functions-are-code-smells for one of many examples of people pointing out that unexpected side effects are bad.

In general the fundamental principle is that software is built in layers, and each layer should present the cleanest possible abstraction to the next one.  And a clean abstraction is one where you have to keep as little as possible in mind to use it.  That's called modularity, and applies to everything from single functions to networked protocols.

Title: Passing an object into a method which changes the object, is it a common (anti-) pattern?

Body:
I am reading about common code smells in Martin Fowler's Refactoring book. In that context, I was wondering about a pattern I am seeing in a code base, and wether one could objectively consider it an anti-pattern.

The pattern is one where a object is passed as an argument to one or more methods, all of which change the object's state, but none of which return the object. So it is relying on the pass by reference nature of (in this case) C#/.NET.

```<code>var something = new Thing();
// ...
Foo(something);
int result = Bar(something, 42);
Baz(something);
</code>```

I find that (especially when methods are not named appropriately) I need to look into such methods to understand if the object's state has changed. It makes code comprehension more complex, since I need to track multiple levels of the call-stack.

I'd like to propose to improve such code to return another (cloned) object with the new state, or anything that is needed to change the object at the call-site.

```<code>var something1 =  new Thing();
// ...

// Let's return a new instance of Thing
var something2 = Foo(something1);

// Let's use out param to 'return' other info about the operation
int result;
var something3 = Bar(something2, out result);

// If necessary, let's capture and make explicit complex changes
var changes = Baz(something3)
something3.Apply(changes);
</code>```

To me it seems the first pattern is chosen on the assumptions

that it is less work, or requires less lines of code

that it allows us to both change the object, and return some other piece of information

that it is more efficient since we have less instances of Thing.

I illustrate an alternative, but to propose it, one needs to have arguments against the original solution. What, if any, arguments can be made to make the case that the original solution is an anti-pattern?

And what, if anything, is wrong with my alternative solution?


问:
How fast should a Python factoring script be?
Just how efficient is "good enough" for all intents and purposes? I wrote a script to simply list off all numbers that divide into an input, x, as pairs (i, n//i) and was just curious how efficient I should be going for? what is the acceptable rate at which the script starts to lose its efficiency? This is my code (although advice is appreciated, I just want to give an idea as to how it works).

```<code>import time
print('''This program determines all basic factors of a given number, x, as ordered            pairs, (a, b) where ab=x.
Type "quit" to exit.''')

timer = input('Would you like a timer? (y/n) ')
while  1:
    try:
        x =(input('x = '))
        T0 = time.time()
        b = []
        n = int(x)**0.5
        ran = list(range(1, int(n)+1))
        if int(x) % 2 == 1:
            ran = ran[::2]
        for i in ran:
            if int(x) % i == 0:
                m = (i, int(x)//i)
                b.append(m)
        else:
            pass
    except ValueError as error_1:
        if x == 'quit':
            break
        else:
            print(error_1)
    except EOFError as error_2:
        print(error_2)
    except OverflowError as error_3:
        print(error_3)
    except MemoryError as error_4:
        print(error_4)
    T1 = time.time()
    total = T1-T0
    print(b)
    print(str(len(b)) + ' pairs.')
    if timer == 'y':
    print("%.5f" % total + ' seconds.')
</code>```

some of the results are:

```<code>x = 9
[(1, 9), (3, 3)]
2 pairs.
0.00000 seconds.

x = 8234324543
[(1, 8234324543)]
1 pairs.
0.07404 seconds.

x = 438756349875
[(1, 438756349875), (3, 146252116625), (5, 87751269975), (15, 29250423325), (25,         17550253995), (75, 5850084665), (125, 3510050799), (375, 1170016933), (557, 787713375),   (1671, 262571125), (2785, 157542675), (8355, 52514225), (13925, 31508535), (41775,   10502845), (69625, 6301707), (208875, 2100569)]
16 pairs.
0.88859 seconds.
</code>```

So this program can be pretty quick, but then the speed drops rather rapidly once you get up to higher numbers. Anyways, ya, I was just wondering what is considered acceptable by todays standards?

答:
There is no absolute answer - performance is relative. Ultimately, the answer depends on the needs of the users.

If you're only ever factoring small numbers, and assuming that you aren't trying to do that millions of times a second, speed doesn't have to be very good, especially if they are typing numbers into a console. Anything under a second is acceptable. If they are using a GUI, response times should generally be under 100ms or so to give the feeling that the results are "immediate".

If you're using the code to crunch millions of numbers, or numbers with hundreds of digits, performance is, of course, more important. However, if you're doing that crunching over night, speed becomes less of a factor, assuming the work gets done before people need it.


问:
Could I GPL this code?
I'm working on reviving a C++ codebase that hasn't been touched since '97.

It's academic software for text analysis, and originally it was non-functional, it wouldn't even compile.

I fixed the code so that it works, and added some new functionality of my own.

I'm doing this privately for someone else, and they will pay me over a student contract. I signed nothing with them, so ultimately, my work belongs to me. Given that they agree (I don't want to be rude), would I be able to relicense this code under GPL, and post it on a site like GitHub?

The current license is as follows:

Copyright (C) 1997, Carnegie Mellon University.  All rights reserved.
  This software is made available for research purposes only.  It may be
  redistributed freely for this purpose, in full or in part, provided
  that this entire copyright notice is included on any copies of this
  software and applications and derivations thereof.

This software is provided on an "as is" basis, without warranty of any
  kind, either expressed or implied, as to any matter including, but not
  limited to warranty of fitness of purpose, or merchantability, or
  results obtained from use of this software.

Seems like I would have to include that notice as well.

答:
No, you can not distribute your revived version of the project under the GPL license.

The current license does not grant you the right to re-license or sub-license the code, which means that the original code must remain under this license.

Your own code, you can copyright with any license you like, but the GPL has the condition in it that its conditions must apply to the entire software. One of the conditions of the GPL is that you can't restrict who can use the software. As the original license does have such a restriction, it is incompatible with the GPL. The result is that you can not distribute a codebase that uses both licenses for parts of it.

The only way out of this is to contact the copyright holders of the original code and ask them if they are willing to release a version that is under a more permissive license.

Title: Could I GPL this code?


答:
IMHO a lot of computer science programs leave many students wandering down there in the weeds. These programs never quite communicate the big picture of what science of computation is all about. The students enter the industry, grappling with how to apply the concepts they have learned, with little insight into how they relate to the real world.

I would say that the heart of science of computation is the ability to reason about computation. And you learn various methods and techniques to do this, and apply them to abstracted problems, that are prototypical primitives found in many real world problems. The trick is to spot these prototypical primitives in the real world, and then reason about things like correctness, complexity, time etc., which, you may agree, are real issues that you need to worry about. Insight into how the parts behave, frequently gives you insight into how the whole behaves. And the same general methods and techniques can also be applied to the whole, just not with the same rigorousness that is afforded to smaller, well abstracted, well defined parts. But in the end, the science of computation, endows you with the ability to make reasonable decisions about how to arrange your computation, with real insight into how it will behave under various conditions.

Title: Is big-O really that relevant when working in industry?

Body:
In every interview I have been in, I have been quizzed on mathematical analysis of complexity, including big-O notation.

How relevant is big-O analysis to development in industry? How often do you really use it, and how necessary is it to have a honed mindset for the problem?


答:
I am not sure if the proposed new solution (of copying objects) is a pattern. The problem, as you have pointed out, is the bad nomenclature of functions.

Let us say I write a complex mathematical operation as a function f(). I document that f() is a function that maps NXN to N, and the algorithm  behind it. If the function is named inappropriately, and not documented, and has no accompanying test cases, and you will have to understand the code, in which case the code is useless.

About your solution, some observations:

Applications are designed from different aspects: when an object is used only to hold values, or is passed across component boundaries, it is wise to change the object's innards externally rather than fill it with details of how to change.

Cloning objects lead to bloating memory requirements, and in many cases lead to the existence of equivalent objects in incompatible states (X became Y after f(), but X is actually Y,) and possibly temporal inconsistency.

The problem you are trying to address is a valid one; however, even with enormous overengineering done, the problem is circumvented, not solved.


问:
Are #regions an antipattern or code smell?
C# allows the use of #region/#endregion keywords to make areas of code collapsible in the editor. Whenever I do this though I do it to hide large chunks of code that could probably be refactored into other classes or methods. For example I have seen methods that contain 500 lines of code with 3 or 4 regions just to make it manageable.

So is judicious use of regions a sign of trouble? It seems to be so to me.

答:
If you have regions IN code you certainly have a problem (barring the case of generated code.)  Putting regions in code is basically saying "refactor this."

However, there are other cases.  One that comes to mind that I did a while back:  A table with a couple thousand precalculated items in it.  It's a description of geometry, short of an error in the table there will never be an occasion to look at it.  Sure, I could have obtained the data from a resource or the like but that would preclude using the compiler to help make it easy to read.


答:
First of all, this doesn't depend upon the "pass by reference nature of" it depends upon objects being mutable reference types.  In non-functional languages that's almost always going to be the case.

Secondly, whether this is a problem or not, depends upon both the object and how tightly the changes in the different procedures are tied together -- if you fail to make a change in Foo and that causes Bar to crash, then it's a problem. Not necessarily a code smell, but it's a problem with either Foo or Bar or Something (probably Bar as it should be checking it's input, but it could be Something being put into an invalid state which it should be preventing).

I wouldn't say that it rises to the level of an anti-pattern, but rather something to be aware.


答:
when methods are not named appropriately

Actually, that is the real code smell. If you have a mutable object, it provides methods to change its state. If you have a call to such a method embedded in a task of some more statements, it is fine to refactor that task to a method of its own - which leaves you in exact the situation described. But if you don't pick method names like Foo and Bar for the new method, but names which make clear that they change the object, I don't see a problem here. Think of

```<code>void AddMessageToLog(Logger logger, string msg)
{
    //...
}
</code>```

or

```<code>void StripInvalidCharsFromName(Person p)
{
// ...
}
</code>```

or

```<code>void AddValueToRepo(Repository repo,int val)
{
// ...
}
</code>```

or

```<code>void TransferMoneyBetweenAccounts(Account source, Account destination, decimal amount)
{
// ...
}
</code>```

or something like that - I don't see any reason here to return a cloned object for those methods, and there is also no reason to look into their implementation to understand that they will change the state of the object passed.

If you don't want side effects, make your objects immutable, it will enforce methods like the above ones to return a changed (cloned) object without changing the original one.

Body:
when methods are not named appropriately

Actually, that is the real code smell. If you have a mutable object, it provides methods to change its state. If you have a call to such a method embedded in a task of some more statements, it is fine to refactor that task to a method of its own - which leaves you in exact the situation described. But if you don't pick method names like Foo and Bar for the new method, but names which make clear that they change the object, I don't see a problem here. Think of

void AddMessageToLog(Logger logger, string msg)
{
    //...
}

or

void StripInvalidCharsFromName(Person p)
{
// ...
}

or

void AddValueToRepo(Repository repo,int val)
{
// ...
}

or

void TransferMoneyBetweenAccounts(Account source, Account destination, decimal amount)
{
// ...
}

or something like that - I don't see any reason here to return a cloned object for those methods, and there is also no reason to look into their implementation to understand that they will change the state of the object passed.

If you don't want side effects, make your objects immutable, it will enforce methods like the above ones to return a changed (cloned) object without changing the original one.


问:
Why one would commit changes to version control every three minutes?
The frequency of commits depend on two factors:

the developer himself: some developers tend to commit often, others may spend hours without committing,

the current work: the same developer may have to commit very frequently when effectuating risky refactoring operations or similar tasks, and quite rarely when working on other parts of the codebase.

From what I observed, beginners tend to commit one or two times per day on average. Developers with a few years experience are probably committing once per hour on average. Committing every fifteen minutes is probably the best thing to do, but I've rarely seen this commit frequency.

Question:

I've spotted in Google Closure Library logs that it has commits nearly every three minutes from the same developer.

What are the benefits of such high frequency?

Are there consequences on the way the code is written?

Is it related to the fact that at Google, codebase is compiled and tested on servers and so one should commit the code to see if it compiles and passes all the unit and integration tests?

答:
I sure hope I don't see a "recommendation" coming along that the more frequent the commits, the better.

In my opinion, each commit should leave the code base as bug-free as possible, so frequent commits are a not a good thing if bugs (i.e. incomplete features) are being knowingly put into the code base.
Also, I think each commit should ideally represent one feature added (modified, removed), so that the feature can be rolled back by undoing a single change list, without at the same time undoing other features that may be desired. So that argues for commits not being too infrequent.

Of course, do I stick to this? Well, I try to, but if sometimes I don't succeed, it's not cause for dismissal :)  I hope.


答:
One theory would be that each commit represents a roll back point and thus each commit is about having a copy of this version of the code base somewhere so that it can be retrieved if so desired.  This is bit of a quick test cycle as both the changes and some initial tests would be done before committing.

The danger here is that if the place where these commits are being taken as the "production ready" code base, things could be an issue.

On the other hand, one could have a bunch of finished features that are to be merged separately and thus this is merging each feature so that the commit is more of a merging in the changes from somewhere else rather than new development or testing.

Title: Why one would commit changes to version control every three minutes?

Body:
The frequency of commits depend on two factors:

the developer himself: some developers tend to commit often, others may spend hours without committing,

the current work: the same developer may have to commit very frequently when effectuating risky refactoring operations or similar tasks, and quite rarely when working on other parts of the codebase.

From what I observed, beginners tend to commit one or two times per day on average. Developers with a few years experience are probably committing once per hour on average. Committing every fifteen minutes is probably the best thing to do, but I've rarely seen this commit frequency.

Question:

I've spotted in Google Closure Library logs that it has commits nearly every three minutes from the same developer.

What are the benefits of such high frequency?

Are there consequences on the way the code is written?

Is it related to the fact that at Google, codebase is compiled and tested on servers and so one should commit the code to see if it compiles and passes all the unit and integration tests?


答:
Depending on how much history-rewriting someone's process does, it's not always possible to tell how the commits in a DVCS were actually timed.  Your linked example project uses MOE, which is an automated way to maintain a project as a combination of open and closed source.  The bursts of commits likely come from use of that automated tool to scrub internal commits to make them public.

Another reason for unusual commit patterns might be a maintainer applying a bunch of patches from email or something.

I've occasionally made very close commits when I'm doing something relatively rote, like fixing a bunch of coverity issues.  I've heard of TDD practitioners doing a commit between every red/green/refactor cycle.  I've heard of paranoid people setting up automatic commits as a sort of autosave.  I'm sure there are other reasons I'm unaware of.

Frequency of pushing is another matter entirely.  The rule there is you should be confident it won't cause other people problems.  I don't think you could be reasonably confident with three minutes between pushes.


问:
Safely fixing production database data
Bugs happen and sometimes data has to be fixed in production. What is the safest way to go about this from a big company standpoint? Are there tools that can help? Here are some considerations driving this requirement...

We need to log who ran the query and what they ran

Ideally we need to give the person access to only run queries against the tables of interest and only for a short time

Whatever is running the queries needs to have some smarts about it to not allow long running and locking SQL to run without explicit permission

This process needs to be DB agnostic or at least understand DB2, Oracle, and SQL Server.

We are trying to reduce the risk of ad-hoc prod fix-up queries from doing the "wrong thing" and at the same time add some security/audtis to the process. Thoughts or Ideas?

答:
re: MainMa's answer...

There is a bug in the software product which causes it to stop working
  when it detects what it thinks being some data inconsistency in the
  database,

How do you know it's a "bug"? The data is inconsistent according to the rules the software product developer laid out.

All developers who could potentially fix the bug in the application
  are unreachable,

The company is currently losing thousands of dollars per hour (let's
  say $6 000, which means $100 per minute),

Apparently a loss of $100/minute is not important enough to the company management for them to locate and insure that competent developers return to fix their mistake and help you restore the database.

The bug is affecting several tables, one of which is huge, and
  concerns only the data itself, not the schema,

All database problems "concern" the schema. How the schema is designed is what is going to determine how you solve this problem.

In order to circumvent the bug, you should experiment a bit with the
  data, which involves both removing and changing it,

That's what your staging database is for. You may need to repopulate it with "corrupted" data from the production database right after you take a full online backup of production.

The database is large and it would take three hours to take or restore
  the backup,

Then you better get that started right away so it can run while you're analyzing the problem, developing your correction scripts, testing and refining them along with the developers and other DBAs helping you.

The last full backup was taken three weeks ago; there are also daily
  incremental backups, and the last daily incremental backup was done 14
  hours ago,

You don't have at least daily full online backups? You're screwed. But you're probably used to that. Good thing that full backup you started above is running. Be sure management tracts every minute of the costs that could have been avoided with daily online backups.

Database backups are assumed reliable; they were severely tested,
  including recently,

Excellent! Then you might not have to restore the database more than once.

Losing 14 hours of data is not acceptable, but the loss of one to two
  hours of data is,

Under the scenario you've described, all bets are off. This is an "information disaster management" situation. A good thing for management to be doing throughout this is documenting the costs that could be avoided in the future with prpoer backups and recovery procedures and resources.

The staging environment was lastly used six months ago; it seems it is
  not up to date, and it may take hours setting it up,

If your backup system supports online backups (i.e. database fully operational during the backup), then you can do the extract to repopulate the staging database at the same time if you have sufficient hardware resources to avoiding slowing down the backup.

The database is Microsoft SQL Server 2008 Enterprise.

Harder to do all this but not impossible. Good Luck!

Title: Safely fixing production database data


答:
This terminology dates back to paper and accounting.
Records are also relevant when describing a "fetchable" part of linear media, such as magnetic tapes.

I'd say that a record hints toward the basic fetchable data unit for storage, and a row hints at a part of a report (often generated from records).
Conceivably, multiple records can be combined in a single row and vice versa.

The subtle difference may or may not be of consequence to your RDB system, but I wouldn't say that the words are 100% synonymous.
It's like getting into a discussion about the difference between up/downloads and streaming.

Title: Is it a row or a record (or a tuple)

Body:
If I look at a database table for editing - is it made up of rows or records?

If I write some sql and then look at the result is this made up of the same elements as the answer to 1.?

Is it the case that they are all rows but in very specific circumstances they are also records?

EDIT

A recent article by Itzik Ben-Gan prompted my question and I see quite a discussion on dba.stackexchange.

In that article Aaron Bertrand brought up the same Itzik quote from his "Training Kit (Exam 70-461): Querying Microsoft SQL Server 2012"

As an example of incorrect terms in T-SQL, people often use the terms
  “field” and “record” to refer to what T-SQL calls “column” and “row,”
  respectively. Fields and records are physical. Fields are what you
  have in user interfaces in client applications, and records are what
  you have in files and cursors. Tables are logical, and they have
  logical rows and columns.


答: I'd argue there's little difference between A.Do(Something) modifying something and something.Do() modifying something. In either case, it ought to be clear from the name of the invoked method that something will be modified. If it's not clear from the method name, regardless of whether something is a parameter, this, or part of the environment, it should not be modified.


问:
Is an atomic action supposed to be deterministic?
I was reading about the at most once property that defines what an atomic action is and I've been curios about this example:

```<code>x = 0, y = 0
x = y + 1 || y = y + 1
</code>```

If we use the 'at most once' definition, we can say that, indeed, x = y + 1 is atomic because

y is only referenced in an another thread and

x is not being read by any thread

But the result of this action is not deterministic, it could be 1 or 2 depending on which operation is being computed first.

I might be wrong from the start, isn't atomicity suppose to grant some kind of determinism?

答:
Atomic comes from the greek word "Atomos" which means indivisible.
In computer science this commonly refers to an operation which can only ever succeed or fail, or a datatype that can be fully read or written without failure.

In any sufficiently complex device, such as the realm of programming, there are any number of failures modes which aren't accounted for (such as sudden power outages, RAM failure etc.)
This means that any kind of "Atomic" behaviour in modern computing is going to have multiple well defined limits when it comes to determinism. Modern CPUs purposely don't always fully account for time due to caches etc. (we have interrupt timers for that) and this issue is magnified as race conditions when it comes to thread interaction (like in your example).

Many modern RDBs offer the practical illusion of Atomicity using transactions on SQL queries, these guarantees are only offered in so far, that, if it is possible to roll back the changes, the DB will do so. If any part of the system is disrupted, all bets are off.

Of course, it is possible to make hardware and software systems which may come closer to a pure definition of Atomic processes. Think of the "black box recorder" in Airplanes.


问:
Using a Public Property AND a Public Field
Where I work, using Properties are discouraged. We have code generation tools to "speed things up". All object data ends up being Public fields. If you request properties anyway, you get something like this:

```<code>Public sFoo as String

Public Property Foo as String
  Get
    Return sFoo
  End Get
  Set(ByVal value as String)
    sFoo = value
  End Set
End Property
</code>```

I can't think of a reasonable argument to do this. Are there any good reasons to use both a Public Property with a Public Field?

答:
No.

There's no good reason for this.  It:

Confuses other programmers by doing something that makes no sense,

Exposes the innards of your class unnecessarily,

Provides two entry points for the same thing,

??

Use Auto-Implemented Properties instead.


问:
MVC Architecture -- How many Controllers do I need?
I have been coding for a while, but mostly scripts and simple applications. I've moved into a new role where it is all about developing Web Apps and using a proper MVC architecture, so I am desperately trying to learn about all that very quickly.

I hope this question is not too similar to "Best Practices for MVC Architecture" but as I am going through a few different tutorials, I noticed that some have multiple controllers for different things.

How many controllers does a single web app need?

I realize this would be difficult to answer without an example so I'll provide one:

Application:

User logs in.

User can do one of three things:

a)  Upload a file (stored in a mongodb database with meta data).

b)  Search for a file.

c)  Log out.

My question is a general one, but I gave the example to help out anyone trying to answer.

答:
In general you may say that every MODEL has its own CONTROLLERs and dedicated VIEWs.
By saying general I mean that this is the best practice.

application Aspects (like user management) should be translated to application service and need to be called by the controller it self, or to wrap your controller (using attributes that make the controller functionality "visible" according to request user role, for instance).

Remember that all controllers should basically handle CRUD operations over model and use different views for different filters.

In my opinion one of the major advantages of MVC as pattern is that it deliver the best way to tie models and views.

About the example you added:
I would create 2 controller: one for the all user login operation (register, login, logout etc.) and the second for file operations (Upload and search).
note that the first should also be backed up with some Aspect related to the Login functionality and the second is ordinary controller