问:
Should I follow the normal path or fail early?
From the Code Complete book comes the following quote:

"Put the normal case after the if rather than after the else"

Which means that exceptions/deviations from the standard path should be put in the else case.

But The Pragmatic Programmer teaches us to "crash early" (p. 120).

Which rule should I follow?

答:
If your else statement contains only failure code then, most likely, it should not be there.

Instead of doing this:

```<code>if file.exists() :
  if validate(file) :
    # do stuff with file...
  else :
    throw foodAtMummy
else :
  throw toysOutOfPram
</code>```

do this

```<code>if not file.exists() :
  throw toysOutOfPram

if not validate(file) :
  throw foodAtMummy

# do stuff with file...
</code>```

You don't want to deeply nest your code simply to include error checking.

And, as everyone else has already stated, the two pieces of advice are not contradictory. One is about execution order, the other is about code order.

Body:
If your else statement contains only failure code then, most likely, it should not be there.

Instead of doing this:

if file.exists() :
  if validate(file) :
    # do stuff with file...
  else :
    throw foodAtMummy
else :
  throw toysOutOfPram

do this

if not file.exists() :
  throw toysOutOfPram

if not validate(file) :
  throw foodAtMummy

# do stuff with file...

You don't want to deeply nest your code simply to include error checking.

And, as everyone else has already stated, the two pieces of advice are not contradictory. One is about execution order, the other is about code order.


问:
Retried Operation with generic Exception
I am looking for a way to get the logic of retrying an operation in a single method while keeping the exception types of the operation.

I.e., the implementation to retry an operation could look like this:

```<code>public void retriedOperation(Operable operable, int maxAttempts) throws Exception {
    for (int attempt = 0; attempt < maxAttempts; attempt++) {
        try {
            operable.doOperation();
            break;
        } catch (Exception e) {
            if (attempt + 1 > maxAttempts) {
                throw e;
            }
        }
    }
}
</code>```

This implementation is however only capable of throwing an unspecified Exception and thereby looses lots of information.

Unfortunately, generic Exceptions can neither be caught nor thrown not be caught in Java, thus something like

```<code>public void <ExceptionType extends Exception> retriedOperation(...) throws ExceptionType { ... }
</code>```

would only allow to catch an unspecific Exception, check if it is of the right type and then cast it. But if it is of another type, it cannot be thrown with this method header.

Is there a way to implement a generic retry function that preserves specific exceptions?

答:
Unfortunately, generic Exceptions can neither be caught nor thrown in Java, thus something like ... is not possible.

Change that to:

```<code>public void <T extends Exception> retriedOperation(...) throws T { ... }
</code>```

And it should work just fine. When T is a checked exception, the compiler will complain appropriately. E.g.

```<code>obj.<IOException>retriedOperation(...);
</code>```

Will force the surrounding method to either handle IOException or declare that it throws it. However, as long as Operable specifies that it throws Exception, your code won't work, since the method would have to check if the caught exception is of a particular type it doesn't yet know. The real solution is to change Operable to specify whatever exception it throws:

```<code>class Operable<T extends Exception>
</code>```

And now you can rewrite your method as

```<code>public <T extends Exception> void retriedOperation(Operable<T> operable, ...) throws T {
    ...
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else {
            throw (T) e;
        }
    }
    ...
 }
</code>```

And everything will work just fine, provided Operable only throws one kind of checked exception. If you need to handle more than one, the solution will get a bit ugly - <s>you'll have to pass a list of class tokens as an argument and check if the caught exception is of a compatible type for any of them.</s> (In retrospect, this wouldn't work as described. You do need class tokens, but you'd need an overload of the method for 2 exceptions, 3 exceptions, etc to get the throws clause right.)

Finally, it seems to me retriedOperation should be a static method.

ContentLicense: CC BY-SA 3.0

Body:
Unfortunately, generic Exceptions can neither be caught nor thrown in Java, thus something like ... is not possible.

Change that to:

public void <T extends Exception> retriedOperation(...) throws T { ... }

And it should work just fine. When T is a checked exception, the compiler will complain appropriately. E.g.

obj.<IOException>retriedOperation(...);

Will force the surrounding method to either handle IOException or declare that it throws it. However, as long as Operable specifies that it throws Exception, your code won't work, since the method would have to check if the caught exception is of a particular type it doesn't yet know. The real solution is to change Operable to specify whatever exception it throws:

class Operable<T extends Exception>

And now you can rewrite your method as

public <T extends Exception> void retriedOperation(Operable<T> operable, ...) throws T {
    ...
    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else {
            throw (T) e;
        }
    }
    ...
 }

And everything will work just fine, provided Operable only throws one kind of checked exception. If you need to handle more than one, the solution will get a bit ugly - <s>you'll have to pass a list of class tokens as an argument and check if the caught exception is of a compatible type for any of them.</s> (In retrospect, this wouldn't work as described. You do need class tokens, but you'd need an overload of the method for 2 exceptions, 3 exceptions, etc to get the throws clause right.)

Finally, it seems to me retriedOperation should be a static method.


问:
Help me catch up on what I've missed since Java 1.4.2
I am about to start my first professional career position as a software developer, and I'm likely going to be writing a lot of Java code.  I don't know that much about what specifically I'll be writing, and besides, I have fairly broad interests when it comes to code anyway.

For reasons not worth discussing, my last internship had me coding only for the Java 1.3 and 1.4 SDK's.  Also, my university education has focused mainly on algorithms, data structures, and other theory, not language features or libraries.

So, with the above in mind, what features, classes, etc. in the current version of Java (what number are we on now, anyway?) would be worth my time to read up on and why?  What have I missed since 1.4.2 that makes your life as a programmer easier?

Examples and stories of how you discovered a particular package or some such and put it to use would also be great.

答:
The changes that I consider most important are:

Generics (e.g. typed collections, like Set)

Enhanced for loop (for (String s : set) {...})

Autoboxing/unboxing (automatically convert between types like Integer to int and vice versa)

Typesafe enums (enum is now a keyword, types can be created out of enums)

Varargs (for printf() function, allows variable number of arguments)

Static import (can now import static methods of a class, such as java.lang.Math)

Annotations

java.util.concurrent (Demonstrates java's concurrency)

Also read What Java are you aiming for?, to get a better understanding of each of the three versions.

ContentLicense: CC BY-SA 2.5


问:
Can a layer consist of multiple projects / dlls?
I am working on the architecture for a new web application and I am pretty much a complete newbie when it comes to architecture. Working my way through .NET Application Architecture Guide, 2nd Edition and learning a lot. I have decided to go for the "standard" 3-layer architecture: Presentation layer, Business layer, Data layer. Will be using ASP.NET MVC and Entity Framework.

Currently the business layer contains the logic and business entities (anemic models). I am planning to use the business entities as EF entities. That would, however, cause the data layer to have a depency on the business layer. This "problem" can be solved by moving the business entities into its own project and have the layers that have dependencies on the business entities reference that project.

Is that an ok / good way of doing things?

Will / can / should
the business entities project be considered part of the business
layer?

Can a layer consist of multiple projects, that is, the
layer only acts as a "logical container"? In the above mentioned
book they talk about how the business layer can consist of "Business
Workflow", "Business Components", "Business Entities", and I assume
that each of those are a separate project (maybe even multiple
projects)?

答:
While there is nothing inherently "wrong" or "bad" with what you describe, it is generally preferable to use an architecturally evident coding style in which the structures in your code accurately reflect the structures in your architecture.  That said, there is nothing wrong with having multiple projects within a layer. This may actually be a good thing -- as long as it is a conscience decision and not an accident.

Generally with the layered style, dependencies should only go "down", meaning a layer above may depend on layers below (how far the dependency goes down is up to you, some say only one layer, others allow the whole stack), but a layer below may not depend on a layer above.

In an ideal world, your layers should be "vertically sliceable" by feature or business object or similar.  If you draw a dependency diagram and they look like spaghetti -- especially if the spaghetti crosses layer boundaries -- you may want to rethink how you are partitioning your system.


问:
Direct database manipulation an anti-pattern?
Recently I learned that some teams have moved all their database manipulation to the actual database through the use of stored procedures. I thought that was pretty clever, since the database becomes a black box and any change to how the data is stored and manipulated won't affect application code. Is it accurate to conclude that manipulating the database in application code is an anti-pattern, since it unnecessarily couples application and storage code, or are there circumstances that would make decoupling sql queries from the application a disadvantage?</p>

答:
I would say that direct database manipulation is often a bad thing. I don't know if it is an anti-pattern though. I think pattern and anti-pattern are overused buzzwords.

The only disadvantage to decoupling is that a good abstraction layer needs more development time and may be overkill for small applications.

The abstraction layer between an application and a database doesn't need to be stored procedures. It could be "middle-ware." Also known as a library or service that performs database actions for the application.

The good thing about that is that changes don't need to be carefully redone in each application that accesses the database.

For example, say that you had a web browser using a local database to store browsing history and bookmarks. And you can't just add a bookmark with an INSERT because there is a complicated relationship between three different tables. A small library could be used by the browser and by a command line tool to make bookmark changes easy to script instead of complicated and prone to breaking with each update.

(Note that "small library" in my opinion rules out a lot of Java ORMs. I saw one command line tool that took 10 seconds to start up and required access to 12 configuration and JAR files. So that it could send 6 or so INSERT and UPDATE commands. Ridiculous.)

Abstracting database access into a service can also improve performance. There have been many desktop business apps written that talk to a database over a VPN. With a 120 ms delay between each SELECT, UPDATE, INSERT, etc. Sending a single request that performs a set of database commands locally is much faster.


问:
Moving back end from Parse.com to Amazon Web Services
I'm looking for insight from someone who has used at least AWS (if not also Parse.com). My iOS app currently uses Parse.com for these purposes:
1) to store user data (by translating between JSON and core data)
2) to run javascript functions to update my database with data from the web
3) for easy Facebook authentication, which is the basis for user accounts

I am now eligible for a massive hosting credit from AWS, so I am trying to assess the difficulty of switching (not to mention new concerns about Parse.com's quality). From what I've read, it seems AWS offers a variety of hosting options. However, in reference to (1), I have not seen any specific mention of JSON tables, and that's the only kind of database I'm familiar with.

So I'm looking for better understanding of which AWS database options would most closely approximate Parse.com's JSON-based database. And I'm also interested in any comments about (2) and (3)---what AWS features would provide the nearest substitutes. Thank you

答:
Ugh. Almost none?  They are really different beasts.  I would suggest that you look at DynamoDB if you want a fast key-value store, and RDS for a good old fashioned database.

There's a mobile SDK that Amazon provides that will let you connect to Dynamo directly from the device.

You might, might, might get something interesting by using CoreData and an RDS instance together, but that's probably not something that you want to do.

For users, you'll have to use AWS federated identity and force your users to login with one of the supported services (Facebook etc).

The two services operate at very different levels of abstraction,  Parse is significantly higher level.


问:
Is it possible for business logic not to creep into the view?
I've developed for several web application projects for the last 3 years, both personal and at work, and I can't seem to figure out whether it's possible for at least some business logic not ending up in the view layer of the application.

In most cases there will be problems like "If the user has selected option x then the application must enable him to supply info for y, if not then s/he should supply info z".
Or do some AJAX operation which should apply some changes to the model but NOT commit them until the user has explicitly requested so. These are some of the simplest problems I've encountered and I can't figure out how it's possible to avoid complex logic in the view.

Most of the books I've read describing MVC usually showcase some very trivial examples, like CRUD operations that just update data on the server and display them, but CRUD is not the case on most rich applications.

Is it possible to achieve having a view with no business logic at all?

答:
I question whether the examples you describe are really business logic. The examples you describe are operations that can be performed on the system. It is how you chose to present the choices to the user that maybe gives the appearance that you are doing business logic in the view.

From the "View" vantage point it is only providing InfoY or InfoZ to the system. Just because your UI implementation is doing some dynamic updates based on an operator choice (ie. enabling InfoY or InfoZ) doesn't make the functionality business logic. It is really view implementation logic. You could very well have simply given the operator a choice to enter InfoY or InfoZ without the whole enabling thing. In that context, would you still consider it business logic? If not, then the same applies for dynamically enabling/disabling info fields.

Same goes for the commit example. These are 2 separate operations the system requires to work properly. Your View has to be able to initiate the proper actions to perform the desired functionality. Does knowing how to use your system mean that the business logic is leaking through? I can see how someone might say yes but if you believe that way then the reality is that there is no such thing as separation of business logic from anything. You have to know what the system is doing/working with to accomplish anything meaningful. Otherwise, it would be a breeze to create a single generic View and Controller that works with every conceivable MVC application. Which we know is impossible.

Bottom line, I think your definition of business logic is not the same as others definition.


问:
Designing unit tests for a stateful system

Background

Test Driven Development was popularized after I already finished school and in the industry. I am trying to learn it, but some major things still escape me. TDD proponents say lots of things like (hereafter referred to as the "single assertion principle" or SAP):

For some time I've been thinking about how TDD tests can be as simple, as expressive, and as elegant as possible. This article explores a bit about what it's like to make tests as simple and decomposed as possible: aiming for a single assertion in each test.

Source: http://www.artima.com/weblogs/viewpost.jsp?thread=35578

They also say things like this (hereafter referred to as the "private method principle" or PMP):

You generally don't unit test private methods directly. Since they are private, consider them an implementation detail. Nobody is ever going to call one of them and expect it to work a particular way.

You should instead test your public interface. If the methods that call your private methods are working as you expect, you then assume by extension that your private methods are working correctly.

Source: How do you unit test private methods?

Situation

I am trying to test a stateful data processing system. The system can do different things for the exact same piece of data given what it's state was prior to receiving that data. Consider a straightforward test that builds up state in the system, then tests the behavior that the given method is intended to test.

SAP suggests that I should not be testing the "state build up procedure", I should assume that the state is what I expect from the build up code and then test the one state change I'm trying to test

PMP suggests that I can't skip this "state build up" step and just test the methods that govern that functionality independently.

The result in my actual code has been tests that are bloated, complicated, long, and difficult to write. And if the state transitions change, the tests have to be changed... which would be fine with small, efficient tests but extremely time consuming and confusing with these long bloated tests. How is this normally done?

答:
The core idea of TDD is that, by writing tests first, you end up with a system that is, at the least, easy to test. Hopefully it works, is maintainable, well documented and so on, but if not, well at least it's still easy to test.

So, if you TDD and end up with a system that is hard to test, something has gone wrong. Perhaps some things that are private should be public, because you need them to be for testing. Perhaps you are not working at the right level of abstraction; something as simple as a list is stateful at one level, but a value at another. Or perhaps you are giving too much to weight to advice not applicable in your context, or your problem is just hard. Or, of course, perhaps your design is just bad.

Whatever the cause is, you are probably not going to go back and write your system again to make it more testable with simple test code. So likely the best plan is to use some slightly more fancy test techniques, like:

Model based testing

Randomised testing


问:
Should a user story be shared between developers?
I commonly see stories that have back-end and front-end development.  For example, consider a large dialog with a few tables and some dynamic controls.  We'll make several stories (maybe one for each table and another for the dynamic control system).

The dev team will then split with one person on the back-end and another on the front-end.  This makes it easy for the back-end person to just worry about the structure of the SQL layer while the front-end person focuses on stuff like layout.  After the initial interface between back- and front-end is agreed, the two developers can focus their attention to get their part done by the end of the sprint.

Then comes the chaos.  Who "owns" which story?  What does "in progress" mean or "done"?  Should we make two separate stories for back-end and front-end?  If so, doesn't that break the idea of user stories based on feature?  Our system has a notion of "sub-tasks", which eases some of these problems.  But sub-tasks add an extra complexity.  Is there a better way?  Is this a "bad" way to use Scrum?

I have been using some form of Agile over the past few years at a couple places.  I have no official training yet, so please forgive any wrong terminology or ideology.  I'm just trying to learn practical ways to improve our process.

答:
Like others have suggested, my team also divides our user stories into tasks. This is generally easy to do if you're managing your user stories via software (such as JIRA or Rally). Then it is easy to tell what parts of the story are moving along.

But an alternative for tasks would be to just reassign ownership as each person finishes up their part. So the story gets passed around -- maybe developer 1 starts it with the backend work, then passes off to developer 2 to do the UI. Then it's passed on to your QA tester for verification. This method should work well in environments where you are using actual cards on wall or if your software doesn't track tasks.

But in any case, I recommend never calling a story "done" until the team agrees that it is done, including testing. That way everybody has a chance to give their input. And if you combine this with ideas about collective code ownership and code reviews then every story is really "owned" by the team anyway. It may be "assigned" to different people along the way, but if somebody is out (sick/vacation/too many meetings?/other) the work can still get done.

My team often accepts user stories as part of our morning stand-up/SCRUM meeting. That way everyone can easily acknowledge or dispute whether it is really "done". Other times we just let our QA engineer do that -- if she's satisfied that it's tested and working, and all the tasks are complete, then we call it done.


答:
You would usually abstract away the setup details into functions so you don't have to repeat yourself.  That way you only have to change it in one place in the test if the functionality changes.

However, you wouldn't normally want to describe even your setup functions as bloated, complicated, or long.  That's a sign that your interface needs refactoring, because if it's difficult for your tests to use, it's difficult for your real code to use as well.

That's often a sign of putting too much into one class.  If you have stateful requirements, you need a class that manages the state and nothing else.  The classes that support it should be stateless.  For your SIP example, parsing a packet should be completely stateless.  You can have a class that parses a packet then calls something like sipStateController.receiveInvite() to manage the state transitions, which itself calls other stateless classes to do things like ring the phone.

This makes setting up the unit testing for the state machine class a simple matter of a few method calls.  If your setup for state machine unit tests requires crafting packets, you've put too much into that class.  Likewise, your packet parser class should be relatively simple to create setup code for, using a mock for the state machine class.

In other words, you can't avoid state altogether, but you can minimize and isolate it.

Title: Designing unit tests for a stateful system

Body:
Background

Test Driven Development was popularized after I already finished school and in the industry. I am trying to learn it, but some major things still escape me. TDD proponents say lots of things like (hereafter referred to as the "single assertion principle" or SAP):

For some time I've been thinking about how TDD tests can be as simple, as expressive, and as elegant as possible. This article explores a bit about what it's like to make tests as simple and decomposed as possible: aiming for a single assertion in each test.

Source: http://www.artima.com/weblogs/viewpost.jsp?thread=35578

They also say things like this (hereafter referred to as the "private method principle" or PMP):

You generally don't unit test private methods directly. Since they are private, consider them an implementation detail. Nobody is ever going to call one of them and expect it to work a particular way.

You should instead test your public interface. If the methods that call your private methods are working as you expect, you then assume by extension that your private methods are working correctly.

Source: How do you unit test private methods?

Situation

I am trying to test a stateful data processing system. The system can do different things for the exact same piece of data given what it's state was prior to receiving that data. Consider a straightforward test that builds up state in the system, then tests the behavior that the given method is intended to test.

SAP suggests that I should not be testing the "state build up procedure", I should assume that the state is what I expect from the build up code and then test the one state change I'm trying to test

PMP suggests that I can't skip this "state build up" step and just test the methods that govern that functionality independently.

The result in my actual code has been tests that are bloated, complicated, long, and difficult to write. And if the state transitions change, the tests have to be changed... which would be fine with small, efficient tests but extremely time consuming and confusing with these long bloated tests. How is this normally done?


问:
How to generate random numbers with a (negative) sloping distribution?
Given a maximum integer value M, I want to generate N integer values that are distributed with a lower frequency when approaching M (preferably M should still have a non-zero probability).
I don't really care much about the probability function, let's assume (half of) a normal distribution.

How would I do that if I don't want to keep a history?

for i := 1 to N do GetNextTestValue(M)

What could GetNextTestValue look like?

FWIW I'm doing this in Delphi

答:
If rolling two and taking the least is too much ;) you could scale a single uniform random so that the distribution favors small results (pseudocode):

```<code>def scaled_random(M):
    r = random()
    return M * r * r
</code>```

random() produces a uniform random number from 0..1

When r is small, r * r will be even smaller, so there are lots of ways to get numbers close to zero.

As r gets closer to 1, then r * r gets closer to 1, so the return value is closer to M. But very few numbers will get that high.

Note that this is going to be a lot faster than the least of 2 random numbers, because multiplication (r * r) is a lot faster than generating a second random. Random number generation is slow compared to basic operations -- even "fast" random number generators are just "fast" relatively.

...

Also, some math libraries support a "power" distribution for random numbers -- I believe that would also do the trick.

Body:
If rolling two and taking the least is too much ;) you could scale a single uniform random so that the distribution favors small results (pseudocode):

def scaled_random(M):
    r = random()
    return M * r * r

random() produces a uniform random number from 0..1

When r is small, r * r will be even smaller, so there are lots of ways to get numbers close to zero.

As r gets closer to 1, then r * r gets closer to 1, so the return value is closer to M. But very few numbers will get that high.

Note that this is going to be a lot faster than the least of 2 random numbers, because multiplication (r * r) is a lot faster than generating a second random. Random number generation is slow compared to basic operations -- even "fast" random number generators are just "fast" relatively.

...

Also, some math libraries support a "power" distribution for random numbers -- I believe that would also do the trick.


问:
MVC pattern synchronisation
I am facing a problem in synchronizing my model and view threads

I have a view which is table. In it, user can select a few rows.
I update the view as soon as the user clicks on any row since I don't want the UI to be slow.
This updating is done by a logic which runs in the controller thread below.

At the same time, the controller will update the model data too, which takes place in a different thread. i.e., controller puts the query in a queue, which is then executed by the model thread - which is a single-threaded interface.

As soon as the query executes, controller will get a signal.

Now, In order to keep the view and model synchronized, I will update the view again based on the return value of the query (the data returned by model) - even though I updated the view already for that user action.

But, I am facing issues because, its taking a lot of time for the model to return the result, by that time user would have performed multiple clicks. So, as a result of updating the view again based on the information from model, the view sometimes goes back to the state in which the previous clicks were made

(Suppose user clicks thrice on different rows. I update the view as soon as the click happens. Also, I update the view when I get data back from the model - which is supposed to be same as the already updated state of the view. Now, when the user clicks third time, I get data for the first click from model. As a result, view goes back to a state which is generated by the first click)

Is there any way to handle such a synchronization issue?

答:
Have the view maintain a reference to the last element that caused a relevant event, so that it can decide whether to display incoming results or not:

```<code>var last_request = nil
void row_selected(any) :
    last_request = any.id
    controller.query(any.id)

void query_completed(id, result) :
    if id == last_request then
        display(result)
    else
        log(result)
</code>```

(Note: your view probably stores this already by holding a reference to what is currently selected.)

This would also handle the case where people click A, then B, and then A again before the first result is in: showing A without popping up with B.

I doubt if this will work.

Here's a quick and dirty SCCE (in Java) that should prove it works.

public class TheView extends JPanel {
  public static void main(String[] args) {
    SwingUtilities.invokeLater( () -> {
      TheView view = new TheView();
      Controller ctrl = new Controller(view);

      JFrame frame = new JFrame();
      frame.getContentPane().add(view);
      frame.pack();
      frame.setVisible(true);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    });
  }

  JTextArea output;
  JTable table;

  public TheView() {
    super(new BorderLayout());

    table = new JTable(new Object[][] {
      {1, "Tootsie"},
      {8, "Elvis"},
      {14, "Michael"}
    }, new Object[] {
      "ID", "Name"
    });
    add(new JScrollPane(table), BorderLayout.NORTH);

    output = new JTextArea(6, 80);
    add(new JScrollPane(output));
  }

  public void addListSelectionListener(ListSelectionListener l) {
    table.getSelectionModel().addListSelectionListener(l);
  }

  public Object getValueAtSelected(int column) {
    int idx = table.getSelectedRow();
    if ( idx < 0 ) return null;
    return table.getValueAt(idx, column);
  }

  public void addOutput(String str) {
    output.append(str + '\n');
  }
}

class Controller {
  ExecutorService executor = Executors.newCachedThreadPool();
  private volatile int lastID;
  TheView view;

  public Controller(TheView view) {
    this.view = view;
    view.addListSelectionListener( (evt) -> {
      Object o = view.getValueAtSelected(0);
      if ( o instanceof Integer && (Integer) o != lastID ) {
        processRequest((Integer) o);
      }
    });
  }

  public void processRequest(int id) {
    lastID = id;
    executor.submit( () -> {
      offerReply(id, new SlowProcessor(id).call());
      return null;
    });
  }

  void offerReply(int id, String result) {
    if ( id == lastID ) {
      SwingUtilities.invokeLater( () -> view.addOutput(result) );
    }
  }
}

class SlowProcessor implements Callable<String> {
  private final int id;

  public SlowProcessor(int id) {
    this.id = id;
  }

  public String call() throws InterruptedException {
    Thread.sleep(2000);
    final String response = "I am the reply to ID " + id;
    return response;
  }
}
```

Title: MVC pattern synchronisation

Body:
Have the view maintain a reference to the last element that caused a relevant event, so that it can decide whether to display incoming results or not:

var last_request = nil
void row_selected(any) :
    last_request = any.id
    controller.query(any.id)

void query_completed(id, result) :
    if id == last_request then
        display(result)
    else
        log(result)

(Note: your view probably stores this already by holding a reference to what is currently selected.)

This would also handle the case where people click A, then B, and then A again before the first result is in: showing A without popping up with B.

I doubt if this will work.

Here's a quick and dirty SCCE (in Java) that should prove it works.

public class TheView extends JPanel {
  public static void main(String[] args) {
    SwingUtilities.invokeLater( () -> {
      TheView view = new TheView();
      Controller ctrl = new Controller(view);

      JFrame frame = new JFrame();
      frame.getContentPane().add(view);
      frame.pack();
      frame.setVisible(true);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    });
  }

  JTextArea output;
  JTable table;

  public TheView() {
    super(new BorderLayout());

    table = new JTable(new Object[][] {
      {1, "Tootsie"},
      {8, "Elvis"},
      {14, "Michael"}
    }, new Object[] {
      "ID", "Name"
    });
    add(new JScrollPane(table), BorderLayout.NORTH);

    output = new JTextArea(6, 80);
    add(new JScrollPane(output));
  }

  public void addListSelectionListener(ListSelectionListener l) {
    table.getSelectionModel().addListSelectionListener(l);
  }

  public Object getValueAtSelected(int column) {
    int idx = table.getSelectedRow();
    if ( idx < 0 ) return null;
    return table.getValueAt(idx, column);
  }

  public void addOutput(String str) {
    output.append(str + '\n');
  }
}

class Controller {
  ExecutorService executor = Executors.newCachedThreadPool();
  private volatile int lastID;
  TheView view;

  public Controller(TheView view) {
    this.view = view;
    view.addListSelectionListener( (evt) -> {
      Object o = view.getValueAtSelected(0);
      if ( o instanceof Integer && (Integer) o != lastID ) {
        processRequest((Integer) o);
      }
    });
  }

  public void processRequest(int id) {
    lastID = id;
    executor.submit( () -> {
      offerReply(id, new SlowProcessor(id).call());
      return null;
    });
  }

  void offerReply(int id, String result) {
    if ( id == lastID ) {
      SwingUtilities.invokeLater( () -> view.addOutput(result) );
    }
  }
}

class SlowProcessor implements Callable<String> {
  private final int id;

  public SlowProcessor(int id) {
    this.id = id;
  }

  public String call() throws InterruptedException {
    Thread.sleep(2000);
    final String response = "I am the reply to ID " + id;
    return response;
  }
}


问:
Program license : Open-Source and commercial?
Currently programming a new software, I'm searching for information about protecting my concept and my source-code. I precise I'm quite new in licensing.

As I'm feeling very concerned by Open-source and sharing with the community, I'm puzzled on the other hand because I want to make some profit of my work (around 1 year of free-time, you can imagine the amount of missed beers in pub!). So I'm looking for a double license, that is compatible, and allows software source-code distributing, but force companies to get a commercial license, or to negotiate directly with me. But I think it is totally contradictory with GPL like licenses.

What are you thinking about that?

答:
If you want to stop companies from using your freely-available software, no free or open license (i.e., FSF- or OSI-approved) will be suitable, because, as stated in the OSI definition:

The license must not restrict anyone from making use of the program in a specific field of endeavor. For example, it may not restrict the program from being used in a business...

To prevent your software from being used by a company, you'd need to come up with your own license that restricted "corporate use" or similar (you should seek qualified legal advice for this). Bear in mind also the practical issue of detecting and stopping a company that uses your freely available program.

If you want to control how companies may redistribute your program (or modified forms of it), then you're on much firmer footing -- dual licensing will serve you well. The GPL might be a perfectly suitable free license option, alongside your own proprietary licensing option: companies who opt for the GPL license could only redistribute your softwre under the GPL. If they wanted to augment your program and sell it as their own proprietary product, they would likely rather negotiate with you than be forced to place their own modifications under the GPL.

(Bear in mind that you should still seek legal advice when drafting your proprietary license. If you're interested in this, but not able to bear the legal expense up front, you might invite companies to negotiate a non-GPL license with you directly and retain legal counsel whenever a company epxresses interest.)


答:
I work this way (Struts2 + Hibernate):

My Struts Actions is only responsible for show informations on web browser. Not thinking.

User -> Action -> Service -> Repository -> Data Access

Or:

I Want See -> How to see -> What to Do -> How to Get -> Where to get

So, in first layer (the view) I have something like:

```<code>public String execute ()   {
    try {
        CourseService cs = new CourseService();
        Course course = cs.getCourse(idCourse);
    } catch (NotFoundException e) {
        setMessageText("Course not found.");
    } catch (Exception e) {

    }
    return "ok";
}
</code>```

As you see, my "view" do not think. It's asking for a service (for manage courses) a specific course. That service can do many things more, like reports, seraches, and so on. The results is always a list or a specific object (like the example).
The services are the real machine, apply rules and access the Repository (to manage the data).

So, if I put my Services, Repositories and DAOS in different libraries, I can use it even in a text-based program, or a Window based desktop system with changing nothing.

The service knows what to do, but does not know how to show.
The view knows how to show, but does not know what to do.
The same with Service / Repository: The service send and request for the data, but does not knows where the data is and how to take it. The repository "make up" the raw data to buisines objects so the Service can work with.

But the Repository does not know anything about the database. The database kind (MySQL, PostgreSQL, ... ) concerns to DAO.

You can change the DAO if you want to change the database and it must not affect the upper layers.
You can change the Repository if you want to update your data management, but this must not affect the DAO and upper layers.
You can change the Services if you want to change your logic, but this must not mess with layers above nor below.

And you can change anything in view, even the technology (web, desktop, text) but this must not implies in touch anything below.

The business logic is Service.
But how to interact with this is to view. What button to show now? Can the user see this link?
Think your system is a console-based program: you must deny if the wrong user choose #> myprogram -CourseService -option=getCourse -idCourse=234 or stop him to press the keys to write this command?

Talking in web-based systems (Struts+JavaEE) I have a separate GUI controller package. In view Action I give the logged user and the class gives me the buttons (or any interface element I want).

```<code>                <div id="userDetailSubBox">
                    <c:forEach var="actionButton" items="${actionButtons}" varStatus="id">
                        ${actionButton.buttonCode}
                    </c:forEach>
                </div>
</code>```

And

```<code>private List<ActionButton> actionButtons;
</code>```

Remember to keep this out from the services. This is VIEW stuff. Keep it in the Struts Actions. Any interface interactions must be fully separate from the real business code, so if you port your system, will be easy to cut what you won't need anymore.

Title: Is it possible for business logic not to creep into the view?

Body:
I've developed for several web application projects for the last 3 years, both personal and at work, and I can't seem to figure out whether it's possible for at least some business logic not ending up in the view layer of the application.

In most cases there will be problems like "If the user has selected option x then the application must enable him to supply info for y, if not then s/he should supply info z".
Or do some AJAX operation which should apply some changes to the model but NOT commit them until the user has explicitly requested so. These are some of the simplest problems I've encountered and I can't figure out how it's possible to avoid complex logic in the view.

Most of the books I've read describing MVC usually showcase some very trivial examples, like CRUD operations that just update data on the server and display them, but CRUD is not the case on most rich applications.

Is it possible to achieve having a view with no business logic at all?

Body:
I work this way (Struts2 + Hibernate):

My Struts Actions is only responsible for show informations on web browser. Not thinking.

User -> Action -> Service -> Repository -> Data Access

Or:

I Want See -> How to see -> What to Do -> How to Get -> Where to get

So, in first layer (the view) I have something like:

public String execute ()   {
    try {
        CourseService cs = new CourseService();
        Course course = cs.getCourse(idCourse);
    } catch (NotFoundException e) {
        setMessageText("Course not found.");
    } catch (Exception e) {

    }
    return "ok";
}

As you see, my "view" do not think. It's asking for a service (for manage courses) a specific course. That service can do many things more, like reports, seraches, and so on. The results is always a list or a specific object (like the example).
The services are the real machine, apply rules and access the Repository (to manage the data).

So, if I put my Services, Repositories and DAOS in different libraries, I can use it even in a text-based program, or a Window based desktop system with changing nothing.

The service knows what to do, but does not know how to show.
The view knows how to show, but does not know what to do.
The same with Service / Repository: The service send and request for the data, but does not knows where the data is and how to take it. The repository "make up" the raw data to buisines objects so the Service can work with.

But the Repository does not know anything about the database. The database kind (MySQL, PostgreSQL, ... ) concerns to DAO.

You can change the DAO if you want to change the database and it must not affect the upper layers.
You can change the Repository if you want to update your data management, but this must not affect the DAO and upper layers.
You can change the Services if you want to change your logic, but this must not mess with layers above nor below.

And you can change anything in view, even the technology (web, desktop, text) but this must not implies in touch anything below.

The business logic is Service.
But how to interact with this is to view. What button to show now? Can the user see this link?
Think your system is a console-based program: you must deny if the wrong user choose #> myprogram -CourseService -option=getCourse -idCourse=234 or stop him to press the keys to write this command?

Talking in web-based systems (Struts+JavaEE) I have a separate GUI controller package. In view Action I give the logged user and the class gives me the buttons (or any interface element I want).

                <div id="userDetailSubBox">
                    <c:forEach var="actionButton" items="${actionButtons}" varStatus="id">
                        ${actionButton.buttonCode}
                    </c:forEach>
                </div>

And

private List<ActionButton> actionButtons;

Remember to keep this out from the services. This is VIEW stuff. Keep it in the Struts Actions. Any interface interactions must be fully separate from the real business code, so if you port your system, will be easy to cut what you won't need anymore.


答:
In most cases there will be problems like "If the user has selected option x then the application must enable him to supply info for y, if not then s/he should supply info z"

That is logic for the model, not the view.  It may be a "view-model", created specifically to support the UI, but it is still model logic.  The control sequence is:

Controller attaches a handler for view events

View attaches a handler for model events

The user selects option X.

The view raises an event "Option X Selected"

Controller receives the event and calls model.selectOptionX()

The model raises an event "Model state changed"

The view receives the model changed event and updates the view to match the new state:

inputY.enable(model.yAllowed());
inputZ.enable(model.zAllowed());

    UI                     View              Controller              Model
    |.checkbox X checked.> |                   |                     |
    |                      | .. X selected ...>|                     |
    |                      |                   |-----> set X ------->|
    |                      |                   |                     |
    |                      |< .............state changed ............|
    |                      |                   |                     |
    |                      |-------------- Get state --------------->|
    |                      |                   |                     |
    |                      |<----------- new state ------------------|
    | <-- UI updates ------|

This is the classic MVC pattern.  It is possible to completely test the model logic separate from the UI.  The controller and view are very thin and easy to test.

=== In response to Dunk ===

The Model in a UI MVC pattern is (usually) not a business object model.  It is just the model for the UI state.  In a desktop application, it may hold references to multiple business models.  In a Web 2.0 application, it is a Javascript class that holds the UI state, and communicates via AJAX to the server.  It is very important to be able to write hands-off unit tests of the UI state model, as that is where most UI bugs are found.  The view and controller should be very thin connectors.


问:
Best algorithm to correlate similar articles
which is the best way to correlate and group similar articles?

I mean something like Google News, which groups under a single topic different articles from different sources.

I'm not interested in something much sophisticated, it is just important to be efficient in terms of speed and resources needed. I can live with a correlation only on short text like the titles of the articles, not the article itself.

I read a paper which talks about tuples of two or three words (best with three) to extract and use to produce a score to achieve the correlation, but it's way too much academic for me

答:
If you are using Solr then there is a MoreLikeThisHandler

And in case using Sunspot with it, then its even simpler

post = Post.first
   Sunspot.more_like_this(post, Post, Page) do
     fields :title, :body
     with(:updated_at).greater_than(1.month.ago)
     facet(:category_ids)
   end


问:
Extract all related class type aliasing and enum into one file or not
I have many models in my project, and some other classes just need the class declaration and pointer type aliasing. It does not need to know the class definition, so I don't want to include the model header file. I extract all the model's declaration into one file to let every classes reference one file.

model_forward.h

```<code>class Cat;
typedef std::shared_ptr<Cat> CatPointerType;
typedef std::shared_ptr<const Cat> CatConstPointerType;

class Dog;
typedef std::shared_ptr<Dog> DogPointerType;
typedef std::shared_ptr<const Dog> DogConstPointerType;

class Fish;
typedef std::shared_ptr<Fish> FishPointerType;
typedef std::shared_ptr<const Fish> FishConstPointerType;

enum CatType{RED_CAT, YELLOW_CAT, GREEN_CAT, PURPLE_CAT}

enum DogType{HATE_CAT_DOG, HUSKY, GOLDEN_RETRIEVER}

enum FishType{SHARK, OCTOPUS, SALMON}
</code>```

Is it acceptable practice? Should I make every unit, which needs a class declaration, depends on one file? Does it cause high coupling?

Or I should put these pointer type aliasing and enum definition inside the class back?

cat.h

```<code>class Cat
{
    typedef std::shared_ptr<Cat> PointerType;
    typedef std::shared_ptr<const Cat> ConstPointerType;

    enum Type{RED_CAT, YELLOW_CAT, GREEN_CAT, PURPLE_CAT}
    ...
};
</code>```

dog.h

```<code>class Dog
{
    typedef std::shared_ptr<Dog> PointerType;
    typedef std::shared_ptr<const Dog> ConstPointerType;

    enum Type{HATE_CAT_DOG, HUSKY, GOLDEN_RETRIEVER}
    ...
}
</code>```

fish.h

```<code>class Fish
{ ... };
</code>```

Any suggestion will be helpful.

答:
Having a single file with all your class declarations seems like asking for trouble to me. There are architectural as well as tooling based reasons for my statement.

Let's look at tooling first. Most compilers can generate partially compiled files (such as .pch) based on which header files are included. These files are recreated only when those header files change. For large enterprise projects, this can mean the difference between a 5 min build and a 1 hour build. If you put all your declarations in one file, adding a single class will trigger a full build - not too desirable. There are intense debates around whether to use pre-compiled files in the first place, but this point is definitely something to keep in mind.

Many tools such as IDEs also use header scope to determine the level of auto-complete, etc. With a global header file, I've seen IDEs slow to a crawl as they try to process the massive include tree.

Secondly, as your project grows and you start using hundreds of classes, having them all declared in a single file will cause a lot of unnecessary coupling. The whole point of header files is to specify the compilation/lookup scope for your objects. It is better for each class to know only what it strictly needs. This enables future modularization and extensibility.

OwnerDisplayName: Chen OT


问:
Why don't we completely de-couple frontend JS frameworks and backend APIs?
Whenever we implement a frontend framework in the likes of Backbone, AngularJS etc. there's an integration process involved with the backend technologies like NodeJS, Rails, Yii etc. (like setting up routes, generating views or adding libs etc.) which varies depending upon what you select at the front-end and what you take at the backend, my question is:

Why don't we completely de-couple the process so that front-end (HTML, CSS, JS etc.) is completely independent while backend APIs returns us desired data only, just like we do in mobile development.

答: Alright I've found what I was looking for, the simplest answer to my question is that we could do this sort of de-coupling and depending upon what and why we need it, something like Hoodie framework (http://hood.ie/) already implements what I had been thinking about, but I presume it's not just that, we can use this sort of implementation in pretty much any given front-end framework.


问:
Modifying an open-source license with optional requests
A general question about open-source licenses:  I know you can't modify them yourself (i.e. "GPL except you can't do this") and writing your own is generally a bad idea.  However, is it feasible to add "Please do this" riders?

For example, say that I want to license something under the GPL. Can I add a clause which says "If you release a fork of this software, you are hereby requested to contact so-and-so and notify them"?  Would this count as a different license?  For that matter, is the license even the right place for such a request, or should it go in a README (and if so, how would you get it to propagate)?

Edit: To clarify, I'm primarily asking whether this is something that can be done, and only secondarily whether it's a good idea (I suspected not, and the first responses confirm it).  I have no intent of actually doing so, it's just inspired by an unrelated discussion I had.

答:
I am not a lawyer, but

don't put such things in the license, which is a legal document to be mostly read by lawyers.

Avoid changing a single byte or sign in legal documents. You are probably not a lawyer neither.

Notice that the legal text of license is usally not open, in the sense that you probably are not allowed to change that text (and still call the license by its original name). Also, common licenses (like the GPL and many other OSI approved licenses) have a well established understanding (some lawyers, at least in big corporation, already know them). In some big organizations, people might be forbidden to use any nearly free software with a bizarre license.

Just put such a wish (it is not legally binding) in the README file. Better yet, put your source repository on some widely known forge (like gitorious or github etc...)

BTW, such requests are not mandatory. But in practice, you'll have few downloads at first, and you should be very happy if someone fork or contribute to your project.

Also, by releasing your software you should put some trust on the users and you are requiring trust from contributors (and users also). So be nice, and expect a priori other people to be as nice as you.


答:
This is an architectural choice and you don't need any particular kind of framework to accomplish it, whether on front- or back-end.

One way to accomplish it (and this is supported by at least some single app javascript frameworks) is to write your front-end with no knowledge or connections to the backend beyond a set of URLs that supply or accept whatever data you require.

Really, your own answer is correct ;)

Title: Why don't we completely de-couple frontend JS frameworks and backend APIs?

Body:
Whenever we implement a frontend framework in the likes of Backbone, AngularJS etc. there's an integration process involved with the backend technologies like NodeJS, Rails, Yii etc. (like setting up routes, generating views or adding libs etc.) which varies depending upon what you select at the front-end and what you take at the backend, my question is:

Why don't we completely de-couple the process so that front-end (HTML, CSS, JS etc.) is completely independent while backend APIs returns us desired data only, just like we do in mobile development.


问:
How should I handle measurement logging in my Discrete Event Simulation engine?
I'm attempting to build a Discrete Event Simulation library by following this tutorial and fleshing it out.

How should I handle logging metrics in my Discrete Event Simulation engine?

If you don't want/need background, skip to The Design or The Question section below...

Simulation

The goal of a simulation of the type in question is to model a process to perform analysis of it that wouldn't be possible or at least feasible in reality.

Take the canonical example of a simulation of this kind is a Bank:

Customers enter the bank and get in line with a statistically distributed frequency

Tellers are available to handle customers from the front of the line one at a time with a certain distribution

As the line grows longer, the number of tellers available may have to be increased based on certain business rules

You can break this down into generic objects:

Entity: These would be the customers

Generator: This object generates Entities according to a distribution

Queue: This object represents the line at the bank.  They find much real world use in acting as a buffer between customers and a limited service.

Activity: This is a representation of the work done by a teller.  It generally processes Entities from a Queue

Discrete Event Simulation

Instead of a continuous tick by tick simulation such as one might do with physical systems, a "Discrete Event" Simulation is a recognition that in many systems only critical events require process and the rest of the time nothing important to the state of the system is happening.

In the case of the Bank, critical events might be a customer entering the line, a teller becoming available, the manager deciding whether or not to open a new teller window, etc.

In a Discrete Event Simulation, the flow of time is kept by maintaining a Priority Queue of Events instead of an explicit clock.  Time is incremented by popping the next event in chronological order (the minimum event time) off the queue and processing as necessary.

The Design

I've got a Priority Queue implemented as a Min Heap for now.

In order for the objects of the simulation to be processed as events, they implement an ISimulationEvent interface that provides an EventTime property and an Execute method. Those together mean the Priority Queue can schedule the events, then Execute them one at a time in the correct order and increment the simulation clock appropriately.

The simulation engine is a basic event loop that pops the next event and Executes it until there are none left.  An event can reschedule itself to occur again or allow itself to go idle.  For example, when a Generator is Executed it creates an Entity and then reschedules itself for the generation of the next Entity at some point in the future.

The Question

How should I handle logging metrics in my Discrete Event Simulation engine?

In the midst of this simulation, it is necessary to take metrics.  How long are Entities waiting in the Queue? How many Acitivity resources are being utilized at any one point? How many Entities were generated since the last metrics were logged?

It follows logically that the metric logging should be scheduled as an event to take place every few units of time in the simulation.

The difficulty is that this ends up being a cross-cutting concern: metrics may need to be taken of Generators or Queues or Activities or even Entities. Consider also that it might be necessary to take derivative calculated metrics: e.g. measure a, b, c, and ((a-c)/100) + Log(b).

I'm thinking there are a few main ways to go:

Have a single, global Stats object that is aware of all of the simulation objects.  Have the Generator/Queue/Activity/Entity objects store their properties in an associative array so that they can be referred to at runtime (my chosen language doesn't support reflection). This way the statistics can be attached as needed Stats.AddStats(Object, Properties). This wouldn't support calculated metrics easily unless they are built into each object class as properties somehow.

Have a single, global Stats object that is aware of all of the simulation objects. Create some sort of ISimStats interface for the Generator/Queue/Activity/Entity classes to implement that returns an associative array of the important stats for that particular object. This would also allow runtime attachment, Stats.AddStats(ISimStats). The calculated metrics would have to be hardcoded in the straightforward implementation of this option.

Have multiple Stats objects, one per Generator/Queue/Activity/Entity as a child object. This might make it easier to implement simulation object-specific calculated metrics, but clogs up the Priority Queue a little bit with extra things to schedule. It might also cause tighter coupling, which is bad :(.

Some combination of the above or completely different solution I haven't thought of?

Let me know if I can provide more (or less) detail to clarify my question!

I may be in error using the Aspect-Oriented tag, but I suspect that people of that background would have good advice for this situation.

答:
You have your answer already based on an observation you made:
You have a Cross cutting concern and this definitely falls into the realm of an aspect.
I just wrote about this yesterday as you are trying to do something identical to that post.

You're trying to roll a DES from scratch and that's ok. But, leveraging existing libraries to make use of aspects is crucial and acceptable.

In addition, in this example you can get a motivation for how to express the cutpoint. Spring AOP offers a syntax for doing so but you could also use AspectJ. I am SURE .NET offers facilities for aspects as well but I am not familiar with them. A clever programmer could probably use some macros or pragmas to do it in C as well.

Do I win the bounty? :)


问:
What was before MVC?
MVC is used a lot (not only in web apps) and it seems it's the 'go to' approach when designing software. There are also a lot of MVC versions.

My question is: what was before MVC? How did people structure large software systems?

Obviously 'separation of concerns' wasn't invented with MVC (even if it wasn't called that). I assume this type of thinking, which is crucial for building and maintaining software, was present long ago.

But in more technical terms, how was software structured before MVC?

答:
MVC is about User Empowerment for Interactive GUI Systems. It was invented at about the same time that GUIs were, and only shortly after Interactive Systems became available (and before they became widespread). User Empowerment (at least in the sense that Alan Kay's group understood it, namely that programming should be so easy that users wouldn't have to depend on programmers for programming) still hasn't happened yet.

So, in a sense, there was no "before". At the time that MVC was invented, there were only about a dozen or so programs that would have benefited from MVC, and the inventors of MVC knew all of them and (probably) drew inspiration from them.

More interesting is the fact that the community which invented MVC 35 years ago has mostly abandoned it by now. Self (a direct descendant of Smalltalk) appeared in 1987 with the Fabrik UI (inspired by the Alternate Reality Kit), which is distinctly different from MVC, and Squeak Smalltalk (the Smalltalk dialect designed by the original creators of Smalltalk) adopted a port of Fabrik called Morphic instead of MVC in the 1990s (MVC is only included in the Squeak distribution for legacy programs). Pharo, a modern fork of Squeak, gets rid of MVC altogether, in favor of Morphic. Most commercial Smalltalks nowadays use some variation of MVP, not MVC.

Title: What was before MVC?


答:
Learning by example works for me

Here is a quick example of idiomatic Java 6

```<code>public class Main {
  public static void main(String[] args) {
    // Shows a list forced to be Strings only
    // The Arrays helper uses generics to identify the return type
    // and takes varargs (...) to allow arbitary number of arguments
    List<String> genericisedList = Arrays.asList("A","B","C");

    // Demonstrates a for:each loop (read as for each item in genericisedList)
    for (String item: genericisedList) {
      System.out.printf("Using print formatting: %s%n",item);
    }

    // Note that the object is initialised directly with a primitive (autoboxing)
    Integer autoboxedInteger = 1;
    System.out.println(autoboxedInteger);

  }
}
</code>```

Don't bother with Java5, it's deprecated in respect to Java6.

Next step, annotations. These just define aspects to your code that allow annotation readers to fill in boilerplate configuration for you. Consider a simple web service that uses the JAX-RS specification (it understands RESTful URIs). You don't want to bother doing all the nasty WSDL and mucking about with Axis2 etc, you want a quick result. Right, do this:

```<code>// Response to URIs that start with /Service (after the application context name)
@Path("/Service")
public class WebService {

  // Respond to GET requests within the /Service selection
  @GET
  // Specify a path matcher that takes anything and assigns it to rawPathParams
  @Path("/{rawPathParams:.*}")
  public Response service(@Context HttpServletRequest request, @PathParam("rawPathParams") String rawPathParams) {
    // Do some stuff with the raw path parameters

    // Return a 200_OK
    return Response.status(200).build();
  }
}
</code>```

Bang. With a little sprinkle of configuration magic in your web.xml you're off. If you're building with Maven and have the Jetty plugin configured, your project will have it's own little web server right out of the box (no fiddling about with JBoss or Tomcat for you), and the above code will respond to URIs of the form:

```<code>GET http://localhost:8080/contextName/Service/the/raw/path/params
</code>```

Job done.

Title: Help me catch up on what I've missed since Java 1.4.2

Body:
I am about to start my first professional career position as a software developer, and I'm likely going to be writing a lot of Java code.  I don't know that much about what specifically I'll be writing, and besides, I have fairly broad interests when it comes to code anyway.

For reasons not worth discussing, my last internship had me coding only for the Java 1.3 and 1.4 SDK's.  Also, my university education has focused mainly on algorithms, data structures, and other theory, not language features or libraries.

So, with the above in mind, what features, classes, etc. in the current version of Java (what number are we on now, anyway?) would be worth my time to read up on and why?  What have I missed since 1.4.2 that makes your life as a programmer easier?

Examples and stories of how you discovered a particular package or some such and put it to use would also be great.

Body:
Learning by example works for me

Here is a quick example of idiomatic Java 6

public class Main {
  public static void main(String[] args) {
    // Shows a list forced to be Strings only
    // The Arrays helper uses generics to identify the return type
    // and takes varargs (...) to allow arbitary number of arguments
    List<String> genericisedList = Arrays.asList("A","B","C");

    // Demonstrates a for:each loop (read as for each item in genericisedList)
    for (String item: genericisedList) {
      System.out.printf("Using print formatting: %s%n",item);
    }

    // Note that the object is initialised directly with a primitive (autoboxing)
    Integer autoboxedInteger = 1;
    System.out.println(autoboxedInteger);

  }
}

Don't bother with Java5, it's deprecated in respect to Java6.

Next step, annotations. These just define aspects to your code that allow annotation readers to fill in boilerplate configuration for you. Consider a simple web service that uses the JAX-RS specification (it understands RESTful URIs). You don't want to bother doing all the nasty WSDL and mucking about with Axis2 etc, you want a quick result. Right, do this:

// Response to URIs that start with /Service (after the application context name)
@Path("/Service")
public class WebService {

  // Respond to GET requests within the /Service selection
  @GET
  // Specify a path matcher that takes anything and assigns it to rawPathParams
  @Path("/{rawPathParams:.*}")
  public Response service(@Context HttpServletRequest request, @PathParam("rawPathParams") String rawPathParams) {
    // Do some stuff with the raw path parameters

    // Return a 200_OK
    return Response.status(200).build();
  }
}

Bang. With a little sprinkle of configuration magic in your web.xml you're off. If you're building with Maven and have the Jetty plugin configured, your project will have it's own little web server right out of the box (no fiddling about with JBoss or Tomcat for you), and the above code will respond to URIs of the form:

GET http://localhost:8080/contextName/Service/the/raw/path/params

Job done.


答:
Actually the MVC concept pre-dates graphical GUIs.

It first appeared as an architecture in large mainframe CICS installations.

The motivation was scalability rather than useability, and, to overcome some of the single threading, single ownership issues associated with CICS processes or "region" in M/F speak.

So you had the Controller which contained the application logic in a separate program which could run in one of several "Application Owning Regions".

Then you had the View as a separate program which could run in any of the "Terminal Owning Regions" where users could log in and start a session.

Finally you had the Model in a "Data Owning Region" there could be several of these but an olde worldy VSAM file or IMS database had to be wholly owned by a single CICS region. These days "DOR"s have mostly been replaced by connections to a real DB2 database.

So apart from the actual GUI almost everything you think of as "modern" IT was implemented on the mainframe in the last century.

In case you were wondering VSAM is effectivly a "key"/"value" data store. IMS/DB is a NoSql database.

Title: What was before MVC?

Body:
MVC is used a lot (not only in web apps) and it seems it's the 'go to' approach when designing software. There are also a lot of MVC versions.

My question is: what was before MVC? How did people structure large software systems?

Obviously 'separation of concerns' wasn't invented with MVC (even if it wasn't called that). I assume this type of thinking, which is crucial for building and maintaining software, was present long ago.

But in more technical terms, how was software structured before MVC?


问:
Why doesn't Ruby have implicit conversion of Fixnum into String?
Ruby normally makes things easy. However, it doesn't allow implicitely converting a number to a string:

```<code>2.0.0p247 :010 > "a"+1
TypeError: no implicit conversion of Fixnum into String
</code>```

Why is this when nearly every other language allows it, including Perl, PHP, Java and VBA?

答:
Languages that have implicit conversion to string usually have it for all types, not just numbers. Implicit conversions are usually bad if you want strong typing, type errors that could have been discovered in compile time(in case of compiled static-typed languages) or as exceptions in runtime(in case of interpreted or dynamic-typed languages) may turn into logic errors(the worst kind of error) or unrelated exceptions.

Some languages are willing to deal with this to have a simple string syntax for creating strings, but Ruby doesn't need it because it has string interpolation:

```<code>[1] pry(main)> "a"+1
TypeError: no implicit conversion of Fixnum into String
from (pry):1:in `+'
[2] pry(main)> "a#{1}"
=> "a1"
</code>```

Body:
Languages that have implicit conversion to string usually have it for all types, not just numbers. Implicit conversions are usually bad if you want strong typing, type errors that could have been discovered in compile time(in case of compiled static-typed languages) or as exceptions in runtime(in case of interpreted or dynamic-typed languages) may turn into logic errors(the worst kind of error) or unrelated exceptions.

Some languages are willing to deal with this to have a simple string syntax for creating strings, but Ruby doesn't need it because it has string interpolation:

[1] pry(main)> "a"+1
TypeError: no implicit conversion of Fixnum into String
from (pry):1:in `+'
[2] pry(main)> "a#{1}"
=> "a1"


问:
Why does IIS default to Recycling the Application Pool every 1740 minutes?
Why does IIS default to recycle the app pool after a given time? Is there some specific reason other than perhaps most web apps are not managing the memory prudently? Given that you are managing your application's memory properly, is is safe to go ahead and turn this off? What are some potential down sides, up benefits to turning off recycling or keeping it on?</p>

答:
1740 minutes is 29 hours:

Back when IIS 6 was being developed—which is the version that
  introduced application pools—a default needed to be set for the
  Regular Time Interval when application pools are automatically
  recycled.

Wade suggested 29 hours for the simple reason that it’s the smallest
  prime number over 24. He wanted a staggered and non-repeating pattern
  that doesn’t occur more frequently than once per day. In Wade’s words:
  “you don’t get a resonate pattern”. The default has been 1740 minutes
  (29 hours) ever since!

http://weblogs.asp.net/owscott/archive/2013/04/06/why-is-the-iis-default-app-pool-recycle-set-to-1740-minutes.aspx


问:
Can an object oriented program be seen as a Finite State Machine?
This might be a philosophical/fundamental question, but I just want to clarify it.

In my understanding a Finite State Machine is a way of modeling a system in which the system's output will not only depend on the current inputs, but also the current state of the system. Additionally, as the name suggests it, a finite state machine can be segmented in a finite N number of states with its respective state and behavior.

If this is correct, shouldn't every single object with data and function members be a state in our object oriented model, making any object oriented design a finite state machine?

If that is not the interpretation of a FSM in object design, what exactly people mean when they implement a FSM in software? am I missing something?

Thanks

答:
I don't believe the accepted answer is completely correct.

You cannot model an arbitrary program written in a Turing Complete language, whether it is object-oriented or not, as a Finite State Machine. Almost all modern computer languages, such as Java, C++, or Smalltalk, are Turing Complete.

For instance, you cannot create a Finite State Machine to recognize a sequence of objects where you have n instances of one object followed by n instances of another object because Finite State Machines are incapable of writing n to a variable. They can only read input and switch to a state.


答:
You may want to think about using a MVVM approach. You said you want your view to be responsive, hence, you update on every click, but then you also state that it is taking a lot of time for the model to return the result. These two just don't work together.

With a MVVM design you get a separate view-model (the last VM), which should be created in such a way that it can provide the view with data almost instantaneously when you click another row. Also, if the model data itself is changed, the view-model can tell two things: 1) if the changed data is even relevant to the current view, i.e. whether it is currently displayed at all and 2) whether the change is an actual change as opposed to the data it gave the view last time. In both cases, the view need not change.

Finally, you move the synchronization aspect between the threads to another boundary, where updates on the model need to be sent to the view-model, which may be queried at the same time due to clicks in the view. You have to synchronize on these updates of course, however, both the update of the view-model and the queries should be really fast. In particular, as the view-model shouldn't do much more than derive some string values or such for displaying, it is much faster than a user clicking on different rows. Furthermore, the queries are fast enough to allow blocking in your mouse listener, such that you do not even have to care about race conditions.

tl;dr - create a separate model for your view, which supports fast queries, and make the view updates blocking (i.e. not asynchronous).

Title: MVC pattern synchronisation

Body:
I am facing a problem in synchronizing my model and view threads

I have a view which is table. In it, user can select a few rows.
I update the view as soon as the user clicks on any row since I don't want the UI to be slow.
This updating is done by a logic which runs in the controller thread below.

At the same time, the controller will update the model data too, which takes place in a different thread. i.e., controller puts the query in a queue, which is then executed by the model thread - which is a single-threaded interface.

As soon as the query executes, controller will get a signal.

Now, In order to keep the view and model synchronized, I will update the view again based on the return value of the query (the data returned by model) - even though I updated the view already for that user action.

But, I am facing issues because, its taking a lot of time for the model to return the result, by that time user would have performed multiple clicks. So, as a result of updating the view again based on the information from model, the view sometimes goes back to the state in which the previous clicks were made

(Suppose user clicks thrice on different rows. I update the view as soon as the click happens. Also, I update the view when I get data back from the model - which is supposed to be same as the already updated state of the view. Now, when the user clicks third time, I get data for the first click from model. As a result, view goes back to a state which is generated by the first click)

Is there any way to handle such a synchronization issue?


问:
Help me catch up on what I've missed since Java 1.4.2
I am about to start my first professional career position as a software developer, and I'm likely going to be writing a lot of Java code.  I don't know that much about what specifically I'll be writing, and besides, I have fairly broad interests when it comes to code anyway.

For reasons not worth discussing, my last internship had me coding only for the Java 1.3 and 1.4 SDK's.  Also, my university education has focused mainly on algorithms, data structures, and other theory, not language features or libraries.

So, with the above in mind, what features, classes, etc. in the current version of Java (what number are we on now, anyway?) would be worth my time to read up on and why?  What have I missed since 1.4.2 that makes your life as a programmer easier?

Examples and stories of how you discovered a particular package or some such and put it to use would also be great.

答: java.util.concurrent was introduced in 1.5. The best resource for learning it is (probably) the Java Concurrency in Practice book. IMHO concurrency is Java's most important competitive advantage compared to anything else so it's definitely worth knowing well.</p>


问:
Message Passing: How to detect and/or handle "dead ends"
I'm playing with a mental model for distributed actor system that communicates using messages. In this, it is possible for an actor to create another actor. I've encountered one specific situation where I'm not really sure how to resolve. Consider this sequence of events:

Actor 1 requests creation Actor 2. As part of the "construction", it passes its own ID.

Actor 1 requests its own deletion.

System sends KILL message to all Actors who subscribed to {Actor1|KILL}

Actor 2 is created, saves ID of "1" sent to it as construction parameter.

Actor 2 attempts to send a message to Actor 1.

???

Actor 2 detects that Actor 1 is gone, and reacts.

Since Actor 1 and 2 can be on physically different machines, querying "Does Actor X exist?" every time (or before every time) you attempt to send a message will introduce latency that shouldn't be there in the typical case. Similarly, blocking until you know "Send Success" or "Send Fail" seems like a bad idea. It also seems that litering code with if(send() == fail) { ... } is ugly and error-prone. Are there known solutions for robustly and cleanly handling these sorts of situations?

答:
This problem has been faced may times when trying to build a reliable communication protocol on top of an unreliable one. That starts with TCP (as the underlying IP protocol is unreliable) and any protocol that uses UDP as transport mechanism.

The basic idea is that each message/packet gets an identification number and the recipient sends an acknowledgment of the messages/packets that it received. If the sender doesn't get an acknowledgment within a certain time frame, then the message is considered lost and the sender retries sending it. After a certain number of retries, delivery of the message is usually given up and a failure is reported to the application.

On the application level, there are two main ways to handle it:

A blocking send function. This should only be used if the timeouts are relatively short. You don't want to block your actor for a minute because the recipient is difficult to reach. A blocking send function can either return a status indicating success/failure, or it can throw an exception (if failure is considered an exceptional situation and/or it is likely that the direct callers of send can't really do anything with the error except passing it on up the stack).

A non-blocking send function. In this case, the failure notification will often be in the form of a callback or event that arrives some time after sending the message.

In either case, for messages where the actor isn't interested in the success/failure of delivery, the actor can just choose to ignore failure indications, or there can be a mechanism to say to the lower layers "don't bother retrying this message".


问:
Should I follow the normal path or fail early?
From the Code Complete book comes the following quote:

"Put the normal case after the if rather than after the else"

Which means that exceptions/deviations from the standard path should be put in the else case.

But The Pragmatic Programmer teaches us to "crash early" (p. 120).

Which rule should I follow?

答:
I think @JackAidley said the gist of it already, but let me formulate it like this:

without Exceptions (e.g. C)

In regular code flow, you have:

```<code>if (condition) {
    statement;
} else if (less_likely_condition) {
    less_likely_statement;
} else {
    least_likely_statement;
}
more_statements;
</code>```

In the “error out early” case, your code suddenly reads:

```<code>/* demonstration example, do NOT code like this */
if (condition) {
    statement;
} else {
    error_handling;
    return;
}
</code>```

If you spot this pattern – a return in an else (or even if) block, rework it immediately so the code in question does not have an else block:

```<code>/* only code like this at University, to please structured programming professors */
function foo {
    if (condition) {
        lots_of_statements;
    }
    return;
}
</code>```

In the real world…

```<code>/* code like this instead */
if (!condition) {
    error_handling;
    return;
}
lots_of_statements;
</code>```

This avoids nesting too deep and fulfils the “break out early” case (helps to keep the mind – and the code flow – clean) and doesn’t violate the “put the more likely thing into the if part” because there simply is no else part.

C and cleanup

Inspired by an answer on a similar question (which got this wrong), here's how you do cleanup with C. You can use one or two exit points there, here's one for two exit points:

```<code>struct foo *
alloc_and_init(size_t arg1, int arg2)
{
    struct foo *res;

    if (!(res = calloc(sizeof(struct foo), 1)))
        return (NULL);

    if (foo_init1(res, arg1))
        goto err;
    res.arg1_inited = true;
    if (foo_init2(&(res->blah), arg2))
        goto err;
    foo_init_complete(res);
    return (res);

 err:
    /* safe because we use calloc and false == 0 */
    if (res.arg1_inited)
        foo_dispose1(res);
    free(res);
    return (NULL);
}
</code>```

You can collapse them into one exit point if there is less cleanup to do:

```<code>char *
NULL_safe_strdup(const char *arg)
{
    char *res = NULL;

    if (arg == NULL)
        goto out;

    /* imagine more lines here */
    res = strdup(arg);

 out:
    return (res);
}
</code>```

This use of goto is perfectly fine, if you can deal with it; the advice to stay off using goto is directed at people who cannot yet decide by themselves whether a use is good, acceptable, bad, spaghetti code, or something else.

Exceptions

The above talks about languages without exceptions, which I highly prefer myself (I can use explicit error handling much better, and with much less surprise). To quote igli:

```<code><igli> exceptions: a truly awful implementation of quite a nice idea.
<igli> just about the worst way you could do something like that, afaic.
<igli> it's like anti-design.
<mirabilos> that too… may I quote you on that?
<igli> sure, tho i doubt anyone will listen ;)
</code>```

But here's a suggestion how you do it well in a language with exceptions, and when you want to use them well:

error return in the face of exceptions

You can replace most of the early returns with throwing an exception. However, your normal program flow, i.e. any code flow in which the program did not encounter, well, an exception… an error condition or somesuch, shall not raise any exceptions.

This means that…

```<code># this page is only available to logged-in users
if not isLoggedIn():
    # this is Python 2.5 style; insert your favourite raise/throw here
    raise "eh?"
</code>```

… is okay, but…

```<code>/* do not code like this! */
try {
    openFile(xyz, "rw");
} catch (LockedException e) {
    return "file is locked";
}
closeFile(xyz);
return "file is not locked";
</code>```

… is not. Basically, an exception is not a control flow element. This also makes Operations look weird at you (“those Java™ programmers always tell us that these exceptions are normal”) and can hinder debugging (e.g. tell the IDE to just break on any exception). Exceptions often require the run-time environment to unwind the stack to produce tracebacks, etc. There are probably more reasons against it.

This boils down to: in a language supporting exceptions, use whatever matches the existing logic and style and feels natural. If writing something from scratch, get this agreed on early. If writing a library from scratch, think of your consumers. (Do not, ever, use abort() in a library either…) But whatever you do, do not, as a rule of thumb, have an exception thrown if operation continues (more or less) normally after it.

general advice wrt. Exceptions

Try to get all in-program use of Exceptions agreed on by the whole dev team first. Basically, plan them. Do not use them in abundance. Sometimes, even in C++, Java™, Python, an error return is better. Sometimes it is not; use them with thought.

Body:
I think @JackAidley said the gist of it already, but let me formulate it like this:

without Exceptions (e.g. C)

In regular code flow, you have:

if (condition) {
    statement;
} else if (less_likely_condition) {
    less_likely_statement;
} else {
    least_likely_statement;
}
more_statements;

In the “error out early” case, your code suddenly reads:

/* demonstration example, do NOT code like this */
if (condition) {
    statement;
} else {
    error_handling;
    return;
}

If you spot this pattern – a return in an else (or even if) block, rework it immediately so the code in question does not have an else block:

/* only code like this at University, to please structured programming professors */
function foo {
    if (condition) {
        lots_of_statements;
    }
    return;
}

In the real world…

/* code like this instead */
if (!condition) {
    error_handling;
    return;
}
lots_of_statements;

This avoids nesting too deep and fulfils the “break out early” case (helps to keep the mind – and the code flow – clean) and doesn’t violate the “put the more likely thing into the if part” because there simply is no else part.

C and cleanup

Inspired by an answer on a similar question (which got this wrong), here's how you do cleanup with C. You can use one or two exit points there, here's one for two exit points:

struct foo *
alloc_and_init(size_t arg1, int arg2)
{
    struct foo *res;

    if (!(res = calloc(sizeof(struct foo), 1)))
        return (NULL);

    if (foo_init1(res, arg1))
        goto err;
    res.arg1_inited = true;
    if (foo_init2(&(res->blah), arg2))
        goto err;
    foo_init_complete(res);
    return (res);

 err:
    /* safe because we use calloc and false == 0 */
    if (res.arg1_inited)
        foo_dispose1(res);
    free(res);
    return (NULL);
}

You can collapse them into one exit point if there is less cleanup to do:

char *
NULL_safe_strdup(const char *arg)
{
    char *res = NULL;

    if (arg == NULL)
        goto out;

    /* imagine more lines here */
    res = strdup(arg);

 out:
    return (res);
}

This use of goto is perfectly fine, if you can deal with it; the advice to stay off using goto is directed at people who cannot yet decide by themselves whether a use is good, acceptable, bad, spaghetti code, or something else.

Exceptions

The above talks about languages without exceptions, which I highly prefer myself (I can use explicit error handling much better, and with much less surprise). To quote igli:

<igli> exceptions: a truly awful implementation of quite a nice idea.
<igli> just about the worst way you could do something like that, afaic.
<igli> it's like anti-design.
<mirabilos> that too… may I quote you on that?
<igli> sure, tho i doubt anyone will listen ;)

But here's a suggestion how you do it well in a language with exceptions, and when you want to use them well:

error return in the face of exceptions

You can replace most of the early returns with throwing an exception. However, your normal program flow, i.e. any code flow in which the program did not encounter, well, an exception… an error condition or somesuch, shall not raise any exceptions.

This means that…

# this page is only available to logged-in users
if not isLoggedIn():
    # this is Python 2.5 style; insert your favourite raise/throw here
    raise "eh?"

… is okay, but…

/* do not code like this! */
try {
    openFile(xyz, "rw");
} catch (LockedException e) {
    return "file is locked";
}
closeFile(xyz);
return "file is not locked";

… is not. Basically, an exception is not a control flow element. This also makes Operations look weird at you (“those Java™ programmers always tell us that these exceptions are normal”) and can hinder debugging (e.g. tell the IDE to just break on any exception). Exceptions often require the run-time environment to unwind the stack to produce tracebacks, etc. There are probably more reasons against it.

This boils down to: in a language supporting exceptions, use whatever matches the existing logic and style and feels natural. If writing something from scratch, get this agreed on early. If writing a library from scratch, think of your consumers. (Do not, ever, use abort() in a library either…) But whatever you do, do not, as a rule of thumb, have an exception thrown if operation continues (more or less) normally after it.

general advice wrt. Exceptions

Try to get all in-program use of Exceptions agreed on by the whole dev team first. Basically, plan them. Do not use them in abundance. Sometimes, even in C++, Java™, Python, an error return is better. Sometimes it is not; use them with thought.


答:
Enums, to replace final statics and constants and help you remove references to strings and magic numbers. An example taken from the good people at sun/oracle :

```<code>public enum Planet {
    MERCURY (3.303e+23, 2.4397e6),
    VENUS   (4.869e+24, 6.0518e6),
    EARTH   (5.976e+24, 6.37814e6),
    MARS    (6.421e+23, 3.3972e6),
    JUPITER (1.9e+27,   7.1492e7),
    SATURN  (5.688e+26, 6.0268e7),
    URANUS  (8.686e+25, 2.5559e7),
    NEPTUNE (1.024e+26, 2.4746e7),
    PLUTO   (1.27e+22,  1.137e6);

    private final double mass;   // in kilograms
    private final double radius; // in meters
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }
    public double mass()   { return mass; }
    public double radius() { return radius; }

    // universal gravitational constant  (m3 kg-1 s-2)
    public static final double G = 6.67300E-11;

    public double surfaceGravity() {
        return G * mass / (radius * radius);
    }
    public double surfaceWeight(double otherMass) {
        return otherMass * surfaceGravity();
    }
}
</code>```

and

```<code>public static void main(String[] args) {
        double earthWeight = Double.parseDouble(args[0]);
        double mass = earthWeight/EARTH.surfaceGravity();
        for (Planet p : Planet.values())
           System.out.printf("Your weight on %s is %f%n",
                             p, p.surfaceWeight(mass));
    }
</code>```

Body:
Enums, to replace final statics and constants and help you remove references to strings and magic numbers. An example taken from the good people at sun/oracle :

public enum Planet {
    MERCURY (3.303e+23, 2.4397e6),
    VENUS   (4.869e+24, 6.0518e6),
    EARTH   (5.976e+24, 6.37814e6),
    MARS    (6.421e+23, 3.3972e6),
    JUPITER (1.9e+27,   7.1492e7),
    SATURN  (5.688e+26, 6.0268e7),
    URANUS  (8.686e+25, 2.5559e7),
    NEPTUNE (1.024e+26, 2.4746e7),
    PLUTO   (1.27e+22,  1.137e6);

    private final double mass;   // in kilograms
    private final double radius; // in meters
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }
    public double mass()   { return mass; }
    public double radius() { return radius; }

    // universal gravitational constant  (m3 kg-1 s-2)
    public static final double G = 6.67300E-11;

    public double surfaceGravity() {
        return G * mass / (radius * radius);
    }
    public double surfaceWeight(double otherMass) {
        return otherMass * surfaceGravity();
    }
}

and

public static void main(String[] args) {
        double earthWeight = Double.parseDouble(args[0]);
        double mass = earthWeight/EARTH.surfaceGravity();
        for (Planet p : Planet.values())
           System.out.printf("Your weight on %s is %f%n",
                             p, p.surfaceWeight(mass));
    }


问:
If I unite many web apps into one, will I save resources?
I'm comparing 2 different approaches of J2EE application architecture:

Divide independent parts as modules of one big web app.

Divide independent parts as different web apps running on same server.

Between these approaches I prefer the second one because it allows me to make changes without redeploying the whole application. Imagine that you want to change something in app2. In the case of one big app you have to redeploy the whole application. In the second case you have to only redeploy app2.

But I have some doubts about resources consumption such as memory usage and CPU usage. I personally think that each J2EE application, no matter how large it is, has some minimal limit of memory it will necessary use. This minimal limit is what is needed for context loading, web framework config files, jar libs and other things. My hypothesis sounds like "Having many web apps running on same server leads to multiplication of wasting of default minimal resources." Is the picture below correct? Does one big application save me from default resorces overhead multiplication shown on the picture?

答:
It is a little unclear if you mean sharing the same J2EE container or physical server. Regardless, my suggested approach is the same but I don't know if I am suggesting option 2 (which I think I am) or a third option you had not considered.

If you try and host lots of apps as one app it means you will suffer from far more from things like threading overhead within the app. The OS is better at managing this sort of thing usually. Also especially as the number of apps grows, that being able to deploy just one thing point is very useful. In general it will be a little less but a larger app will have more minimum overhead so the difference is not as pronounced as your diagram indicates and we are talking about such small amounts of resources that you should favour the robust and flexible approach over scrimping for a few megabytes of memory.

My company recently threw out a monolithic Jetty container in preference of lots of tiny webapps each with their own embedded Jetty server running on the same server. Mostly because it was taking over 30 minutes to restart the server!

Yes it can use a little more in the way of initial resources but the coordination resources are lesser. You also gain the ability to split them across several boxes. Also one component crashing is less likely to affect the others. Also you can scale them individually e.g. you may need 3 instances of app 2 but only 1 of the others. In addition you can tweak the minimum resources assigned on a per-app basis which would likely let you pair it down smaller.

Additionally joining them together can make tracing down the cause of a problem harder as the root cause may not be in the app that failed. This again comes down usually to resources in that App2 may be creating lots of objects starving App3 causing an OOM in app3. This would take down all 3 but would look like app3 was the cause when it was actually app2

Thus advice in terms of resources, flexibility, scalability and robustness is option 2, many small apps.