答:
First, many compiled implementations of programming languages have builtins or intrinsics, that is functions which are known to the compiler and which are compiled in a special way.

For C or C++ compiled by GCC  there are many builtin functions. Ocaml has external functions, etc....

Then, some implementations offer some way to use the underlying framework. So GCC (which is translating to assembler) is able to embed assembly code, MELT (translated to C++) is able to embed C++ code (using code_chunk, defprimitive, defcmatcher etc...), and so on.

At last, standard libraries of the languages are using some underlying implementation layer. In particular, C standard libraries are generally using syscalls to invoke elementary operations provided by the operating system kernel.

BTW, using a free software operating system (like GNU/Linux) and compiler (like GCC) and library (like GNU libc or musl-libc) helps a lot, since you can always study the source code of free software.

Read also about homoiconic languages, reflection, ....

Title: How are basic functions implemented in a programming language if they are not built in?

Body: The lowest levels of a programming language's library functions are always obscure and often have no code that looks like it even remotely does anything. Some languages have these functions like getting substrings, converting between data types, querying a variable's data type, and so forth implemented as part of their standard libraries, but I can't imagine how these low-level functions can be expressed using said language. How are these things achieved? I'm not asking for how it is done with all languages, but rather what the general method of doing this is conceptually.</p>


问:
how can i make a program written in c++ with qt to text and graphic mode?
I have seen in many programs, almost only on linux, that when you run the program with a graphical manager(Clicking the executable) the program runs in a graphical window and when you run it from the terminal it runs on text mode.
I want to know how  to do that.
Does anyone know how?</p>

答:
It is operating system specific.

On Linux with X11, you could simply use the fact that DISPLAY is an unset environment variable outside of graphical desktop interfaces (or test for the success of XOpenDisplay);

You might also use isatty(3) on STDIN_FILENO(which is 0) to test if stdin is a terminal (but you could also open /dev/tty and see if it fails, cf tty(4))
so simply code

```<code>if (getenv("DISPLAY"))
   startmyGUIapplication();
else if (isatty(STDIN_FILENO))
   startmyterminalapplication();
else
   error(); // application started outside, e.g. from `crontab`
</code>```

Regarding Qt, I guess that QApplication would fail to be constructed if not used in a GUI, Or its exec function would fail.

PS. On Linux with a Wayland desktop (or on MacOSX with Quartz), I don't know how to do that, but I am sure there is a simple solution.

ContentLicense: CC BY-SA 3.0

Body:
It is operating system specific.

On Linux with X11, you could simply use the fact that DISPLAY is an unset environment variable outside of graphical desktop interfaces (or test for the success of XOpenDisplay);

You might also use isatty(3) on STDIN_FILENO(which is 0) to test if stdin is a terminal (but you could also open /dev/tty and see if it fails, cf tty(4))
so simply code

if (getenv("DISPLAY"))
   startmyGUIapplication();
else if (isatty(STDIN_FILENO))
   startmyterminalapplication();
else
   error(); // application started outside, e.g. from `crontab`

Regarding Qt, I guess that QApplication would fail to be constructed if not used in a GUI, Or its exec function would fail.

PS. On Linux with a Wayland desktop (or on MacOSX with Quartz), I don't know how to do that, but I am sure there is a simple solution.


问:
Are web sockets a browser feature or supplied by a specific OS version?
Are web sockets a web browser feature, developed and evolving as the browser developers want, or this feature dependent on the OS version?

For example, can I use this feature in JavaScript in IE and other browsers from Windows 8 only?

If it is a browser feature, which versions is it stable in Chrome, Mozilla, Opera?

答:
webSocket is implemented in browsers (not in the underlying OS).  It is built on top of TCP/IP which comes from the OS.

You can see which versions of which browsers support webSockets here:http://caniuse.com/#feat=websockets


问:
What are useful metrics for source code?
What are useful metrics to capture for source code?

How can metrics, like for example (Executable?) Lines of Code or Cyclomatic Complexity help with quality assurance or how are they beneficial in general for the software development process?

答:
To the best of my knowledge, the number of bugs found directly correlates with lines of code (probably churn), modulo language, programmer, and domain.

I don't know of any other straightforward and practical metric well-correlated with bugs.

One thing I'd like to do is start running the numbers for different projects I'm on -
Test Coverage :: kLOC, and then discuss "perceived quality" to see if there is a correlation.

ContentLicense: CC BY-SA 2.5


问:
Algorithm that generates a group of men and women who are each interested in everyone from the other gender
In my dating app, I need to compile lists of men and women where all of the men in the list are potentially interested in all of the women in the list, and vice versa.

That is, in a list of 10 men and 10 women, any given women matches the criteria set by all 10 men and any given man matches the criteria of all 10 women. I don't want any men in the group who aren't of interest to all the women, and vice versa.

The criteria is very simple. The properties for each person are:

Age

Interests (array)

Desired partner's age range

Example: if Man1 is described as

31

Cooking, tennis, math

20, 31

A 29 year old woman who likes tennis and is looking for a man between x<=31 and y>=31 is a match.

I've been thinking about how to implement this, but it's unlike any simple data fetching/manipulation I've ever done. The reason is because rather than being a single query, (i.e. get all people where gender=female AND age>=low & age<=hight etc..) the query has to be checked anew each time when a new person is added. That is, each time a new man or woman is added to the list, all subsequent people have to be checked against them too (because I don't want to add a man who one or more women don't find interesting).

Does anyone have any ideas on a strategy for implementing this algorithm.

As an aside, I am using MongoDB, so if comfortable for you, it would be great to speak in those terms.

Thank you very much in advance!

答:
In other words, the whole database would have to undergo some major reindexing (recalculating all the matches) every time a new person is added.

The strategy in such cases is to maintain a smaller, cached dataset ("delta"), in this case containing new people added throughout the day, which gets merged into the database on a daily basis - could be at night, where the server isn't so busy.

How would it work in your case?

Every new person is added into delta - sort of a waiting room. For these people, we can calculate their "top 10" matches immediately.

Old users don't get to see new users just yet. (Or you might recalculate 10 top matches only for people who popped up as top 10 matches for that new person, as that shouldn't be too expensive in terms of resources).

Every night delta gets merged into the main index and everybody's matches get recalculated.

The tradeoff here is that new people may not appear immediately in search results.


问:
Is it a good idea to contextually name predefined functional interfaces?
I am currently working with Java 8 and using functional interfaces a lot. I often find myself writing code like this:

```<code>public interface MessageHandler extends Consumer<String> { }
</code>```

Is this a good idea or an indicator of me abusing functional interfaces to make Java feel more like C#?

Edit: Maybe to expand a little:

```<code>public class MessageGenerator {

    public void registerMessageHandler(MessageHandler handler) {
    // [...]

    public interface MessageHandler extends Consumer<String> { }
}
</code>```

答:
Anything that makes code more readable while keeping the semantics unchanged is good. Whether or not this is due to your experience with another language is irrelevant - programming languages are tools to achieve ends, not values in themselves.

Therefore, if your way of writing things reads better than using the bare language-provided types, do it. (Things could be different if adding another layer of types affected the efficiency of the code that is actually run, but I'm fairly certain that in this case it doesn't.)


问:
Queue rescheduling naming convention (Command pattern)
For my project I'm creating a queueing mechanism based on the Command Pattern, which can execute one of a number of jobs. Jobs can add other jobs to the queue or can be added by a human. Most of the jobs are done after executing once, but certain jobs will need to be rescheduled at a later time.

I decided I want to create a seperate dataset about jobs that need to be rescheduled and create a seperate process that loops over these at a set interval to add new jobs to the queue.

I'm stuck at what's the right naming convention for my dataset and (looping) process for rescheduling jobs. My thinking is that it's going to look something like this:

My datasets:

Job (in the queue) -
Information about which job to execute.

Incident Report -
Any result that needs to more attention gets logged here.

Result (multiple) -
All data that resulted from the executed jobs.

Scheduled Job (What to call?) -
Information about a job that needs to be executed in the future and the timestamp my process needs to add the job to the queue.

My objects:

Client -
A object that gets a job from the queue and maps to a specific command class and passes it to the command invoker.

Command (multiple) -
Contains logic to of the job and job data to pass around dependencies.

Command Invoker -
Gives the final call to execute the command and removes it from the queue afterwards. This class will probably also be responsible for updating data about scheduled jobs.

Job Scheduler -
A independent object that can add jobs at any time from a job that's being executed.

I'm not sure if I need to add the process of rescheduling jobs as a a seperate job or as a different application altogether. I hope somebody can give me some advice of how to go forward.

答:
Scheduled

Technically a scheduled job implies a job scheduler. You talk about writing your own scheduler but normally this would be handled at quite a low level and takes into account things like available resources and job priority, not just when the job wants to be run.

In English, I would say that scheduled implies a timetable.

Deferred

Technically implies that the job is waiting for something, an external service to become available or resources to be freed up.

But again, in English I might be expecting the opposite to be true, deferred referring to the fact that the job is put off until some defined time.

Personally I'd go with the first: scheduled job. You plan on writing something you are going to call a job scheduler and not a deferred job handler, so that makes sense.

PS. I don't know if this would fit with the rest of your system, but have you considered creating threads that wait for the deferral period to pass before checking the queue. Java for example has a Thread.sleep(timePeriod) method otherwise you would still have the computational over head of the thread having to wake up every so often to check what time it was but at least it wouldn't be accessing your data structure each time.


问:
Add file paths to database
I am scanning a directory of files and want to add them to a database. I have two variants:

```<code>for file in walk(basedir):
    files.append(file)
for file in files:
    add_to_database(file)
</code>```

versus

```<code>for file in walk(basedir):
    add_to_database(file)
</code>```

The former has the advantage that if both the database and the scanned dir reside on the same physical disk, jumping between two locations on disk (assuming spindels) is avoided and thus should be faster, at the cost of additional memory consumption.

The latter is much shorter. I am tending towards the latter, adding a note that the database should not reside on the same disk as the scanned dir.

Any thoughts on this?

答:
Premature optimization is the root of all evil. -- Donald Knuth

Any decent operating system is going to solve the jumping-around problem for you, using memory caches of disk blocks.  Solving that problem by accumulating an unnecessary list of filenames creates a new problem of memory consumption - how well will the first version work with 50,000,000 files?  Forget the note, unless your performance tests actually demonstrate a significant impact.

Title: Add file paths to database


答:
I wholeheartedly agree with this:

Interfaces should almost always be named after what they do, not after
  some generic syntactic idea.

(Taken from this answer: https://softwareengineering.stackexchange.com/a/276866/41811)

So, adding a functional interface whose name explains precisely what the underlying Consumer<String> is going to be used for is a very good idea.  It harms nothing, and it improves readability.

Title: Is it a good idea to contextually name predefined functional interfaces?

Body:
I am currently working with Java 8 and using functional interfaces a lot. I often find myself writing code like this:

```<code>public interface MessageHandler extends Consumer<String> { }
</code>```

Is this a good idea or an indicator of me abusing functional interfaces to make Java feel more like C#?

Edit: Maybe to expand a little:

```<code>public class MessageGenerator {

    public void registerMessageHandler(MessageHandler handler) {
    // [...]

    public interface MessageHandler extends Consumer<String> { }
}
</code>```


问:
How important are code formatting guidelines?
Coding standards are common in any software development organization, but how important are they to follow?  I can understand the need for some consistency, but when dealing with simple things like the position of braces, line length, etc., I'm not sure excessively strict standards contribute much to software development.

Isn't it more important that your code is readable, not that it conforms to a predefined standard?  It seems they're more like... guidelines anyway.

答:
Asking everyone to 100% adhere to the same standard code formatting guideline is like asking everyone to collaborate separately on writing a 100 page paper with the same writing style.

Hopefully everyone will write the paper in English (or same language), but different styles will be apparent.  Some will write it well, others not.  Some will use contractions, some will spell the words out fully (example: it's verus it is).  Etc.

I think you touched on the most important points:

It's a guideline

Readability

If you want the code to adhere to the same formatting, like a paper to be in the same writing style, it'll need editing and revising.  The code will need to be cleaned up, reviewed, re-factored, etc.

I've never been in a shop where I was completely happy with another developer's coding style or formatting (at minimal because it's not exactly like mine).  But I'll be content if I can read/understand it and if it's consistent.  Everything else is the sugar on the syntactic sugar.

So to answer your question: somewhat important, but it's certainly not the end of the world if they don't.


问:
Method extraction vs underlying assumptions
When I split big methods (or procedures, or functions — this question is not specific to OOP, but since I work in OOP languages 99% of the time, it's the terminology that I'm most comfortable with) into a lot of small ones, I often find myself displeased with the results. It becomes harder to reason about these small methods than when they were just blocks of code in the big one, because when I extract them, I lose a lot of underlying assumptions that come from the context of the caller.

Later, when I look at this code and see individual methods, I don't immediately know where are they called from, and think about them as ordinary private methods that can be called from anywhere in the file. For example, imagine an initialisation method (constructor or otherwise) split into a series of small ones: in the context of method itself, you clearly know that object's state is still invalid, but in an ordinary private method you probably go from assumption that object is already initialised and is in a valid state.

The only solution I've seen for this is the where clause in Haskell, which allows you to define small functions that are used only in the "parent" function. Basically, it looks like this:

```<code>len x y = sqrt $ (sq x) + (sq y)
    where sq a = a * a
</code>```

But other languages I use don't have anything like this — the closest thing is defining a lambda in a local scope, which is probably even more confusing.

So, my question is — do you encounter this, and do you even see this is a problem? If you do, how do you typically solve it, particularly in "mainstream" OOP languages, like Java/C#/C++?

Edit about duplicates: As others noticed, there are already questions discussing splitting methods and small questions that are one-liners. I read them, and they don't discuss the issue of underlying assumptions that can be derived from caller's context (in example above, object being initialised). That's the point of my question, and that's why my question is different.

Update: If you followed this question and discussion underneath, you might enjoy this article by John Carmack on the matter, in particular:

Besides awareness of the actual code being executed, inlining functions also has the benefit of not making it possible to call the function from other places. That sounds ridiculous, but there is a point to it. As a codebase grows over years of use, there will be lots of opportunities to take a shortcut and just call a function that does only the work you think needs to be done. There might be a FullUpdate() function that calls PartialUpdateA(), and PartialUpdateB(), but in some particular case you may realize (or think) that you only need to do PartialUpdateB(), and you are being efficient by avoiding the other work. Lots and lots of bugs stem from this. Most bugs are a result of the execution state not being exactly what you think it is.

答:
I often see this, and agree that it is a problem. Usually I resolve it by creating a method object: a new specialized class whose members are the local variables from the original, too-large method.

The new class tends to have a name like 'Exporter' or 'Tabulation', and it gets passed whatever information is necessary to do that particular task from the larger context. Then it is free to define even smaller helper code snippets that are in no danger of being used for anything but tabulating or exporting.


答:
I think the answer in most cases is context.
As a developer writing code, you should assume your code is going to be changed in the future.
A class might be integrated with another class, might replace it's internal algorithm, or might be split off to several class in order to create abstraction.
Those are things beginner developers usually don't take into consideration, causing a need for messy workarounds or complete overhauls later.

Extracting methods is good, but to some degree.
I always try to ask myself these questions when inspecting or before writing code:

Is this code only used by this class/function? will it stay the same in the future?

If I'll need to switch out some of the concrete implementation, can I do it easily?

Can other developers on my team understand what's done in this function?

Is the same code used somewhere else in this class? you should avoid duplication in almost all cases.

In any case, always think single responsibility. A class should have one responsibility, it's functions should serve one single constant service, and if they do a number of actions, those actions should have their own functions, so it's easy to differentiate or change them later.

Title: Method extraction vs underlying assumptions

Body:
When I split big methods (or procedures, or functions — this question is not specific to OOP, but since I work in OOP languages 99% of the time, it's the terminology that I'm most comfortable with) into a lot of small ones, I often find myself displeased with the results. It becomes harder to reason about these small methods than when they were just blocks of code in the big one, because when I extract them, I lose a lot of underlying assumptions that come from the context of the caller.

Later, when I look at this code and see individual methods, I don't immediately know where are they called from, and think about them as ordinary private methods that can be called from anywhere in the file. For example, imagine an initialisation method (constructor or otherwise) split into a series of small ones: in the context of method itself, you clearly know that object's state is still invalid, but in an ordinary private method you probably go from assumption that object is already initialised and is in a valid state.

The only solution I've seen for this is the where clause in Haskell, which allows you to define small functions that are used only in the "parent" function. Basically, it looks like this:

```<code>len x y = sqrt $ (sq x) + (sq y)
    where sq a = a * a
</code>```

But other languages I use don't have anything like this — the closest thing is defining a lambda in a local scope, which is probably even more confusing.

So, my question is — do you encounter this, and do you even see this is a problem? If you do, how do you typically solve it, particularly in "mainstream" OOP languages, like Java/C#/C++?

Edit about duplicates: As others noticed, there are already questions discussing splitting methods and small questions that are one-liners. I read them, and they don't discuss the issue of underlying assumptions that can be derived from caller's context (in example above, object being initialised). That's the point of my question, and that's why my question is different.

Update: If you followed this question and discussion underneath, you might enjoy this article by John Carmack on the matter, in particular:

Besides awareness of the actual code being executed, inlining functions also has the benefit of not making it possible to call the function from other places. That sounds ridiculous, but there is a point to it. As a codebase grows over years of use, there will be lots of opportunities to take a shortcut and just call a function that does only the work you think needs to be done. There might be a FullUpdate() function that calls PartialUpdateA(), and PartialUpdateB(), but in some particular case you may realize (or think) that you only need to do PartialUpdateB(), and you are being efficient by avoiding the other work. Lots and lots of bugs stem from this. Most bugs are a result of the execution state not being exactly what you think it is.


问:
What is better repository design?
I have tables that I insert, delete and update, but I read from views.  At times, I may read from the tables as well.  What is a better generic interface for a Repository:

```<code>public interface IViewRepository<T>
{
  //Read queries
}

public interface ITableRepository<T>
{
  //Insert, Update, Delete queries
}
</code>```

or just one repository to handle both tables and views

```<code>public interface IRepository<TTable,TView>
{
  //CRUD
}
</code>```

Is it better to have something like IPersonRepository and ICarRepository and then in the interfaces, make the methods generic such as T GetPerson<T> and T GetCar<T>?

答:
I think the question needs to be split into two parts. Firstly, what is the role of the POCOs representing your database objects, and secondly, how best to structure repositories to deal with them.

In answer to the first question, you seem to have chosen to map your POCOs directly to database objects- one class exactly represents on table, or one view. But there's another option too, which is to have a class represent an entity- the conceptual object that your data describes. For example, instead of a CarView, CarHeaderTable and CarVersionTable (or whatever naming scheme you use), your POCO would just be a Car.

The main pros and cons of these two options as I see them:

Pro-Direct mapping

It's very simple! There's no need to deal with any complexities in mapping database objects to POCOs.

It still provides many of the benefits of an ORM (or a hand-rolled solution involving mapping database objects to POCOs). You still remove repetitive code involving pulling data into and out of DataTables, you still isolate your non data-access code from having to worry about SQL, and so on.

Pro-Conceptual POCOs

Rather than just shield your code from SQL concerns, you get to shield it from persistence concerns altogether (at least as far as your class design goes). Now any code that just wants to deal with a Car can deal with a Car, without having to worry itself about whether this is a Car that's designed to be read or a Car that's designed to be written to, and whether it's just the immutable bits of a Car or just the mutable bits, or both. As your design stands, it doesn't really do anything to address impedance mismatch (Robert C. Martin talks about this here)

You cut down on the number of classes which are really just there to provide the same information in different ways. I don't know what you do currently when you want to add a method (perhaps a simple calculation) to one of these POCOs. Is that banned? Do you duplicate it across all classes representing the same thing? Do you create a CarHelper that does things the Car should really be able to do itself? With a single Car class that's no longer a problem.

If you pick the second of the above two options, this question pretty much goes away. But maybe you've already considered the above, or you do so now and decide that on balance you one to stick with the direct POCO-to-DB object mapping. In that case, you're still left with the question of which option is best.

To start with, as Robert Harvey said, you probably don't want Table and View in your terminology, as it's very specific to databases. Readable and Writeable might be better terminology, for both versions.

Beyond that, I think the best option is the one that suits the consumers of these repositories. Does code which reads usually also want to write, and vice-versa? Then packaging them together, as in the second version, is probably a good idea.

As Eric King alluded to in the comments, starting with a base repository is actually a somewhat backwards way of approaching this- you're starting by creating an inheritance structure designed to deal with common/repeated concerns, without actually having any repeated concerns to deal with!

So my advice would be- create an ICarRepository and add to it as is needed by its consuming code. Do the same thing with IPersonRepository. As these classes grow, you can refactor- do you find that putting the table-related members together with the view-related ones feels like a violation of the ISP (Interface Segregation Principle)? Then split them up. Is there repeated, generic-feeling functionality? Then extract a base Repository<T> (or Repository<TWriteable,TReadable>) class. That way instead of doing design based on guesswork, you'll be creating a design driven by how it's used.

Title: What is better repository design?


问:
Open source License that doesn't require credit
Is there a known open-source license where the user who reuses or redistributes the code is not required to give credit to the author?  This is actually the same as just assuming copyright to the collection but placing the contents on the public domain.

P.S.

For me that is the real "open" and real "free" software, for not only everyone that uses it but also everyone that reads it and contributes to it is not bound to and is free in mind from any conditions that could prevent from them doing anything on the software (including parts of software that already resides within their brains) .  No forced or not-so-obvious or tempted viral injection of philosophies.

答:
It is impossible to give up ownership of copyright in the United States, and most other countries. You have it, whether you want to or not, and you can't give it up, whether you want to or not.

The most permissive thing you can do, is release it under something like the creative commons public domain dedication, usually abbreviated to CC-0: https://creativecommons.org/publicdomain/zero/1.0/

This allows anyone to use the software for anything without any conditions.

Copyright isn't the only intellectual property. You could take out a trademark, which is another form of intellectual property, on the name of your software. A trademark is orthogonal to copyright; they cover different things, and can be mixed and matched any way you like. Things that are covered by trademark law aren't covered by copyright law, the same goes for the other way round.

Reading your comments, it seems that it might be a trademark you're looking for, rather than a copyright license.


问:
When would someone use MongoDB (or similar) over a Relational DBMS?
I'm a bit confused about the whole NoSQL thing and such.
When would you choose to use something like MongoDB over something like Oracle or MySQL?
I don't really understand the "difference" as far as usage goes between them.

From my understanding NoSQL type databases aren't meant to replace RDBMSes, but what exactly are they meant to do?

答:
The immediate and fundamental difference between MongoDB and an RDBMS is the underlying data model. A relational database structures data into tables and rows, while MongoDB structures data into collections of JSON documents. JSON is a self-describing, human readable data format. Originally designed for lightweight exchanges between browser and server, it has become widely accepted for many types of applications.

JSON documents are particularly useful for data management for several reasons. A JSON document is composed of a set of fields which are themselves key-value pairs. This means each JSON document carries its own human readable schema design with it wherever it goes, allowing the documents to easily move between database and client applications without losing their meaning.

JSON is also a natural data format for use in the application layer. JSON supports a richer and more flexible data structure than tables made up of columns and rows. In addition to supporting field types like number, string, Boolean, etc., JSON fields can be arrays or nested sub-objects. This means we can represent a set of sophisticated relations which are a closer representation of the objects our applications work with. Using JSON documents in our database means we don’t need an object relational mapper between our database and the applications it serves. We can persist our data in the right form


答: I think you are looking for bipartite(men/women) complete(all men like all women and viceversa). I would tackle the problem from a graph perspective where each user is a node and two nodes are connected if they are mutually interested. Then you can create a matrix and apply some kind of clustering or graph pattern mining. If you think this can help I can provide links when at home(writing from my mobile). I don't know if MongoDB can solve this problem. </p>

Title: Algorithm that generates a group of men and women who are each interested in everyone from the other gender

Body:
In my dating app, I need to compile lists of men and women where all of the men in the list are potentially interested in all of the women in the list, and vice versa.

That is, in a list of 10 men and 10 women, any given women matches the criteria set by all 10 men and any given man matches the criteria of all 10 women. I don't want any men in the group who aren't of interest to all the women, and vice versa.

The criteria is very simple. The properties for each person are:

Age

Interests (array)

Desired partner's age range

Example: if Man1 is described as

31

Cooking, tennis, math

20, 31

A 29 year old woman who likes tennis and is looking for a man between x<=31 and y>=31 is a match.

I've been thinking about how to implement this, but it's unlike any simple data fetching/manipulation I've ever done. The reason is because rather than being a single query, (i.e. get all people where gender=female AND age>=low & age<=hight etc..) the query has to be checked anew each time when a new person is added. That is, each time a new man or woman is added to the list, all subsequent people have to be checked against them too (because I don't want to add a man who one or more women don't find interesting).

Does anyone have any ideas on a strategy for implementing this algorithm.

As an aside, I am using MongoDB, so if comfortable for you, it would be great to speak in those terms.

Thank you very much in advance!


答:
I don't think it's a big issue, but I agree it's troublesome. Usually I just place the helper immediately after its beneficiary and add a "Helper" suffix. That plus the private access specifier should make its role clear. If there's some invariant that doesn't hold when the helper is called, I add a comment in the helper.

This solution does have the unfortunate drawback of not capturing the scope of the function it helps. Ideally your functions are small so hopefully this doesn't result in too many parameters. Normally you'd solve this by defining new structs or classes to bundle up the parameters, but the amount of boilerplate required for that can easily be longer than the helper itself, and then you're back where you started with no obvious way of associating the struct with the function.

You already mentioned the other solution - define the helper inside the main function. It may be a somewhat uncommon idiom in some languages, but I don't think it'd be confusing (unless your peers are confused by lambdas in general). This only works if you can define functions or function-like objects easily though. I wouldn't try this in Java 7, for example, since an anonymous class requires introducing 2 levels of nesting for even the smallest "function". This is as close to a let or where clause as you can get; you can refer to local variables before the definition and the helper can't be used outside of that scope.


问:
What makes Python more used as an implementation language than the others?
Perl and Python are often compared to each other (let's not forget Ruby), and almost always those discussions will come to the conclusion pretty much anything you can do in one or the other.

Without going into that, I've noticed that Python however, is often used as an implementation language (uhmm, maybe the term here is incorrect technically - a language you use to, for example, enable some degree of scripting in a large application ... Tecplot, Rhinoceros etc.; these are from the scientific area; there are others surely) and Perl never (well, to my knowledge at least).

So I was wondering - what makes Python more suitable for something like that? What particulars make a language more suitable to be implemented as part of a larger app. for scripting in general? Is it only that that wasn't so common 10 years ago (scripting in applications), and Python is just at its peak at the moment, ... or something else?

答:
Python is pretty easy to embed and has good documentation on how to do it.

Also, Python has a pretty approachable syntax, even for new users. Perl tends to have obtuse syntax making it less approachable for new users.

Another common language for embedding is Lua. It is known to be fairly easy to embed and has low operating overhead.

Python is well known and used in the Scientific community thanks to SciPy and NumPy, which may influence your particular observations.

ContentLicense: CC BY-SA 4.0


问:
Ideal way of updating app's views when data changes
Okay this is not platform specific question. But any answer related to iOS,Android or Windows Phone will help. So I am building a chat application (yes another one) but I am really confused about how you pros handle GUI update when a chat message arrives. I am not really concerned about performance issues but how devs update various part of app's GUI showing updated data.

For example Whatsapp has one master list where all the open chats are listed and then a separate chat display window(activity in case of Androids).

So when some message arrives, how do they update both views at the same time? Like if I am already chatting with someone and I receive a new message, the list gets updated as soon as the message arrives. I get this part but how is master list updated. Are they constructing whole of master view again after each and every single message? I just wanted to know the ideal mechanism to deal with this scenario.

答:
Fundamental concept:

At a low(er) level, the UI element is subscribed to events coming from the data collection (array, list, dictionary, etc...) that holds the data that is changing.  When the collection changes, it signals an event to the effect of "My data has changed" and subscribers to that event handle it accordingly.  As you described in your example, that's when the visual representation of the message list is updated.

Concept in practice:

Most languages / frameworks provide for something called data binding.  Instead of your manually having to subscribe the UI element to the events from the data collection, you bind the UI element to the data collection instead.  The framework then handles the boilerplate code involved with signaling an event and updating the UI element.

The MVVM Pattern is a good place to start in understanding how data binding works in practice.  Microsoft also provides additional specific guidance on the MVVM pattern.

Data binding is a fairly prevalent practice across a variety of platforms:

iOS data binding approach

AngularJS data binding

Xamarin's implementation

Android and MVVM for the MS crowd


答:
The core concern here should probably not be disk costs, but correctness and intent.

If you intend to do more than just insertion of the files in the list, you may want to prefer the accumulate-then-insert solution, as that gives you a consistent list of files to do further work with. It also lets you use bulk insertion functionality to your database instead of inserting exactly one file at a time. This also limits the duration of transactions and locks, as the insertion phase is separated from the gather phase.

If you on the other hand interleave calls, the database starts working earlier. A highly efficient approach would be to run two tasks, one that generates a sequence of entries for the other to consume as it goes, as slack in the generation can be buffered in the sequence.

In the end, just misquote Knuth and do what works. It's probably not a bottleneck.

Title: Add file paths to database

Body:
I am scanning a directory of files and want to add them to a database. I have two variants:

```<code>for file in walk(basedir):
    files.append(file)
for file in files:
    add_to_database(file)
</code>```

versus

```<code>for file in walk(basedir):
    add_to_database(file)
</code>```

The former has the advantage that if both the database and the scanned dir reside on the same physical disk, jumping between two locations on disk (assuming spindels) is avoided and thus should be faster, at the cost of additional memory consumption.

The latter is much shorter. I am tending towards the latter, adding a note that the database should not reside on the same disk as the scanned dir.

Any thoughts on this?


答:
Many languages let you nest functions like Haskell.  Java/C#/C++ are actually relative outliers in that regard.  Unfortunately, they are so popular that people come to think, "It has to be a bad idea, otherwise my favorite 'mainstream' language would allow it."

Java/C#/C++ basically think a class should be the only grouping of methods you ever need.  If you have so many methods that you can't determine their contexts, there are two general approaches to take:  sort them by context, or split them by context.

Sorting by context is one recommendation made in Clean Code, where the author describes a pattern of "TO paragraphs."  This is basically putting your helper functions immediately after the function that calls them, so you can read them like paragraphs in a newspaper article, getting more details the further you read.  I think in his videos he even indents them.

The other approach is to split your classes.  This can't be taken very far, because of the annoying need to instantiate objects before you can call any methods on them, and inherent problems with deciding which of several tiny classes should own each piece of data.  However, if you've already identified several methods that really only fit in one context, they are probably a good candidate to consider putting into their own class.  For example, complex initialization can be done in a creational pattern like builder.


问:
Write progress from a long running process
We have some long running processes which could run for as long as an hour up to 6 hours.

Some of the processes are started by hand and the user wants to see what the progress of the process is.

Without getting into to much details of the actual details, you could think of:

Fetching data

Update client info

remove false data

create external  files

create pdf

This process of course consists of loads of different classes, and sometimes I want those individual classes to write progress.

For example: When I am only interested in high overview progress, I could write the progress from the top level facade, but I also want to write progress in the service which creates the pdf's, so that class and it's subclasses also have to write progress.

My question is: how can I write progress from all those classes regarding the same 'base' process without passing some kind of processid from class to class?

What I thought of is creating a loggingservice class which takes care of the logging and passing that from class to class, but that seems so nasty to hand every single class the logging service.

Second I thought of is to create a static loggingservice class for the logging (which I find common in applications for the normal error logging) but then I still have to pass the processId around

Third I thought of creating a factory to be called from every class, but then I still have to pass the processId around

Fourth I thought of injecting the loggingservice class in every class, but then I still have to pass the processId around and it seems like a wrong kind of dependency for a class to have, a dependency for a logger.

So I am looking for either number 5, or reasons why 1,2,3 or 4 is a good idea anyway and the downsides I see are not relevant or important.

答:
I usually do this by letting every long-running class implement an interface, e.g. LongRunning, with a single method reportProgress(). Your logging service would simply be notified of the existence of such long runners, periodically query their status, and then report on the general state of the world in whatever way it sees fit.

Your business code still has to be interleaved with logging statements that way, but otherwise your existing classes don't have to adapt to anything external, and that's the most important thing in my view: not changing business code that already does its job for extraneous reasons.


答:
You are correct that all of these solutions dirty your code with logging / reporting code that breaks separation of concerns. This sort of problem is exactly why Aspect Oriented Programming exists:

Wikipedia (emphasis mine):

Aspect-oriented programming entails breaking down program logic into distinct parts (so-called concerns, cohesive areas of functionality). Nearly all programming paradigms support some level of grouping and encapsulation of concerns into separate, independent entities by providing abstractions (e.g., functions, procedures, modules, classes, methods) that can be used for implementing, abstracting and composing these concerns. Some concerns "cut across" multiple abstractions in a program, and defy these forms of implementation. These concerns are called cross-cutting concerns.

Also relevant: Cross-cutting concern

Essentially, you want something that can touch upon all aspects of your application in a particular scenario. In your case, such logging is a cross-cutting concern.

I can't help you with any implementation details as your question doesn't mention a language or a platform. But many languages offer Aspect Oriented Programming natively, or there are frameworks that assist with this process.

Examples:

Java: Guice AOP

Python: Pytilities

Ruby: Aquarium

PHP: Go!

Title: Write progress from a long running process

Body:
We have some long running processes which could run for as long as an hour up to 6 hours.

Some of the processes are started by hand and the user wants to see what the progress of the process is.

Without getting into to much details of the actual details, you could think of:

Fetching data

Update client info

remove false data

create external  files

create pdf

This process of course consists of loads of different classes, and sometimes I want those individual classes to write progress.

For example: When I am only interested in high overview progress, I could write the progress from the top level facade, but I also want to write progress in the service which creates the pdf's, so that class and it's subclasses also have to write progress.

My question is: how can I write progress from all those classes regarding the same 'base' process without passing some kind of processid from class to class?

What I thought of is creating a loggingservice class which takes care of the logging and passing that from class to class, but that seems so nasty to hand every single class the logging service.

Second I thought of is to create a static loggingservice class for the logging (which I find common in applications for the normal error logging) but then I still have to pass the processId around

Third I thought of creating a factory to be called from every class, but then I still have to pass the processId around

Fourth I thought of injecting the loggingservice class in every class, but then I still have to pass the processId around and it seems like a wrong kind of dependency for a class to have, a dependency for a logger.

So I am looking for either number 5, or reasons why 1,2,3 or 4 is a good idea anyway and the downsides I see are not relevant or important.


问:
For a concrete SQL Repository, should I encapsulate the SQL logic inside or outside the repository methods?
If I have a concrete repository based on SQL data access, should I pass in SQL to the repository methods or encapsulate them within the methods.  I feel if I pass them in, then I am coupling my repository with SQL data access, so I am leaning toward putting the SQL in the methods?  Here are my two options:

```<code>public GetPeople(string sql)
{
   //Query people with passed in sql
}

public GetPeople()
{
  //Query people with sql logic here, possibly conditional logic
}
</code>```

答:
As always, it's useful to think about the pros and cons of each approach:

Pro passing in SQL

It's flexible. If you have a lot of different queries that are difficult to parameterize you won't end up with a ton of methods, or having to design around it.

Anti passing in SQL

It's generally a bad idea to present a larger interface than is necessary. The interface may not seem any larger- it's still one method- but it makes a huge promise of "Give me practically ANY query and I'll run it for you". This can be really problematic in, for example, testing, because now instead of testing a class that claims it can answer one specific question, you have to test a class that claims it can answer any question. The same difficulty arises if you're mocking out the repository rather than testing it.

You end up with absolutely no separation of concerns. SQL concerns will be sprayed throughout your code-base; no matter what a class's responsibility is, it's also going to be implicitly having to deal with the exact implementation and structure of your persistence. It'll be far more difficult to write loosely-coupled or Single Responsibility Principle-compliant code.

For data which can only be one of a small fixed number of values, it's usually considered good practice to use an enum. This is essentially because the compiler can't peer inside strings- it can't recognise your typos, your IDE can't provide intellisense based on string values and so on. You want to be strongly typed rather than "stringly typed".

So if that's important for simple data, think how much more important it is for code. The last thing you want is to have behaviour inside strings, with typos causing run-time errors, unit testing completely impossible, no intellisense, no stepping through with a debugger, none of the nice things we get from writing code as code rather than as string values.

Of course you'll need your SQL to be somewhere, but as part of a repository method it's isolated somewhere that the whole method can be tested as a sensible unit. And outside your repositories, the queries you want to perform will be represented as methods called on objects, rather than as values inside strings.

As you can see, this list is a bit one-sided. The kind of "flexibility" you gain is really the worst kind, analogous to adding params object[] extra to every method just in case you need it at some point in the future. Even if there wasn't such a hefty collection of downsides, it'd still be a YAGNI violation. So I would strongly recommend not passing in SQL, certainly not as your starting point for the repository.

If you do, at some point in the future, find yourself in the quite unusual situation where you do need to make many, many different queries, and the differences between them are something hard to simply parameterize, there are still probably better ways to deal with this than passing in SQL. For example, you could create classes which can be used to build up queries by having methods called on them, which then expose the final SQL as a property. But this scenario definitely isn't worth prematurely planning around.


答:
The term you are after is one of the following, they are (relatively fungible)

Embedded language

Application scripting language

Extension language

Lua, JavaScript and Python seem to be some of the most common of these, mainly due to the fact that there is a lot of support for embedding them, and their syntax is considered by many as simple and quite easy to learn.

A few other notable examples of extension languages, Java, used in Eclipse and JetBrains IntelliJ based IDEs.  VimL / VimScript in Vim. Emacs Lisp in GNU/Emacs. (GNU also promote Guile, a Scheme variant as it's extension language of choice.)

At the moment, it's hard to say which language is most commonly used as Extension language, but Lua is extraordinarily easy to embed, JS and Python are relatively difficult (by comparison) but still not especially hard.  MRuby has been developed specifically to be embeddable, however it drops a large part of the standard library as a result.

Within the Microsoft ecosystem, (since the introduction of .Net) CLR languages are all able to extend popular MS apps, VS, MS Office etc.

Title: What makes Python more used as an implementation language than the others?

Body:
Perl and Python are often compared to each other (let's not forget Ruby), and almost always those discussions will come to the conclusion pretty much anything you can do in one or the other.

Without going into that, I've noticed that Python however, is often used as an implementation language (uhmm, maybe the term here is incorrect technically - a language you use to, for example, enable some degree of scripting in a large application ... Tecplot, Rhinoceros etc.; these are from the scientific area; there are others surely) and Perl never (well, to my knowledge at least).

So I was wondering - what makes Python more suitable for something like that? What particulars make a language more suitable to be implemented as part of a larger app. for scripting in general? Is it only that that wasn't so common 10 years ago (scripting in applications), and Python is just at its peak at the moment, ... or something else?


问:
Will simply adding a 'Allow Cross Origin Requests' to my node app work?
I'm trying to make a 'frontend web scraper'. I had the idea of setting up a node app that had a dynamic route that used Request (the NPM package) to scrape pages and displayed them as it's own. Then my JS plugin would add an invisible iframe to whatever page it's used on with of 'nodeapp.com/[URL-TO-SCRAPE]'. Then use the inter page getElementById() function to get the text. The reason I ask this question is because I know that you can't use getElementById() across multiple origins, but if I was able to get the page on a heroku app with a 'Allow Cross Origin Requests' header would this work? I know my question is very confusing.</p>

答:
What you're describing is a reverse proxy.

CORS allows cross-origin reading of resources, but it does not allow cross-origin iframe reads. However, if your reverse proxy serves permissive CORS headers (e.g., Access-Control-Allow-Origin: *), then the contents of your reverse proxy will be readable with an Ajax request. You simply need to make an Ajax request to nodeapp.com/[URL-TO-SCRAPE], load the fetched HTML into a document, and then find the element with myNewDocument.getElementById.

Note that if the page reading the iframe is on the same origin as the reverse proxy, CORS isn't even necessary. (If they're different origins, then CORS on the fetched page is sufficient to allow the proxy content to be read.)

Note also that reverse proxies will not use the user's cookies when making the request to the page. So, for example, when your reverse proxy fetches gmail.com, it will show the user the Gmail login page, not the user's inbox. If the content you're trying to read is not protected by credentials (i.e., it can be read without logging in), then there won't be any issues.


问:
How do tools facilitate writing functional specifications?
C2 wiki on functional specifications suggest that this can be facilitated by tools, how?

A Functional Specification is a list of demands and constraints intended to describe a product to be designed and built...

...tools for describing software products have been developed to the point that functional specs are no longer of any use.

Why not just type a structured Word document?

答:
Functional specifications are typically presented as a document, but depending on your purposes, creating the specification in Word may not be the best choice. There are other options - word processors, spreadsheets, and requirements management tools (1, 2) are some common tools used to create and maintain functional specifications.

Requirements management tools (I'm familiar with IBM Rational DOORS, but there are others) are essentially requirements databases that support creating, maintaining, tracing, and generally managing requirements. Some tools support importing from documents and spreadsheets, as well as outputting into these formats. Internally, they allow you to capture requirements as unique objects (think a row in a database, where each requirement has various attributes). You can also manage changes, by tracing other items (lower level requirements, design artifacts, tests) and seeing what may have to change if a requirement changes.

Spreadsheets, to me, are a step lower than a formal requirements management tool. They support more of the requirements management functions (traceability, tracking various attributes in line with the requirement statement, managing changes).

Of course, you can always do what you suggest - start a well formatted document in your favorite word processor to capture software requirements. However, it is more difficult to ensure some aspects of good requirements. Specifically, traceability (often implemented via requirement IDs) becomes more difficult and the text associated with a requirement needs to be more verbose to capture importance and verification method.

I don't think that any tool has superseded functional specifications. I do think that processes and how tools are used have superseded the traditional idea of a functional specification document.

In agile methods, requirements are often captured as use cases and user stories. In this environment, your functional specification may be uploading your use cases and user stories in some electronic format to a file store or wiki. Even in more plan-driven methods, the use of requirements management tools have replaced the document, where a document is only generated as necessary to provide requirements to external entities.

At the end of the day, the purpose of a requirements specification (functional and non-functional) is to somehow capture what the software is supposed to do (and, after it's finished, what it does in its current state). This set of characteristics drives testing (especially system and acceptance testing). More important than creating a functional specification document is ensuring that the customer and development organization (the design team, the development team, and the test team) are on the same page when it comes to what the system is supposed to do.


问:
OOP (possibly Java-specific): Comprehensive Set of Method Categories
I am working on a coding convention to follow for my Java projects.  I find it easier to find my way through a class when I group its methods by category.  For example, rather than having each getter/setter pair for a variable one after another in a long list, I find it easier to group all the getters in a section, and all the setters in another.  This means my code is organized like this:

```<code>public class MyClass {
    //=========================== Instance Fields ============================//

    //========================== Instance Interface ==========================//
    //----------------------------- Constructors -----------------------------//

    //------------------------------- Getters --------------------------------//

    //------------------------------- Setters --------------------------------//

    /* More categories? */

    //============================ Static Fields =============================//

    //=========================== Static Interface ===========================//

}
</code>```

The problem with this approach is one with my knowledge: I do not know how to categorize every method.  Obviously, I am familiar with constructors, destructors, getters, and setters.  I have also heard of observers/queries, transformers/mutators, and iterators, though I have not yet found standardized names for these.  But then there are methods that leave me scratching my head, like methods for immutable classes that return a new version of that object that represents a change to that immutable state.

Is there a standardized set of categories in OOP that cover what methods can do?  If so, could someone provide a list of these names and explanations for what that category does?  If these categories are language-specific, could you also provide a Java-specific set?

答:
Is there a standardized set of categories in OOP that cover what methods can do?

No, since by definition, methods can do anything. But you're solving a symptom.

I find it easier to find my way through a class when I group its methods by category.

This is a sign that your classes are too big, and/or doing too much. It also might be a sign that you're not using your IDE as efficiently as you could be.

Java makes this difficult, especially if you're javadoc-ing everything but you shouldn't need this level of organization to navigate in your class. IDEs provide go to source/declaration. They provide class summaries to help navigation. And if your class is properly only dealing with one responsibility, it should only take up a few screens at most anyways.

Having fields, constructors, properties and methods in groups helps the readability of the code. Grouping methods by visibility can sometimes help, sometimes not. Doing more is probably overkill. Needing more is a sign that something has gone wrong.


答:
Instead of thinking of logging (i.e. your application telling some logging system, perhaps using  syslog(3) on Linux, what is going on) you might think of it differently: your application could be a server for requests querying its state.

Then you might even make your app some JSONRPC server (and you'll have also to code the tiny command-line client to query it).

You could also have your app becoming a specialized web server (e.g. using some HTTP server library like libonion, etc... see this list) and be queriable thru usual browser technologies.

These days, for an application which can run an entire working day, I would enable some web server technologies inside it. Even a cheap printer is today able to give its status thru some web interface.

Your internal classes might give their state e.g. by updating some "global" variables or application wide data, etc... (Of course use mutexes for synchronization issues).

The aspect-oriented perspective from durron597's answer is still relevant. If your application is a big C or C++ code compiled by GCC, you might consider using MELT to customize the compiler for such (aspect-oriented) purposes. But that would be compiler specific, would take a week of effort, etc.

BTW, I am not sure that an externally queriable state should be fine-grained. I believe that updating that state every dozen of seconds is enough (I'm not thinking of periodical upgrade, but of coarse-grained state). Then you probably don't have to touch a big lot of code. YMMV.

Whatever you do, you have to design it quite early. The wikipages on continuations, application checkpointing, persistence might be relevant.


问:
What to call an HTTP API that is not RESTful?
What would you call an API that is HTTP-based, uses URI to name resources and HTTP verbs (PUT, POST, DELETE, GET...) to manipulate those resources?

According to Roy Fielding's complaints it is not REST, because there is no hypermedia.

Internally, in my team, everyone calls it "REST API". I call it "REST-like" but it is not descriptive and its meaning is fuzzy. I'm quite confused about it, since there is huge disagreement about REST. I don't want take part in flame wars, but just use correct terms.

答:
It is a CRUD interface (Create, Read, Update, Delete) over HTTP.

I can't think of any authorities to back it up this assertion, so I hope you get more and better answers.


问:
PHP OOP: value property is guaranteed different?
Imagine this code:

```<code>class Test
{
    public $result;

    public function makeSum($a,$b)
    {
        $sum = $a+$b;
        $this->result = $sum;
    }

}
</code>```

In a webserver.

At same exact moment, two browsers call a page that performs that operation. First one has $a=1 and $b=2 and second one $a=5 and $b=4.

Are we sure that for first page $result will be 3 and for second one 9? Or is there possibility that result could be "wrong" for the page asking?

I'm talking in particular for PHP, but question can be general...

I think that will be never problems, but I would know if it's true and why.

Thank you!

答: They wont mix up. The function runs seperate on each page(browser). Wherever you declared the $a=1 and $b=2 will provide: 3. Same for the $a=5 and $b=4 will provide: 9. So you dont have to worry about that.


答:
I don't agree that you should be sorting your methods by category, or even by visibility. It may seem, at first, like this is a good thing to do, but what you're actually doing is imposing order for the sake of order, but not for any particular reason. Consider ensuring that your address book were sorted by phone number. Certainly, it would be organized, but your organization scheme would not be very useful. What are you trying to minimize with your address book? Answer: the amount of time it takes you to look up an address. Keep this in mind towards the end of my answer.

What, then, should the organization scheme be?

From Clean Code:

Have you ever chased your tail through a class, hopping from one function to the next, scrolling up and down the source file, trying to divide how the functions relate and operate, only to get lost in a rat's nest of confusion? Have you ever hunted up the chain of inheritance for the definition of a variable or function? This is frustrating because you are trying to understand what the system does, but you are spending your time and mental energy on trying to locate and remember where the pieces are.

Concepts that are closely related should be kept vertically close to each other. Clearly this rule doesn't work for concepts that belong in separate files. But then closely related concepts should not be separated into different files unless you have a very good reason. Indeed, this is one of the reasons that protected variables should be avoided.

You should read the entire chapter, it goes on at some length about this. I could put it all here but I don't want to violate Robert Martin's copy right too much. But, basically, the next part says this:

Local variable declarations should be as close to their usage as possible.

Keep your instance variables (fields) at the top, as you're already doing.

Put dependent functions after the functions that call them.

#3 is the key organization concept. You want to read your code like you would read a newspaper article. Each public method should have it's private dependencies immediately following, with good variable names. Remember that address book. The goal is to minimize the amount of time you spend scrolling up and down your classes to find relevant behavior, so that your mind can focus on the "what the system does" as you continue to program.

Title: OOP (possibly Java-specific): Comprehensive Set of Method Categories

Body:
I am working on a coding convention to follow for my Java projects.  I find it easier to find my way through a class when I group its methods by category.  For example, rather than having each getter/setter pair for a variable one after another in a long list, I find it easier to group all the getters in a section, and all the setters in another.  This means my code is organized like this:

```<code>public class MyClass {
    //=========================== Instance Fields ============================//

    //========================== Instance Interface ==========================//
    //----------------------------- Constructors -----------------------------//

    //------------------------------- Getters --------------------------------//

    //------------------------------- Setters --------------------------------//

    /* More categories? */

    //============================ Static Fields =============================//

    //=========================== Static Interface ===========================//

}
</code>```

The problem with this approach is one with my knowledge: I do not know how to categorize every method.  Obviously, I am familiar with constructors, destructors, getters, and setters.  I have also heard of observers/queries, transformers/mutators, and iterators, though I have not yet found standardized names for these.  But then there are methods that leave me scratching my head, like methods for immutable classes that return a new version of that object that represents a change to that immutable state.

Is there a standardized set of categories in OOP that cover what methods can do?  If so, could someone provide a list of these names and explanations for what that category does?  If these categories are language-specific, could you also provide a Java-specific set?


答:
Richardson Maturity Models goes like this

 POST everywhere. A single endpoint. (SOAP)

 POST everywhere. Multiple endpoints. (resources)

 HTTP VERBS. Multiple endpoints.

 Like 2 and returns links to resources. (RESTful)

So according to the model I would call it a webservice conforming to richardson level 2 or something along those lines.

http://martinfowler.com/articles/richardsonMaturityModel.html

Title: What to call an HTTP API that is not RESTful?

Body:
What would you call an API that is HTTP-based, uses URI to name resources and HTTP verbs (PUT, POST, DELETE, GET...) to manipulate those resources?

According to Roy Fielding's complaints it is not REST, because there is no hypermedia.

Internally, in my team, everyone calls it "REST API". I call it "REST-like" but it is not descriptive and its meaning is fuzzy. I'm quite confused about it, since there is huge disagreement about REST. I don't want take part in flame wars, but just use correct terms.


问:
Getting to know my way around a database with hundreds of tables
I'm new to a small company that's pretty much run by one guy. He knows all the ins and outs of the system which is quite large. We have a database with about 300 different tables. I'm struggling to keep track of where everything in the database is and what relates to what. What methods can be used to manage large databases, or does it mostly come down to going through other examples in the code base to find what you need?</p>

答:
For the database that I am responsible for I do the following:

expose all metadata in views so you can see groups of related tables in a more human readable fashion

every view/table has a comment, every column has a comment. Yes, it's a pain but it helps new people

every function/procedure/trigger has a one line comment that starts with Summary.  I extract the procedure/function name and comment into a table.

Toad has an option to document your database as an html file. It makes for dry reading but it is another means to access the structure

have a library of standard queries used to access commonly requested information

have packages that will implement commonly requested items like access, new metadata, disabling metadata

don't be too clever. That brilliant code you wrote in a flash of insight is not likely to be understood by you six months later or a new team member.  If you must, document and comment the code.


问:
Explaining the difference between Product Backlog Item and a Task
I've run into this challenge a couple of times and I'm hoping someone can provide some references, training or advice on how to explain the difference between a Product Backlog Item and a Task in TFS.

I understand and have explained that a Product Backlog Item is the "What" and the Task is the "How".  I have also explained that the PBI is the requirement and the Task is how the requirement is met.

I'm repeatedly met with blank stares and head scratching when I explain this.  It seems that the Software Engineers I explain this to can not make the distinction.  It is all the same to them.

I believe my other challenge is that I am not able to effectively illustrate why it is important to make the distinction.

答:
I tend to offer this when asked:-

A PBI, or Story is something more than one person can get around.

A Tasks is something only one person can pickup.

OwnerDisplayName: Brad J


问:
How are basic functions implemented in a programming language if they are not built in?
The lowest levels of a programming language's library functions are always obscure and often have no code that looks like it even remotely does anything. Some languages have these functions like getting substrings, converting between data types, querying a variable's data type, and so forth implemented as part of their standard libraries, but I can't imagine how these low-level functions can be expressed using said language. How are these things achieved? I'm not asking for how it is done with all languages, but rather what the general method of doing this is conceptually.</p>

答:
You might do well to take an assembly language class.  It would clarify for you how data is actually represented in memory.  Types are just an abstract construct to make working with data easier.  You don't need them for programming.  You just need to agree on a representation.

For example, one of the simpler representations for a string is an array of characters with a null (zero) at the end.  You know how to work with arrays, right?  You know how to test if an element of an array is zero, right?  You know how to assign an element of an array to zero, right?  That's all you need to know to be able to find a substring.

How about querying for some data's type, in a dynamically-typed language?  Again, all you need is a representation.  Maybe you make it a struct with the first element being the size of the data, the second being the actual data, and the third being a null-terminated character array containing the name of the type.  You know how to work with structs, right?  We already discussed how to work with a null-terminated string.  That's all you need to know to be able to query for a type.

How about converting between types, say from a string to an int?  Again, you just agree on a representation, which in this case would be ASCII.  You know how to look something up in a table, right?  In this case, the digits are all conveniently arranged consecutively, so all you have to do is subtract 48 to get one character's integer value.  For multiple digits, all you have to do is a loop that multiplies by 10 and adds the next character's value.

In other words, the general process is to come up with some representation in terms of what is already defined in the language, and use that to create higher-level abstractions.


问:
Rich Domain Models, Encapsulation, and the Problem of Constructor Over-Injection
I am refactoring an e-commerce web-application, currently working on the UserBasket class, which will have to handle adding or removing items, changing their quantity, getting total amount, total number of items etc.. When displaying the basket, the item's name, description and main-image-filename are also needed.

The UserBasketthen has to know the price of the Item for the given quantity. Different methods of calculating the current applicable price should be swappable. I could employ the Strategy pattern either in some sort of ItemPriceGetter with which the UserBasket would be constructed, leaving the item unaware of this, or construct the Item itself with a PriceFindingStrategy.

I have reservations against a completely anemic domain model. An item should be able to tell me its price for a certain customer and quantity on a certain date - it should be able to tell the filename of its main image, its availability etc.

Essentially, in the database, items (and other domain entities) have multiple 1-to-n relations with sometimes complex and varying logic to find the currently applicable one among them (for price, image, description etc).

If I don't want an anemic domain model, but there will be different strategies for getting the 'right' related information, how do I avoid constructor over-injection when there are multiple such 1-to-n relations from an item where a strategy to chose the right one is needed.

An Item-Class is there to tell you about data relating to items, and perform business logic that is centered around them - so making it able to tell you its price for a given customer and quantity, its main-image-filename or some such doesn't seem like a violation of the Single Responsibility Principle.

With an anemic domain model, I would have the logic neatly divided and encapsulated, but now, for - say - an itemlist to find out availability, price, name and image of an item, it would need not just an item, but also an ItemPriceFinder, ItemAvailabilityFinder, ItemImageFinder (or some such) - cohesion would (seemingly) suffer, and things that properly belong to the item are no longer encapsulated there.

With a rich domain model, the item itself will have to have an ItemPriceStrategy,ItemAvailabilityStrategy, ItemImageStrategy or similar. So it seems I'm stuck with either injecting a lot of dependencies or losing coherence and making my domain model anemic... and in the latter case, I would still have classes (which e.g. need a lot of info about Items) which I would have to construct with the Domain Object itself and most of the services to get related data.

What is the best practice to deal with such a situation? Specifically: How should the different ways of getting and filtering the related information for one kind of business entity based on contextual parameters be encapsulated and how should it be integrated so as to maximize coherence and avoid violating the single responsibility principle?

答:
I would go with the anemic domain model here. Consider the example of your ItemImageFinder. Consider a few scenarios:

You decide to extend your system to also include Image thumbnails, or including alternate images.

Now you need to modify your Item behavior. Clearly this is not the only reason for Item to change, so you are violating SRP.

You either have to create a behemoth method, or multiple different methods for image behavior.

With a ItemImageFinder, all these changes would be in a class relating to Images, not the entire item.

You need to create a command line tool.

Now your items have to load up all this image data, which it cannot even render.

You decide to have multiple implementations of the Item interface.

Perhaps one of the implementations doesn't need to look up Items. Now you have all this behavior you don't need.

Also, I am not sure why you want the ImageFinder class to be ItemImageFinder. It could just be ImageFinder, with a method getImage(Item). It could then be extended to have a method getThumbnail(Item) or a method getImage(SomeOtherObject).

You said yourself "cohesion would (seemingly) suffer." Firstly, I don't agree that it does. But forget about "accepted wisdom" for a second: Even if it did, what exactly would be the drawbacks to such a cohesion breakdown? I can't think of any.


问:
Why is the hashCode method usage of HashSet not specified in the API?
I was trying to debug my code which uses a HashSet and searching through the SO, I found out that I needed to override the hashCode method as well. The strange part is, checking the related API, I did not see any part in it mentioning about the hashCode method. Quoting the definition of the add method of HashSet as seen in the API:

public boolean add(E e)

Adds the specified element to this set if it is not already present.
  More formally, adds the specified element e to this set if this set
  contains no element e2 such that (e==null ? e2==null : e.equals(e2)).
  If this set already contains the element, the call leaves the set
  unchanged and returns false.

Now in the quotation above, I don't see anywhere that mentions about the hashCode method. Shouldn't the correct statement have been like:

... if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)) AND if this set contains no element e2 such that (e==null ? e2==null : e.hashCode() == e2.hashCode()).

Now if you say that: "If o1.equals(o2) returns true, o1.hashCode() == o2.hashCode() MUST evaluate to true as well.", then I would ask three questions:

Where is that fact specified? (in general, or in the API)

Even if that fact is specified somewhere, where in the API it is specified that HashSet makes use of the hashCode method?

If that fact is indeed correct, why isn't the compiler enforces overriding the hashCode method, whenever the equals method is overridden?

答: Absent an explicit promise not to do so, any equality-based collection is allowed to use hashCode if so inclined to quickly decide that things don't match (note that sorted collections which regard items of equal rank as matching would not be allowed to do so, since items may have equal rank and yet be unequal).  Further, there is no guarantee that hash-set implementations will always call hashCode.  It would be legitimate to have a hashSet implementation which didn't bother calling hashCode on anything until they contained some number of items.  This could be useful in some nested-collection contexts which produce many collection instances that never get very many items added.  Thus, the name hashSet basically says performance will be tied to the quality of the hash function, but that doesn't mean its' the only thing that can or will use it.


答:
An Item-Class is there to tell you about data relating to items, and
  perform business logic that is centered around them - so making it
  able to tell you its price for a given customer and quantity, its
  main-image-filename or some such doesn't seem like a violation of the
  Single Responsibility Principle.

Yes it is a violation of the SRP.  It is okay if the item knows its main-image-filename, and its base price, but it is not okay if the item has knowledge of customers so that it can tell you its final price for a given customer.

As a rule of thumb, ("a principle with broad application that is not intended to be strictly accurate or reliable for every situation",) the same item class should be viable in a manufacturing application instead of a sales application, where there would be no notion of a customer.  Such a class could perhaps contain some extra information which would be unnecessary in another application, (like materials necessary to manufacture, or time to manufacture,) but at least it would not fail with a class not found: "Customer" error.

To think of it from another point of view, why should the item class be able to tell you how much it would cost for a certain customer, instead of the other way around: a customer class being able to tell you how much a certain item would cost for it.  Whenever you come across dilemmas like this, you know that neither class is the right place for the logic.

As another rule of thumb, classes should only contain logic which deals with classes that they are immediately related.  So, the customer class will presumably have orders, so of course it is okay if the customer class contains logic that can tell you, for example, what is the total sum of all orders ever placed.  This makes the customer class non-anemic.  But the item class probably would not have any immediate relationships (in either direction) with the customer class, so this probably means that there should be no logic in either class involving the other.  If this means that the item will have to be anemic, so be it.

In my experience, when you have a piece of logic that you want to put somewhere, but there appears to be no model entity which is the one right entity to contain this logic, it is best to move this logic to the "model" object, which by definition knows all the entities and the relationships between them.  This tends to result in a quite fat main model class, which is the opposite of anemic, if that's any consolation.

Title: Rich Domain Models, Encapsulation, and the Problem of Constructor Over-Injection

Body:
I am refactoring an e-commerce web-application, currently working on the UserBasket class, which will have to handle adding or removing items, changing their quantity, getting total amount, total number of items etc.. When displaying the basket, the item's name, description and main-image-filename are also needed.

The UserBasketthen has to know the price of the Item for the given quantity. Different methods of calculating the current applicable price should be swappable. I could employ the Strategy pattern either in some sort of ItemPriceGetter with which the UserBasket would be constructed, leaving the item unaware of this, or construct the Item itself with a PriceFindingStrategy.

I have reservations against a completely anemic domain model. An item should be able to tell me its price for a certain customer and quantity on a certain date - it should be able to tell the filename of its main image, its availability etc.

Essentially, in the database, items (and other domain entities) have multiple 1-to-n relations with sometimes complex and varying logic to find the currently applicable one among them (for price, image, description etc).

If I don't want an anemic domain model, but there will be different strategies for getting the 'right' related information, how do I avoid constructor over-injection when there are multiple such 1-to-n relations from an item where a strategy to chose the right one is needed.

An Item-Class is there to tell you about data relating to items, and perform business logic that is centered around them - so making it able to tell you its price for a given customer and quantity, its main-image-filename or some such doesn't seem like a violation of the Single Responsibility Principle.

With an anemic domain model, I would have the logic neatly divided and encapsulated, but now, for - say - an itemlist to find out availability, price, name and image of an item, it would need not just an item, but also an ItemPriceFinder, ItemAvailabilityFinder, ItemImageFinder (or some such) - cohesion would (seemingly) suffer, and things that properly belong to the item are no longer encapsulated there.

With a rich domain model, the item itself will have to have an ItemPriceStrategy,ItemAvailabilityStrategy, ItemImageStrategy or similar. So it seems I'm stuck with either injecting a lot of dependencies or losing coherence and making my domain model anemic... and in the latter case, I would still have classes (which e.g. need a lot of info about Items) which I would have to construct with the Domain Object itself and most of the services to get related data.

What is the best practice to deal with such a situation? Specifically: How should the different ways of getting and filtering the related information for one kind of business entity based on contextual parameters be encapsulated and how should it be integrated so as to maximize coherence and avoid violating the single responsibility principle?


问:
How do you separate view from logic in a Winform application?
I know there are patterns like MVC to separate view from logic, however, I don't know how common they are in Winform applications.

For a C# Winform application, I may start with a Form and gradually add UI components to it, then for the events of components, (click, textchanged...) I call my functions, or directly write my logic there!

I know that is a bad habit, but I don't know what is the best way to start such a project in Visual Studio (a template, a framework, starting point),  Does MVC the only solution? Should I do it for any project?!

I would like to receive some guidelines or lightweight framework to get started.

答:
Obviously WinForms does not natively support one design pattern over another - the one that might not work is MVVM because you cannot "bind" data to the view model and have it update the data directly. </p>

<p>Otherwise - I would attempt WinForms with MVP - I've seen that done before -
here's a link to look at https://winformsmvp.codeplex.com/ </p>

Body:
Obviously WinForms does not natively support one design pattern over another - the one that might not work is MVVM because you cannot "bind" data to the view model and have it update the data directly.

Otherwise - I would attempt WinForms with MVP - I've seen that done before -
here's a link to look at https://winformsmvp.codeplex.com/


问:
Where can I get free public raw data?
In web development, a mashup is a web page or application that uses and combines data, presentation or functionality from two or more sources to create new services.

There are many sources for getting data (raw information). Governments are good examples.

However many of those cost and have complicated licensing.
For instance SMHI in Sweden sells temperature data meanwhile our neighbor country Norway gives it away for free.

One would say what kind of application are you building and what data do you need?  I would say give me some interesting data and I will do a good mashup of it. I could just plot it on Google maps for instance.

So the question is: Where can I get free data?

Note: I'm not interested in data mining using a webcrawler!

Please share your sources with me.

答:
Somebody asked pretty much the same question on Reddit Compsci a while back... here's what I had to say then.  I think it all still stands.

Poke around some of these sites, I'm reasonably sure there's something there to catch your interest.

/r/datasets

/r/opendata

http://www.data.gov

http://data.australia.gov.au/

http://data.gov.uk

https://stats.stackexchange.com/questions/7/locating-freely-available-data-samples/

http://kevinchai.net/datasets/

http://infochimps.com/datasets

http://datamob.org/

http://en.wikipedia.org/wiki/Linked_Data#Datasets

http://theinfo.org/

Depending on what you're trying to do, there are tons and tons of datasets out there.  One that's fun to play with, but might or might not be relevant to you, is the Enron Email Dataset.  It's the result of a LOT of internal Enron corporate email being subpoenaed and released to the public back during the big Enron scandal.

And if you can't find exactly the data you want, don't underestimate the possibility of writing your own crawler/scraper.  Depending on what data you want, it may be fairly straightforward to just crawl the web for your own dataset.   There are all sorts of tools - from wget to apache droids - for helping you programmatically retrieve information.

Title: Where can I get free public raw data?


问:
Method extraction vs underlying assumptions
When I split big methods (or procedures, or functions — this question is not specific to OOP, but since I work in OOP languages 99% of the time, it's the terminology that I'm most comfortable with) into a lot of small ones, I often find myself displeased with the results. It becomes harder to reason about these small methods than when they were just blocks of code in the big one, because when I extract them, I lose a lot of underlying assumptions that come from the context of the caller.

Later, when I look at this code and see individual methods, I don't immediately know where are they called from, and think about them as ordinary private methods that can be called from anywhere in the file. For example, imagine an initialisation method (constructor or otherwise) split into a series of small ones: in the context of method itself, you clearly know that object's state is still invalid, but in an ordinary private method you probably go from assumption that object is already initialised and is in a valid state.

The only solution I've seen for this is the where clause in Haskell, which allows you to define small functions that are used only in the "parent" function. Basically, it looks like this:

```<code>len x y = sqrt $ (sq x) + (sq y)
    where sq a = a * a
</code>```

But other languages I use don't have anything like this — the closest thing is defining a lambda in a local scope, which is probably even more confusing.

So, my question is — do you encounter this, and do you even see this is a problem? If you do, how do you typically solve it, particularly in "mainstream" OOP languages, like Java/C#/C++?

Edit about duplicates: As others noticed, there are already questions discussing splitting methods and small questions that are one-liners. I read them, and they don't discuss the issue of underlying assumptions that can be derived from caller's context (in example above, object being initialised). That's the point of my question, and that's why my question is different.

Update: If you followed this question and discussion underneath, you might enjoy this article by John Carmack on the matter, in particular:

Besides awareness of the actual code being executed, inlining functions also has the benefit of not making it possible to call the function from other places. That sounds ridiculous, but there is a point to it. As a codebase grows over years of use, there will be lots of opportunities to take a shortcut and just call a function that does only the work you think needs to be done. There might be a FullUpdate() function that calls PartialUpdateA(), and PartialUpdateB(), but in some particular case you may realize (or think) that you only need to do PartialUpdateB(), and you are being efficient by avoiding the other work. Lots and lots of bugs stem from this. Most bugs are a result of the execution state not being exactly what you think it is.

答:
For example, imagine an initialisation method split into a series of small ones: in the context of method itself, you clearly know that object's state is still invalid, but in an ordinary private method you probably go from assumption that object is already initialised and is in a valid state. The only solution I've seen for this is...

Your concern is well-founded. There is another solution.

Take a step back. What fundamentally is the purpose of a method? Methods only do one of two things:

Produce a value

Cause an effect

Or, unfortunately, both. I try to avoid methods that do both, but plenty do.  Let's say that the effect produced or the value produced is the "result" of the method.

You note that methods are called in a "context". What is that context?

The values of the arguments

The state of the program outside of the method

Essentially what you are pointing out is: the correctness of the result of the method depends on the context in which it is called.

We call the conditions required before a method body begins for the method to produce a correct result its preconditions, and we call the conditions which will be produced after the method body returns its postconditions.

So essentially what you are pointing out is: when I extract a code block into its own method, I am losing contextual information about the preconditions and postconditions.

The solution to this problem is make the preconditions and postconditions explicit in the program. In C#, for instance, you could use Debug.Assert or Code Contracts to express preconditions and postconditions.

For example: I used to work on a compiler which moved through several "stages" of compilation. First the code would be lexed, then parsed, then types would be resolved, then inheritance hierarchies would be checked for cycles, and so on. Every bit of the code was very sensitive to its context; it would be disastrous, for instance, to ask "is this type convertible to that type?" if the graph of base types was not yet known to be acyclic! So therefore every bit of code clearly documented its preconditions. We would assert in the method that checked for type convertibility that we had already passed the "base types acylic" check, and it then became clear to the reader where the method could be called and where it could not be called.

Of course there are lots of ways in which good method design mitigates the problem you've identified:

make methods that are useful for their effects or their value but not both

make methods that are as "pure" as possible; a "pure" method produces a value that depends only on its arguments, and produces no effect. These are the easiest methods to reason about because the "context" they need is very localized.

minimize the amount of mutation that happens in program state; mutations are points where code gets harder to reason about