问:
Graphs and minimum spanning trees?
I am having a hard time finding information on how Graphs and spanning tree's work and how to construct/structure them. The reason is that I'm using a Delaunay Triangulation algorithm within the LibGDX framwork and this got me an array of indices. I can draw my triangles and points but how to properly setup a graph/MST structure is a problem.

I supply my vertices's as an array of floats as well:

```<code>float[] points = new float[6] {80, 30, 40, 45, 0, 10};
</code>```

Each pair refers to a point of the map. Using DelaunayTriangulator.computeTriangles I get an array of indices, in this case

```<code>ShortArray indices = triangulator.computeTriangles(points, false);
System.out.println(indices);
//Output [1, 0, 2, 1, 2, 3]
</code>```

Now I can draw all the edges and I'm actually doing this just using this data. But I suppose I create a node and graph class to help me out here, I just don't have a clue how this should look. For example, should I have multiples of the same points with different parents, or should I have a single node for a point with a list of points it is connected to? I'm very new to graphs and MST and there is plenty of information on the subject but I cannot find good practical examples.

答:
Your idea for "single node for a point with a list of points it is connected to" should work, as it describes an adjacency list. Two canonical ways to represent graphs are via adjacency lists and adjacency matrices, for which the Wikipedia pages have some simple examples:

https://en.wikipedia.org/wiki/Adjacency_list

https://en.wikipedia.org/wiki/Adjacency_matrix

In the case of an adjacency list, it often makes sense to use a dictionary/mapping data structure, e.g. a HashMap in Java.

Just one example to note two additional caveats... let's say the below represents a graph with four nodes and three edges:

```<code>(1) -- (2) -- (3)
        |
       (4)
</code>```

An adjacency list could be represented like so: {1: [2], 2: [1, 3, 4], 3: [2]}

Note that:

The above graph is unweighted -- if it were weighted, the the edge weights would need to be represented, e.g. as a possible implementation that follows the above adjacency list {1: [(2, 3)], 2: [(1, 5), (3, 2)...] ...} where 1: (2, 3) means the edge between node 1 and node 2 has weight of 3.

The above graph is undirected -- if it were directed, the adjacency list would potentially contain fewer edges.

MSTs are edge subsets of graphs, so usually no additional structure is required to represent them.

Title: Graphs and minimum spanning trees?

Body:
Your idea for "single node for a point with a list of points it is connected to" should work, as it describes an adjacency list. Two canonical ways to represent graphs are via adjacency lists and adjacency matrices, for which the Wikipedia pages have some simple examples:

https://en.wikipedia.org/wiki/Adjacency_list

https://en.wikipedia.org/wiki/Adjacency_matrix

In the case of an adjacency list, it often makes sense to use a dictionary/mapping data structure, e.g. a HashMap in Java.

Just one example to note two additional caveats... let's say the below represents a graph with four nodes and three edges:

(1) -- (2) -- (3)
        |
       (4)

An adjacency list could be represented like so: {1: [2], 2: [1, 3, 4], 3: [2]}

Note that:

The above graph is unweighted -- if it were weighted, the the edge weights would need to be represented, e.g. as a possible implementation that follows the above adjacency list {1: [(2, 3)], 2: [(1, 5), (3, 2)...] ...} where 1: (2, 3) means the edge between node 1 and node 2 has weight of 3.

The above graph is undirected -- if it were directed, the adjacency list would potentially contain fewer edges.

MSTs are edge subsets of graphs, so usually no additional structure is required to represent them.


问:
Why should PHP developer use/learn VI editor?
Why should PHP developer use/learn VI editor ?

I mean there are 10 most amazing editors like PHPStorm, Netbeans which increases developers productivity.

Lets just consider PHPStorm. I never got amazed by editor like PHPStorm.

It has 1000s of features. Right from syntax hints, showing weak errors, warnings, notices etc.

When we compare number of features provided by VI Editor & those provided by editors like PHPStorm, we see it like 10 vs 1000 features.

My question is : Why should I learn to use Vi editor?

P.S. I am intermediate linux(Ubuntu) user.

Edit : Who told me to learn VI ? => Normally its required skill in Job Listing for PHP developer

Thanks.

答:
Simple answer: Because you will need it.

On productive unix/linux environments you will likely only find vi/vim as editor.

Also you will not be allowed to install additional software on the productive server (like your favourite IDE).

Additionally most server environments will have no GUI (when speaking of unix/linux)
 Therefore remote desktop is no option there.

So you have to live with a simple editor (like vi) via ssh.

ContentLicense: CC BY-SA 3.0


问:
Is anything in programming truly evil?
So, there are a bunch of questions appearing asking is X evil, is Y evil.

My view is that there are no language constructs, algorithms or whatever which are evil, just ones which are badly used.  Hell, if you look hard enough there are even valid uses of goto.

So does absolute evil, that is something which is utterly incompatible with best practice in all instances, exist in programming?  And if so what is it?  Or is it just bad programmers not knowing when something is appropriate?

Edit: To be clear, I'm not talking about things programmers do (such as not checking return codes or not using version control - they're choices made by bad programmers), I mean tools, languages, statements, whatever which are just bad...

答: No tool is inherently evil. Its existence may be utterly foolish for all but a single use case but that does not make it evil. It puts the onus of deciding the proper use on the programmer.</p>

ContentLicense: CC BY-SA 2.5

Title: Is anything in programming truly evil?


问:
private copyright to include in the closed source code for the company
I'm wondering on what's the practice of writing in the copyright area to use for the company I work for.

Earlier I was working solo but now we have hired more developers. Company is not so much concerned about the copyright stuff since they deliver products only but I want to enforce some kind of protection for the company's source code, so what should I configure in IDE's for developers working on the code?

答:
If you are writing the code on behalf of some company, then nine times out of ten, the copyright on the code is owned by the company and not by the individuals writing the code.

For that reason, the copyright statement should most likely be:

Copyright (C) 2015, Company name

  All rights reserved.

Some companies might want a more elaborate statement of what is allowed and what isn't. Such statements should be drafted in cooperation with the legal department or company lawyer.


问:
Best way to handle blank dates
I'm trying to create a contact book application, and currently I'm working on a class called Person. One of the fields of person is dateOfBirth, however I don't know how to handle unknown dates. Until now I have been using java.time.LocalDate for dateOfBirth and I've been initialising the field to null at instantiation. This isn't ideal, because it's resulting in null pointer exceptions when I try to compare dateOfBirth to other dates such as the LocalDate.now().

What would be the best way to handle dateOfBirth? Should I just create an entirely new class and manage unknown dates internally? Or is ther some better way to do it. I was going to just extend LocalDate but it's immutable so can't be extended without going to the source.

答:
Your options are:

1) Use null. Then you must not forget to check for null. Annotations @NotNull and @Nullable (and similar) will help you avoid NullPointerException's.

2) Use Optional. This is like being forced to check for null. But it adds some overhead and other indirections.

3) Use the DefaultObject pattern: Create a static final LocalDate DEFAULT as the default. I don't like this, since later it's easy to forget you don't have a real, known date.

4) Use the NullObject pattern: Create your own class that will wrap a java.time.LocalDate, and then, instead of null, define and consistently use: static final MyLocalDate UNKNOWN

5) Use an utility class to always compare or process dates. So, instead of date1.foo(date2) you would use UtilDates.foo(date1, date2). Method foo should accept nulls.

But before choosing one of these options you must decide what to do when you don't know the date. For example, when checking if some person is older than 21, but dateOfBirth is unknown, what do you wanna do? Do you want to always assume the person is older than 21? Or always younger than 21? Do you want to issue a warning and abort the current operation,  forcing the user to enter a date? Depending on what you want to do each of the options above have pros and cons.

There is another one, maybe not an option in your case, but:

6) Force the user to choose a valid date (i.e., disallow nulls) when Person is being instantiated/saved.

Title: Best way to handle blank dates


答:
IMHO "because you may need to edit files on the production server and there is no IDE/GUI on production servers" can't be the answer.

In any professional shop an ordinary developer has no access to the production server. If the shop has a a size of > 10 employees they will have a system administrator/devops team for that.

Even if we assume the team is so small that it has no system administration/devops people then maybe the developer has also the role of system administrator/devops, which means that he may needs vim (or emacs, nano ...) as part of this role.

All the IDEs have the possibility (native or via plugin) to access files on a remove file system by just tunnelling through SSH/FTP or whatever is available to reach the servers. So even if the shop has no deployment process or the deployment is broken, you'll easily be able to edit files on the server without vim.

Why should a PHP developer use/learn VI editor then?

This are the reasons I can think of:

All of the tools you mentioned in your question are also available with vim. Syntax highlighting, xdebug, etc. are all there. You just need to install plugins and configure vim to fit your demands. Obviously "phpStorm" is an IDE fitted for PHP development so it has all those out of the box, while vim is an extendable text-editor, which means you have to put a lot of work to make it fit your workflow. You may have a look at this video which shows a fantastic tmux + vim setup - you'll notice his vim doesn't look like your vim anymore.

I think when mastered a no-mouse-only-keyboard-workflow is effectively faster. This takes a lot of practive, but when you stand next to a vim-magician you'll just be buffed how fast he is. A working pace that IMHO can never be reached by regular IDEs.

Because not everything works out of the box, you'll get a lot more insight how things actually work behind the scenes. Again this is of course a huge time investment when compared to an out-of-the-box solution.

As already outlined vim comes pretty bare-bone when compared to a full blown IDE. This also gives you the chance to create a personal workflow by yourself. All the keybindings, macros, plugins, visual appereance - the whole behaviour of the editor is under your control. You form your own personal workflow instead of using that given by the IDE.

Using it brings a geeky-warm-feeling of beeing oldschool.

So to sum up, it's a huge investment of time to learn it, but it may make sense because you gain a lot of insight and are able to form your own workflow.

If you are not only a developer, but also in the role of a system administrator or DevOps it is a clearly needed skill for interacting with the servers.

Title: Why should PHP developer use/learn VI editor?

Body:
Why should PHP developer use/learn VI editor ?

I mean there are 10 most amazing editors like PHPStorm, Netbeans which increases developers productivity.

Lets just consider PHPStorm. I never got amazed by editor like PHPStorm.

It has 1000s of features. Right from syntax hints, showing weak errors, warnings, notices etc.

When we compare number of features provided by VI Editor & those provided by editors like PHPStorm, we see it like 10 vs 1000 features.

My question is : Why should I learn to use Vi editor?

P.S. I am intermediate linux(Ubuntu) user.

Edit : Who told me to learn VI ? => Normally its required skill in Job Listing for PHP developer

Thanks.


问:
MainService vs. Application
My conceptual question circles around Android. What I like to do is running a service that acts as the central point for application-wide things and combine this with an event-system. For instance, when a user clicks a button that causes IO, this button dispatches an event (Broadcast, Intent, greenrobot.EventBus, whatever), the MainService then receives the event and kicks off, for instance, an IntentService. Once the IntentService is finished, I again dispatch an Event back to the MainService and so forth.

This works very nice for me, it splits the concerns and I have no clutter in my Activities/Fragments, it helps me organize things.

But I am not sure if I really need that MainService, at least for this particular case. I extend Application anyway and registering a BroadcastReceiver or EventBus is no problem at all. Should I get rid of the MainService?

答:
Application object is not responsible for delegating events to different part of the app. I would suggest not to clutter it with such responsibilities.

From what I understand, your MainService class is some sort of dispatcher that initiates some service or activity when it gets a particular event. This should be a separate class as you have designed. I would suggest to change its name if possible as MainService does not give proper idea about what it really does. You could call it something like EventDispatcherService or CentralEventHandlingService etc.

Title: MainService vs. Application


问:
How to research API usage?
I'd like to find out how often and if a certain pattern in a certain programming language is used.

In my case - I'd like to find out how many/if people do eval("/"+regexString+"/") in JavaScript and/or compose regular expressions from strings using /.

Typically, I perform a GitHub search - I did this when working on a feature in the past, and it was for a much smaller API with a clear function call and a smaller scoped use case - doing this manually doesn't seem practical here.

I'm doing this in order to characterise an API I'm working on and I'm considering whether or not this is something people do in order to provide a better and more consistent API..

How can I research how common this pattern is?

(I'd appreciate answers based on science and known practices)

答:
You might want to search for Javascript static program analysis tools (like this question), e.g. Flow. You'll find many research papers on that subject.

I've heard several talks on that subject, and IIRC eval  is used, sometimes carelessly or needlessly, in many practical Javascript software.

Your question can be understood in two different ways:

How often is eval("/"+regexString+"/") statically appearing in various Javascript source code?

How often is eval("/"+regexString+"/") dynamically executed in some given application?

You could hack some existing Javascript implementation to detect such patterns.

Notice that if regexString is a single line string starting with a /  character,  eval("/"+regexString+"/") is evaluating a comment!

Don't forget the halting problem & Rice's theorem; hence, static program analysis can never be entirely satisfactory.

Title: How to research API usage?


问:
Using a one-shot class to store not-quite-global variables
I sometimes find myself writing classes (in Python, in my case) that are used like this:

```<code>MyClass(some_args).go()
</code>```

In other words, there's only one method in the class that any external code would call, and it will only ever get called once. There might be a return value from go() but often there isn't, and when there isn't, I could even call go from the class's __init__.

So why even bother with the class, instead of just writing go() as a standalone function? Because what goes on inside go is complicated. There may be several levels of nested function calls, and there are certain pieces of information that are needed in different spots. If I try to write all this without a class, I end up with a many of the functions returning multiple values. Sometimes the argument lists also get uncomfortably long. If I wrap everything up inside MyClass, then I can put all this information in member variables of the MyClass instance. These become not-quite-global variables, and they're generally stuff that feels like it make sense to store in a class.

Does this practice have a name? Is it a pattern, or an anti-pattern? And if the latter, how should I structure my code instead?

答:
Like Ixrec said - put the implementation in another file. But since you need a state that you don't want to make global - put that state in a class!

OK, that came up a bit confusing. What I mean is to keep the class, but hide it from the user. The user will only see a global function that internally creates the class and call it's go method. Actually - ditch the go. Since all it does is calling other functions, you probably should do that from that external function.

So, instead of

```<code>class MyClass:
    def __init__(self):
        self.x = 1
        self.y = 2

    def op1(self):
        self.x += self.y

    def op2(self):
        self.y += self.x

    def go(self):
        self.op1()
        self.op2()
        return self.x * self.y
</code>```

Write this:

```<code>class __MyClass:
    def __init__(self):
        self.x = 1
        self.y = 2

    def op1(self):
        self.x += self.y

    def op2(self):
        self.y += self.x

    def calc_result(self):
        return self.x * self.y

def my_function():
    my_object = __MyClass()
    my_object.op1()
    my_object.op2()
    return my_object.calc_result()
</code>```

That way, you still have a class that holds all the data, but the user sees a single function.

Body:
Like Ixrec said - put the implementation in another file. But since you need a state that you don't want to make global - put that state in a class!

OK, that came up a bit confusing. What I mean is to keep the class, but hide it from the user. The user will only see a global function that internally creates the class and call it's go method. Actually - ditch the go. Since all it does is calling other functions, you probably should do that from that external function.

So, instead of

class MyClass:
    def __init__(self):
        self.x = 1
        self.y = 2

    def op1(self):
        self.x += self.y

    def op2(self):
        self.y += self.x

    def go(self):
        self.op1()
        self.op2()
        return self.x * self.y

Write this:

class __MyClass:
    def __init__(self):
        self.x = 1
        self.y = 2

    def op1(self):
        self.x += self.y

    def op2(self):
        self.y += self.x

    def calc_result(self):
        return self.x * self.y

def my_function():
    my_object = __MyClass()
    my_object.op1()
    my_object.op2()
    return my_object.calc_result()

That way, you still have a class that holds all the data, but the user sees a single function.


问:
How to write a test to cover a bugfix of a segfault
There was a bug that I recently fixed that was causing a segmentation fault (due to an out-of-bounds access).  The maintainer of the project is asking me to write a unit test to cover the bugfix.

How can I do this?  The bug exhibited undefined behavior, so even if my test passed, it's not proof of anything.  Should I use a loop to test it 100 times to make the test more likely to catch a regression?

答:
If your language supports bounds checks, activate them for testing. That's certainly the easiest and the safest way to do this. As someone suggested in the comments, why not declare @cython.boundscheck(isDebug) where isDebug is defined at the beginning of the module (I've never worked with cython, so I'm not sure it's that easy)

That said, there are cases when you can't just activate bounds checks (example: you're using a low-level library like LAPACK or IPP that just takes a buffer and expects it to be the right size). The only way I'm aware of to guarantee access violations here is to use low-level operating system functions to allocate memory in such a way that the address immediately before (or after) the allocated block is read and write protected. On windows, VirtualAlloc, VirtualProtect and friends let you do things like that. It wastes a lot of memory and you can only protect the space before or after the block (unless the size of the buffer is a multiple of a memory page size). But to find hard-to-reproduce out of bounds memory access errors, it's sometimes worth all that.


问:
Ternary operator considered harmful?
For example, would you prefer this one-liner

```<code>int median(int a, int b, int c) {
    return (a<b) ? (b<c) ? b : (a<c) ? c : a : (a<c) ? a : (b<c) ? c : b;
}
</code>```

or an if/else solution involving multiple return statements?

When is ?: appropriate, and when is it not? Should it be taught to or hidden from beginners?

答:
Absolutely not evil. In fact, it's pure, and if-then-else isn't.

In functional languages like Haskell, F#, ML etc., it's the if-then-else statements that are considered evil.

The reason for this is that any "action" like an imperative if-then-else statement requires you to separate a variable declaration from its definition, and introduces state to your function.

For instance, in the following code:

```<code>const var x = n % 3 == 1
    ? Parity.Even
    : Parity.Odd;
</code>```

vs.

```<code>Parity x;
if (n % 3 == 1)
    x = Parity.Even;
else
    x = Parity.Odd;
</code>```

The first one has two advantages aside from being shorter:

x is a constant, and so offers much fewer chance of introducing bugs, and can potentially be optimized in ways the second could never be.

The type is made clear by the expression, so the compiler can effortlessly infer that x needs to be of type Parity.

Confusingly, in functional languages, the ternary operator is often called if-then-else. In Haskell, you might say x = if n mod 3 == 1 then Odd else Even.

Title: Ternary operator considered harmful?

Body:
Absolutely not evil. In fact, it's pure, and if-then-else isn't.

In functional languages like Haskell, F#, ML etc., it's the if-then-else statements that are considered evil.

The reason for this is that any "action" like an imperative if-then-else statement requires you to separate a variable declaration from its definition, and introduces state to your function.

For instance, in the following code:

const var x = n % 3 == 1
    ? Parity.Even
    : Parity.Odd;

vs.

Parity x;
if (n % 3 == 1)
    x = Parity.Even;
else
    x = Parity.Odd;

The first one has two advantages aside from being shorter:

x is a constant, and so offers much fewer chance of introducing bugs, and can potentially be optimized in ways the second could never be.

The type is made clear by the expression, so the compiler can effortlessly infer that x needs to be of type Parity.

Confusingly, in functional languages, the ternary operator is often called if-then-else. In Haskell, you might say x = if n mod 3 == 1 then Odd else Even.


问:
Compilation to bytecode vs machine code
Does compilation that produces an interim bytecode (like with Java), rather than going "all the way" to machine code, generally involve less complexity (and thus likely take less time)? </p>

答:
The complexity of compilation depends largely on the semantic gap between the source language and the target language and the level of optimization you want to apply while bridging this gap.

For example, compiling Java source code to JVM byte code is relatively straight forward, since there is a core subset of Java that maps pretty much directly to a subset of JVM byte code. There are some differences: Java has loops but no GOTO, the JVM has GOTO but no loops, Java has generics, the JVM doesn't, but those can be easily dealt with (the transformation from loops to conditional jumps is trivial, type erasure slightly less so, but still manageable). There are other differences but less severe.

Compiling Ruby source code to JVM byte code is a lot more involved (especially before invokedynamic and MethodHandles were introduced in Java 7, or more precisely in the 3rd Edition of the JVM spec). In Ruby, methods can be replaced at runtime. On the JVM, the smallest unit of code that can be replaced at runtime is a class, so Ruby methods have to be compiled not to JVM methods but to JVM classes. Ruby method dispatch doesn't match JVM method dispatch and before invokedynamic, there was no way to inject your own method dispatching mechanism into the JVM. Ruby has continuations and coroutines, but the JVM lacks the facilities to implement those. (The JVM's GOTO is restricted to jump targets within the method.) The only control flow primitive the JVM has, that would be powerful enough to implement continuations are exceptions and to implement coroutines threads, both of which are extremely heavyweight, whereas the whole purpose of coroutines is to be very lightweight.

OTOH, compiling Ruby source code to Rubinius byte code or YARV byte code is again trivial, since both of those are explicitly designed as a compilation target for Ruby (although Rubinius has also been used for other languages such as CoffeeScript, and most famously Fancy).

Likewise, compiling x86 native code to JVM byte code is not straight-forward, again, there is a pretty large semantic gap.

Haskell is another good example: with Haskell, there are several high-performance, industrial strength production-ready compilers which produce native x86 machine code, but to this date, there is no working compiler for either the JVM or the CLI, because the semantic gap is so big that it is very complex to bridge it. So, this is an example where compilation to native machine code is actually less complex than compiling to JVM or CIL byte code. This is because native machine code has much lower level primitives (GOTO, pointers, …) that can be easier "coerced" to do what you want than using higher level primitives such as method calls or exceptions.

So, one could say that the higher level the target language is, the more closely it has to match the semantics of the source language in order to reduce the complexity of the compiler.

Title: Compilation to bytecode vs machine code


问:
Why don't Windows/Linux use relational Databases (RDBMS)?
Why don't Windows/Linux use relational databases (RDBMS)?

I know they use file systems to store all data but don't you think it is more efficient to use databases like we use in web sites/web apps?

Please elaborate on the use of a file system over a database for storage.

This is not a duplicate of When should use of database be preferred over parsing data from a text file? I am talking in terms of only operating system contexts, and that question is generalized.

答:
I think the other answers provide a wide spectrum of reasons as to why operating systems do not rely on relational databases internally/exclusively so I'll just share an interesting piece of information that I once stumbled upon.

Apparently, there are technologies that allow you to mount relational databases as file systems when their use is justified. Oracle DBFS (Database File System) is an example. This snippet from the documentation explains the rationale behind it quite well:

Database File System (DBFS) leverages the features of the database to store files, and the strengths of the database in efficiently managing relational data, to implement a standard file system interface for files stored in the database. With this interface, storing files in the database is no longer limited to programs specifically written to use BLOB and CLOB programmatic interfaces. Files in the database can now be transparently accessed using any operating system (OS) program that acts on files.

The solution provides a set of interfaces (command line clients, code libraries) for LOB data that is stored in database tables. This can be used on Windows and Linux operating systems (although as far as I can tell, the level of integration varies between them)

Source: docs.oracle.com

According to the documentation, the file system should be possible to use in a transparent manner on Linux

On Linux, the dbfs_client also has a mount interface that utilizes the Filesystem in User Space (FUSE) kernel module to implement a file-system mount point that provides transparent access to the files stored in the database and requires no changes to the Linux kernel. It receives standard file system calls from the FUSE kernel module, and translates them into OCI calls to the PL/SQL procedures in the DBFS Content Store.

Therefore, the answer to your question is that, in general, there's no reason for an operating system to use a relational database as a file system (and in case of the core components of an OS, this would actually be troublesome). At the same time it is possible for one to do it when some problem calls for it.


答:
Perhaps I can flip the question around, and ask if there is anything in programming that is absolutely and perfectly good?  If you can't think of one thing (I know I can't), then the concept of evil is also just as muddy.

There are common behaviors that lead to mistakes, misunderstandings, and other general confusion--but to say that language feature X is inherently evil is to admit that you really don't understand the purpose of feature X.

There are common behaviors that can save a lot of heartache and avoid some misunderstandings--but to say that language feature Y is inherently good is to admit that you don't fully understand all the implications of using feature Y.

We are a people of finite understanding, and strong opinions--a dangerous combination.  Hyperbole is just a way of expressing our opinions, exagerating facts until they become fiction.

Nevertheless, if I can avoid behaviors that lead to problems and pursue behaviors that avoid them, I just might be a bit more productive.  At the end of the day that's what it's all about.

Title: Is anything in programming truly evil?

Body:
So, there are a bunch of questions appearing asking is X evil, is Y evil.

My view is that there are no language constructs, algorithms or whatever which are evil, just ones which are badly used.  Hell, if you look hard enough there are even valid uses of goto.

So does absolute evil, that is something which is utterly incompatible with best practice in all instances, exist in programming?  And if so what is it?  Or is it just bad programmers not knowing when something is appropriate?

Edit: To be clear, I'm not talking about things programmers do (such as not checking return codes or not using version control - they're choices made by bad programmers), I mean tools, languages, statements, whatever which are just bad...


问:
UML : What is an Activity in an Activity diagram?
I am translating a Use Case diagram step into an Activity Diagram. Does every step of my UC diagram describe an Activity ? Is there one and only one Activity in an Activity Diagram ?</p>

答: An activity is an ongoing nonatomic execution within a state machine. The ovals on an activity diagram are either action states or activity states.  Action states are the atomic execution of an operation.   Activity states are nonatomic and can be decomposed on another activity diagram.  So, no, there does not have to one and only only activity per activity diagram.  And, no, every step of a use case does not necessarily correspond to an activity.  They may be action states or activity states or possibly neither.


问:
How to decompose Monolithic applications into Microservices with interdependent functional modules?
I work with a large monolithic web application that has between 12-24 functional modules and these are all maintained inside a single war project structure.  While the code itself is already segmented into well defined and independent packages, there are implications to deploying a single web application in this way from scaling to maintainability and so forth; very much what most industry advocates say is problematic with this type of architectural design.

I want to split this monolithic application into smaller deploy-able components, but there are a few issues that make this difficult for me to grasp.

Domain Model

Nearly all of our domain model classes have some relationship with other domain model classes from other modules.  For example, a Product contains a relationship to a User that created the record and User resides in a common module while Product is in inventory.

Many microservice advocates tend to suggest that each microservice be self contained and have it's own set of resources.  This would imply it's own database, generally speaking but a self contained schema in a shared database is possible.  We know foreign keys are available across schema boundaries, but certain not that of databases.

The question then becomes whether Product should merely store the id or name of the User and then have the service call the User service to get user details if some end point requires that additional data rather than imposing it via foreign keys?

Web/UI

In our case, there are often times when business wants to capture additional data points that require not only a UI adjustment but a domain model adjust.  So, should the Web/UI be included along with the microservice and it's domain model classes in a single deployable artifact?  There is inherent coupling between this code, but the coupling between layers is based on well defined interface contracts.

I guess the question is then around scalability.  If the two were deployed separately, the backend service or the Web/UI could be scaled independently where-as being deployed together wouldn't allow for such design.

答:
Regarding your first question: for proper decoupling services should only store IDs of objects belonging to other services 9if they can not avoid the dependency at all). Sometimes the dependency can be extracted to a separate "hub" service whose sole role is connecting data retrieved from other services which themselves are not aware of the dependency. An example could be having a "customer service", a "product service" and a "pricing service" which would by themselves not know at all about any other, and on top of that an "order service" which could store the IDs of the customer, order and pricing information that participate in an order and implement all business logic related to order processing. This way three services can do without any external dependencies or any knowledge about any other services' domain models.

Regarding the second question, it is usually good to separate the UI from backend services and their data models. It does require some additional boilerplate code and repackaging of data, but the UI model spilling back to domain model can be much worse (messy code, forcing this mess onto other cosumers of the service's data).


答:
Uncomfortably long argument lists and multiple return values can usually be addressed by grouping values into structured data types or encapsulating them in classes. If there are no clear groupings, hiding that by sweeping it into object state with other unrelated values is only furtherly detrimental.

Methods (even methods intended to be private) should leave objects in a consistent state when they return. That becomes more difficult to achieve as the object's state gets more complex. Often it means factoring out some code into external/static functions so that you have: 1) a method that transitions the object from one valid state to another, which is accomplished by 2) functions that implement well-defined procedures, which may be passed a subset of values from the object state, but are separately testable.

Lastly, a function should be exposed as a function. That means clients should be calling my_function(some_args) and not MyClass(some_args).go(). If my_function is implemented as the latter, you are at least isolating client code from its ambiguities.

Title: Using a one-shot class to store not-quite-global variables

Body:
I sometimes find myself writing classes (in Python, in my case) that are used like this:

```<code>MyClass(some_args).go()
</code>```

In other words, there's only one method in the class that any external code would call, and it will only ever get called once. There might be a return value from go() but often there isn't, and when there isn't, I could even call go from the class's __init__.

So why even bother with the class, instead of just writing go() as a standalone function? Because what goes on inside go is complicated. There may be several levels of nested function calls, and there are certain pieces of information that are needed in different spots. If I try to write all this without a class, I end up with a many of the functions returning multiple values. Sometimes the argument lists also get uncomfortably long. If I wrap everything up inside MyClass, then I can put all this information in member variables of the MyClass instance. These become not-quite-global variables, and they're generally stuff that feels like it make sense to store in a class.

Does this practice have a name? Is it a pattern, or an anti-pattern? And if the latter, how should I structure my code instead?


问:
how to test a generator with unittest?
I have programmed a small iterator in Python:

```<code>class anything():
    def __init__(self):
        self.i=1

    def __iter__(self):
        return self

    def next(self):
        if self.i>100:
            raise StopIteration
        self.i=self.i+1
        return self.i
</code>```

and I would like to use unittest of Python to check if some value on the generated list is even (I am just doing it for learning testing unit in Python). So I would like to have something like:

```<code>def main()
   for x in anything():
        assert x%2==0
</code>```

but I just do not know how to accomplish that. I have read some material online, but there are no examples that teach how to manage the unit test within classes.

答:
Below is an example of a test. BTW, you have a bug in your class. Probably self.i=self.i+i should be self.i=self.i+1

```<code>#!/usr/bin/env python
# -*- Python -*-
"Unit test for Columnize"
import unittest
from it import anything

class TestI(unittest.TestCase):

    def test_basic(self):
        for x in anything():
            if x % 2 == 0:
                self.assertTrue(True, "Found value %d" % x)
                return
        self.assertTrue(False, "No even found in Anything")

if __name__ == '__main__':
    unittest.main()
</code>```

Title: how to test a generator with unittest?

Body:
Below is an example of a test. BTW, you have a bug in your class. Probably self.i=self.i+i should be self.i=self.i+1

#!/usr/bin/env python
# -*- Python -*-
"Unit test for Columnize"
import unittest
from it import anything

class TestI(unittest.TestCase):

    def test_basic(self):
        for x in anything():
            if x % 2 == 0:
                self.assertTrue(True, "Found value %d" % x)
                return
        self.assertTrue(False, "No even found in Anything")

if __name__ == '__main__':
    unittest.main()


答: Today's evil was yesterdays perfect.  It's evolution.</p>

Title: Is anything in programming truly evil?


答:
This is a natural progress of encapsulation, abstraction, and general code organization. As you extract pieces of code from a function into their own separate functions, you may notice that they share a lot of state that requires passing numerous parameters around. Promoting this state to fields of a class -- and said functions to methods of the class -- helps to reduce clutter and improve readability.

Note that in language like Python, where standalone functions are allowed, you may want to hide the existence of your class behind a function that both instantiates the object and calls its go method. This way, the class becomes an implementation detail and your API remains the same, even if e.g. the logic becomes complicated enough to warrant a whole subpackage.


问:
Shape-Checking algorithm
I normally have a very intuitive approach to an efficient algorithm. In essence, I know what the bottleneck is, and how I can improve the algorithm. However, I'm now stuck and I am in the need of some "inspiration".

The problem

The idea itself is very easy. I have a matrix of n x m booleans. I input another grid, also of n x m booleans. The question this algorithm has to solve is if the input shape can ever be matched on the output shape: this may be done by mirroring, rotating and moving the input shape around. I only need to know if the two shapes can be matched or not: the actual transformations do not matter.

Examples:

Target shape:

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

Input:

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

Clearly, this can be done. The transformation is simple:

1) Rotate counterclockwise:

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

2) Move down:

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

A quick check can easily be done: count how many zeros or ones are in the input matrix. If this doesnt match the numbers of zeros and ones in the target shape, then the target shape cannot be made.

A more broader, general question would be what specific class of algorithm I'm looking for. It isn't really clear for me, though using my example I'd say that a carefully constructed pathfinding algorithm could work.

I also want to note that I am not a computer science student, programming is one of my hobbies. I do have proper understanding of "basic matrix manipulations" - maybe there is a wonderful "math trick" for this.

答:
You can simply "trim" the shapes (remove rows and columns full of 0) and then try the 8 rotations + reflections.

This also gives you another heuristic: after trim the size must be the same or a rotation

Title: Shape-Checking algorithm


问:
Has variable width types been replaced by fixed types in modern C?
I came across an interesting point today in a review over on Code Review. @Veedrac recommened in this answer that variable size types (e.g. int and long) be replaced with fixed size types like uint64_t and uint32_t. Citation from the comments of that answer:

The sizes of int and long (and thus the values they can hold) are
  platform-dependent. On the other hand, int32_t is always 32 bits long.
  Using int just means that your code works differently on different
  platforms, which is generally not what you want.

The reasoning behind the standard not fixing the common types is partially explained here by @supercat. C was written to be portable across architectures, in contrary to assembly which was usually used for systems programming at the time.

I think the design intention was originally that each type other than
  int be the smallest thing that could handle numbers of various sizes,
  and that int be the most practical "general-purpose" size that could
  handle +/-32767.

As for me, I've always used int and not really worried about the alternatives. I've always thought that it is the most type with best performance, end of story. The only place I thought fixed width would be useful is when encoding data for storage or for transfer over a network. I've rarely seen fixed width types in code written by others either.

Am I stuck in the 70s or is there actually a rationale for using int in the era of C99 and beyond?

答:
There is a common and dangerous myth that types like uint32_t save programmers from having to worry about the size of int.  While it would be helpful if the Standards Committee were to define a means of declaring integers with machine-independent semantics, unsigned types like uint32_t have semantics which are too loose to allow code to be written in a fashion which is both clean and portable; further, signed types like int32 have semantics which are for many applications ways defined needlessly tightly and thus preclude what would otherwise be useful optimizations.

Consider, for example:

```<code>uint32_t upow(uint32_t n, uint32_t exponent)
{
  while(exponent--)
    n*=n;
  return n;
}

int32_t spow(int32_t n, uint32_t exponent)
{
  while(exponent--)
    n*=n;
  return n;
}
</code>```

On machines where int either cannot hold 4294967295, or can hold 18446744065119617025, the first function will be defined for all values of n and exponent, and its behavior will not be affected by the size of int; further, the standard will not require that it yield different behavior on machines with any size of int  Some values of n and exponent, however, will cause it to invoke Undefined Behavior on machines where 4294967295 is representable as an int but 18446744065119617025 is not.

The second function will yield Undefined Behavior for some values of n and exponent on machines where int cannot hold 4611686014132420609, but will yield defined behavior for all values of n and exponent on all machines where it can (the specifications for int32_t imply that two's-complement wrapping behavior on machines where it is smaller than int).

Historically, even though the Standard said nothing about what compilers should do with int overflow in upow, compilers would have consistently yielded the same behavior as if int had been large enough not to overflow.  Unfortunately, some newer compilers may seek to "optimize" programs by eliminating behaviors not mandated by the Standard.

Body:
There is a common and dangerous myth that types like uint32_t save programmers from having to worry about the size of int.  While it would be helpful if the Standards Committee were to define a means of declaring integers with machine-independent semantics, unsigned types like uint32_t have semantics which are too loose to allow code to be written in a fashion which is both clean and portable; further, signed types like int32 have semantics which are for many applications ways defined needlessly tightly and thus preclude what would otherwise be useful optimizations.

Consider, for example:

uint32_t upow(uint32_t n, uint32_t exponent)
{
  while(exponent--)
    n*=n;
  return n;
}

int32_t spow(int32_t n, uint32_t exponent)
{
  while(exponent--)
    n*=n;
  return n;
}

On machines where int either cannot hold 4294967295, or can hold 18446744065119617025, the first function will be defined for all values of n and exponent, and its behavior will not be affected by the size of int; further, the standard will not require that it yield different behavior on machines with any size of int  Some values of n and exponent, however, will cause it to invoke Undefined Behavior on machines where 4294967295 is representable as an int but 18446744065119617025 is not.

The second function will yield Undefined Behavior for some values of n and exponent on machines where int cannot hold 4611686014132420609, but will yield defined behavior for all values of n and exponent on all machines where it can (the specifications for int32_t imply that two's-complement wrapping behavior on machines where it is smaller than int).

Historically, even though the Standard said nothing about what compilers should do with int overflow in upow, compilers would have consistently yielded the same behavior as if int had been large enough not to overflow.  Unfortunately, some newer compilers may seek to "optimize" programs by eliminating behaviors not mandated by the Standard.


答:
Magic numbers.

Implicitness is inherently evil, and here's the reason why:

Title: Is anything in programming truly evil?


问:
What is faster? Using REST API or querying a database directly?
What is faster performance wise? Creating a REST API and having your web app use the REST API to do all interactions with your database OR querying your database directly (i.e. using whatever typical object your language uses to query a database such as JDBC for Java)?

The way I see it with REST:

You make an object in your code to call the REST method

Call http method

Code inside your REST API queries the database

Database returns some data

REST API code packs up the data into Json and sends it to your client

Client receives Json/XML response

Map response to an object in your code

On the other hand, querying a database directly:

You make an object with query string to query the database

Database returns some data

Map response to an object in your code

So wouldn't this mean that using a REST API would be slower? Maybe it depends on the type of database (SQL vs NoSQL)?

答:
I don't know where you get lost, but it is pretty clear, when you're using REST API you are doing extra step, and extra step "always" mean slower when programming involved.

There's pros and cons, but if you can access database directly from your application it always better to call it directly instead of using Web API, of course if you use Web API you can easily port your application to different platform.


答:
When you add complexity the code will run slower.  Introducing a REST service if it's not required will slow the execution down as the system is doing more.

Abstracting the database is good practice.  If you're worried about speed you could look into caching the data in memory so that the database doesn't need to be touched to handle the request.

Before optimizing performance though I'd look into what problem you're trying to solve and the architecture you're using, I'm struggling to think of a situation where the database options would be direct access vs REST.

Title: What is faster? Using REST API or querying a database directly?

Body:
What is faster performance wise? Creating a REST API and having your web app use the REST API to do all interactions with your database OR querying your database directly (i.e. using whatever typical object your language uses to query a database such as JDBC for Java)?

The way I see it with REST:

You make an object in your code to call the REST method

Call http method

Code inside your REST API queries the database

Database returns some data

REST API code packs up the data into Json and sends it to your client

Client receives Json/XML response

Map response to an object in your code

On the other hand, querying a database directly:

You make an object with query string to query the database

Database returns some data

Map response to an object in your code

So wouldn't this mean that using a REST API would be slower? Maybe it depends on the type of database (SQL vs NoSQL)?


问:
SDK/DB isDeleted vs Integration Testing
((Using "users" as an example to represent one of many record types))

An application with user tracking typically has a User table.  Many, if not all, companies mandate that a User record should never be actually deleted.  Instead, a discrimating field "isDeleted" should be added.  The other possibility is a shadow table that tracks deleted users and its own set of questions which shouldn't be addressed here.

So in general, to retrieve a list of users, I may have a method like so:

public ICollection<User> GetUsers() {
    return Users.Where(x => x.isDeleted == false);
}
```

<p>So I have an SDK which wraps a web service which call domain services which depend on data access which hits my database.  The eventuallity is something like so:</p>

<pre class="lang-cs prettyprint-override"><code>public void DeleteUser(int id) {
    var user = Users.Where(x => x.id == id).Single();
    user.isDeleted = true;
    user.SaveDatShiz();
}
</code>```

So what about my Integration Test?  I have an Integration Test something like so:

public void TestUserCreation() {
    Dependency.CreateUser(user);
    var integratedUser = Dependency.GetUserBySomething(user.Something);
    Assert.AreEqual(integratedUser, user, "wut?");
    Dependency.DeleteUser(integratedUser.id); //Clean up!
}
```

The key above is that my Integration Test thinks it is cleaning up, but in reality, my Production Database has three times more fake test users than actual users.  The table is SUPER bloated from running Integration Tests on Deployment in a Continuous Deployment environment.

So how do I let my Integration Tests ACTUALLY Delete a user?  I'm not asking for a code answer, I'm asking for a architecturally correct answer.

E.G.: Should I create an endpoint that actually does a delete, but require a key that only the Integration Test knows?  That seems messy...

E.G.2: Should I get access directly to the production database and run delete queries against it?  (Lol, totally lawl no.)

E.G.3: Nobody else worries about this, so I shouldn't (Non-Refundable!!! I mean.. Not Acceptable!!!!)

答:
Firstly, I'd try to not run tests on true production databases if possible, but I know this cannot always be avoided.

In my tests of this type, I ensure the database is as expected with a range of simple AddEntry, DeleteEntry, AssertEntry and AssertEntryCount routines that either insert, delete, assert the content of, or assert the expected count of rows in tables with specified fields and values.

These have a TableName parameter and then a ParamArray parameter called ColumnsAndValuesAndOptionalConnectString (as well as a couple of straight SQL query overloads) that expects field names, then the same number of values and finally an optional connection string.

In your case, I'd have one (or as few as possible) test that creates a new user and if it succeeds the cleanup does actually drop the user created.

The rest should refer to a single (or again as few as possible) "Integration Testing" user that is normally marked as deleted, but that user is undeleted while tests are performed upon it.

To answer your question: "Should I provide a way to really delete a user?" If you don't want to access the database directly to "run delete queries against it", you have to choose between creating new test users for every test or creating some code path that actually deletes users. If you do go for the second option you can make the user deletion routine only available to your test code by a number of means, and depending upon your development environment, you may be able to avoid showing it on your public API.

Perhaps the most straightforward solution is to identify test users in some explicit way and define a DeleteTestUser public API that is documented to only delete test users, but does so completely.

Title: SDK/DB isDeleted vs Integration Testing


问:
Is anything in programming truly evil?
So, there are a bunch of questions appearing asking is X evil, is Y evil.

My view is that there are no language constructs, algorithms or whatever which are evil, just ones which are badly used.  Hell, if you look hard enough there are even valid uses of goto.

So does absolute evil, that is something which is utterly incompatible with best practice in all instances, exist in programming?  And if so what is it?  Or is it just bad programmers not knowing when something is appropriate?

Edit: To be clear, I'm not talking about things programmers do (such as not checking return codes or not using version control - they're choices made by bad programmers), I mean tools, languages, statements, whatever which are just bad...

答:
Everything that happens to work just by accident is inherently evil.

Let's consider the following C program, which happens to actually work on my machine, using default compiler options:

```<code>#include <stdio.h>
int main(int argc, char *argv[]) {
   char string[10];
   int y;
   for (y=0; y<10; string[12]++) {
      printf("%d\n", y);
   }
}
</code>```

Nothing, really nothing could ever excuse the way this program increments the loop counter. It's just a undefined effect that happens to do the right thing on my machine, my compiler, my default options.

Title: Is anything in programming truly evil?

Body:
Everything that happens to work just by accident is inherently evil.

Let's consider the following C program, which happens to actually work on my machine, using default compiler options:

#include <stdio.h>
int main(int argc, char *argv[]) {
   char string[10];
   int y;
   for (y=0; y<10; string[12]++) {
      printf("%d\n", y);
   }
}

Nothing, really nothing could ever excuse the way this program increments the loop counter. It's just a undefined effect that happens to do the right thing on my machine, my compiler, my default options.


问:
Early subtasking at the beginning of each sprint
I have joined a new team which is using Agile/Scrum, and their development process is as follows:

1) developers review each story before each sprint to make sure it doesn't miss anything critical. There's a formal state for that in the workflow.

2) during the Sprint kickoff, the entire team does an estimation (poker planning) on how many story points each story would cost.

3) finally, immediately after each sprint starts, each developer is required to eagerly break down all of assigned stories into subtasks with time estimates (as opposed to subtasking before starting each story).

The main argument for the last step is that it helps to discover if implementing a story would take longer than anticipated and warn scrum master about potential risks of missing sprint deadlines.

Yet I find this counter-productive, mainly because of the following reasons:

if the aim is to provide rough estimate, story points (step #2) is what does the job. Otherwise why bother with story points at all? - just do subtasking early on.

if the aim is to provide accurate estimates, then this is a clear example of what is described in Human Task Switches Considered Harmful. This, I think, is especially the case for fresh developers who join existing teams in big projects where understanding what needs to be done can take up to 50% of the time. You are required to get into details of story #1, then story #2, #3, etc. etc. which yields a lot of information churn.

I am also being told that such practice is "by the book" and I'm not even meant to discuss this. Can anyone provide a reference to such practice - whether this is clearly defined in Scrum bibles, and/or perhaps provide any extra insight?

答:
If that's how your company wants to run their development and have shut down discussion, your choices are limited, or you at least run the risk of upsetting people.

Given that the ultimate goal of agile is working software of value, you could try offering to help out by measuirng your team's ability to deliver (points delivered/estimated, bugs in sprint, no. of tests, code coverage, uptime, sales generated - whatever). Be prepared for all outcomes - it may be that this way of working works for them even if it makes no sense to you. If you are right the waste will become self evident.

Be wary of following process for process sake - this wastes time and still delivers poor products. A good agile team experiments, measures and learns. The best way to change behaviour without descending into opinion is with evidence based decisions.

This is also my opinion. I suggest you try for yourself and measure the outcome - see what I did there :)


答:
If you're concern is speed, then yes a Rest service will be slower for the reasons stated above. However, speed of the type you describe is rarely the primary concern and if it is, can be addressed in other ways. Premature optimisation is the root of all evil.

Consider if your primary concern is interoperability (mobile, web, B2B), now REST is very attractive because it is technology agnostic.

Suppose you code for a database. What would you do if you choose to change your underlying data store. How hard would it be to do if you are tightly coupled to the underlying store?

The real answer is it depends, but hopefully I've given you some things to think about!


问:
What are the most used pattern to manage a lot of interconnected parameters?
I recently start to work on an application that drive different measurement device.

Before the user start a measure, she sets the parameters of it.

Actually, considering all measurements type there are 50+ parameters.

The difficulty here is that every settings depends on others for:

Being available

List of available values

so on..

Moreover, some measurement settings depend on previous measure results and settings.

To make it short : we have a lot of stuff that are interconnected.

The actual pattern is to validate everything as soon as a values is changed. It cost a lot (in time) and we are going to add a lot of more parameters : it will break.

We try to implement a pattern where we use ObservableValues and where all parameters register on all values it depend on.

It became hard when the parameters depend on an other reference measure. If the reference change, we have to stop listening on the previous reference and start to listen on the new reference.

Etc...

An other issue is that when we work on our pattern and we had more capabilities (like serialization), or when we had some helper class (like factory), we build big files with 50+ parameters or functions.

Is there any other good pattern or library to do it ?

答:
There are tools to help you manage the complexity; see for example the Feature Model approach.

However, if I had to do it, I'd try to go for a constraint programming approach (feature trees are basically a simplified notation for constraints).
Since you are using C#, I am going to point you to Prolog.NET. Note however that even though I already used Prolog, I don't know Prolog.Net specifically.

Note: I will edit this answer later with an example, if possible (I don't have much time now). By the way, I'd rather use one of your example, if you could provide some.


问:
How should a developer reject impossible requirements?
Here's the problem I'm facing:

Quote From Project Manager:

Hey Spark, I'm assigning you the task of developing a framework that could be used for many different iOS applications. Here are the requirements:

It should be able to detect the thickness of the thumb or fingers being used to manipulate the UI.

With this information, all elements of the UI should be arranged & sized automatically.

For a larger thumb, elements should be arranged nearer the center of the screen.

For a smaller thumb, elements should be arranged nearer the corners of the screen.

For a larger thumb, all fonts should be smaller. (We're assuming an adult in this case.)

For a smaller thumb, all fonts should be larger. (We're assuming a younger person in this case.)

Summary:

This framework is required for creating user-friendly user interfaces programmatically. The framework should be developed in such a way that we can use for as many projects as needed, so it must also be very developer-friendly.

I am the developer given this task, so my questions are as follows:

How can I explain that these requirements are a little ridiculous?

How can I explain that it would be better to concentrate on developing actual projects?

How can I explain that even if this were possible, I wouldn't recommended developing such a thing?

How do I say NO to this project politely, gently, and respectfully?

How can I explain that even for a developer with 3 years of experience, this might not be possible?

答:
Don't outright say no as that would hurt his feelings. Just make it clear that due to technology constraints that 60% of the time it will work every time.

And once he realises the impracticality and cost involved in such an undertaking, suggest a more practical approach within his budget such as having a setting that allows you to change text size. And the Russians took a pencil into space.

Try to get him to state the problem and requirement and not the solution and design for future projects.


问:
What is the point of designing Lua C APIs?
I am a newbie of Lua. After studying some Lua C APIs examples, I am a little confused.

I can see the Lua C API is used for processing Lua scripts:

```<code>......
lua_State *L = luaL_newstate();
luaL_openlibs(L);
luaL_loadfile(L, argv[1]);
lua_call(L, 0, 0);
lua_close(L);
......
</code>```

Or calling a Lua function from C code:

```<code>/* calling f("hello", 4.5) */
lua_getglobal(L, "f");
lua_pushstring(L, "hello");
lua_pushnumber(L, 4.5);
lua_call(L, 2, 1);
</code>```

So what is the point of designing Lua C APIs? If just do these functions, I think call lua program is enough, no need to use Lua C APIs.

答:
There are many situations when calling Lua functions from a program written in another language is better than calling a Lua script.

When you distribute a program that does useful things, it's easier to link the relevant part of the Lua library in and do things within your program than to bundle the entire Lua system and install that for every user of your program. Not everybody wants that much extra code, some users will already have Lua installed, you have to keep the user's Lua separate from your bundled Lua, etc.

Bundling the entire language can take up a lot of space. Linking only some functions in can make the resulting package of your program much smaller.

It's more efficient not to create a new process every time you want to use the functionality implemented in Lua. If this is several times per second, the speed-up will be substantial.

Passing data to a new process and receiving return data is complicated; you have to either set up inter-process communication via shared memory, pipes, ports or something similar, or parse the STDOUT of the external program. That works fine for small values, but not wel lat all for large, structured data.

Note that not all of these reasons always apply. There are many use cases where none apply, and bundling the scripting language is in fact the better solution. But there certainly are other cases where bundling would be overkill, and that's why the programmatic API exists.


答:
Create a Parameter class (assuming C#):

class Parameter<T>
{
  T Value;
  string Name;
}

Then build a graph with nodes containing Parameter values and dependencies as their references in the same graph.

And next do all the operations on the graph as a whole, not directly on parameters:
graph.SetValue(parameter, value)
or
graph.SetValue(parameterName, value)

Title: What are the most used pattern to manage a lot of interconnected parameters?

Body:
I recently start to work on an application that drive different measurement device.

Before the user start a measure, she sets the parameters of it.

Actually, considering all measurements type there are 50+ parameters.

The difficulty here is that every settings depends on others for:

Being available

List of available values

so on..

Moreover, some measurement settings depend on previous measure results and settings.

To make it short : we have a lot of stuff that are interconnected.

The actual pattern is to validate everything as soon as a values is changed. It cost a lot (in time) and we are going to add a lot of more parameters : it will break.

We try to implement a pattern where we use ObservableValues and where all parameters register on all values it depend on.

It became hard when the parameters depend on an other reference measure. If the reference change, we have to stop listening on the previous reference and start to listen on the new reference.

Etc...

An other issue is that when we work on our pattern and we had more capabilities (like serialization), or when we had some helper class (like factory), we build big files with 50+ parameters or functions.

Is there any other good pattern or library to do it ?


答:
Lua is not only -and not mainly- a standalone interpreter program (/usr/bin/lua on my Linux/Debian desktop) of the Lua scripting language, but Lua is mostly a library to embed an interpreter into (existing) applications (e.g. luatex is embedding Lua inside tex).

This is the main strength of Lua, to be embeddable in your application. Lua was originally designed for that purpose. So you have some existing application, and you can (with not too much efforts) embed the Lua interpreter library inside your application to enable some parts of it to be scriptable by Lua.

This is explained in the chapter §24 – An Overview of the C API, which starts with:

Lua is an embedded language. That means that Lua is not a stand-alone package, but a library that can be linked with other applications so as to incorporate Lua facilities into these applications.

You may be wondering: If Lua is not a stand-alone program, how come we have been using Lua stand alone through the whole book? The solution to this puzzle is the Lua interpreter (the executable lua). This interpreter is a tiny application (with less than five hundred lines of code) that uses the Lua library to implement the stand-alone interpreter. This program handles the interface with the user, taking her files and strings to feed them to the Lua library, which does the bulk of the work (such as actually running Lua code).

This ability to be used as a library to extend an application is what makes Lua an extension language. At the same time, a program that uses Lua can register new functions in the Lua environment; such functions are implemented in C (or another language) and can add facilities that cannot be written directly in Lua. This is what makes Lua an extensible language.

These two views of Lua (as an extension language and as an extensible language) correspond to two kinds of interaction between C and Lua. In the first kind, C has the control and Lua is the library. The C code in this kind of interaction is what we call application code. In the second kind, Lua has the control and C is the library. Here, the C code is called library code. Both application code and library code use the same API to communicate with Lua, the so called C API.

In that case you need to bind (i.e. wrap) some of your routines as primitive functions called by Lua scripts, and you also need to be able to run Lua (e.g. by interpreting some bytecode or script).

So the point of designing some Lua C API is to be able to use Lua to script some existing application or software (and not mainly to extend a standalone Lua interpreter with something else, even if that is possible thru plugins loaded in loadlib.c, which gets called by require ...)

Notice also that embedding an interpreter inside your application is a very strong architectural software design decision (that IMHO you should make quite early).

Title: What is the point of designing Lua C APIs?

Body:
I am a newbie of Lua. After studying some Lua C APIs examples, I am a little confused.

I can see the Lua C API is used for processing Lua scripts:

```<code>......
lua_State *L = luaL_newstate();
luaL_openlibs(L);
luaL_loadfile(L, argv[1]);
lua_call(L, 0, 0);
lua_close(L);
......
</code>```

Or calling a Lua function from C code:

```<code>/* calling f("hello", 4.5) */
lua_getglobal(L, "f");
lua_pushstring(L, "hello");
lua_pushnumber(L, 4.5);
lua_call(L, 2, 1);
</code>```

So what is the point of designing Lua C APIs? If just do these functions, I think call lua program is enough, no need to use Lua C APIs.


问:
How to quantify the work perfomed by a developer/programmer?
I know the best four naive ways of achieving this.

Commit count: In the code repository count the number of commits done by a user. However this is just what the name says, counting the commits. It cannot separate near empty commits from commits having hours of thinking and sweat.

Line count: Counting the number of lines of code produced by a developer. However developers can practice verbose programming, use inefficient algorithms which take lots of code to be made, or just create ugly and large code. So it is hard to use this as a good metric of the work performed.

Time count: I could count the time that a developer spent working. But no one can work one hour straight. Moreover, some programmers can preform 2h of work in just 1h, and vice-versa. And in the end is not the time that counts but the progress the project made. I don't care if a developer spends 5 years or 5 minutes coding, in the end the project is to be completed in its due date. This leads to our final bullet:

Feature count: Counting the number of features closed by a developer will keep track of the overall project's progress. However I cannot tell if those features were toy-features or they were insanely hard to accomplish. Moreover, I cannot tell one developer from another in order to see who performed most of the work. I could estimate the difficulty of each feature, however most of the times that is unfeasible because (i) it is frequent that unexpected problems arise during a feature, (ii) we tend to over simplify things, (iii) for some significant amount of features the work of estimating their difficulty greatly overlaps with the task of doing it, i.e., we can only know how long it takes to close that feature after closing it.

So, in the end, how can one measure, quantify and compare the work performed by developers in a project?

答:
All of the measures you propose are naive and bad, however, some are much, much worse than others.

Specifically, the first three are very bad - in fact, trivially subverted. Only the last one - implemented functionality - should even be considered in a business decision.

Obviously this measure lives and dies by how well the "functionality measure" maps to actual business value. That is a grave problem, but it's one that you have to solve anyway! Someone, somewhere, must make estimates about the cost and the benefit of any given feature, story, function point, whatever you call it, because that's the only reasonable way to decide which of them to do and in which order. Whatever measure you use to make these decisions should also be used to gauge the value added to the business by the ones implementing them.


答:
You measure it by spending the hours necessary to manage the project.

If you wait until all is said and done, you have no way of pulling statistics out of the final product. You can't even look at the artifacts of the process and measure the contribution levels automatically without falling back on the naive statistics.

As progress is made during the project you mentally determine who are the strong and weak contributors. You adjust their workloads to match their skills, strengths, and weaknesses. By the end of the project you will have a good idea the relative rankings of each part of the project team as it relates to your project.

Title: How to quantify the work perfomed by a developer/programmer?

Body:
I know the best four naive ways of achieving this.

Commit count: In the code repository count the number of commits done by a user. However this is just what the name says, counting the commits. It cannot separate near empty commits from commits having hours of thinking and sweat.

Line count: Counting the number of lines of code produced by a developer. However developers can practice verbose programming, use inefficient algorithms which take lots of code to be made, or just create ugly and large code. So it is hard to use this as a good metric of the work performed.

Time count: I could count the time that a developer spent working. But no one can work one hour straight. Moreover, some programmers can preform 2h of work in just 1h, and vice-versa. And in the end is not the time that counts but the progress the project made. I don't care if a developer spends 5 years or 5 minutes coding, in the end the project is to be completed in its due date. This leads to our final bullet:

Feature count: Counting the number of features closed by a developer will keep track of the overall project's progress. However I cannot tell if those features were toy-features or they were insanely hard to accomplish. Moreover, I cannot tell one developer from another in order to see who performed most of the work. I could estimate the difficulty of each feature, however most of the times that is unfeasible because (i) it is frequent that unexpected problems arise during a feature, (ii) we tend to over simplify things, (iii) for some significant amount of features the work of estimating their difficulty greatly overlaps with the task of doing it, i.e., we can only know how long it takes to close that feature after closing it.

So, in the end, how can one measure, quantify and compare the work performed by developers in a project?


答:
"by the book" - that's your problem. You're drowning in more process than you would have had if you were working waterfalls.

There is no 'book' for Agile, there's only the agile manifesto that says "get stuff done without all the overhead". So, if you're estimating sizes and then splitting the stories up into tasks to re-estimate them, then that's a pointless process overhead that needs to be made more efficient - this is what agile is about. Scrum and all the others are really starting point guidelines for how you start doing agile. As you do it, you should identify these points that make no sense, or do not help your team work more effectively, and you should change them.

However, some people think that proscribed ways of working need to be written in stone and never deviated from, no matter how stupid they become. I would try to split stories into tasks before the scrum meeting - you say developers are required to review each story, well, here's the chance to do the splitting at the same time as part of the review. Then you can declare the tasks that comprise the story in the scrum meeting (do not allocate time to them!) and let people then decide how large a workpackage the story is, based on this additional information contained (which is never a bad thing, informed decision making is much better than guesswork,a nd can only be done when you have information to feed into the decision making).

After the meeting, you can still assign times to the tasks (though I fail to see the point of this, sprints are not based on time, they're based on "how much stuff you expect to do" which is measured in story points,not time. This is a common problem with scrum, points do not mean time but you have to complete, say, 20 points per fortnight therefore 2 points = 1 day's work. Its supposed to be a quick guess at how many tasks to put in the sprint so you are neither overloaded nor underworked, not how many will actually get done. The best sprints are those that have a couple of tasks left over, which shows you estimated perfectly. Completing every task shows people either rushed the last ones or delayed completing them at the end - neither is productive).

So, in short - print a copy of the Agile Manifesto out, and the anti-agile version. I bet you're doing more anti than agile. Scrum tends to be like that. The only way to fix it is to engage with your team and get buy-in for change. Don't let the management tell you how your team is to work, that's not agile either, and that will be written in The Book.

Title: Early subtasking at the beginning of each sprint

Body:
I have joined a new team which is using Agile/Scrum, and their development process is as follows:

1) developers review each story before each sprint to make sure it doesn't miss anything critical. There's a formal state for that in the workflow.

2) during the Sprint kickoff, the entire team does an estimation (poker planning) on how many story points each story would cost.

3) finally, immediately after each sprint starts, each developer is required to eagerly break down all of assigned stories into subtasks with time estimates (as opposed to subtasking before starting each story).

The main argument for the last step is that it helps to discover if implementing a story would take longer than anticipated and warn scrum master about potential risks of missing sprint deadlines.

Yet I find this counter-productive, mainly because of the following reasons:

if the aim is to provide rough estimate, story points (step #2) is what does the job. Otherwise why bother with story points at all? - just do subtasking early on.

if the aim is to provide accurate estimates, then this is a clear example of what is described in Human Task Switches Considered Harmful. This, I think, is especially the case for fresh developers who join existing teams in big projects where understanding what needs to be done can take up to 50% of the time. You are required to get into details of story #1, then story #2, #3, etc. etc. which yields a lot of information churn.

I am also being told that such practice is "by the book" and I'm not even meant to discuss this. Can anyone provide a reference to such practice - whether this is clearly defined in Scrum bibles, and/or perhaps provide any extra insight?


答:
If find it hard to answer this question.

The correct general answer should be: it depends.

The way I see it with REST:

You make an object in your code to call the REST method

Call http method

Code inside your REST API queries the database

Database returns some data

REST API code packs up the data into Json and sends it to your client

Client receives Json/XML response

Map response to an object in your code

There is a mistake in your thought.

And this mistake stems from the fact, that you do not fully understand REST and its principles. REST was not invented, because some nerds found it cool (of course it is) to send Javascript-objects via HTTP over the wire. The main advantage of using HTTP is the possibility of using Caching. If you make your results cacheable, then there are less requests to be made to the DB. And no marshalling is involved. The answer could be delivered directly.

Insofar @Klees answer is not quite right:

When you add complexity the code will run slower. Introducing a REST service if it's not required will slow the execution down as the system is doing more.

When dealing with cacheables results, there is no impact on your application: delivering known answers to known questions could be done via reverse-proxies.


答:
You cannot measure and you cannot quantify. Give those ideas up from the beginning. Peopleware goes into great detail about how some people offer value simply by being catalysts for the rest of the team. Those people must not be dismissed because they're not producing lines of code. Likewise, we've all worked with developers who churn out work but are so destructive to the team (through attitude or carelessness) that the team is better off without them.

You can quantify the value of a team, by what functionality it provides for the business and what the business gains from it. But that should be done only at a team level.

You can also compare developer value within a team. But not necessarily in the way you're thinking. It's all about peer-review through creating regular feedback opportunities.

Start with stand-up meetings every day. A developer should always be able to justify to other developers what they were doing the previous day. To be clear, stand-up meetings are not designed to justify a developer's existence. And if the meetings feel that way, they will cease to work. But a stand-up meeting is a regular feedback tool and thus, by nature, will immediately give you hints about problem developers.

That is, sometimes a stand-up report is going to be "I achieved nothing because..." but that's fine, as long as it's not every day (although if it is every day, you want to consider that a management failure before deciding it's an individual failure).

Next, start doing 1-to-1 meetings. Regularly, reliably, off-site and anonymous. You'll quickly learn if an individual is a drain on the team or if another individual is a consistent benefit.

Finally, do regular, periodical 360 reviews. Make no mistake, these are hard to get right. It must be anonymous and seen to be anonymous; ideally collated by an independent third-party. But if you do it right, this is when you'll start seeing an actual numerical value of one developer compared to another. And, perhaps more importantly, of your value as a manager.


答:
Not to be too serious, but ...

We have very myopic views of "evil". People who kill lots of other people are evil. People who steal from others are evil. Every nation (that I know of) has some evil in their past. Some would like to deny it.

Is there evil in programming? We innocent programmers might like to think "not really". However, once I had a conversation with the inventor of a widely-used hierarchical database, on this very subject. Want to know who was one of the best customers? The secret police of Communist Poland.

Is there evil in the world now? You bet. And are they using programmers? You bet.

Title: Is anything in programming truly evil?


答:
Additionally to what @miniBill already wrote: after trimming the shape (or "moving" the shape to the lower left edge inside your m x n matrix), interpret the result as a binary number. Now do the same with the other 7 rotations & reflections, which yields you 8 numbers. Pick the minimum from those 8 values and assign this number to your original matrix, lets call this number the "code number" of the matrix

That way, two matrixes contain the same shape if and only if they have the same code number. This will allow you to work very efficiently with shape sets, for example by utilizing a dictionary or a hashset to store matrixes you alreay have and others you want to test against that set.

Title: Shape-Checking algorithm

Body:
I normally have a very intuitive approach to an efficient algorithm. In essence, I know what the bottleneck is, and how I can improve the algorithm. However, I'm now stuck and I am in the need of some "inspiration".

The problem

The idea itself is very easy. I have a matrix of n x m booleans. I input another grid, also of n x m booleans. The question this algorithm has to solve is if the input shape can ever be matched on the output shape: this may be done by mirroring, rotating and moving the input shape around. I only need to know if the two shapes can be matched or not: the actual transformations do not matter.

Examples:

Target shape:

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

Input:

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

Clearly, this can be done. The transformation is simple:

1) Rotate counterclockwise:

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

2) Move down:

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

A quick check can easily be done: count how many zeros or ones are in the input matrix. If this doesnt match the numbers of zeros and ones in the target shape, then the target shape cannot be made.

A more broader, general question would be what specific class of algorithm I'm looking for. It isn't really clear for me, though using my example I'd say that a carefully constructed pathfinding algorithm could work.

I also want to note that I am not a computer science student, programming is one of my hobbies. I do have proper understanding of "basic matrix manipulations" - maybe there is a wonderful "math trick" for this.


问:
What does the Spring framework do? Should I use it?  Why or why not?
So, I'm starting a brand-new project in Java, and am considering using Spring.  Why am I considering Spring?  Because lots of people tell me I should use Spring!  Seriously, any time I've tried to get people to explain what exactly Spring is or what it does, they can never give me a straight answer.  I've checked the intros on the SpringSource site, and they're either really complicated or really tutorial-focused, and none of them give me a good idea of why I should be using it, or how it will make my life easier.  Sometimes people throw around the term "dependency injection", which just confuses me even more, because I think I have a different understanding of what that term means.

Anyway, here's a little about my background and my app :

Been developing in Java for a while, doing back-end web development.  Yes, I do a ton of unit testing.  To facilitate this, I typically make (at least) two versions of a method : one that uses instance variables, and one that only uses variables that are passed in to the method.  The one that uses instance variables calls the other one, supplying the instance variables.  When it comes time to unit test, I use Mockito to mock up the objects and then make calls to the method that doesn't use instance variables.  This is what I've always understood "dependency injection" to be.

My app is pretty simple, from a CS perspective.  Small project, 1-2 developers to start with.  Mostly CRUD-type operations with a a bunch of search thrown in.  Basically a bunch of RESTful web services, plus a web front-end and then eventually some mobile clients.  I'm thinking of doing the front-end in straight HTML/CSS/JS/JQuery, so no real plans to use JSP.  Using Hibernate as an ORM, and Jersey to implement the webservices.

I've already started coding, and am really eager to get a demo out there that I can shop around and see if anyone wants to invest.  So obviously time is of the essence.  I understand Spring has quite the learning curve, plus it looks like it necessitates a whole bunch of XML configuration, which I typically try to avoid like the plague.  But if it can make my life easier and (especially) if make it can make development and testing faster, I'm willing to bite the bullet and learn Spring.

So please.  Educate me.  Should I use Spring?  Why or why not?

答:
What does the Spring framework do?

Spring is as today not only, what was known as a simple framework, it is a complete ecosystem.

Topics covered by the spring ecosystem:

Spring Framework (e.g. Dependency Injection, AOP ...)

Spring Cloud

Spring Data

Spring Security

Spring Batch

Spring Social

See here for full coverage of the ecosystem. It is possible to cherry-pick projects, so that you could use Google Guice for DI and e.g. Spring Security to handle security related things. YOu do not have to buy into the whole ecosystem.

The Spring-framework itself covers today mainly

Dependency Injection

Aspect-Oriented Programming including Spring's declarative transaction management

Spring MVC web application and RESTful web service framework

Foundational support for JDBC, JPA, JMS

Source spring.io

In general, you could say, that Spring is a collection of implemented Patterns and Practices in code, which could help to improve or speedup your application development cycle.

For what it (the core-framework) is most known for is it's capabilities in the field of dependency injection. Spring itself has, what is called Inversion of control container or short IoC Container or even shorter the container (for which "spring" is sometimes used synonymous).

What is dependency injection?

Dependency injection means, that your object receives every dependency to other objects via an externalized mechanism.

Say, you have a car, the typical way, it is implemented is:

```<code>public class Car {

    Engine e;

    public Car() {
        e = new Engine();
    }

}
</code>```

The car object is dependent on an engine. Since the engine is implemented as a member of car, it can not be swapped out for e.g. a test engine.

Now dependency injection comes into play:

```<code>public class Car {

    Engine e;

    public Car(Engine e) {
        this.e = e;
    }

}
</code>```

After that, you are able to switch engines. What you see above is called constructor injection. There are other types like e.g. setter-injection or method-injection.
How does Spring help you with this? Spring allows it to mark components to be injected with the annotation @Autowired and does the wiring of the injecteed object automatically - it is likely, that the component you want to inject has itself dependencies. Injectables - so to say - are marked via @Component

```<code>public class Car {

    Engine e;

    @Autowired
    public Car(Engine e) {
        this.e = e;
    }

}
</code>```

But that is only one of the many features Spring has to offer.

Should I use Spring? Why or why not?

Since Spring is not very intrusive and offers many aids you should consider using spring. Especially for new projects, Spring Boot is very attractive. start.spring.io offers a easy to use point'n'click-interface to generate a project template to get started. It is even possible to use curl to retrieve a template:

```<code>curl start.spring.io

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/

:: Spring Initializr ::  https://start.spring.io

This service generates quickstart projects that can be easily customized.
Possible customizations include a project's dependencies, Java version, and
build system or build structure. See below for further details.

The services uses a HAL based hypermedia format to expose a set of resources
to interact with. If you access this root resource requesting application/json
as media type the response will contain the following links:
+-----------------+-----------------------------------------+
| Rel             | Description                             |
+-----------------+-----------------------------------------+
| gradle-build    | Generate a Gradle build file            |
| gradle-project  | Generate a Gradle based project archive |
| maven-build     | Generate a Maven pom.xml                |
| maven-project * | Generate a Maven based project archive  |
+-----------------+-----------------------------------------+

...
</code>```

On the other hand, frameworks like spark or dropwizard offer a good starting point for quick web-app creation too.

Body:
What does the Spring framework do?

Spring is as today not only, what was known as a simple framework, it is a complete ecosystem.

Topics covered by the spring ecosystem:

Spring Framework (e.g. Dependency Injection, AOP ...)

Spring Cloud

Spring Data

Spring Security

Spring Batch

Spring Social

See here for full coverage of the ecosystem. It is possible to cherry-pick projects, so that you could use Google Guice for DI and e.g. Spring Security to handle security related things. YOu do not have to buy into the whole ecosystem.

The Spring-framework itself covers today mainly

Dependency Injection

Aspect-Oriented Programming including Spring's declarative transaction management

Spring MVC web application and RESTful web service framework

Foundational support for JDBC, JPA, JMS

Source spring.io

In general, you could say, that Spring is a collection of implemented Patterns and Practices in code, which could help to improve or speedup your application development cycle.

For what it (the core-framework) is most known for is it's capabilities in the field of dependency injection. Spring itself has, what is called Inversion of control container or short IoC Container or even shorter the container (for which "spring" is sometimes used synonymous).

What is dependency injection?

Dependency injection means, that your object receives every dependency to other objects via an externalized mechanism.

Say, you have a car, the typical way, it is implemented is:

public class Car {

    Engine e;

    public Car() {
        e = new Engine();
    }

}

The car object is dependent on an engine. Since the engine is implemented as a member of car, it can not be swapped out for e.g. a test engine.

Now dependency injection comes into play:

public class Car {

    Engine e;

    public Car(Engine e) {
        this.e = e;
    }

}

After that, you are able to switch engines. What you see above is called constructor injection. There are other types like e.g. setter-injection or method-injection.
How does Spring help you with this? Spring allows it to mark components to be injected with the annotation @Autowired and does the wiring of the injecteed object automatically - it is likely, that the component you want to inject has itself dependencies. Injectables - so to say - are marked via @Component

public class Car {

    Engine e;

    @Autowired
    public Car(Engine e) {
        this.e = e;
    }

}

But that is only one of the many features Spring has to offer.

Should I use Spring? Why or why not?

Since Spring is not very intrusive and offers many aids you should consider using spring. Especially for new projects, Spring Boot is very attractive. start.spring.io offers a easy to use point'n'click-interface to generate a project template to get started. It is even possible to use curl to retrieve a template:

curl start.spring.io

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/

:: Spring Initializr ::  https://start.spring.io

This service generates quickstart projects that can be easily customized.
Possible customizations include a project's dependencies, Java version, and
build system or build structure. See below for further details.

The services uses a HAL based hypermedia format to expose a set of resources
to interact with. If you access this root resource requesting application/json
as media type the response will contain the following links:
+-----------------+-----------------------------------------+
| Rel             | Description                             |
+-----------------+-----------------------------------------+
| gradle-build    | Generate a Gradle build file            |
| gradle-project  | Generate a Gradle based project archive |
| maven-build     | Generate a Maven pom.xml                |
| maven-project * | Generate a Maven based project archive  |
+-----------------+-----------------------------------------+

...

On the other hand, frameworks like spark or dropwizard offer a good starting point for quick web-app creation too.


问:
Creating a queue for web services
I have a program running that collects metadata from the internets.

Every so often a summary of this data is written up (every 30 min or so) and the summary is posted to a database.

The summary is also sent out to many web service APIs.

I'm trying to avoid the problem of this program locking up when webservice APIs timeout. So I'm thinking of creating a queue to process these webservice requests.

How should I create this queue? With a database of some sort? It could be a program storing queued items in memory, I suppose. Is there some standard process for creating a queue for webservice calls?

答:
Not sure what your programming environment is?

On Windows I've used MSMQ and a database table for it.

MSMQ is of course a good candidate because it is programmed to be a queue, and a database table isn't.

But when the application was live, I found a database table was easier to monitor. The default MSMQ tooling was (at that time) somewhat limited and a database table is Always easy to monitor.
Besides that you can write any progress in the same database record so you easily can get an overview of the current task running.

But.... when your database gets offline and because of that your task throws an exception, you can't write that status to your 'queue' (being the same database) so in that case you are better of using a 'real' queue.

Title: Creating a queue for web services