问:
What's the best way of building an administrative UI for an existing SPA application?
I’m working on an application where the client-side interface and backend server are completely separate applications. The backend is written in Ruby and only serves JSON via HTTP. The client is a completely “static” single-page browser application that communicates with the JSON API. I now need to build an administrative interface that will be used to curate content served by the JSON API.

I see a number of ways I could conceivably build this:

Extend the existing single-page application. Initially this seemed like the most obvious way to do it because I already have a lot of existing code for communicating with the API. The downside I see here is that the admin section would feel very tacked on. The admin concerns are largely orthogonal to the functionality of the existing SPA and I’m not convinced the amount of code reuse would actually warrant combining the two applications.

A separate single-page application. This could work fine. I would have to duplicate some code from the existing SPA but I think this makes a little more sense since the admin interface very much feels like a separate application. The admin area does not need a spectacular UI, though, and a traditional server-rendered web application might be a way to reduce the development effort required to build the admin interface.

A server-rendered web application. All the server-rendered web applications I’ve built in the past have been directly connected to a database. This, however, would need to communicate with the JSON API on each request. I’m sure it’s possible but it’s not very familiar to me and don’t see much discussion about this approach.

A server-rendered web application in the same process as the JSON API. This way the code rendering pages for the admin interface can directly access the db/model layer and doesn’t need to make separate HTTP requests to render the page. The part I don’t like about this is that it complects the API code with UI code and I’d rather keep those completely separate.

I’ve been considering the tradeoffs in each of these cases and would be very interested to hear other’s opinions. Have you developed a similar architecture? Which approach did you take and why?

答:
All other things being equal, I prefer not to use two different architectures in the same application, unless there's a good reason to do so (native handheld device support, for example).

That said, your solution depends entirely on your requirements.  If all the administrative UI does is set some values in the database, and it will never run outside your intranet, there are all sorts of things (like the JSON API) that you can dispense with.  It might be simpler to just stand up a more traditional server-rendered UI.

On the other hand, you do have a bunch of SPA stuff done already, and some of it might be reusable.  Consistent look and feel (and operation) is always nice.  Like I said, it depends entirely on what your requirements are.

Your decision will essentially follow the same thought process you went through originally when you decided to make a SPA application, but with different requirements and possibly with a different outcome.

I'm not sure what you mean when you say that the API code will be complected with UI code.  The whole point of having a JSON API is to allow you to be agnostic about the way you write your user interface.  Your API might have additional methods or endpoints added to it to support administrative operations, but that doesn't affect your existing UI at all.


问:
Which approach is right doing use case first or classes first ? why?
There are people who prefer to do use cases first and then do the classes, but there are also some who prefer to do class diagram first and then use cases. So is it personal choice for convenience? What are the pros and cons of the above ways?</p>

答:
You "forgot" to mention it, but I assume you are talking about gathering requirements for a new software by using UML, right?

I think the first step in this should always be to understand the use cases (and I am not talking about fancy use case diagram, I am talking about the business process of your users, what they are doing and how the new software shall be integrated into their work). You can do this by interviewing people, by observing them or by working with them.

To safe the result of this process you can try to incorporate use case diagrams, but these diagrams will provide only a very high level abstraction of what you have learned in the step before. So you will have to add a more detailed description to any use case. This description can make use of other tools:

verbal description of the processes in natural language

example scenarios (also called "user stories")

class diagrams for modeling business entities and the data on a very detailed level

class diagrams as a form of domain model like in "domain driven design"

data flow diagrams (still missing in UML)

UI drafts

test cases

other UML diagrams (though IMHO seldom really helpful)

[...]

So if your job is to model a high level overview of the system, you will probably create use case diagrams first, each one with a more or less small description. If you are going to flesh out the details of a certain use case, where the data to be processed is modeled down to the attribute level, you may start with only one use case and do a lot of detailed bottom-up modeling (maybe incorporating class diagrams as one of many tools) before you go to the next use case. So the order for modeling depends on what your assigned task is, and how big and complex the piece of software is you have to analyse.

Be aware that many software projects in the past have failed because they were completely overanalysed - hundreds of pages of specs created over months without building a line of code first (of course, other projects failed because they were not well analysed at all), so it is important to find the right balance. Be also aware that most software systems will be created release by release - so the task of gathering requirements for version 1.0 is only the first step. For version 2,3,4,5 you will typically have to describe only the additional requirements compared to the previous version. Often the set of use cases is mostly stable between releases, but the detailed differences between version n and n+1 are of interest. So the tools I listed above for the detailed use case description become typically more important than use case diagrams after version 1.0 is in production.

ContentLicense: CC BY-SA 3.0


问:
Workflow: Using binary document formats in Git without locks (moving from subversion)
We're a software consultancy with a multitude of projects for different customers. We traditionally use Subversion, but are currently considering moving to Git.

A significant portion of the documents we produce are shared with our customers (requirements, global designs, test specs, etc), and we use MS Office to produce these. In Subversion, we could use its "Lock" feature to ensure that no one was editing the same document at the same time. In Git, you can't do that since by its distributed nature, git doesn't have locks.

Locks are really little more than a communication mechanism, but they're a very effective one.

Currently, our code and customer-facing documents are typically in different subfolders of a different svn repository. When moving to git, what would you recommend we do? I see a set of options:

We move the svn repositories to git 1-on-1. Instead of using locks on the Office files, we do what the git people suggest and somehow try to change our workflow to fix it. This could be working in a branch on any document edit, and merging that over review. This approach breaks over e.g. Excel sheets that contain project management info; they're easily edited by team members (and we encourage that this is done), but not subject to any formal review process

We use git for code and svn for docs and project management. This has the disadvantage that certain more design-ish documents won't be "nearby" the code it specs, increasing the chance that people forget to update them. Additionally, everybody has to use and understand two sets of tools. That said, maybe this is a great opportunity to move to text-based doc tools (latex, markdown, HTML, whatever) for non-customer-facing design docs.

Like 1, but we hack up a git lock command that does what svn lock does for us (toggle the read-only flag appropriately and sync with a server through some means).

I don't buy the argument that locks don't work in a DVCS because the system should even work when you're entirely offline. Svn locks can be overridden as well; they're a communication mechanism. Without some sort of network connection, you won't get your computer to communicate a lot.

We can't be the only shop who're very happy with how svn lock fits in our workflow, right?

Any ideas or tips?

I found https://stackoverflow.com/questions/119444/locking-binary-files-using-git-version-control-system but the discussion is rather technical; i'm looking for ways to solve or avoid the practical problem of two team members editing the same binary file at the same time.

答:
Put your first 2 solutions together and you don't need a third.

If you save your spreadsheets on disk as CSVs, Excel will still edit them and then git will be happy to merge them for you.

Similarly, you can open, edit, and save your files in Word if they are HTML or (god help us) RTF.  Word of course will add more bloat than useful text, but it's still just text that git is happy to merge for you.

Granted, these solutions assume that you don't make use or could move away from MS-specific features which is really only possibly an issue on the Excel side.

Unless of course you also require Word to be installed on a system to be able to read your documentation, which is in itself a terrifying prospect to me...


问:
Should I create Use Cases or create Class Diagrams first?
So I'm designing an Education Management System and I'm wondering if I should be creating the Use Cases or the Class Diagrams first?</p>

答:
Actually, Jim Coplien advises not to dive into the Use Case diagrams too soon, but rather to first find out the simplest mental model for the domain.

Focus on the essence of the system form (what the system is) without being unduly influenced by the functionality that the system provides (what the system does).

http://www.leansoftwarearchitecture.com/home/lean-and-agile-architecture-techniques

For if your system thinks about the domain in different terms and concepts than its users, they'll have trouble understanding each other. And if your domain model is solid, it will be easier to implement changing requirements on top of it.

So I think the answer is: That depends on what you're planning to put in those Use Case and Class diagrams.

I'd start thinking about classes for the domain model. Talk with people who currently are working in this domain, find out in which terms they think and talk about education. Once you understand the domain, think about the Use Cases. Then as you start implementing technical stuff, think about the classes and objects that you'll use to implement this.

Don't be shy to produce code rather than diagrams all along. A picture is nice, but compiling and running code is a lot more concrete. So classes that model your domain are a good first and reusable artefact, even better than a class diagram.


问:
Does Sublime's "minimap" improve productivity?
I'm a pretty big fan of Sublime.  One of my favorite features is the ability to scroll through your file by using the compressed image of your text on the upper right hand corner (minimap).  My gut feeling is this does positive things for productivity:

Does having this minimap to scroll through actually improve productivity?

P.S. - Side question: Did Sublime invent this idea, or did they take it from another text editor?

答: I know this is an old question, but I just found a case where I'm glad I got the minimap. Here's a generated file (search results), I could instantly see where I should scroll to.


问:
Are there any programming languages that use strict evaluation that also have overloaded values?
Haskell supports overloaded values, where a single overloaded value can behave
sort of like a superposition of values each with a different type. For example, here's a simple type class:

```<code>class Truthy t where
  truthy :: Integer -> t

instance Truthy Integer where
  truthy x = x       -- some computation that results in an Integer

instance Truthy Bool where
  truthy x = x /= 0  -- some computation that results in a Bool
</code>```

Passing a number to truthy returns an overloaded value of type Truthy t => t. This same value can be used as an Integer or a Bool:

```<code>Prelude> let y = truthy 17
Prelude> if y then y else 42
17
</code>```

Note that y is used in a Bool context (the condition) and also in a numeric
context (the then clause, which needs to match the type of the numeric else
clause).

Haskell also uses lazy evaluation, so it isn't surprising that the two
results of truthy 17 are computed lazily. This means that while an overloaded
value is conceptually a bundle of values of different types, only the instances that are actually used perform computation.

Are there any programming languages that have overloaded values like this but which use strict evaluation?

If so, what are the evaluation semantics of overloaded values like? Are overloaded values:

strict (meaning that you have to perform computations for instances you'll never use)

non-strict (which would be inconsistent with non-overloaded values)

something else?

答:
This is a pretty bog-standard feature of many programming languages that support some kind of operator overloading. However, most languages that do so only support this for built-in types such as booleans, strings, or numeric types.

In Perl, a variable doesn't generally have an actual type. Instead, it's coerced to various types however the context requires it. The + operator coerces its operands to numbers, while not extracts a boolean representation. User-defined objects can hook into this coercion process. Example:

package Truthy {
    use Scalar::Util 'looks_like_number';

    # this sets up overloading
    use overload '0+' => \&as_num, 'bool' => \&as_bool;

    # ignore this constructor code
    sub new {
        my ($class, $value) = @_;
        # this is as close as vanilla Perl gets to type checking ... bleh.
        die "\$value must be a number" if not looks_like_number $value;
        return bless \$value => $class;
    }

    sub as_num {
        my ($self) = @_;
        print "called as_num\n";
        return $$self;
    }

    sub as_bool {
        my ($self) = @_;
        print "called as_bool\n";
        return $self != 0;
    }
}

my $y = Truthy->new(17);
print +($y ? $y : 42), "\n";
```

<p>While Perl is a strict language, the coercion methods are only executed whenever the coercion is actually requested. However, the value is not cached in any way.</p>

<p>The <strong>Python</strong> language is similar, except that the overloading mechanism uses specially named methods such as <code>__str__</code> and <code>__int__</code>.</p>

<p>One interesting language that actually allows arbitrary coercions even between user-defined types is <strong>Scala</strong>. We can register “implicit” methods that supply conversions. They are only executed when that conversion is requested, so that these conversions end up having the same semantics as Perl's or Python's overloading mechanism.</p>

```class Truthy(val x: Int) { }

implicit def asInt(t: Truthy): Int = t.x
implicit def asBool(t: Truthy): Boolean = t.x != 0

val x = new Truthy(17)
val result: Int = if (x) x else 42
```

You may have noticed that I'm not using type classes (or their equivalents in OOP languages: interfaces, traits) anywhere. Most languages do not support return-type polymorphism. Instead, I expressed your code in terms of coercions which ends up doing the same thing, by very different means.

Body:
This is a pretty bog-standard feature of many programming languages that support some kind of operator overloading. However, most languages that do so only support this for built-in types such as booleans, strings, or numeric types.

In Perl, a variable doesn't generally have an actual type. Instead, it's coerced to various types however the context requires it. The + operator coerces its operands to numbers, while not extracts a boolean representation. User-defined objects can hook into this coercion process. Example:

package Truthy {
    use Scalar::Util 'looks_like_number';

    # this sets up overloading
    use overload '0+' => \&as_num, 'bool' => \&as_bool;

    # ignore this constructor code
    sub new {
        my ($class, $value) = @_;
        # this is as close as vanilla Perl gets to type checking ... bleh.
        die "\$value must be a number" if not looks_like_number $value;
        return bless \$value => $class;
    }

    sub as_num {
        my ($self) = @_;
        print "called as_num\n";
        return $$self;
    }

    sub as_bool {
        my ($self) = @_;
        print "called as_bool\n";
        return $self != 0;
    }
}

my $y = Truthy->new(17);
print +($y ? $y : 42), "\n";

While Perl is a strict language, the coercion methods are only executed whenever the coercion is actually requested. However, the value is not cached in any way.

The Python language is similar, except that the overloading mechanism uses specially named methods such as __str__ and __int__.

One interesting language that actually allows arbitrary coercions even between user-defined types is Scala. We can register “implicit” methods that supply conversions. They are only executed when that conversion is requested, so that these conversions end up having the same semantics as Perl's or Python's overloading mechanism.

class Truthy(val x: Int) { }

implicit def asInt(t: Truthy): Int = t.x
implicit def asBool(t: Truthy): Boolean = t.x != 0

val x = new Truthy(17)
val result: Int = if (x) x else 42

You may have noticed that I'm not using type classes (or their equivalents in OOP languages: interfaces, traits) anywhere. Most languages do not support return-type polymorphism. Instead, I expressed your code in terms of coercions which ends up doing the same thing, by very different means.


问:
Should instance variables be bound to the instance right in the beginning of the method they are created in?
A common problem for me - and it's not really a problem, but somehow I again and again ask myself, what is the normal way to handle this - is that there is a method and within this method a couple of variables are created, used and finally are supposed to be retained as instance variables.

Somehow I want to avoid dot notation, so I prefer variables to be local in a method instead accessing instance variables. Indeed only sometimes access time really matters cause the difference is not so big, but also when there are several variables with already longish descriptive names, if all these are referenced with obj. or self. it makes everything even longer and things become IMO less readable. This is why I tend to do have everything local and in the end of the method "save" it as instance variable. For instance

```<code>classdef myclass < handle
    properties
        basal_blood_pressures
        ...
    end

    methods
        function obj = myclass()
        end
        function output = verifyBloodPressures(obj, p)
            basal_blood_pressures = getBloodPressures('basal', p);
            n = numel(basal_blood_pressures);
            output = zeros(n);

            for ii = 1:n
                basal_blood_pressures(ii) = basal_blood_pressures(ii) ...
                ...
                output(ii) = ...
            end
            % Attach all variables to instance here
            % instead of doing it right in the beginning
            obj.basal_blood_pressures = basal_blood_pressures;
            obj.blood...
            obj...
        end
    end
end
</code>```

But doing this attachment in the end also does not "feel right" somehow. Any advice on this? Is there any good way how to proceed here?

答:
It's hard to answer this question since sometimes it does indeed make sense for a method to change an object's state. However, based on your sample code, I'd say that you might want to look into having your code splitted in two different classes.

One would be BloodPressureCalculator and hold your method. The latter should return an instance of the other class (let's call it BloodPressureData) that holds the different values your method produces.

These should probably be readonly too, as it's likely that messing around with blood pressure results wouldn't make sense.


问:
Lambda expressions with no parameters in Haskell and / or lambda calculus
In eager languages like Scheme and Python, you can use a lambda expression without parameters to delay evaluation, e.g. in Scheme (Chicken Scheme):

```<code>#;1> (define (make-thunk x) (lambda () (+ x 1)))
#;2> (define t (make-thunk 1))
#;3> (t)
2
</code>```

In line 2, t is bound to the unevaluated expression (lambda () (+ 1 1)), which is then evaluated to 2 in line 3.

Similarly, in Python:

```<code>>>> def make_thunk(x): return lambda: x + 1
...
>>> t = make_thunk(1)
>>> t()
2
</code>```

Using this technique one can implement lazy evaluation in an eager language.

So, I was expecting that Haskell would not have lambda expressions without parameters because the language is already lazy and there is no need to build delayed expressions. To my surprise, I found out that in Haskell it is possible to write the lambda expression

```<code>\() -> "s"
</code>```

which can only be applied to the () value like so:

```<code>(\() -> "s") ()
</code>```

giving the result

```<code>"s"
</code>```

Applying this function to any argument other than () throws an exception (at least as far as I could see during my tests). This seems different from delayed evaluation in Scheme and Python, because the expression still needs an argument to be evaluated.
So what does a lambda expression without variables (like \() -> "s") mean in Haskell and what can it be useful for?

Also, I would be curious to know if similar parameterless lambda expressions exist in (some variety of) lambda-calculus.

答:
() -> "s" is a lambda function which takes one argument:

```<code>ghci> :t (\() -> "s")
(\() -> "s") :: () -> [Char]
</code>```

(), the empty tuple (sometimes known as Unit), is a fully-fledged type in Haskell. It only has one member (ignoring _|_*), which is also written as (). Look at the definition of ():

```<code>data () = ()
</code>```

This means the form on the left-hand side of your lambda expression is syntactically a pattern-match which matches (), the only member of the type (). There's only one valid way to call it (which is to supply () as an argument) because there's only one valid member of the type ().

Such a function is not very useful in Haskell, because by default terms are lazily evaluated anyway, as you observed in your question.

For a much more detailed explanation, see this answer.

*_|_ is called "bottom" or "undefined". It always type-checks, but it crashes your program. The classic example of how to get a _|_ is let x = x in x.

Body:
() -> "s" is a lambda function which takes one argument:

ghci> :t (\() -> "s")
(\() -> "s") :: () -> [Char]

(), the empty tuple (sometimes known as Unit), is a fully-fledged type in Haskell. It only has one member (ignoring _|_*), which is also written as (). Look at the definition of ():

data () = ()

This means the form on the left-hand side of your lambda expression is syntactically a pattern-match which matches (), the only member of the type (). There's only one valid way to call it (which is to supply () as an argument) because there's only one valid member of the type ().

Such a function is not very useful in Haskell, because by default terms are lazily evaluated anyway, as you observed in your question.

For a much more detailed explanation, see this answer.

*_|_ is called "bottom" or "undefined". It always type-checks, but it crashes your program. The classic example of how to get a _|_ is let x = x in x.


答:
You're misinterpreting what () means in Haskell. It isn't the lack of a value, it is rather the only value of the Unit type (the type itself being referred to by an empty set of parentheses ()).

Since lambdas can be constructed to use pattern matching, the lambda expression \() -> "s" is explicitly saying "create an anonymous function, expecting an input that matches the () pattern". There isn't much point to doing it, but it's certainly allowed.

You can use pattern matching with lambdas in other ways as well, for example:

```<code>map (\(a, b) -> a + b) [(1,2), (3,4), (5,6)] -- uses pattern matching to destructured tuples

map (\(Name first _) -> first) [Name "John" "Smith", Name "Jane" "Doe"] -- matches a "Name" data type and its first field

map (\(x:_) -> x) [[1,2,3], [4,5,6]] -- matches the head of a list
</code>```

Title: Lambda expressions with no parameters in Haskell and / or lambda calculus

Body:
In eager languages like Scheme and Python, you can use a lambda expression without parameters to delay evaluation, e.g. in Scheme (Chicken Scheme):

```<code>#;1> (define (make-thunk x) (lambda () (+ x 1)))
#;2> (define t (make-thunk 1))
#;3> (t)
2
</code>```

In line 2, t is bound to the unevaluated expression (lambda () (+ 1 1)), which is then evaluated to 2 in line 3.

Similarly, in Python:

```<code>>>> def make_thunk(x): return lambda: x + 1
...
>>> t = make_thunk(1)
>>> t()
2
</code>```

Using this technique one can implement lazy evaluation in an eager language.

So, I was expecting that Haskell would not have lambda expressions without parameters because the language is already lazy and there is no need to build delayed expressions. To my surprise, I found out that in Haskell it is possible to write the lambda expression

```<code>\() -> "s"
</code>```

which can only be applied to the () value like so:

```<code>(\() -> "s") ()
</code>```

giving the result

```<code>"s"
</code>```

Applying this function to any argument other than () throws an exception (at least as far as I could see during my tests). This seems different from delayed evaluation in Scheme and Python, because the expression still needs an argument to be evaluated.
So what does a lambda expression without variables (like \() -> "s") mean in Haskell and what can it be useful for?

Also, I would be curious to know if similar parameterless lambda expressions exist in (some variety of) lambda-calculus.

Body:
You're misinterpreting what () means in Haskell. It isn't the lack of a value, it is rather the only value of the Unit type (the type itself being referred to by an empty set of parentheses ()).

Since lambdas can be constructed to use pattern matching, the lambda expression \() -> "s" is explicitly saying "create an anonymous function, expecting an input that matches the () pattern". There isn't much point to doing it, but it's certainly allowed.

You can use pattern matching with lambdas in other ways as well, for example:

map (\(a, b) -> a + b) [(1,2), (3,4), (5,6)] -- uses pattern matching to destructured tuples

map (\(Name first _) -> first) [Name "John" "Smith", Name "Jane" "Doe"] -- matches a "Name" data type and its first field

map (\(x:_) -> x) [[1,2,3], [4,5,6]] -- matches the head of a list


问:
Pros and Cons of Facebook's React vs. Web Components (Polymer)
What are the main benefits of Facebook's React over the upcoming Web Components spec and vice versa (or perhaps a more apples-to-apples comparison would be to Google's Polymer library)?

According to this JSConf EU talk and the React homepage, the main benefits of React are:

Decoupling and increased cohesion using a component model

Abstraction, Composition and Expressivity

Virtual DOM & Synthetic events (which basically means they completely re-implemented the DOM and its event system)

Enables modern HTML5 event stuff on IE 8

Server-side rendering

Testability

Bindings to SVG, VML, and <canvas>

Almost everything mentioned is being integrated into browsers natively through Web Components except this virtual DOM concept (obviously). I can see how the virtual DOM and synthetic events can be beneficial today to support old browsers, but isn't throwing away a huge chunk of native browser code kind of like shooting yourself in the foot in the long term? As far as modern browsers are concerned, isn't that a lot of unnecessary overhead/reinventing of the wheel?

Here are some things I think React is missing that Web Components will take care of for you. Correct me if I'm wrong.

Native browser support (read "guaranteed to be faster")

Write script in a scripting language, write styles in a styling language, write markup in a markup language.

Style encapsulation using Shadow DOM

React instead has this, which requires writing CSS in JavaScript. Not pretty.

Two-way binding

答:
I have not used Web Components, but it looks like they require you to add manually coded mutation logic to event handlers.

snippet from Polymer example:

```<code> <script>
   Polymer({
     counterChanged: function() {
       this.$.counterVal.classList.add('highlight');
     },
 ...
</code>```

The whole point of React is to reduce complexity by eliminating mutation logic. Instead you naïvely regenerate a virtual DOM and let React's diff algorithm figure out what needs to change in the real DOM.

Body:
I have not used Web Components, but it looks like they require you to add manually coded mutation logic to event handlers.

snippet from Polymer example:

 <script>
   Polymer({
     counterChanged: function() {
       this.$.counterVal.classList.add('highlight');
     },
 ...

The whole point of React is to reduce complexity by eliminating mutation logic. Instead you naïvely regenerate a virtual DOM and let React's diff algorithm figure out what needs to change in the real DOM.


答:
Well, the other answers cover what \() -> "something" means in Haskell: an unary function that takes () as argument.

What is a function without arguments? – A value. Actually, it can occasionally be useful to think of variables as nullary functions that evaluate to their value. The let-syntax for a function without arguments (which doesn't actually exist) ends up giving you a variable binding: let x = 42 in ...

Does lambda calculus have nullary functions? – No. Every function takes exactly one argument. However, this argument may be a list, or the function may return another function that takes the next argument. Haskell prefers the latter solution, so that a b c is actually two function calls ((a b) c). To simulate nullary functions, you have to pass some unused placeholder value.


答:
Use cases first is the right approach because tons of software engineers before us have found out already

I have not heard about people who prefer coding first (class diagrams) and think about it only afterwards (use cases) and still are able to produce non-trivial working software. On the contrary I have heard about many projects who failed completely, run out of budget etc. just because of that.

But maybe I have misunderstood the original intent of your question.

Some "cons of classes first" are: lessons learned, full size picture available as How Projects Really Work - http://www.projectcartoon.com

Some "pros of use cases first" are: because literature recommends it, e.g.

Scott W. Ambler in his online book "Agile Modeling" in chapter "Requirements Envisioning: An Agile Best Practice → What Should You Model Initially?" says:

For the first release of a system you need to take several days to identify some high-level requirements as well as the scope of the release (what you think the system should do). The goal is to get a good gut feel what the project is all about. For your initial requirements model my experience is that you need some form of:

Usage model

Domain model

User interface model(s)

3.1 Usage Model

Usage models enable you to explore how users will work with your system, which is absolutely critical if you're to understand what they need. Your usage model may be a collection of essential use cases or system use cases...

3.2 Domain Model

Part of your initial modeling efforts, particularly for a business application, will likely include the development of a conceptual domain model. This model should be very slim, capturing the main business entities and the relationships between them...your model doesn't need to be complete, it just needs to cover enough information to make you comfortable with the primary business concepts...

3.3 User Interface Model(s)

The user interface (UI) is the portion of software with which a user directly interacts. For most stakeholders the UI is the system so it is crucial to the initial success of your project to ensure that you understand what stakeholders expect of the UI. One way to explore the requirements for the UI is to create what are called essential UI prototypes, also known as an abstract prototypes or paper prototypes...

Title: Which approach is right doing use case first or classes first ? why?

Body: There are people who prefer to do use cases first and then do the classes, but there are also some who prefer to do class diagram first and then use cases. So is it personal choice for convenience? What are the pros and cons of the above ways?</p>


问:
What is the most robust, extensible way to represent a contract in code?
I would like to find or create a syntax to express business contracts programmatically, and I am looking for a robust, flexible, future-resistant way to do this.

A client should be able to add a negotiation points of varying types to the contract.

An example of a boolean negotiation point:

"There is a pre-payment penalty?" (yes/no)

While the above is certainly doable, it seems more difficult to describe the relationships between the negotiation points in an abstract way.

Some examples:

$600 is paid by "Client A" for inspection.

The above amount is paid by "Client B" if condition Y (information that should have been disclosed before the inspection was not disclosed).

Some other possible functionality:

Virtual fields are calculated based on the numeric values of other fields.

Notes:

It certainly seems like XML or possibly JSON-schema are possible candidates for describing the above.  But I am open to other options.

http://en.wikipedia.org/wiki/List_of_XML_markup_languages

Many thanks,

答:
The most commonly accepted way is to use a Business Rules Engine of some sort.

Of course, if you're willing to roll your own BRE, and just need a reading on the markup language to use, I would imagine that XML is as good as any.  It is hierarchical, has namespaces, and is unlikely to become obsolete any time soon.  Since it's likely that we're not talking about gigabytes of markup here, the angle bracket tax is unlikely to be a real issue.


答: At the syntax level, either XML or JSON would do fine. But that's the easy bit. The challenge is defining what can go in the rules. I would adopt a standard object modelling approach: what are the entities you need to represent, and what are their attributes and relationships? When you know that, encoding it in XML is easy.</p>

Title: What is the most robust, extensible way to represent a contract in code?

Body:
I would like to find or create a syntax to express business contracts programmatically, and I am looking for a robust, flexible, future-resistant way to do this.

A client should be able to add a negotiation points of varying types to the contract.

An example of a boolean negotiation point:

"There is a pre-payment penalty?" (yes/no)

While the above is certainly doable, it seems more difficult to describe the relationships between the negotiation points in an abstract way.

Some examples:

$600 is paid by "Client A" for inspection.

The above amount is paid by "Client B" if condition Y (information that should have been disclosed before the inspection was not disclosed).

Some other possible functionality:

Virtual fields are calculated based on the numeric values of other fields.

Notes:

It certainly seems like XML or possibly JSON-schema are possible candidates for describing the above.  But I am open to other options.

http://en.wikipedia.org/wiki/List_of_XML_markup_languages

Many thanks,


问:
Use a service layer with MVC
If a controller gets too fat and model instantiation starts to add up, a service layer could be used.

If I just wrap the logic inside a service class, I will get a bunch of Services with one/two methods. This feels like a code smell. Any best practices regarding this?

Can a service instantiate models?

If a service instantiates models, the services can't be unit tested. They can only be covered by integration tests?

答:
I find services really helpful to perform logic that may need to perform by more than one controller or that is just not specific enough to be part of the controller, besides the fact that it stops my controllers of getting too big and hard to read...

I personally disagree with 'aaa' when he says that "model (where the bussiness logic happends)" since thats the whole reason you have controllers, in my opinion models need to be simple data abstractors so controller can perform the needed task; again services should not get involved into data abstraction task...

just saying yo....

Title: Use a service layer with MVC


问:
Making an MVC app extensible for multiple business markets
Suppose you are to create a single, global e-commerce application to support multiple markets in different regions of the world using ASP.NET MVC.

Although most of the business logic for the application is reusable for different markets, some markets want to implement their own views and client side validation logic depending on the controller action called. The controller logic should remain the same, only the view should be altered depending on the specific market's need—and they will supply the view to use.

In short, you need to provide a way for your MVC to be extensible for these situations.

What recommendations can anyone provide as to how to best handle this?

What are the best practices around extensibility with MVC controllers/views within this context?

Or is it a bad idea overall?

I'm hoping for something clean that reduces the risk of breaking the rest of the MVC code base.

答:
Wait, they want "to implement their own [...] client side validation logic", but not server-side validation logic? This sounds as an important issue, security-wise.

In the same way, having a bunch of views written by a third-party running on your server is out of question, since those views can contain harmful code.

Now, if you need to let your customers to extend your application, you need to have plugin architecture. One way is to use MEF. Another way is to create your own implementation with AppDomains.

You can find an example of such extensibility here. Note: the code is written by me and is covered by MIT license.

In both cases, you should be very careful with permissions you grant to the custom-written code. Since it is written by third-parties and runs on your servers, make sure you understand correctly (and test thoughtfully) what can be accessed by the code, and what can't.


问:
When should I refactor a private class into a package-private class?
When I began implementing a class in my system (let's call it A), I realized I needed some kind of object that does something. So I needed a new class (let's call it B), but I made it a private static class of A.

Now, B is still only ever used by A, but A grew much bigger. Including the code for B, it's 320 LoC long.

The question is, should I move B outside of A, into a separate package-private class? It's still only ever used by A, but since A is getting big I think I should split it into smaller parts.

答:
The size of class A doesn't really matter, provided it follows the following criteria:

It's only responsible for one thing

It groups logically related functionality

As long as that criteria is fulfilled, you do not need to split up the functionality into separate classes.  The difficulty is in determining whether the class is actually responsible for more than one thing.

I tend to avoid private classes as they clutter up code.  The only reason I would create a private class usually is for a data container for temporary data which is only used by that class.  In pretty much every other circumstance I would create classes separately from each other.


问:
"Open-source" licenses that explicitly prohibit military applications
I am a researcher, and in my research I do a lot of programming. I am a big fan of the open-source concept - especially in research, where transparency and reproducibility is already a big part of the culture. I gladly contribute as much as I can to the community, and releasing my code for anyone to use is part of that.

However, in research there is always a certain measure of uncertainty about what the stuff you produce will be used for. I fully understand that I can't copyright any results or conclusions - but I can protect how others use my code, and I would like to make sure that there is no (legal) way to incorporate software I produce in military applications.

I've read through a few of the shorter ones of the common OSS licenses, and summaries of some more, but they all seem to focus solely on the questions "do you earn money on my code?" and "do you make my code available with your program?" - nothing about what the program actually does with the code.

Are there any good open-source licenses that explicitly prohibit all kinds of military applications?

Update:

After reading up some more on how OSS works, I've realized that a license that meets my needs by definition will not be open-source, since open-source licenses cannot discriminate against fields. Thus, I'm rather looking for a license that is like an open-source license, except that it prohibits military use. I want this license to be already existing, authored or at least reviewed by someone who actually knows licensing, since I don't.

Also, in response to a couple of remarks that this will be difficult to enforce: yes, I realize that. But this is more for myself than for the legal implications; if I use a license like this, and a military organization uses my code anyway, they are breaking the law and they are doing it despite my explicit instructions not to. Thus, the potentially gruesome things that they do with applications that include software I've written are no longer "on my conciousness", since they stole the software from me. (And somewhere I have a naïve hope that if they need something I've done, and my license prohibits them from using it legally, they'll get someone elses program that does the same thing and allows them to use it. Not that governments always do, but they always should abide by the law...)

It's a moral safeguard, so to speak, rather than something I actually expect to bring up in court (if my mediocre code is ever used by CIA...)

答:
Following the links on this page i found nothing up-to-date and available, neither the mentioned modified GPL nor the PeaceOSL. But you can read the latter here.
And I wouldn't be sure how well defined the term any harm, which is their criteria, is in legal systems.

Maybe you want to contact the authors.


问:
Is it common to have a constructor with 7 elements for example?
Is it common to have a constructor with 7 elements for example? or is it better to use many setters instead?</p>

答:
First, I want to point out the excellent back and forth in the comments that shows the issue is nuanced - and often a religious debate.

There are many Java-specific comments about different frameworks, etc. - but I think the real meat of a question like this should stand alone from a specific framework choice and possibly even language.

I think the question you didn't ask was: "Does my object need seven others to work properly?" This may be a design smell - or it might be completely normal at a high-level tier of your complex program. This is the question I would ask first - any weirdness about the number of inputs doesn't change depending on the method of object creation.

Once it's known that all these objects as inputs do make sense, then it comes down to how the object is created. To @Robert Harvey's point, it's important to have a fully-baked object, or else you have to check if the object is good before you do any work anywhere in the object. I have seen that type of code and it tends to be less maintainable - I feel I can say that objectively. All arguments coming in on constructors is a nice clean way to do this, but if your inversion of control framework does it via private properties - does it matter? Protection exists in both cases.


答:
In MVC the Model, is not just a DTO or set of Managers/Services it is meant to represent the concepts your application is modelling. You can think of this as the entire domain or the business logic including state and behaviours. Now given that we know that the purpose of the controller becomes a bit clearer. It's job is simply to translate commands onto the Model and the result back onto the views. This is usually done in the form of ViewModels which are different but often confused with the Model in MVC.

If you don't have a well defined Model then you may have gotten to the point where most of that logic now resides in the Controllers themselves. At this point in order to start reducing the size of your controllers you can start to pull this logic back into manager or service objects. These services typically return and operate on DTO/Entity like objects. Then the controller becomes the mapping layer between these services and the View Models. For a few good tips on mapping have a look at this article Friends don't let friends use AutoMapper.

As for your questions, the first one depends a lot on your applications. You'll need to do refactoring along the way which should become more apparent once you've removed the logic from your controllers. As for testing there is no problem instantiate models inside services however if you find it testing difficult it's probably just a sign you need to break up the service into smaller parts each with a single responsibility.

Title: Use a service layer with MVC

Body:
If a controller gets too fat and model instantiation starts to add up, a service layer could be used.

If I just wrap the logic inside a service class, I will get a bunch of Services with one/two methods. This feels like a code smell. Any best practices regarding this?

Can a service instantiate models?

If a service instantiates models, the services can't be unit tested. They can only be covered by integration tests?


问:
How to avoid global state without large function signatures?
So, there are some good answers to this question, namely:
Why is Global State so Evil?

I have a specific question about the alternatives Mikera proposed as the answer with the second most up-votes. All of them seem like they would be good ways to avoid using global state, but I want to know which of these alternatives is the best performance wise. Obviously this depends on the language you are using, but for my particular question I am asking about JavaScript. However, I think that this could apply to other languages like Java.

So, say I have a JavaScript function that calls 10 JavaScript functions in series (e.g. using the Node.JS async library in an async.series block, the scoping rules of async making this all the more difficult), and this serial operation requires shared variables to handle the state of the entire operation. This state information is no longer useful after the "parent" function returns. Now, one can avoid some of the need for a shared state by practicing good design while writing the functions, but in my specific case I've determined that they all need to read and possible modify the shared state.

So, I can follow mikera's approach and:
Instantiate a new function every time this "parent" function is called using a functor to create a closure, for example:

```<code>function newFirstStep(sharedState)
{
    return function firstStep(a,b)
    {
         //some logic with shared state
    }
}

function parentFunction()
{
    var sharedState = {"functionStartTime": 1400232233};
    var step1 = newFirstStep(sharedState);
    step1(1, 2);
}
</code>```

or define the functions inside the parent function:

```<code>function parentFunction()
{
    var sharedState = {"functionStartTime": 1400232233};
    function step1(a,b)
    {
        //logic with shared state
    }
    step1(1,2);
}
</code>```

The second option screams "bad for code re-use" to me, as well as making it difficult to test step1.

The other alternative is to add an extra context object that I pass into each function call as another argument. When I was trying to figure out how to do this before, I thought it to be extremely clunky and ugly to have to add an extra argument for each shared state variable to every single function just to have the same state, but having just a single context object per mikera's suggestion means I only have to add one extra argument to each function. This is much more palatable. However, it just "feels" unnecessary to have to pass this around since all of them "share" it. Perhaps I am just way too obsessed over an extremely minor detail?

Anyway, so here is my question:
If I use either of the possible ways to create a closure (functor or define directly in the parent function), it seems extremely inefficient to have to create 10 brand new functions every time I call this parent function. I mean, 95% of the functions are already defined. This just seems really inefficient... and I would feel the same way about doing that in a language like Java (creating new instances of objects all the time just to get a shared state).

So, is the context argument the best performance wise? I'm tearing my hair out trying to decide on whether or not to use functors for each function or adding an extra context object argument to each function signature because none really seem like a "great" solution. Am I focusing on micro-micro-optimizations and just need to focus on writing the **** code?

答:
Just write code.  Don't worry about performance unless performance is shown to be a problem.

And to the two you have, let me add a third.  Create a base object with all of the desired functions as methods, expecting this to have your state.  Then have your stateful objects set the base object as their prototype.  And now your methods simply exist, and get called, and state is passed around without having another visible parameter.

I am not a JavaScript programmer, and so don't have a strong opinion about which of these is best.


问:
Components having GPL and MIT/BSD license but released under MIT license
If a component “A” is under MIT License ,but it contains some GPL files, according to GPL the whole code should be GPL. But the component is released under MIT. Is it possible? If yes/no, on what scenarios can it happen or can get complied

Example i have Jar files contains few files which has GPL license but still jar file released under MIT?

How is that possible?

Please mention few components name where you come across, GPL license and MIT or BSD license with in it, but release under BSD or MIT

答:
If a jar file (or other compiled binary) is built from sources that, in part, are licensed with the GPL license, then the jar file must be distributed under the terms of that license.

If there is a project that contains GPL source code, but distributes its binaries under a different license, then that project is in violation of the GPL license. If possible you should avoid using those binaries or you should at the very least treat them as being covered by the GPL license.

In legal terms, there isn't much that you can do, as only the copyright holders whose copyright is being violated can take legal steps against such violations.

Note that the project authors are perfectly within their rights to use a different, GPL compatible, license for their own source files and they can also distribute binaries under that license if no GPL source files were used to build that binary.


问:
Are there any actual examples of profitable programmer's "worker's cooperatives"?
http://en.wikipedia.org/wiki/Worker_cooperative

I'm curious whether there are, anywhere in the world, worker's cooperatives that center on a technology business that involves either programming, IT, or some sort of IT or programming related consulting or services.

The wikipedia link above is an overview of the concept. The short form explanation is that a co-op is a worker-owned business. Also there is the notion that every worker owns shares in the business.

I am interested in knowing whether an example of a "programmer's/IT co-op" even exists.

Note: I am not talking about nor asking about a government-funded incubator nor any other socialized, state supported group. I also don't mean "co-working", which is renting an office with other self employed people doing their own thing.

I mean a going, profitable IT business operating in a competitive environment that is worker-owned and run.

答:
Autodesk, which develops AutoCAD, Maya, and a bunch of other things, pretty much started out as workers' cooperatives.

You can read in detail about that in co-founder John Walker's amusing and chatty collection of historical notes, The Autodesk File.

Autodesk started out in 1981, during the early days of microcomputers. Several programmers, most with day jobs, decided to develop a few programs, roll them out, and then jump behind whichever one seemed to sell the best. The company name, Autodesk, comes from a database for CP/M that I'm not sure ever shipped. When they showed off AutoCAD, they couldn't answer the phones or duplicate floppies fast enough, and they all quit their day jobs and became insanely rich.

ContentLicense: CC BY-SA 2.5


问:
Do Agile projects use abbreviated defect reporting?
I'm accustomed to relatively rigid defect reporting, something like this.

```<code>Steps to reproduce:
1. Access customer manager for user Test01
2. Check "User must change password" and click Apply
3. Access login page
4. Enter user name and password
5. Click Login

Expected results:
6. Site displays user profile page (see use case 21.1.2)

Actual results:
6. Site displays error page (see attached screen shot)
</code>```

I recently joined an Agile project where the defect reports look more like this:

```<code>Can't sign on with user Test01, see screenshots
</code>```

In my many years of development experience, I've found that the longer defect reports serve numerous purposes, e.g. it succinctly communicated the precise problem and avoids any sort of judgmental language, and clearly represents the defect as a departure from a required behavior, rather than allowing the QA engineer to make up defects for behaviors that "seem" wrong.

Agile methodology de-emphasizes the importance of documentation.  Instead we're encouraged to pick up the phone and talk to each other.

Is this a valid application of Agile principles?  Or should defect reports be fairly verbose even when we're trying to be agile?

答:
"Agile" does not mean you have no rules and processes - just that you should try to get by with as little as possible (but no less, to paraphrase the Einstein quotation). The Agile Manifesto expresses this as "Individuals and interactions over processes and tools".

In your case that means you should discuss this with your colleagues. Explain the benefits you see in having more structured bug reports, and try to find a solution that everyone can work with.

Maybe some of your colleagues have good reasons for not wanting to require more structured reports (for example, not scaring off users who want to report bugs, or because they found that the structure never quite made sense) - or maybe they just never thought about it.
You'll only find out by asking :-).


问:
c++ coding practice class vs. "free" functions
I am currently writing my first bigger project in c++. Its basic linear algebra. I am aware that boost libraries and others exist, but for various reasons I need to write my own. Purpose of the library is to perform certain vector operations (adding, substraction, etc. ...) for statistical data analysation. So ease of use of the functions has to be taken into consideration.

I started to write a class:

```<code>typedef std::vector<double> vec;
typedef std::vector<std::vector<double> > mat;

class Vector{
public:
    Vector(){}
    Vector(vec){}
    ~Vector(){}

    //functions to act on the vectors
    vec add(double){...}
    //many more...

private:
    vec v
};
</code>```

I soon realised that for simple vector arithmetic the class had some inconveniences: the missing assignment operators came to haunt me rather quickly.

Since I do not have long term coding experiences I want to know whether a "simple" file that contains all the necessary functions like:

```<code> from Vector.h:

 typedef std::vector<double> vec;
 typedef std::vector<std::vector<double> > mat;

 vec add(vec v, double d){...};
 ...
</code>```

is a proper solution for this kind of problem or if it is preferable to consider the class solution?

答:
Your best bet would be to do operator overloads.

```<code>vec operator+(const vec& rhs) const
</code>```

is what you'd use for a declaration, this page covers it in quite some detail: http://en.wikibooks.org/wiki/C%2B%2B_Programming/Operators/Operator_Overloading

Then you could just say:

```<code>vec a;
vec b;
vec c;

// Do stuff to initialize a and b

c = a + b;
</code>```

Body:
Your best bet would be to do operator overloads.

vec operator+(const vec& rhs) const

is what you'd use for a declaration, this page covers it in quite some detail: http://en.wikibooks.org/wiki/C%2B%2B_Programming/Operators/Operator_Overloading

Then you could just say:

vec a;
vec b;
vec c;

// Do stuff to initialize a and b

c = a + b;

OwnerDisplayName: dgnuff


答:
One advantage of a free function in your particular case is that you can implement both addition of vectors and doubles

```<code>vec add(vec v, double d);
</code>```

and vice versa

```<code>vec add(double d, vec v);
</code>```

This is not possible with member functions.

Member functions, however, have the benefit of being able to access and even modify objects' internal states, which may be useful (generally, this is the reason for writing functors instead of functions). But I suppose in your case this is neither required nor even needed.

As for whether to write a wrapper class or not, it's a separate question. It depends on whether your vector needs to have an additional state or member functions that you want to be called with member function syntax (e.g. v.sort()). Sometimes it's just more elegant to write sort(v).

There're also a couple of other issues with your code. First, I don't see any reason for passing vectors around by values. Use const references instead. Second, the vector algebra is the classic example of where using operator overloading suggests itself.

Oh, and don't forget to write the += operator (it's convenient and may be implemented more efficiently).

Title: c++ coding practice class vs. "free" functions

Body:
I am currently writing my first bigger project in c++. Its basic linear algebra. I am aware that boost libraries and others exist, but for various reasons I need to write my own. Purpose of the library is to perform certain vector operations (adding, substraction, etc. ...) for statistical data analysation. So ease of use of the functions has to be taken into consideration.

I started to write a class:

```<code>typedef std::vector<double> vec;
typedef std::vector<std::vector<double> > mat;

class Vector{
public:
    Vector(){}
    Vector(vec){}
    ~Vector(){}

    //functions to act on the vectors
    vec add(double){...}
    //many more...

private:
    vec v
};
</code>```

I soon realised that for simple vector arithmetic the class had some inconveniences: the missing assignment operators came to haunt me rather quickly.

Since I do not have long term coding experiences I want to know whether a "simple" file that contains all the necessary functions like:

```<code> from Vector.h:

 typedef std::vector<double> vec;
 typedef std::vector<std::vector<double> > mat;

 vec add(vec v, double d){...};
 ...
</code>```

is a proper solution for this kind of problem or if it is preferable to consider the class solution?

Body:
One advantage of a free function in your particular case is that you can implement both addition of vectors and doubles

vec add(vec v, double d);

and vice versa

vec add(double d, vec v);

This is not possible with member functions.

Member functions, however, have the benefit of being able to access and even modify objects' internal states, which may be useful (generally, this is the reason for writing functors instead of functions). But I suppose in your case this is neither required nor even needed.

As for whether to write a wrapper class or not, it's a separate question. It depends on whether your vector needs to have an additional state or member functions that you want to be called with member function syntax (e.g. v.sort()). Sometimes it's just more elegant to write sort(v).

There're also a couple of other issues with your code. First, I don't see any reason for passing vectors around by values. Use const references instead. Second, the vector algebra is the classic example of where using operator overloading suggests itself.

Oh, and don't forget to write the += operator (it's convenient and may be implemented more efficiently).

OwnerDisplayName: shakurov


问:
MVC: Where is the right place to set error messages?
I have a ASP.NET MVC application where in all my Models have an Errors Property used to store non-validation errors which I than display in my Views. Where is the right place to populate the error list according to MVC? Inside the model or inside the controller?

First Option

```<code>public class MyModel
{
 public DataOperationResult DoSomething()
  {
   //do something with data
   if (result != DataOperation.Success)
   {
     Errors.Add("Something went wrong");
   }
   return result;
 }
}
</code>```

Second option

```<code> public class MyController
  {
   public ActionResult DoSomething()
    {
     MyModel model = new myModel();
     DataOperationResult result = model.DoSomething();
     if (result != DataOperation.Success)
     {
      model.Errors.Add("Something went wrong");
     }
  }
}
</code>```

答: I don`t think storing error in models is good idea. Models are responsible for storing data not data and error. You breaking single responsibility principle. You should store erroros in ViewModels and populate them in controller. </p>


问:
How to organize and label methods intended for debug?
I have a class System, which uses a bunch of other classes, to achieve some complex signal processing.

In debugging System, one needs to observe the output signal for patterns. This is not achievable by a debugger, because of the large number of samples going through.

However, if certain parts of System can be isolated and hooked to the environment, instead of System, this will allow for simpler transformations to be performed on the signal. Thus, it becomes easier to see if those individual parts are working.

This is in addition to tests to each class, that comprises System. Once integrated, the otherwise working components may exhibit bugs. Furthermore, testing 2 or 3 of those chained together is another approach to understanding why System is not performing correctly.

Consequently, methods were introduced in System to hook various inters from/to the environment. Those methods are not needed to a final user of the class, but also cannot be removed.

How can these methods be arranged, named, and mixed-in so that the interface is clear to an end user of the class? Also, while still providing the debugging behavior hacks?

答:
My first reaction is that you should examine the possibility to use e.g. event tracing or logging in order to observe the system's behavior instead of having explicit methods in your class. Existing frameworks often gives you the possibility to modify levels of output dynamically, i.e. at run time, with overhead that is acceptable for most environments.

That being said, if this is really the way you want to go, maybe something like this would be a bit cleaner (pseudo code, not C++):

```<code>interface IDebugInfo
{
  int SomeDebugCounter();
}

interface IDebugInfoProvider
{
  IDebugInfo GetDebugInfo();
}

class System
  : IDebugInfoProvider
{
  class SystemDebugInfo : IDebugInfo
  {}

  IDebugInfo GetDebugInfo()
  {
    return new SystemDebugInfo(...);
  }
}
</code>```

Body:
My first reaction is that you should examine the possibility to use e.g. event tracing or logging in order to observe the system's behavior instead of having explicit methods in your class. Existing frameworks often gives you the possibility to modify levels of output dynamically, i.e. at run time, with overhead that is acceptable for most environments.

That being said, if this is really the way you want to go, maybe something like this would be a bit cleaner (pseudo code, not C++):

interface IDebugInfo
{
  int SomeDebugCounter();
}

interface IDebugInfoProvider
{
  IDebugInfo GetDebugInfo();
}

class System
  : IDebugInfoProvider
{
  class SystemDebugInfo : IDebugInfo
  {}

  IDebugInfo GetDebugInfo()
  {
    return new SystemDebugInfo(...);
  }
}


答:
You might read about assert, which is relevant only if NDEBUG is not preprocessor defined.

So this suggests to wrap your debug-specific code with

```<code> #ifndef NDEBUG
    //// debug specific code
 #endif
</code>```

and you could compile your production binary with -DNDEBUG ...

My preference is simply to mention e.g. dbg in every name (of type, of function or method, of variable) related to debugging...

Title: How to organize and label methods intended for debug?

Body:
I have a class System, which uses a bunch of other classes, to achieve some complex signal processing.

In debugging System, one needs to observe the output signal for patterns. This is not achievable by a debugger, because of the large number of samples going through.

However, if certain parts of System can be isolated and hooked to the environment, instead of System, this will allow for simpler transformations to be performed on the signal. Thus, it becomes easier to see if those individual parts are working.

This is in addition to tests to each class, that comprises System. Once integrated, the otherwise working components may exhibit bugs. Furthermore, testing 2 or 3 of those chained together is another approach to understanding why System is not performing correctly.

Consequently, methods were introduced in System to hook various inters from/to the environment. Those methods are not needed to a final user of the class, but also cannot be removed.

How can these methods be arranged, named, and mixed-in so that the interface is clear to an end user of the class? Also, while still providing the debugging behavior hacks?

Body:
You might read about assert, which is relevant only if NDEBUG is not preprocessor defined.

So this suggests to wrap your debug-specific code with

 #ifndef NDEBUG
    //// debug specific code
 #endif

and you could compile your production binary with -DNDEBUG ...

My preference is simply to mention e.g. dbg in every name (of type, of function or method, of variable) related to debugging...


答:
Bug reports from users always seem to follow this template:

I can't {action here} when I {another action here}

Or

When I {action here} it doesn't work

There's not much you can do about that. However, regardless of your development methodology, getting these kinds of bug reports from QA testers is absolutely unacceptable. When QA sends a bug report my way with that little information, I kick it back telling them to give me steps to reproduce and clearly state what went wrong and what should be happening.

If QA can only give you a bug report in one of the formats above, that means the QA tester may need some help from a developer to root out the problem, or if the tester is new to the project and not familiar with the business rules. This is acceptable, but not until after due diligence from the tester.

You can encourage users to give you more detailed bug reports, but know that you will get probably get little information. When that happens, have QA vet the bug to see if it can be reproduced, or contact the client and set up a walk through.

Title: Do Agile projects use abbreviated defect reporting?

Body:
I'm accustomed to relatively rigid defect reporting, something like this.

```<code>Steps to reproduce:
1. Access customer manager for user Test01
2. Check "User must change password" and click Apply
3. Access login page
4. Enter user name and password
5. Click Login

Expected results:
6. Site displays user profile page (see use case 21.1.2)

Actual results:
6. Site displays error page (see attached screen shot)
</code>```

I recently joined an Agile project where the defect reports look more like this:

```<code>Can't sign on with user Test01, see screenshots
</code>```

In my many years of development experience, I've found that the longer defect reports serve numerous purposes, e.g. it succinctly communicated the precise problem and avoids any sort of judgmental language, and clearly represents the defect as a departure from a required behavior, rather than allowing the QA engineer to make up defects for behaviors that "seem" wrong.

Agile methodology de-emphasizes the importance of documentation.  Instead we're encouraged to pick up the phone and talk to each other.

Is this a valid application of Agile principles?  Or should defect reports be fairly verbose even when we're trying to be agile?


答:
It is important to remember that Agile is not a set of strict rules, but rather a mindset of process improvement. As Dave Thomas has famously pointed out, agile is an adjective, not a noun. By definition, you can't do agile, you can only be agile.

So how an agile team handles bug reports should be based on the most effective way that the team has discovered that helps deliver working software. This could be different for different teams depending on the context they work in. If the process you are using doesn't work for you, change it. If you see a way that it could be better, change it. (If it cannot be changed, you aren't agile)

The thing to do would be to find out why it is the way that it is. Other answers here have proposed possible explanations. Talk to your tech lead or your team lead and ask how they came to the current process. Make suggestions about how to improve the process.


答:
There are no rules in Agile that say you must have abbreviated bug reports -- the type of bug reports is controlled by whatever works best for your team or organization. If the abbreviated reports work for everyone, that's agile. If complex bug reports work best, that's agile too. </p>

<p>Agile is empowering the team to do whatever it is that lets them be the most productive, without being forced to adhere to a particular set of rules established by someone outside the team. </p>

Body:
There are no rules in Agile that say you must have abbreviated bug reports -- the type of bug reports is controlled by whatever works best for your team or organization. If the abbreviated reports work for everyone, that's agile. If complex bug reports work best, that's agile too.

Agile is empowering the team to do whatever it is that lets them be the most productive, without being forced to adhere to a particular set of rules established by someone outside the team.


问:
Act as MySQL server in Java/Android
Is it possible to act as a MySQL server in a Java or Android application, such that applications like HeidiSQL can connect to it?

What I want to do is to write an application for Android which behaves as a MySQL server for an arbitrary database on that device. Since there are many MySQL clients that can connect to MySQL servers, it would be ideal if I could mimic such a server.

As it currently stands, I have three options:

Use some sort of MySQL server library (if that exists);

Write the server myself, including implementing the (trivial/needed parts of the) protocol (is this feasible?);

Drop the MySQL server approach altogether and write a specific client/server myself.

In the end, the server (Android application) should be able to process and respond to simple queries a client sends to it.

Which options are feasible, and best suitable?

答:
Sit down and write the client/server properly yourself.

If you are not willing to implement all of the protocol, just doing part of it can leave you with significant and strange breakages when some application tries to:

prepare a statement

iterate over a result set

do a transaction (and a rollback!)

do something 'at the same time' as another thing (can you do a update foo set bar = bar + 1 without getting into an infinite loop?)

do nested statements (example:

```<code>SELECT  PLAYERS.PLAYERNO, NAME,
   (SELECT   COUNT(*)
    FROM     PENALTIES
    WHERE    PLAYERS.PLAYERNO =
             PENALTIES.PLAYERNO) AS NUMBER_OF_PENALTIES,
   (SELECT   COUNT(*)
    FROM     TEAMS
    WHERE    PLAYERS.PLAYERNO =
             TEAMS.PLAYERNO) AS NUMBER_OF_TEAMS
FROM    PLAYERS
</code>```

This isn't just for trying to present the "I'm a MySQL server to the world" but just "I'm an SQL server to the world"...

There are simpler things than a MySQL server.  You could go for just "I'm a database" and use ODBC to connect to it rather than trying to mirror MySQL.  Or something like GNOME-DB.

All of this, however, presupposes that the data that you have behind this interface is actually relational and can be queried in a relational manner.  If it isn't you may be finding yourself with the object-relational impedance mismatch in reverse (and then back again?).

Thus, returning back to my original suggestion.  Write the client and server in accordance with the data that you have modeled behind it.  Trying to write something that matches the appearance of a database is going to involve nearly writing a database... and that is no little task.

Title: Act as MySQL server in Java/Android

Body:
Sit down and write the client/server properly yourself.

If you are not willing to implement all of the protocol, just doing part of it can leave you with significant and strange breakages when some application tries to:

prepare a statement

iterate over a result set

do a transaction (and a rollback!)

do something 'at the same time' as another thing (can you do a update foo set bar = bar + 1 without getting into an infinite loop?)

do nested statements (example:

SELECT  PLAYERS.PLAYERNO, NAME,
   (SELECT   COUNT(*)
    FROM     PENALTIES
    WHERE    PLAYERS.PLAYERNO =
             PENALTIES.PLAYERNO) AS NUMBER_OF_PENALTIES,
   (SELECT   COUNT(*)
    FROM     TEAMS
    WHERE    PLAYERS.PLAYERNO =
             TEAMS.PLAYERNO) AS NUMBER_OF_TEAMS
FROM    PLAYERS

This isn't just for trying to present the "I'm a MySQL server to the world" but just "I'm an SQL server to the world"...

There are simpler things than a MySQL server.  You could go for just "I'm a database" and use ODBC to connect to it rather than trying to mirror MySQL.  Or something like GNOME-DB.

All of this, however, presupposes that the data that you have behind this interface is actually relational and can be queried in a relational manner.  If it isn't you may be finding yourself with the object-relational impedance mismatch in reverse (and then back again?).

Thus, returning back to my original suggestion.  Write the client and server in accordance with the data that you have modeled behind it.  Trying to write something that matches the appearance of a database is going to involve nearly writing a database... and that is no little task.


答:
Abandon server-side views completely and have the server side deliver only data (JSON, XML, whatever is convenient, but not HTML). The client side will be pure HTML and Javascript.  That allows clients to present data any way they like without requiring any server side code.

However, this statement is troublesome:

their own ... client side validation

Client-side validation is for the convenience of the user. Validation still has to be done on the server side.  One approach is to allow them to specify validations in a small language that can be interpreted at runtime.  For example, validation could be limited to regular expressions on each value from the client side.  Another possibility is to run code in a sandbox so the code can only operate on the data provided.

Title: Making an MVC app extensible for multiple business markets

Body:
Suppose you are to create a single, global e-commerce application to support multiple markets in different regions of the world using ASP.NET MVC.

Although most of the business logic for the application is reusable for different markets, some markets want to implement their own views and client side validation logic depending on the controller action called. The controller logic should remain the same, only the view should be altered depending on the specific market's need—and they will supply the view to use.

In short, you need to provide a way for your MVC to be extensible for these situations.

What recommendations can anyone provide as to how to best handle this?

What are the best practices around extensibility with MVC controllers/views within this context?

Or is it a bad idea overall?

I'm hoping for something clean that reduces the risk of breaking the rest of the MVC code base.


问:
Divide and Conquer Algorithm clarification needed
I have a homework assignment for a data structure/algorithm class. The task is to take an unsorted array of size n (example: [-8, 3, 2, -3, 3, 1, -3, -5]), and we have to use a divide and conquer approach, w/ recursion, to find the subsequence with the largest product.

It is the same as this question: http://www.wou.edu/~broegb/Cs345/MaxSubsequenceSum.pdf except instead of sum, my question looks for a product.

I understand a D&C approach is desirable because it has time complexity log(n) (halving) instead of n^2 (nested loop). What I'm unclear on is: is the entire function supposed to be one recursive call? Or is it like:

Divide into halves.

Recursive function to find largest and smallest (bc neg * neg) products of left half

Same but right half

Same but for the "border" of the midpoint and left half

Same but for the "border" of the midpoint and right half

Compare all values

Is this done with if/else's and then recursive calls, or is it all the same recursive function with if/else's inside it? Is there a methodical way I can try to tackle this program? I feel very lost.

答:
The divide and conquer algorithm has 3 steps at each level:

A recursive call on the left half.

A recursive call on the right
half.

Calculate the maximum mixed sum.

Steps 1 and 2 are recursive, they just call the function again using the new end points. Step 3 is not, it just uses the fact that the sum/product must include the border values to make only n iterations. For example, if you had [1 2 3 4 5 6] it knows a mixed sum/product must have 3 and 4, and it can just check 123, 23, 3 and 4, 45, 456, and then combine the two to get the max mixed sum/product.

Now you just compare the results from steps 1, 2, and 3 and the largest is the maximum sub-sum/product possible.

EDIT: Some simplified pseudo code:

function maxProd(array)

A = maxProd(array[first half])

B = maxProd(array[second half])

C = Calculate the maximum product that contains an element from both halves

return max(A,B,C)


问:
how to modularize wcf services?
I am working on a WCF application that supports 4 different applications.

lets call those 4 application: App1, App2, App3, and App4.

this WCF Application has 4 services. one for each application.  4 services are very similar, thats why I want to combine them together into 1 wcf application.  Here's the problem, if I need to change the service for App1, I need to redeploy the entire application. even tho, services for App2, App3, and App4 have no changes.  I try to avoid that, but I dont want to create 4 different WCF applications because they are very similar, if there's a change, I probably have to change it 4 times and redeploy 4 times.

I am thinking about using WCF and MEF. I just want to know what other options out there I can explore.

答: One solution is to create WCF interfaces that support extensibility. That is, instead of simply calling a method with a fixed set of parameters, consider calling a method that takes as a parameter, an identifier (which could be an integer) for the method to be called internally. The parameters for the secondary method are packaged as an array of class instances passed as a single parameter to the WCF method.</p>

Title: how to modularize wcf services?


问:
Is there a way for Object 1 to call Object 2's enums in a function call?
For example, if I have two classes "Director" and "Follower". I want the Director to tell the follower where to go (ex: follower1.go(direction.LEFT)), and I want the Director to know what directions it can tell the Follower to go when coding in an IDE that gives completion suggestions.

I know I can already either do:

```<code>public void go(String direction);
</code>```

or

```<code>public void goLeft();
public void goRight();
public void goUp();
public void goDown();
</code>```

But the first won't give me options in an IDE (or at least, I don't know how to show the options), and the second could be hard to maintain for a less trivial function. Ideally, I would like something like,

```<code>public enum Direction{LEFT, RIGHT, UP, DOWN};
public void go(Direction direction);
</code>```

But of course, that doesn't work (at least in Java, and Direction is part of the Follower class). Is there a roundabout way to use enums (or any other way) to get something like the 3rd effect, where I can both limit the parameters of a function, and make it easily visible in an IDE that gives completion suggestions?

答:
I think if you remove public, it will work:

```<code>enum Direction{LEFT, RIGHT, UP, DOWN};
</code>```

though I believe it that this enum will only be accessible to other classes that are in the same package as Follower.

Why does Direction need to be contained within the Follower class, when the Director (which I assume is a separate class) will also need to make use of it? If you want to limit the scope of this enum, you could declare it in the same package, but in a separate file. That way you can change it to having public scope when you need it to be accessed elsewhere, and the syntax for accessing it is neater and cleaner, too.

Body:
I think if you remove public, it will work:

enum Direction{LEFT, RIGHT, UP, DOWN};

though I believe it that this enum will only be accessible to other classes that are in the same package as Follower.

Why does Direction need to be contained within the Follower class, when the Director (which I assume is a separate class) will also need to make use of it? If you want to limit the scope of this enum, you could declare it in the same package, but in a separate file. That way you can change it to having public scope when you need it to be accessed elsewhere, and the syntax for accessing it is neater and cleaner, too.


问:
How should I make progress further as a programmer?
I have just left my college after doing graduation in computer engineering,during my college life I tried to do some freelancing in local market.I succeeded in the last year and earned some small amounts based on joomla,wordpress and visual basic based job.I had some small projects on php,mysql also.
After finishing my undergrad life,I sat for an written test for post of python programmer and luckily I got the job and is working there(Its a small software firm do most of the  task in python).Day by day I have gained some experience with core python.

Meanwhile an USA based web service firm called me for the interview and after finishing three steps(oral+mini coding project+final oral)they selected me(i was wondered!).And I am going to join their with in few days.There I have to work in python(based on Django framework,I know only basic of this framework).

My problem is when I started to work with python simultaneously I worked in Odesk as a wordpress,joomla,drupal,php developer.
Now a days I am feeling that I am getting "Jack of all trades master of none".

My current situation is i am familiar with several popular web technologies but not an expert.I want to make myself skilled.
How should I organize myself to be a skilled web programmer?

答: I guess you have to choose. I started with python, but realized that where I wanted to do was C#. Now, I'm learning C# (and Visual Studio).</p>


答:
There are two ways you can with this.

As FrustratedWithFormDesigner pointed out, you can make the enum a top level entity.

The other option is to leave it as a inner-member of one of you classes. To do this, you can either qualify the enum with the host class name:

```<code>go(Follower.Direction.LEFT);
</code>```

Or you can import the enum and use as you would normally expect:

```<code>import somepackage.Follower.Direction
...
go(Direction.LEFT);
</code>```

Now, in your case, I would probably suggest going with the top-level enum, as Direction doesn't strike me immediately as "belonging" to either Follower or Director.

For completeness, I should mention there's actually a third way to access the enum elements: static imports.  This method should be used judiciously, if at all, but it is something to be aware of.

```<code>import static somepackage.Direction.*;
....
go(LEFT);
</code>```

Title: Is there a way for Object 1 to call Object 2's enums in a function call?

Body:
For example, if I have two classes "Director" and "Follower". I want the Director to tell the follower where to go (ex: follower1.go(direction.LEFT)), and I want the Director to know what directions it can tell the Follower to go when coding in an IDE that gives completion suggestions.

I know I can already either do:

```<code>public void go(String direction);
</code>```

or

```<code>public void goLeft();
public void goRight();
public void goUp();
public void goDown();
</code>```

But the first won't give me options in an IDE (or at least, I don't know how to show the options), and the second could be hard to maintain for a less trivial function. Ideally, I would like something like,

```<code>public enum Direction{LEFT, RIGHT, UP, DOWN};
public void go(Direction direction);
</code>```

But of course, that doesn't work (at least in Java, and Direction is part of the Follower class). Is there a roundabout way to use enums (or any other way) to get something like the 3rd effect, where I can both limit the parameters of a function, and make it easily visible in an IDE that gives completion suggestions?

Body:
There are two ways you can with this.

As FrustratedWithFormDesigner pointed out, you can make the enum a top level entity.

The other option is to leave it as a inner-member of one of you classes. To do this, you can either qualify the enum with the host class name:

go(Follower.Direction.LEFT);

Or you can import the enum and use as you would normally expect:

import somepackage.Follower.Direction
...
go(Direction.LEFT);

Now, in your case, I would probably suggest going with the top-level enum, as Direction doesn't strike me immediately as "belonging" to either Follower or Director.

For completeness, I should mention there's actually a third way to access the enum elements: static imports.  This method should be used judiciously, if at all, but it is something to be aware of.

import static somepackage.Direction.*;
....
go(LEFT);


问:
How can I test my camera-dependent android app on most devices?
We are developing an app for taking photos faster. We do this by actually taking videos instead of photos and processing the individual images in the video on the fly and combine them to create a high-resolution image. Since this app is heavily dependent upon the hardware of the various devices, I was wondering how we could go about testing this on, say 50% of devices in one go? Are there for example groups of people that allow for all sorts of people to run tests on their devices? I would be willing to pay for each test on each on each device. What are my options?</p>

答: There are services out there for this sort of thing. This article mentions some. Searching for something like "android device testing" should also lead you to some. Obviously you would need to evaluate which service gives you the functionality you need.</p>


问:
Ifology - how to write this statement better?
I'm wondering how to write the if statement in the following block in a better way. It's supposed to operate when $a is 14, 22, 30 and for all following values at intervals of 8, up to some limit. The current way is obviously not good since the action must be performed each time that periodic pattern is fulfilled, and this would require many, many OR operators.

```<code>if($a == 14 || $a == 22 || $a == 30 || $a == 38 || $a == 46... until some number){
    do something...
}
</code>```

答:
```<code>if($a % 8 == 6 && $a >= 14 && a <= some_number)
</code>```

<p>In general, if you want periodicity, think modulus. </p>

Body:
if($a % 8 == 6 && $a >= 14 && a <= some_number)

In general, if you want periodicity, think modulus.


问:
How does the JVM handle an exception thrown by the main method?
I understand exceptions, throwing them, handling them, and propagating them to a method lower in the call stack (i.e. throws).

What I don't understand is this:

```<code>public static void main(String[] args) throws Exception {
    ...
}
</code>```

Now, I assume that in the case that main throws an Exception, the JVM handles it (correct?). If that's the case, then my question is:

How does the JVM handle exceptions thrown by main? What does it do?

答:
You might think that the public static void main method in Java or the main function in C is the real entry point of your program – but it isn't. All high-level languages (including C) have a language runtime that initializes the program, and then transfers control flow to the entry point. In the case of Java, initialization will include:

setting up the JVM

loading required classes

running static initializer blocks. This can execute user-defined code before main is invoked. These blocks aren't supposed to throw exceptions.

There are a variety of ways to implement exception handling, but for the purpose of this question, they all can be viewed as a black box. The important thing however is that the language runtime must always provide an outermost exception handler that catches all exceptions that aren't caught by user code. This exception handler will usually print out a stack trace, shut down the program in an orderly fashion, and exit with an error code. Properly shutting down the program includes destroying the object graph, invoking finalizers, and freeing resources such as memory, file handles, or network connections.

For purposes of illustration, you can imaging the runtime wrapping all code in a giant try-catch that looks like

```<code>try {
    loadClasses();
    runInitializers();
    main(argv);
    System.exit(0);
} catch (Throwable e) {
    e.printStackTrace();
    System.exit(-1);
}
</code>```

except that it's not necessary for a language to actually execute code like this. The same semantics can be implemented in the code for throw (or equivalent) that searches for the first applicable exception handler.

Body:
You might think that the public static void main method in Java or the main function in C is the real entry point of your program – but it isn't. All high-level languages (including C) have a language runtime that initializes the program, and then transfers control flow to the entry point. In the case of Java, initialization will include:

setting up the JVM

loading required classes

running static initializer blocks. This can execute user-defined code before main is invoked. These blocks aren't supposed to throw exceptions.

There are a variety of ways to implement exception handling, but for the purpose of this question, they all can be viewed as a black box. The important thing however is that the language runtime must always provide an outermost exception handler that catches all exceptions that aren't caught by user code. This exception handler will usually print out a stack trace, shut down the program in an orderly fashion, and exit with an error code. Properly shutting down the program includes destroying the object graph, invoking finalizers, and freeing resources such as memory, file handles, or network connections.

For purposes of illustration, you can imaging the runtime wrapping all code in a giant try-catch that looks like

try {
    loadClasses();
    runInitializers();
    main(argv);
    System.exit(0);
} catch (Throwable e) {
    e.printStackTrace();
    System.exit(-1);
}

except that it's not necessary for a language to actually execute code like this. The same semantics can be implemented in the code for throw (or equivalent) that searches for the first applicable exception handler.


问:
Is Testing a necessary part of Agile methodology?
I have been on numerous teams that try to practice Agile methodologies and often these teams are test centric. Is testing a necessary part of practicing the Agile methodology or is it just a XP practice that has been latched on over the years?</p>

答:
Testing is absolutely essential to agile, primarily because agile is based around incremental improvements: the difficulty is that it can sometimes be hard to see how the current changes will effect your old code. The best way to be confident  that you haven't broken something is to test it, and to know HOW to test it. That way you find the bug immediately, not down the road when you have forgotten exactly what you did when you were writing the code that broke some old feature.

The reason this is different from more traditional, top-down design type programming is that in that environment its a) very difficult to test until you have the finished product b) in theory you are considering all the design criteria at the same time, and so you are less likely to make a design decision that breaks previous design decisions.


问:
How to check in website/url have been updated or not?
I am trying to make a Android application which will take your URL and if there is new update on that website then it will show the user that this link have been updated.

I am working on the project which will check for the website if they have been updated or not.
I know that there are RSS on most of websites, but I am talking about those websites which don't have but are important for us. Like the websites where result will be posted but for that I will have to check that website again and again.

How can I check that website is updated or not?

答: You could have your app calculate a hash of whatever the response from the website is, store it, then periodically check the website and compare a rehash of its response to your stored response. If they're different, then the website changed. If they're not, then there's a small chance they changed and managed to keep the same hash, but most likely the website is the same. That seems to me to be the only truly general solution. Using specific solutions for sub-cases (like websites with RSS) would be a better first-attempt, then you could use the hashing strategy as a fallback.</p>


答: Both of your examples might be perfectly agile. It all depends on your needs, your people, and the current phase of the development cycle. Generally I've seen QA teams use screen captures and recording as a support tool to complement the bug report. Why? According to QA people, getting good screen captures and recordings is not as easy as just typing. Also there are some steps that are less prone to be represented as a screen capture, like changing configurations by command line; developers will love that you typed that, so they can just c&p it; they will hate you if you only attached a screen capture :)</p>


答:
All Java code runs in the context of a thread. The linked JavaDoc explains the error handling and exit criteria, but here is the gist of it:

The JVM spins itself up and prepares the execution environment.

The JVM creates a thread which will run the main() method using whatever command-line parameters are applicable.

The JVM sets a default uncaught exception handler that prints the exception to standard error and terminates.

The JVM executes the thread.

In the case of an uncaught exception, the program effectively dies per the third item above. This behavior is further specified in the Java Language Specification, Section 11.3

Additional info

Others have mentioned static blocks and how they execute before main(). However, this requires a bit more explanation to understand correctly.

When loading a class, the class loader must initialize all static final state and run all static blocks before the class can be used, to include instantiating instances of the class (aside: create a Java class where a class constant is initialized in a static block after creating an instance of the class, and the constructor references the constant. Boom!). However, this all happens in the class loader logic before any code can reference the class. Furthermore, the class is loaded in whatever thread referenced the class.

What this means is if the class containing main() references another class (e.g. class constant) then that class must be loaded before main() executes to include its static blocks. Otherwise, the static blocks are executed as above. If the class fails to load, then the class containing main() will also fail to load and the program will terminate.

Another FYI: static blocks can throw. Errors are thrown as-is. Exceptions are forbidden (compile-time error). RuntimeExceptions are wrapped in ExceptionInInitializerError. These are handled per the uncaught exception handler, which will typically either kill the thread or the application (main thread) unless you carefully wrap the class reference (and loading) in a try-catch.

Title: How does the JVM handle an exception thrown by the main method?

Body:
I understand exceptions, throwing them, handling them, and propagating them to a method lower in the call stack (i.e. throws).

What I don't understand is this:

```<code>public static void main(String[] args) throws Exception {
    ...
}
</code>```

Now, I assume that in the case that main throws an Exception, the JVM handles it (correct?). If that's the case, then my question is:

How does the JVM handle exceptions thrown by main? What does it do?