问:
What should I do in C++ when implementing a container class: storing objects by value or by reference?
I'm new to C++, coming from Java.

In Java, all variables (except for primitives) are essentially pointers. They hold the address of whatever they're 'holding'.

So any Java data structure stores it's data by reference. You can also store by value, i.e. save and return a copy of any item you store, but that would take extra work and isn't native to the language.

For example, the collections ArrayList, HashSet, and a simple array all store the addresses of the items they 'store', and not the actual items.

However in C++, you have a choice: when implementing a container class, you can either store and return to the user items by value or by reference.

For example, here's a simple Stack class I wrote (omitted irrelevant stuff):

```<code>template <typename T> class Stack {
public:
    Stack(...) : ... { }

    void push(const T& item) {
        if(size == capacity - 1)
            enlargeArray();

        data[indexToInsert++] = &item;
        size++;
    }

    const T& pop() {
        const T& item = *data[indexToInsert - 1];
        data[indexToInsert - 1] = 0;
        indexToInsert--;
        size--;
        return item;
    }

    int getSize() const {
        return size;
    }
private:
    const T** data;
    int indexToInsert;
    int size;
    int capacity;

    void enlargeArray() {
        // omitted
    }
};
</code>```

This data structure takes and returns data by reference. push takes a const reference, and pop returns a const reference. The backing array is an array of pointers, not objects.

However push could also look like so:

```<code>    void push(T item) {
        if(size == capacity - 1)
            enlargeArray();

        data[indexToInsert++] = item;
        size++;
    }
</code>```

And pop could return a T, not a const T&, etc.

My question is: what is the preferred approach in C++? Is there a preferred approach? Which approach should I normally take when implementing 'container' classes?

答:
Depends on if the container "owns" the object and they are a base class.

If the container doesn't own the object then you should use pointers and be careful of the danglers (make sure no container holds a pointer to the object when it is destroyed).

If the container owns the object and is not a base class then you should store by value.

Otherwise (container owns and there are subclasses) you should store using a std::unique_ptr to ensure no slicing happens on store and proper destruction.


答:
Firstly, you probably shouldn't implement a container class. 95% of the time you should one included in the standard library. If you just want to learn, or are in the 5%, carry on.

If you are defining a template, leave the decision up to your users. You users can use:

Stack<Foo> if they want by value.
Stack<Foo*> if they want by pointer.
Stack<std::unique_ptr<Foo>> if they want pointers that clean up after themselves.

When choosing which to use, you should default to by value, unless you've got a good reason to do something different. Inside your stack class, just store everything by value. If the use of the template needs indirection, they can use T=pointer type.

Looking at your code:

```<code>void push(const T& item) {
    if(size == capacity - 1)
        enlargeArray();

    data[indexToInsert++] = &item;
    size++;
}
</code>```

You can't do that. &item records the pointer to whatever was passed in. But you have no idea how long the pointer will be valid for. It could become invalid right after push finished. In that case, you've stored a pointer to an invalid place. In general, you can't assume that a pointer remains valid. You should instead be copying the item.

ContentLicense: CC BY-SA 3.0

Title: What should I do in C++ when implementing a container class: storing objects by value or by reference?

Body:
I'm new to C++, coming from Java.

In Java, all variables (except for primitives) are essentially pointers. They hold the address of whatever they're 'holding'.

So any Java data structure stores it's data by reference. You can also store by value, i.e. save and return a copy of any item you store, but that would take extra work and isn't native to the language.

For example, the collections ArrayList, HashSet, and a simple array all store the addresses of the items they 'store', and not the actual items.

However in C++, you have a choice: when implementing a container class, you can either store and return to the user items by value or by reference.

For example, here's a simple Stack class I wrote (omitted irrelevant stuff):

```<code>template <typename T> class Stack {
public:
    Stack(...) : ... { }

    void push(const T& item) {
        if(size == capacity - 1)
            enlargeArray();

        data[indexToInsert++] = &item;
        size++;
    }

    const T& pop() {
        const T& item = *data[indexToInsert - 1];
        data[indexToInsert - 1] = 0;
        indexToInsert--;
        size--;
        return item;
    }

    int getSize() const {
        return size;
    }
private:
    const T** data;
    int indexToInsert;
    int size;
    int capacity;

    void enlargeArray() {
        // omitted
    }
};
</code>```

This data structure takes and returns data by reference. push takes a const reference, and pop returns a const reference. The backing array is an array of pointers, not objects.

However push could also look like so:

```<code>    void push(T item) {
        if(size == capacity - 1)
            enlargeArray();

        data[indexToInsert++] = item;
        size++;
    }
</code>```

And pop could return a T, not a const T&, etc.

My question is: what is the preferred approach in C++? Is there a preferred approach? Which approach should I normally take when implementing 'container' classes?

Body:
Firstly, you probably shouldn't implement a container class. 95% of the time you should one included in the standard library. If you just want to learn, or are in the 5%, carry on.

If you are defining a template, leave the decision up to your users. You users can use:

Stack<Foo> if they want by value.
Stack<Foo*> if they want by pointer.
Stack<std::unique_ptr<Foo>> if they want pointers that clean up after themselves.

When choosing which to use, you should default to by value, unless you've got a good reason to do something different. Inside your stack class, just store everything by value. If the use of the template needs indirection, they can use T=pointer type.

Looking at your code:

void push(const T& item) {
    if(size == capacity - 1)
        enlargeArray();

    data[indexToInsert++] = &item;
    size++;
}

You can't do that. &item records the pointer to whatever was passed in. But you have no idea how long the pointer will be valid for. It could become invalid right after push finished. In that case, you've stored a pointer to an invalid place. In general, you can't assume that a pointer remains valid. You should instead be copying the item.


问:
Design pattern name for an API wrapper class
I am writing a class that wraps (the parts of) an external API I am using. Let's take the GitHub API as an example.

My imaginary GitHub class now has a fetchUser() and fetchRepository() method. When GitHub decides to host their API at github-api.com I only have to change it once. Nice. But what's the name of this - very common - approach?

Could it be a facade as it's a simpler interface to a more complicated one? An adapter as it links two incompatible APIs, or should I simply call it a wrapper class?

答:
Some alternative suggestions because sometimes things need to 'sound right'

It could be considered a ClientProxy.  Depends how things will be packaged.  Will this become a stand-alone DLL?  If so, it's possibly a client proxy.

Perhaps it is only a convenience class of a larger application (ie. leaves the door open to more advanced usage)?  If so, it could be a "Helper" (though I dislike the term) -- a "Utility" is better.  Better still would be a "StreamlinedClient" --"Easy" or "Simple" feel too unprofessional but when combined with "Interface" they can sound reasonable: "SimplifiedInterface"

Now, if this wrapper is intended to hide the advanced implementation in such a way that your application will only use your wrapper when interfacing with the external API... it's simply a Service or a ServiceWrapper.

Facade is overused (especially in Java): and your simplified description fits; however, I tend to think of this only when encapsulating without adding much in the way of logic (sort of a workflow that is not really related to the problem being solved).

ContentLicense: CC BY-SA 4.0


问:
Common Methods for communication between Offline Software and Web Application?
The purpose/s of this question is to discover what are some of the most reliable methods of achieving communication between existing offline software and a web application.

(Example) Scenario:

A person has written a piece of software that primarily runs "offline" on a cluster/network of local servers (accessible physically).

This piece of software is a structural mapping of the highway system and was written in a language like C++ over many years and has been well maintained.

Now, this person wants to build a web application (in a language like Ruby/Python) that is attempting to take traffic-flow data via a government API and wants to:

Take this data and load it into to the offline software

Use the offline software to map out better traffic flows (and other statistical analyses)

Send this data back to the web application to be communicated via HTML5/Javascript to a client/s

Some points to be held constant:

This is the system the client has specified and the only way

Both the offline system and the web application will be using SQL for their databases

The person has invested a large number of hours and maintenance that do not warrant a rewrite of the offline software

Based on the above, what are some options for achieving this?

Can this be achieved on an application and/or database layer?

Which layer would provide a structure where neither application has to be modified to function with the other application? (separation of concerns)

What is the most common (known) method for achieving such communication?

答:
I've been successful using JSON for communicating between online applications and workstation software.

A possible workflow would be as follows:

Admit input via a web application (e.g., forms, REST-API, text message, what have you)

Emit a "job" id in response to the input

Codify the input as a JSON document

Pass the JSON document to a batch-processing application capable of reading the JSON file and running the workstation application with those inputs

The workstation application stores the results either as a JSON file which can be immediately displayed on the website, or (better), stored in a database which can then be queried by the web application.

Mark the "job id" as done.

The user can now use the job id to retrieve the results. If the whole thing is very rapid you may do it all on-line and dispose of the job id.

Just as suggestion... it has worked for me.


问:
How to host a web service with dependencies on many APIs/SDKs which expose methods in different languages
A project I'm working on currently depends on several SDKs and APIs that perform identical tasks, but for different external products.  For example, in an Internet of Things world we have a common interface of TurnOn, TurnOff, GetStatus, etc.  Having all of these dependencies in the meat and potatoes of my project is getting messy, and I want to pull it out into a separate web service that exposes these common functions over a REST API.

My question is this: What is the recommended architecture for having a web service expose a REST API that, when called, resolves the requested IP to the correct SDK and goes through the standard request/response cycle?  Especially in a way that scales and handles SDKs that expose methods in different programming languages.

For context, here is an example request that the API might expose... /things/{ip address}/turn_on, which would then resolve that the IP address belongs to a Hoover vacuum and make a call to the Hoover vacuum SDK, which might expose methods written in C#.  Alternatively, it might resolve that the IP Address belongs to a different brand of vacuum which exposes its methods in C++.

答:
Design and build a REST API first. Be careful -- it really isn't as easy as it looks. Stateless, cacheable, resource identifiers not addresses. Not that easy.

Then simply implement by abstracting over the concrete implementations you've already done. You will have to make tech choices, but you haven't told us anything about your contraints. For example, what kind of server would you choose?

As to your example, it has problems.

The REST endpoint should probably be /things/vacuum/{id}

you would need to send it a POST request (GET cannot change state)

POST data would probably contain the field "power=on".


问:
What are the disadvantages of test-first programming?
It's all the rage nowadays. "Everyone" recommends it. That in and of itself makes me suspicious.

What are some disadvantages you have found when doing test-first (test-driven) development? I'm looking for personal experiences from knowledgeable practitioners--I can read the hypothetical musings of a hundred wannabes elsewhere on the internet.

I ask not because I am looking to hate TDD, but because it is my job to improve software development process, and the more we can learn about the problems people encounter, the better chance we have of improving the process.

答:
One situation in which test-first really gets in my way is when I want to quickly try out some idea and see if it can work before I write a proper implementation.

My approach is normally:

Implement something that runs (proof of concept).

If it works, consolidate by adding tests, improving design, refactoring.

Sometimes I do not get to step 2.

In this case, using TDD has turned out to have more disadvantages than advantages for me:

Writing tests during the implementation of the proof of concept just
slows me down and interrupts my flow of thoughts: I want to understand an idea and I do not want to waste time testing details of my first rough implementation.

It may take longer to find out if my idea is worth something or not.

If it turns out that the idea was useless, I have to throw away both my code and my nicely written unit tests.

So, when I have to explore some new ideas, I do not use TDD and only introduce unit tests when I get a feeling the new code is getting somewhere.

ContentLicense: CC BY-SA 2.5


问:
What are your favorite version control systems?
This is more a discussion question than an actual attempt to determine the "best", since that clearly varies by the needs of the organization. I'm more curious about the arguments in favor of different systems across categories (centralized vs distributed, open vs proprietary, etc).

So, what do you think is the best version control system?

答:
Not ClearCase, at least for a Unix/Linux system (perhaps with Windows the installer is easier).  It was easier for me to learn a new tool, Perforce, rather than upgrading our ClearCase server.

I currently use Perforce at work and I like it but I have no idea if it is the best.  Setting up the command line environment and the Perforce Server is a bit awkward, but using the Visual Client is fairly easy.  I like to think the users have a fairly easy time with it for everyday tasks; it is just the initial setup takes some work.


答: The benefits of TDD is that it forces you to guard your code against people who don't understand it. Yes, this often includes yourself. But, what happens when the code isn't worth guarding? There is a lot of code that shouldn't even be there in the first place! So the problem with TDD is when it comes to developers who write bad code. TDD probably wont help them write good code, it is much more likely that they will write horrible tests as well. Thus in their case TDD will only add to the mess; badly written and/or redundant tests aren't any more fun than other forms of bad code.</p>

Title: What are the disadvantages of test-first programming?

Body:
It's all the rage nowadays. "Everyone" recommends it. That in and of itself makes me suspicious.

What are some disadvantages you have found when doing test-first (test-driven) development? I'm looking for personal experiences from knowledgeable practitioners--I can read the hypothetical musings of a hundred wannabes elsewhere on the internet.

I ask not because I am looking to hate TDD, but because it is my job to improve software development process, and the more we can learn about the problems people encounter, the better chance we have of improving the process.


问:
DDD - If an object is saved as a whole to the database, is it per definition an entity, or is it still possible that it is a value object?
I'm learning about Domain Driven Design and struggling with the question if a particular object should be handled as entity or value object.

All possible surname prefixes are kept in a database table. (The data is used in a combo box). Since there are records kept of all these prefixes, should Prefix be seen as an entity? Or is it still possible to handle it as a value object?

答:
I thought the difference was the linkage with the database. So an Entity object has state that maintains its place in the DB, whereas a value object simply contains the data.

Writing the object back to the DB ends up as a update call in both cases, however the entity will use the internally-held key to refer back to the DB row, whereas the value object needs to get the key from its data... not much difference in practice ultimately!

I'd prefer a value object as I'm old-fashioned that way, I'd read only what was needed and update just that data. Less data and less state is always good.


问:
Is there a cleaner way to test extras_require
I have code reviewed a piece of Python code, but to me it looks really ugly, hacky and complex for something that can be achieved very easily.

The code looks something similar to the following:

_extra.py (this is supposed to be a private module because of the underscore):

```<code>import dependency

class Extra(dependency.Cls):
    ...
</code>```

setup.py

```<code>setup(
    ...
    name='somepkg',
    extras_require={
        ...
        'extra': ['dependency']})
</code>```

public.py

```<code>_dist = pkg_resources.working_set.find(
    pkg_resources.Requirement.parse('somepkg'))

if 'extra' in _dist:
    from _extra import Extra
</code>```

So that the extras_require can be tested using:

```<code>class ExtraTest(unittest.TestCase):
    ...
    # Some test cases where the requirement actually is available

    def test_require_extra(self):
        dist = mock.Mock(pkg_resources.Distribution)
        self.dist.extras = []
        public = helper.import_or_reload('public')
        with self.assertRaises(AttributeError):
            public.Extra
</code>```

My initial thought would be to not have _extra.py exist and have public.py look like:

```<code>try:
    import dependency
except ImportError
    pass
else:
    class Extra(dependency.Cls):
        ...
</code>```

I don't really care that it isn't tested that it can't be imported if it is not in the extras_require.

Does the original code seem like a logical solution?

Should extras_require be tested in any way? If so, how?

答:
If this is all done just to make it possible to test the Extra class, then the code is overcomplicating matters. The code is asking for permission rather than for forgiveness.

You are quite correct, changing the code to catch the ImportError exception would vastly simplify the codebase.

The code shouldn't even try to test the detection, but simply rely on Python's own unit tests to have tested throwing an ImportError properly. At best the unittest should verify what happens if extra is not set (perhaps by the code setting extra = None if the dependency is missing, testing is then as easy as mocking extra = None).


答:
Disadvantages or Costs of TDD

Note: There is a range of different kinds of TDD.  Regardless of unit, BDD, ATDD, or other variants many of the difficulties remain

Side effects

Whether it's mocking, fixtures or functional tests, dependencies on external states or systems are often the source of most complexity in tests, confusion in how to test, and biggest risk in getting it wrong.  A few issues I've seen:

Mocking: forget to assert the order of calls

Mocking: mock doesn't match real call or response

Fixture: test relies on unrealistic data, masking other issues

Fixture: test an impossible state in production

Functional: false build breaks because of dependent system being temporarily unavailable

Functional: speed of test is very slow

You will have to change your approach to coding, for some it will be a drastic change.

Different people code in wildly different ways.  In TDD you need to start with a test that asserts a specific behavior, and then implement so the test passes. I've seen and was a programmer whose programming was not conducive to TDD. It took me about 2 months when I initially started to get used to changing my development approach.

It takes time to understand what you care about testing and what you don't care about testing.

Every team should make an explicit decision on where they want to draw the line in testing.  What things they value that they want tested, and what they don't.  It is often a painful process learning how to write good tests, and what you actually care about testing.  Meanwhile the code will continue to be in a state of flux until there is consistency in both style and approach.

Unit Test specific: large refactors

A large or fundamental refactor of a significant codebase with tens of thousands of unit tests will generate a huge cost in order to update all the tests.  This will often manifest in pushback against doing a refactor even if it is the correct thing to do simply because the cost associated with doing it.


问:
Algorithm for figuring out the enemy flag's location in Stratego
I am currently programming a Stratego game in JavaScript, simply because I wanted to learn to use JavaScript while spending some time to keep my programming skills up to par. (My current work assignments involve no programming.) This info is not entirely relevant though. :-)

The thing is, right now my AI works pretty well already. The AI remembers ranks of pieces that have already been revealed, and will capture or flee depending on this. Pieces that have not yet been revealed are also taken into consideration. For instance, a Marshal will not capture a piece if there's an undiscovered piece next to it, since this latter piece could be a spy. If the spy is no longer alive, the Marshal will only be afraid of non-moving pieces, since those could be bombs. If an unknown piece moves up to the General, the latter will flee, as the unknown piece might be a Marshal. Etc, etc.

My problem is that the AI is currently extremely defensive. It will jump onto opportunities to capture pieces, but it never "plans" to move anywhere, and it never takes the Flag, since it thinks that the Flag might as well be a bomb.

The question is: are there any patterns that can be used as the basis of an algorithm to figure out where the enemy's flag might be? When human players play against each other, what are their tactics to find out the flag's location?

(Note: in the current version, pieces are placed randomly on the board for both players. In the future I will allow the player to place his pieces as he wants, though.)

答: Designate some of the AI pieces as offensive you should assign certain pieces an offensive role. You would then need to decide whether an offensive or defensive move should be taken on a particular turn. Try to use low number pieces, 2,4,5 for scouting and figuring out pieces' ranks (you can also inadvertently run into the flag this way) then send in threes to break up the bombs. Once the board has cleared up, send in the higher ranking pieces. It might be helpful to keep a list of pieces you have designated as attackers, so you can designate new ones when the old ones die. These are just a few thoughts, to get you started. You should try out a bunch of ideas and see what works best. Try sending out waves of attacks, or maybe wait to unleash a massive attack... There are all sorts of strategies the AI can emulate. Maybe even one strategy isn't optimal. Trial and error is your best friend here. Good luck; I love that game!


问:
How to measure his own skill in a programming language?

Possible Duplicate:

  How Can I Know Whether I Am a Good Programmer?

As many programmers I have worked in several languages. While of course there are some that I am more at ease than other, I do not have a real way to precisely measure my skill in a specific language.

So I thought of a system which allows me to help me with that. I am looking for 5 common criteria in programming languages, to which I will have a value from 1 (junior) to 4 ( Senior) to represent my skill.

I however have no real idea of the criteria I should choose for that.

Does anybody have suggestion ?

Thanks.

答: If you can do all Project Euler problems correctly in language X, I would consider you to be an expert in language X.


答:
You already gave the answer yourself in your comment to the other question:  If two Prefix objects with the same content are interchangeable, then Prefix is (probably) a value object.

Another rule of thumb is: "Domain first, infrastructure second", i.e., don't let infrastructure concerns (here: primary keys in database tables) influence your domain model.

Title: DDD - If an object is saved as a whole to the database, is it per definition an entity, or is it still possible that it is a value object?

Body:
I'm learning about Domain Driven Design and struggling with the question if a particular object should be handled as entity or value object.

All possible surname prefixes are kept in a database table. (The data is used in a combo box). Since there are records kept of all these prefixes, should Prefix be seen as an entity? Or is it still possible to handle it as a value object?


答:
My question is: what is the preferred approach in C++? Is there a preferred approach? Which approach should I normally take when implementing 'container' classes?

In C++ you can keep objects by:

value

reference

pointer

smart pointer (std::unique_ptr, std::shared_ptr, YourPointerClass).
(you didn't mention the last two).

Each of these is valid for different situations and imposes different constraints, concerning objects ownership, lifetime management and polymorphic behavior ( that is, there isn't a prefered approach - there are many of them :) ):

use storing by value when:

you are not storing objects with polymorphic behavior (i.e. objects are concrete classes with no base class and no virtual functions, or all objects are of the same runtime type - you are not storing specializations of a base class)

your container owns the objects (i.e. the contained objects should have a lifetime equal to that of the container, and will be destroyed when the container is destroyed)

use storing by reference when:

the stored objects are not owned by the container

your contained objects have a larger scope and lifetime than the container.

you are interested in polymorphic behavior (in this case you should store references to a base class)
Normally you should not do this, as there is a chance of slicing on assignment (unless your class hierarchy supports polymorphic assignment - which is another discussion altogether)

use storing by raw pointer when:

your stored objects expose polymorphic behavior (base class and/or virtual functions)

the container doesn't own the stored objects

use storing by smart pointer when:

your stored objects expose polymorphic behavior

your objects are owned by the container (std::unique_ptr), ownership is shared (std::shared_ptr) or osage of smart pointer is imposed by client code constraints.

the stored objects are expensive to copy/instantiate (edit cf. @NirFriedman)

To support all this, you will probably want to template your class by the stored type and fill in as needed, in client code.


答:
My analogy is barriers on a Scalextric track. If you put them on, you get far less cautious.

People also get a little bit space cadetish about their tests - because they run fine, they believe the code is fully tested whereas it is only the beginning of the testing process.

To my mind TDD is a stepping stone to BDD. A raft of tests that run doesn't really help support developers without knowing what the tests do. With BDD, the test output is in English which documents the testing and thereby builds understanding of the system.


答:
I don't remember how to play Stratego, but in general if you want to encourage a certain type of behaviour in your AI (i.e. being offensive) you have to award some value to that kind of behaviour.

Think about evaluating each potential move on its impact to the overall strength of a position.  Ask: "what are the chances of my position being better or worse if I make this move?"

By focusing on the likelihood of a positive outcome, your AI will sometimes make moves that are offensive, but which are calculated risks.

Title: Algorithm for figuring out the enemy flag's location in Stratego

Body:
I am currently programming a Stratego game in JavaScript, simply because I wanted to learn to use JavaScript while spending some time to keep my programming skills up to par. (My current work assignments involve no programming.) This info is not entirely relevant though. :-)

The thing is, right now my AI works pretty well already. The AI remembers ranks of pieces that have already been revealed, and will capture or flee depending on this. Pieces that have not yet been revealed are also taken into consideration. For instance, a Marshal will not capture a piece if there's an undiscovered piece next to it, since this latter piece could be a spy. If the spy is no longer alive, the Marshal will only be afraid of non-moving pieces, since those could be bombs. If an unknown piece moves up to the General, the latter will flee, as the unknown piece might be a Marshal. Etc, etc.

My problem is that the AI is currently extremely defensive. It will jump onto opportunities to capture pieces, but it never "plans" to move anywhere, and it never takes the Flag, since it thinks that the Flag might as well be a bomb.

The question is: are there any patterns that can be used as the basis of an algorithm to figure out where the enemy's flag might be? When human players play against each other, what are their tactics to find out the flag's location?

(Note: in the current version, pieces are placed randomly on the board for both players. In the future I will allow the player to place his pieces as he wants, though.)


问:
A good guide on choosing the point scale to use with Agile/SCRUM?
We're using Pivotal Tracker for our project, which lets us choose from these three point scales:

```<code>0,1,2,3
0,2,4,8
0,1,3,5,8
</code>```

And I'm looking for a resource to help guide our decision. (After using 0,1,2,3 for two iterations, we can see where one of the others would be a lot more useful or meaningful.)

答:
I think what you want is something that offers enough difference with the smaller points and not that many options for larger stories, based on the fact that anything over 20 or 40 needs to be broken down anyway. This makes sure that you support finer differences for small and regular sized stories and only rough differences for larger sized stories.

When we were doing Scrum we did fine with the Fibonacci based points with 20 being the highest number that we thought would realistically fit into a sprint. If something was 40 or 100 it was basically the developers saying that the story was too large.

Other than that I don't think it makes such a great difference. I'd prefer the Fibonacci based sequence because I've found that it works. However, what works for the team and the product you're developing is fine.


问:
What are classes that produce a result, but are necessarily classes because of the complexity of the task?
What generic name is given to classes that encapsulate a collection of esoteric functions which together perform some larger cohesive but entirely self-contained task useful to the wider application, by producing a computed result given a number of input parameters?

An example might be a class that calculates the shortest path/most efficient route when visiting nodes on a Euclidean plane, given a set of obstacle polygons. Inside this class there might be various generic functions for calculating the distance between two points, whether or not two lines intersect, and whether the intersection is concave or convex relative to a given co-ordinate.

Describe exactly the context that the name or terminology is used: This term will be used when naming classes. In the example class I mentioned above, the term would replace "Foo" in the class name MyCompany_Foo_ShortestPath.

Describe the criteria for acceptance: The term must suitably differentiate it from other common class types, such as caches (e.g. MyCompany_Cache_Prices), adapters (e.g. MyCompany_SQLDatabase_Adapter_MariaDB), data providers (e.g. MyCompany_DataProvider_Products), controllers (e.g. MyCompany_Controller_Users) and models (e.g. MyCompany_Model_Employee), while also going some way to explaining the nature of the class (encapsulated, complex functionality).

Which names/terms have you thought of and discarded as inappropriate? Some ideas I've had have been "functional" classes (in that they act like functions, but have been broken down into smaller functions), and "computational" (in that they compute things). I would guess though that there is already an accepted term for this type of class.

答:
The most proper term I've seen for that type of structure is Method Object.

That being said, I typically use the word "Calculator" in the naming of Method Object classes in my code. "Calculator" indicates that the class would perform a calculation or run an algorithm based on inputs and could potentially live on to be used repeatedly. The term also differentiates it from other classes which contain/transport data or interface with other components. You've even used the same term in your own example: "...a class that calculates the shortest path..."


问:
On GitHub, etiquette and pull requests
If someone forks your repository and commits some changes, what is the accepted way to proceed if you'd like to ask them whether it's alright to pull those changes in?

Can you issue a pull request on the forker's behalf and count on GitHub to alert them somehow? If not -- I notice GitHub doesn't support sending users messages; should you somehow contact the user outside of the site?

edit - By the way, both the question and answer are obviously different from the Q&A linked as "duplicate".

答:
Did they ask you if it was OK to fork in the first place? No, because it's open source. I'd say you can take their changes as long as you abide by the licencing terms without having to worry whether their (sorry, your) open source project code is open source.

If they didn't want you to take the changes, they wouldn't release them as open source (though, obviously this would mean not starting with your work). So just go for it.

Title: On GitHub, etiquette and pull requests


问:
Java application structure: Horizontal vs vertical split
Having a bit of a debate about the starting project structure (using Maven/Eclipse) for a big Java application.

Option 1:

```<code>entities (i.e. the whole database using Hibernate classes-first)
services (i.e. sets of read/write operations on the entities)
app (perhaps split up more further down the line)
</code>```

Option 2:

```<code>area1-entities
area1-services
area1-app
area2-entities
area2-services
area2-app
...
(where area1, area2 etc. are functional areas of the system)
</code>```

Option 2 will clearly result in a great deal more Maven projects/modules and means the classes that would generate the database are distributed amongst multiple projects. Could anyone advise pros/cons of each approach?

答:
I would suggest doing neither.

Trying to enforce a technical layering with a package structure leads to a lot of entanglement in your application. Not to mention the fact that we try so hard to hide everything behind a service interface and the first thing we do (mostly due to packaging) is make everything a public class. This becomes painful when there is a technical separation between a x.y.z.service and x.y.z.repository package, now everything can access the repository. Boom there goes your encapsulation inside the service layer.

Instead you should follow a more functional and onion based approach (clean architecture, hexagonal architecture). This is also nicely in line with the Single Responsibility Principle (when applied to a package) and also in accordance with the packaging principles

Things that change together are packaged together

Things that are used together are packaged together

Oliver Gierke has written a nice post on packaging components together in Java. Simon Brown has written a more general story on the subject.

I would strive for a core package structure like the following to hold the core of your application:

```<code>x.y.z.area1
x.y.z.area2
</code>```

Now if you have a web interface you add, for instance, a web subpackage, for webservice a ws or rest package to hold only that. It basically connects to the core.

```<code>x.y.z.area1.web
x.y.z.area1.ws
x.y.z.area2.rest
</code>```

Now you could consider reusing the objects from inside your core into the other layers, but IMHO it is better to use a specific domain for that layer. As, just as with Object to SQL mapping there is (often) a mismatch in what we want show on the screen or use as XML in the webservice and how the business logic is implemented. Depending on the complexity of the business and web domains you could consider them as seperate problem domains to solve which need to be connected, basically 2 different bounded contexts.

To use a quote from a CQRS resource

It is not possible to create an optimal solution for searching, reporting, and processing transactions utilizing a single model.

Don't try to put everything into a single (domain) model, separate the responsibilities. You probably end up with more (smaller) classes but a cleaner separation between the layers of your application.

Final Note

Remember creating a architecture is deciding on the trade-offs of one solution to the other. It depends highly on the complexity of the domain and should mainly be driven by the functional requirements of your application. However it is influenced by the non-functional (performance, security) and environmental constraints (language to use, platform, experience). And architecture, like coding, is never finished each new requirement can (and maybe should?) lead to a redesign of the application.

Disclaimer

Yes I also tried to put everything in a single model, and yes I also tried to use a technical separation in my applications. However after a couple of years of experience in creating entangled application layering (at first it seems a good idea, then the application starts to grow...) I figured there must be another way.

Links

Clean Architecture, Uncle Bob Martin

Hexagonal Architecture (aka Ports and Adapters), Alistair Cockburn

Whoops where did my architecture go, Oliver Gierke

Principles of OOD, Uncle Bob Martin

Mistakes when applying DDD, Udi Dahan

Bounded Contexts, Martin Fowler

Architecturally Evident Coding Style, Simon Brown

Books

Growing Object-Oriented Software, Guided by Tests

Java Application Architecture: Modularity Patterns with Examples Using OSGi (Robert C. Martin Series)

Domain-Driven Design: Tackling Complexity in the Heart of Software

Software Architecture for Developers

Implementing Domain Driven Design

OwnerDisplayName: Steve Chambers

Body:
I would suggest doing neither.

Trying to enforce a technical layering with a package structure leads to a lot of entanglement in your application. Not to mention the fact that we try so hard to hide everything behind a service interface and the first thing we do (mostly due to packaging) is make everything a public class. This becomes painful when there is a technical separation between a x.y.z.service and x.y.z.repository package, now everything can access the repository. Boom there goes your encapsulation inside the service layer.

Instead you should follow a more functional and onion based approach (clean architecture, hexagonal architecture). This is also nicely in line with the Single Responsibility Principle (when applied to a package) and also in accordance with the packaging principles

Things that change together are packaged together

Things that are used together are packaged together

Oliver Gierke has written a nice post on packaging components together in Java. Simon Brown has written a more general story on the subject.

I would strive for a core package structure like the following to hold the core of your application:

x.y.z.area1
x.y.z.area2

Now if you have a web interface you add, for instance, a web subpackage, for webservice a ws or rest package to hold only that. It basically connects to the core.

x.y.z.area1.web
x.y.z.area1.ws
x.y.z.area2.rest

Now you could consider reusing the objects from inside your core into the other layers, but IMHO it is better to use a specific domain for that layer. As, just as with Object to SQL mapping there is (often) a mismatch in what we want show on the screen or use as XML in the webservice and how the business logic is implemented. Depending on the complexity of the business and web domains you could consider them as seperate problem domains to solve which need to be connected, basically 2 different bounded contexts.

To use a quote from a CQRS resource

It is not possible to create an optimal solution for searching, reporting, and processing transactions utilizing a single model.

Don't try to put everything into a single (domain) model, separate the responsibilities. You probably end up with more (smaller) classes but a cleaner separation between the layers of your application.

Final Note

Remember creating a architecture is deciding on the trade-offs of one solution to the other. It depends highly on the complexity of the domain and should mainly be driven by the functional requirements of your application. However it is influenced by the non-functional (performance, security) and environmental constraints (language to use, platform, experience). And architecture, like coding, is never finished each new requirement can (and maybe should?) lead to a redesign of the application.

Disclaimer

Yes I also tried to put everything in a single model, and yes I also tried to use a technical separation in my applications. However after a couple of years of experience in creating entangled application layering (at first it seems a good idea, then the application starts to grow...) I figured there must be another way.

Links

Clean Architecture, Uncle Bob Martin

Hexagonal Architecture (aka Ports and Adapters), Alistair Cockburn

Whoops where did my architecture go, Oliver Gierke

Principles of OOD, Uncle Bob Martin

Mistakes when applying DDD, Udi Dahan

Bounded Contexts, Martin Fowler

Architecturally Evident Coding Style, Simon Brown

Books

Growing Object-Oriented Software, Guided by Tests

Java Application Architecture: Modularity Patterns with Examples Using OSGi (Robert C. Martin Series)

Domain-Driven Design: Tackling Complexity in the Heart of Software

Software Architecture for Developers

Implementing Domain Driven Design

OwnerDisplayName: M. Deinum


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
Vision without action is a daydream.
Action without vision is a nightmare.

proverb from japan

LastEditorDisplayName: Roger Pate


问:
Difference between patterns: Specification, Guarding, Conditions, Monads, Validation,
I'm currently trying to get my head around a few patterns (especially the ones mentioned in the title above) that are made to address different problems and are being used in different parts of the application, however they seem to heavily overlap in functionality once they are implemented.

Let's take for example the following method:

```<code>public void MyAction(string param) {
    // do something with param
}
</code>```

As long as we want to make sure the parameter is at least initialized, we apply the Guarding pattern in order to make sure that no un-initialized arguments get passed.

```<code>public void MyAction(string param) {
    Guard.Require(param).NotNull();
}
</code>```

However if we also require e.g. the string to be at least 3 characters in length, we have a business rule that needs to be handled by the Validation pattern.

```<code>public void MyAction(User user) {
    Guard.Require(user).NotNull();
    MyBusinessValidatorForUsers(user).UserNameAtLeast3Chars();
}
</code>```

What about if we don't know if the username has been initialized? Monads to the rescue!

```<code>public void MyAction(User user) {
    Guard.Require(user).NotNull();
    user.ToMaybe()
        .With(user.Name).Do(MyBusinessValidatorFor...
}
</code>```

Now imagine for all the patterns, we got a huge framework in use. That's like.. 6 frameworks just to make sure a certain business entity fits the requirements for further use within the business domain.

I know all those patterns go a lot further and usually aren't getting applied within the same scope in a real world application, however especially in simple cases with CRUD persistence layers and simple property bags, I get the feeling that a lot of those patterns can be used to address the exact same thing.

So, where are the main differences between those patterns that legitimate them to be separated in a business application? What would speak against a GuardAndValidateBySpecificationWithMonads framework?

答:
I am having a bit of an issue with some of these things being called "pattern", but clearly, monads, guards and validators are different beasts one may consider patterns.

Particularly interesting about monads is of course, that their available operations mean you can apply other functions transparently within the monad (read: map). Therefore, monads are quite readily reusable.

Similarly, validators are typically reusable outside of your core business logic. I believe you are not taking full advantage of this yet. When I see UserNameAtLeast3Chars, I wonder what this method does that is so specific to a user name and which cannot be handled by a more easily reusable validator StringSizeAtLeast(username, 3). In terms of functional programming, a string size validator really just needs a function to provide the string and the minimum/maximum allowed length, which makes it applicable to a lot of possible strings.

Therefore, to answer your last question first: What speaks against a GuardAndValidateBySpecificationWithMonads-framework, is that you can barely reuse it elsewhere, because it is a very specific beast. In contrast, the other frameworks provide abstractions that are highly reusable on their own.

As for a more practical approach to the issue, it may be worth considering to add a custom abstraction layer, which unites these frameworks if you find yourself continuously writing the same sort of code. Of course, this union is similar to a custom framework, and the above answer about lack of reusability applies again as well.

I'd be more interested in discussing though, which of these frameworks are really necessary, because each of those has different pros/cons and you may reduce the overlap by eliminating those frameworks, where you do not really need the pros all that much.

Quick discussion of the individual patterns and their pros/cons:

Specification: I'm not aware of this as a pattern. Of course, you can have a specification and check against it and call the corresponding framework "specification" again, but that doesn't really make it a pattern of its own.

Condition: This is also not clear to me in the given context. A condition is a well-defined term in programming and occurs for example as part of an if-statement. As a pattern for checking your method input, it makes little sense.

Guard: This is the first one I recognize as a pattern, but it comes with a distinct behavior: a Guard (condition) checks for a certain property to be present on the input and fails hard if that property is not holding, i.e. throws an exception or something similar. This is a pro as well as a con though. On the pro side, every user of your API is immediately penalized for bad inputs, on the con side, every untested usage fails hard during runtime with potentially dangerous consequences due to the changed control flow.

Monads: These are not really a pattern for checking inputs w.r.t. some property. They have a huge number of advantages and really cool stuff you can do with them, but they are quite orthogonal to the rest of the matter discussed here. To say it frankly, you probably do not want to discuss whether a List-framework should be removed, yet lists are the best-known monads. That most people don't think of Lists as monads just shows how transparent they can be.

Validation: This is another interesting pattern for checking inputs, but has a clear distinction to Guarding - it does not fail hard. Validation is typically used when you want to also generate appropriate feedback for users to let them know what is wrong (f.ex. display a message like "Usernames must contain at least 3 characters").

From the point of view of checking method inputs, I'd argue that Guarding and Validation are the main frameworks to look at, and they have quite different applications, because one is geared towards developers, the other towards users.

The remaining "patterns" are no input-checking patterns to me and if you have correspondingly-named frameworks in your application, they may well have a huge overlap with the two main patterns, in which case I suggest you investigate how they differ in terms of treating a violation of the checked property.

Final example how not to consider these concepts as overlapping: consider the property that the given user may be null. You can handle this case with monads, guards, and validations, hence these three things overlap. No! They just share the (implicit) condition user == null, but treat it in completely different ways:

monads: I don't want to care about null, so if it it's not there, just don't do anything with the user. In particular, do not fail or report a problem to the user.

guards: if the user is not present, a developer made a mistake and I'm going to tell her by blowing up. Can't ignore a big bomb exploding in your face after all..

validation: looks like the application-user forgot to select a user, so I better inform the application-user that he should do so.


问:
Is it possible/good idea to reduce chance of crashing by catching Error?
I have a class the implements A which will run a certain method of class B. There is a requirement that this A should never crash when running this operation (which is not possible, right?).

To reduce the chance of crashing I'm catching Throwable around the operation, like so:

```<code>public void method(B b)
{
    try
    {
        b.operation
    }
    catch(Throwable e)
    {
        //Log e
        //Clean up stuff
    }
}
</code>```

My questions are:

Would this actually help in reducing crashes caused by any thrown Error?

Is it a good idea to ever catch an Error?

答:
Simple Answers: No and no.

For example catching an OutOfMemoryError can be bad as without memory what could you do?

Also all other errors are most likely indicate some more serious error where you can do nothing.

For reference see the errors in the package java.lang and decide for every one what you will do when you catch it. If you're happy you will find that perhaps every tenth error could be handled by you.


答: If you want to message them via GitHub, why not use Mention Notifications? Open an issue on your own repository and mention the forker in that issue. The issue should be relevant to the stuff you want to pull, so you can discuss the pull request they need to send. Something like "@JohnSmith has already implemented this feature - can you please make a pull request?".</p>

Title: On GitHub, etiquette and pull requests

Body:
If someone forks your repository and commits some changes, what is the accepted way to proceed if you'd like to ask them whether it's alright to pull those changes in?

Can you issue a pull request on the forker's behalf and count on GitHub to alert them somehow? If not -- I notice GitHub doesn't support sending users messages; should you somehow contact the user outside of the site?

edit - By the way, both the question and answer are obviously different from the Q&A linked as "duplicate".


问:
Is DDD not appropriate for my website or should I introduce a Query Layer?
I have inherited an ASP.NET website application and the previous developer has used what I believe are some DDD concepts. I am new to DDD and I have to admit I am struggling with the practical side of it having come from an N-Tier Transaction Script background.

One of the problems with the site is that it is slow. There is no paging on huge grids and also the business logic layer pulls down way more data than is needed for 90% of operations 70% of which are reads to bind data to grids.

The general design is that the business logic layer has a Service class per aggregate root, with various "GetByX()", 'FindBestMatching()" and "Update()" type methods on it. These Service classes are the points from which trees of domain objects are created such as "Organisation" and "User."

Back in my comfortable transaction script days, my service layer was similar: there would be some logic possibly, a call into a repository (or since EF 6 direct use of EF as it can be mocked for testing) and then the call would return. The objects that were returned would be DTO type objects containing return data relevant, including possibly some POCO entity objects. These DTOs would travel to clients via webservices, be bound to ASP.NET or Silverlight grids...all was good.

My operations on my service layer could be very specific, allowing for queries like:

```<code>"GetUsersWithSurnameIncludeChildren(string surname, int skip, int take)"
</code>```

allowing for nice narrow DB queries that supported paging and eager loading of related data. It was fast and loaded only the data that was actually needed.

Now with this site I have inherited there is an actual OO model of the business domain. These classes are POCOs, not generated from EF, but EF is used database first as a repository (there is a lot of mapping between the domain objects and the EF objects). An example domain object is below (without any logic).

```<code>public class Organisation
{
    public int OrganisationID { get; set; }
    public string Name { get; set; }

    public IList<Organisation> AssociatedOrganisations { get; set; }
    public IList<User> Staff { get; set; }
    public IList<User> Managers { get; set; }

    // Business logic method implemented below here
}
</code>```

Many of the classes are essentially copies of the underlying entity framework objects, others have a significant amount of logic encapsulated within them.

The way the site works currently is that every time the OrganisationService service class creates a new Organisation domain object (and it may create a collection in one hit) it also populates ALL of the fields and collections in that object...and all of the fields and collections in those objects! A huge deep tree is created in memory and a stack of joins and unions (generated by EF) is needed to get all of the data. This is totally inappropriate for a website that mainly displays loads of flat grids.

My questions are:

1) Is an application that is 70% pulling data out of a DB for display and 30% business logic actually a bad candidate for DDD?

2) If DDD is appropriate how are scenarios like this generally designed? Should I implement a separate "Query Service" that is designed just to pull out loads of flat data for binding to pages and grids (these could just be the EF POCOS themselves) and reserve the Domain objects just for parts of the application where logic must actually be performed?

3) Should I only load data into my Domain Object reference types and collections when it is actually accessed (like EF lazy loading...)? Previous posts I have read have suggested lazy loading in a Domain Object is a code smell: DDD Lazy Loading Code Smell

I am about to buy a DDD book tonight :)

答:
I've built several DDD models, persistence was handled by NHibernate. We went with a repository pattern in our early projects and built all of our queries into our repositories.

This is a great idea in theory but what we learnt in practice is that you end up writing a lot of boiler place when implementing the repositories and also they were practically useless anyway. Beyond the standard save, delete, and FindByID method all the actual queries that get used are almost always unique to one particular use case, especially when you take into account which properties you want to eager load.

So we still use a repository pattern but just have save, delete, findByID and findByQuery methods. The query is encapsulated in an object and passed into the repository, the query object is built in the application layer.


问:
Workaround for Java checked exceptions
I appreciate a lot the new Java 8 features about lambdas and default methods interfaces. Yet, I still get bored with checked exceptions. For instance, if I just want to list all the visible fields of an object I would like to simply write this:

```<code>    Arrays.asList(p.getClass().getFields()).forEach(
        f -> System.out.println(f.get(p))
    );
</code>```

Yet, since the get method might throw a checked exception, which does not agrees with the Consumer interface contract, then I must catch that exception and write the following code:

```<code>    Arrays.asList(p.getClass().getFields()).forEach(
            f -> {
                try {
                    System.out.println(f.get(p));
                } catch (IllegalArgumentException | IllegalAccessException ex) {
                    throw new RuntimeException(ex);
                }
            }
    );
</code>```

However in most cases I just want the exception to be thrown as a RuntimeException and let the program handle, or not, the exception without compilation errors.

So, I would like to have your opinion about my controversial workaround for checked exceptions annoyance. To that end, I created an auxiliary interface ConsumerCheckException<T> and an utility function rethrow (updated according to the sugestion of Doval's comment) as follows:

```<code>  @FunctionalInterface
  public interface ConsumerCheckException<T>{
      void accept(T elem) throws Exception;
  }

  public class Wrappers {
      public static <T> Consumer<T> rethrow(ConsumerCheckException<T> c) {
        return elem -> {
          try {
            c.accept(elem);
          } catch (Exception ex) {
            /**
             * within sneakyThrow() we cast to the parameterized type T.
             * In this case that type is RuntimeException.
             * At runtime, however, the generic types have been erased, so
             * that there is no T type anymore to cast to, so the cast
             * disappears.
             */
            Wrappers.<RuntimeException>sneakyThrow(ex);
          }
        };
      }

      /**
       * Reinier Zwitserloot who, as far as I know, had the first mention of this
       * technique in 2009 on the java posse mailing list.
       * http://www.mail-archive.com/javaposse@googlegroups.com/msg05984.html
       */
      public static <T extends Throwable> T sneakyThrow(Throwable t) {
          throw (T) t;
      }
  }
</code>```

And now I can just write:

```<code>    Arrays.asList(p.getClass().getFields()).forEach(
            rethrow(f -> System.out.println(f.get(p)))
    );
</code>```

I am not sure that this is the best idiom to turn around the checked exceptions, but as I explained, I would like to have a more convenient way of achieving my first example without dealing with checked exceptions and this is the simpler way that I found to do it.

答:
another version of this code where checked exception is just delayed :

```<code>public class Cocoon {
         static <T extends Throwable> T forgetThrowsClause(Throwable t) throws T{
            throw (T) t;
        }

        public static <X, T extends Throwable> Consumer<X> consumer(PeskyConsumer<X,T> touchyConsumer) throws T {
            return new Consumer<X>() {
                @Override
                public void accept(X t) {
                    try {
                        touchyConsumer.accept(t);
                    } catch (Throwable exc) {
                        Cocoon.<RuntimeException>forgetThrowsClause(exc) ;
                    }

                }
            } ;
        }
// and so on for Function, and other codes from java.util.function
}
</code>```

the magic is that if you call:

```<code> myArrayList.forEach(Cocoon.consumer(MyClass::methodThatThrowsException)) ;
</code>```

then your code will be obliged to catch the exception

Title: Workaround for Java checked exceptions

Body:
another version of this code where checked exception is just delayed :

public class Cocoon {
         static <T extends Throwable> T forgetThrowsClause(Throwable t) throws T{
            throw (T) t;
        }

        public static <X, T extends Throwable> Consumer<X> consumer(PeskyConsumer<X,T> touchyConsumer) throws T {
            return new Consumer<X>() {
                @Override
                public void accept(X t) {
                    try {
                        touchyConsumer.accept(t);
                    } catch (Throwable exc) {
                        Cocoon.<RuntimeException>forgetThrowsClause(exc) ;
                    }

                }
            } ;
        }
// and so on for Function, and other codes from java.util.function
}

the magic is that if you call:

 myArrayList.forEach(Cocoon.consumer(MyClass::methodThatThrowsException)) ;

then your code will be obliged to catch the exception


问:
Why was Fortran never used to develop an Operating System?
I'm not a Fortran developer myself, but I'm about to use it a little and found myself wondering why, if it is much older than C but equally as performant as C, was it never used to develop any operating system before C and UNIX came along?

A substitute answer, if the above is invalid, might be which operating systems were developed in Fortran. But still, it didn't seem to catch on at all.

答:
I'd say that Fortran, even of pre-C times, abstracts the programmer from hardware details too much.

No pointer support. If you want to pass large amounts of data between subroutines, you use a COMMON block, and you don't control its allocation. Pointer arithmetic and structure allocation control are hard to non-existent.

Data types are numeric-oriented. Referring to a particular byte is a bit hard, let alone bits.

I/O is provided by language statements, not by subroutines. You depend on the compiler's runtime for it, and cannot roll your own.

This is off the top of my head; last time I wrote Fortran-IV code was ~25 years ago.

Possibly you could alter a Fortran compiler to introduce the missing capabilities. But building a special-purpose 'portable assembly' language like C proved to be easier and more effective.


问:
Should test data be checked into version control?
I'm writing some test code for a feature which processes PDF files.  The basic idea behind the tests is that I point them towards some PDFs I've selected specially, they process them and I check that the output is what I expect.

My question is: where should I be storing these large-ish PDFs?  Should I check them into version control along with the code?  Or put them somewhere else?  Obviously, the test code is useless without the PDFs (or even with different PDFs) but still, putting them into our repository feels wrong.

答:
Definitely include that data with your tests and your main application code.  It helps to have a really well organised test suite - so if you're testing pdf extraction (and you have that code nicely encapsulated) then you should be able to construct a path to your test data, based on the path to the app code - that's always worked for me.

With git you can set up a .gitignore to prevent any temporary output or test logging from polluting your repo.


答:
Fortran is a LINEAR programming language and is ill suited to the development of an OS.

The C family of languages are OBJECT ORIENTED PROGRAMMING (OOP) languages. They allow non-linear programs to run multiple, simultaneous routines, branches, sub-routines, all without unnecessary complications.

Think of Fortran as a pipe carrying water from point A to point B.  Think of OOP languages as an ocean stretching from shore to shore, doing all sorts of things, all at once.

Title: Why was Fortran never used to develop an Operating System?

Body:
I'm not a Fortran developer myself, but I'm about to use it a little and found myself wondering why, if it is much older than C but equally as performant as C, was it never used to develop any operating system before C and UNIX came along?

A substitute answer, if the above is invalid, might be which operating systems were developed in Fortran. But still, it didn't seem to catch on at all.


问:
Why is object-level privacy difficult to use as a paradigm, and why is it desirable?
I have heard a prominent language designer remark that no language today enforces real object privacy, and we are still unsure whether it is possible in practice to design a language that does.

Without trying to read this particular person's mind, this piqued my interest. There are, I think, two distinct concepts at work here:

Languages with class-level privacy almost always provide ways to work-around it - for example with introspection. Are these workarounds necessary, in that their absence would make certain problems much harder to solve in the language, and if so, doesn't that indicate that the privacy paradigm is flawed? In other words, do people (ab)use these mechanisms when they are provided, and why?

Class-level privacy is not object-level privacy (an object has access to private state of other objects if they are of the same class), and we don't know how to do the latter. But why would we want to?

答:
Class-level privacy is not object-level privacy (an object has access to private state of other objects if they are of the same class), and we don't know how to do the latter. But why would we want to?

Object-level privacy makes some kinds of encapsulation difficult / impossible to achieve. For example, consider an object that represents a log file format:

```<code>class i_write_things
{
    std::ostream* writer;
public:
    bool equal(i_write_things const& other) { return this->writer == other.writer; }
    void write_to(std::string const& message) { /* ... */ }
};
</code>```

If object-level privacy was in use, the equal implementation wouldn't be able to see writer in the other instance of i_write_things. As such, you would need to create a getter for this property in order to implement equal, which is worse encapsulation: it exposes that the internal implementation of i_write_things uses an ostream.

Body:
Class-level privacy is not object-level privacy (an object has access to private state of other objects if they are of the same class), and we don't know how to do the latter. But why would we want to?

Object-level privacy makes some kinds of encapsulation difficult / impossible to achieve. For example, consider an object that represents a log file format:

class i_write_things
{
    std::ostream* writer;
public:
    bool equal(i_write_things const& other) { return this->writer == other.writer; }
    void write_to(std::string const& message) { /* ... */ }
};

If object-level privacy was in use, the equal implementation wouldn't be able to see writer in the other instance of i_write_things. As such, you would need to create a getter for this property in order to implement equal, which is worse encapsulation: it exposes that the internal implementation of i_write_things uses an ostream.


问:
Are there any OO languages without inheritance?
During a code review today, a colleague of mine said something interesting:

prototype is only useful when you need inheritance - and when's inheritance ever a good idea?

I thought about this and I realised that I usually use inheritance to get around code that was badly designed in the first place. Modern OO style prefers composition over inheritance, but I don't know of any languages which have taken this to heart and actually enforce it.

Are there any general-purpose programming languages with classes, objects, methods, interfaces, and so on, which disallow class-based inheritance? (If such an idea doesn't make sense, why not?)

答:
Setting aside the question of the definition of object oriented programming the question becomes one of "are there languages which use composition only and have no tools for inheritance?"

The answer to this is quite simply "yes".  In go, there are no way to do inheritance as one classically thinks of it.  One can embedded an object in another object and the extend that object.  From Object Desoriented Language (github mirror):

```<code>type Person struct {
        Name string
}

func (p *Person) Intro() string {
        return p.Name
}

type Woman struct {
        Person
}

func (w *Woman) Intro() string {
        return "Mrs. " + w.Person.Intro()
}
</code>```

You've got a person struct that has a Name which is a String.  It has a public function called Intro which returns the name.  The Woman struct also has a function for Intro which accesses the strut embedded in it.  And so one can fulfill the intentions of inheritance by using composition only.

More on this can be seen at GoLang Tutorials: Inheritance and subclassing in Go - or its near likeness.

So yes, it is possible to have an OO language without inheritance, and one does exist.

Within go this is known as embedding and gives enclosing structures the ability to access the embedded fields and functions as if it had them too - but it's not a subclass.  The design philosophy can be found in the Go FAQ: Why is there no type inheritance?

Body:
Setting aside the question of the definition of object oriented programming the question becomes one of "are there languages which use composition only and have no tools for inheritance?"

The answer to this is quite simply "yes".  In go, there are no way to do inheritance as one classically thinks of it.  One can embedded an object in another object and the extend that object.  From Object Desoriented Language (github mirror):

type Person struct {
        Name string
}

func (p *Person) Intro() string {
        return p.Name
}

type Woman struct {
        Person
}

func (w *Woman) Intro() string {
        return "Mrs. " + w.Person.Intro()
}

You've got a person struct that has a Name which is a String.  It has a public function called Intro which returns the name.  The Woman struct also has a function for Intro which accesses the strut embedded in it.  And so one can fulfill the intentions of inheritance by using composition only.

More on this can be seen at GoLang Tutorials: Inheritance and subclassing in Go - or its near likeness.

So yes, it is possible to have an OO language without inheritance, and one does exist.

Within go this is known as embedding and gives enclosing structures the ability to access the embedded fields and functions as if it had them too - but it's not a subclass.  The design philosophy can be found in the Go FAQ: Why is there no type inheritance?


问:
Why is cleverness considered harmful in programming by some people?
I've noticed a lot of questions lately relating to different abstraction techniques, and answers saying basically that the techniques in question are "too clever." I would think that part of our jobs as programmers is to determine the best solutions to the problems we are given to solve, and cleverness is helpful in doing that.

So my question is: are the people who think certain abstraction techniques are too clever opposed to cleverness per se, or is there some other reason for the objection?

EDIT: This parser combinator is an example of what I would consider to be clever code. I downloaded this and looked it over for about half an hour. Then I stepped through the macro expansion on paper and saw the light. Now that I understand it, it seems much more elegant than the Haskell parser combinator.

答:
"Clever code" is any code for which the programmer had to think really hard or use some advanced skill to write it. The problem with that it disregards the need for a certain "cleverness margin", best expressed by Brian W. Kernighan: </p>

<p>"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." </p>

Body:
"Clever code" is any code for which the programmer had to think really hard or use some advanced skill to write it. The problem with that it disregards the need for a certain "cleverness margin", best expressed by Brian W. Kernighan:

"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it."

OwnerDisplayName: Alex


答: In general, I don't bother looking at the network of people who forked my repositories. If they want to commit the changes upstream, they'll send me a PR and we'll start a dialogue in that thread. It gets too cumbersome to track people down and ask them for a PR otherwise.</p>

Title: On GitHub, etiquette and pull requests


答:
You can make the compiler enforce selective inheritance through the use of private / protected, and through modern use of "PImpl", or "Private Implementation" techniques.

Many APIs expose only those components which you would desire a user to inherit, and hide the rest in a separate implementation class.  So you could write classes whose public interfaces are, in fact, uninheritable, only usable through object composition, and compiler-enforced.  This is often good practice, when it uses the compiler to enforce the intent of the software.

A quick search for private member functions in javascript show there is a similar principle, although anybody can see your code if they can use it:
http://www.crockford.com/javascript/private.html

Title: Are there any OO languages without inheritance?

Body:
During a code review today, a colleague of mine said something interesting:

prototype is only useful when you need inheritance - and when's inheritance ever a good idea?

I thought about this and I realised that I usually use inheritance to get around code that was badly designed in the first place. Modern OO style prefers composition over inheritance, but I don't know of any languages which have taken this to heart and actually enforce it.

Are there any general-purpose programming languages with classes, objects, methods, interfaces, and so on, which disallow class-based inheritance? (If such an idea doesn't make sense, why not?)


问:
Best approach for an online store which changes its product’s price over time? [Designing the DB Table]
I am currently creating a website which will allow people to buy consumer products (deodorant, shampoo, toothpastes, etc…) from a store. Those products tend to change price and other details twice per year or more. And I want to show past purchases’ prices and other details to the client.
And I wanted to know what the best approach is.
I’ve come up with the following approaches. Are they any good?

Thanks!

1st. Approach: I have a Product table, with the columns that tend to change, appended with the time of change as a suffix.

2nd Approach: In this one, I have the price and other details in a separate column.

I did make some research:
How to store prices that have effective dates?
http://talentedmonkeys.wordpress.com/2010/05/15/temporal-data-in-a-relational-database/

But couldn't find them appropriate for my problem.

答:
Instead of creating a separate table for each date, create a single details table and index by product id and effective date:

```<code>ProductDetails:
   productId
   dateEffective
   price
   ...
</code>```

This way, you just insert a new row each time the details change.

```<code>insert into ProductDetails( productId, dateEffective, price )
values ( 1234567, '10/06/2014', 1.25 );
</code>```

So you get the price based on the product id and the date; this way, you can get the current price for new orders, and get the price for past orders based on the date.

```<code>select price, dateEffective from ProductDetails where productId = 1234567 and
dateEffective between date1 and date2;
</code>```

You really don't want to create a bunch of separate tables for different time periods, and you really don't want to keep adding columns to the Product table every time details update.

Body:
Instead of creating a separate table for each date, create a single details table and index by product id and effective date:

ProductDetails:
   productId
   dateEffective
   price
   ...

This way, you just insert a new row each time the details change.

insert into ProductDetails( productId, dateEffective, price )
values ( 1234567, '10/06/2014', 1.25 );

So you get the price based on the product id and the date; this way, you can get the current price for new orders, and get the price for past orders based on the date.

select price, dateEffective from ProductDetails where productId = 1234567 and
dateEffective between date1 and date2;

You really don't want to create a bunch of separate tables for different time periods, and you really don't want to keep adding columns to the Product table every time details update.


答:
If you have one thing, which has some attributes which cannot change and others which may change over time, you really have two separate things.  And that means you should consider giving each "thing" its own table.

Neither of your options use the database model to make anyone's job easier.  Selecting entirely different tables is an annoying practice, but occasionally needed as an implementation concern for very large data sets.  Selecting different columns is a TERRIBLE idea, that screams out for further normalization.

Use a separate table for prices, with either date ranges or a "current or closest in the past" model.  Anything else is a headache that you should avoid unless you have a very good reason not to.

Title: Best approach for an online store which changes its product’s price over time? [Designing the DB Table]

Body:
I am currently creating a website which will allow people to buy consumer products (deodorant, shampoo, toothpastes, etc…) from a store. Those products tend to change price and other details twice per year or more. And I want to show past purchases’ prices and other details to the client.
And I wanted to know what the best approach is.
I’ve come up with the following approaches. Are they any good?

Thanks!

1st. Approach: I have a Product table, with the columns that tend to change, appended with the time of change as a suffix.

2nd Approach: In this one, I have the price and other details in a separate column.

I did make some research:
How to store prices that have effective dates?
http://talentedmonkeys.wordpress.com/2010/05/15/temporal-data-in-a-relational-database/

But couldn't find them appropriate for my problem.


问:
Is it necessary to create a database with as few tables as possible
Should we create a database structure with a minimum number of tables?

Should it be designed in a way that everything stays in one place or is it okay to have more tables?

Will it in anyway affect anything?

I am asking this question because a friend of mine modified some database structure in mediaWiki. In the end, instead of 20 tables he was using only 8, and it took him 8 months to do that (it was his college assignment).

EDIT

I am concluding the answer as: size of the tables does NOT matter, until the case is exceptional; in which case the denormalization may help.

Thanks to everyone for the answers.

答:
Uncle Bob would argue that More is Simpler.

See http://c2.com/cgi/wiki?FearOfAddingTables

"a good design is generally simplified by adding tables"

I believe that almost all entities are many-to-many, which requires more tables.

Make a countries table with the continent code in it. Oh, you can't because there are actually 8 transcontinental countries. Same with currencies. Panama uses two.


问:
What are your favorite version control systems?
This is more a discussion question than an actual attempt to determine the "best", since that clearly varies by the needs of the organization. I'm more curious about the arguments in favor of different systems across categories (centralized vs distributed, open vs proprietary, etc).

So, what do you think is the best version control system?

答:
MPW: Well, I can't really give it a review in spite of my efforts.

This was back when I was learning programming in high school, and the only really free C++ compiler to be had was Macintosh Programming Workbench, which I kept on a zip disk and popped into whichever Performa was available in the lab.

MPW came with dozens of tools (none of which were resedit, that was a separate download), and one of them was a version control utility.  It popped open a small window with a single line of text, and you were to drag and drop your projects or files onto it.  It had no documentation that I was ever able to discover, unusual considering everything else seemed to have great docs, and so I never quite worked out how to use it.

That was my first brush with VC, and the last one for a good long while.  Now I use git for everything.


问:
JavaFX with or without Rich Client Platform
I'm starting to delve into JavaFX and have heard that one of the cons of java fx is that there isn't a mature rich client platform or application framework ala eclipse rcp or netbeats platform for it.

Why does JavaFX need a rich client platform? Do these things offer something that pure java fx does not offer on it's own? Does this lack of an application framework mean that JavaFX is not suited for huge enterprise applications that require plugins and stuff like that?

答:
Not having an RCP framework does NOT mean JavaFX is not suited for big applications, but requires you to invent more things yourself. Anyways there are RCP frameworks for JavaFX. One is built on top of Eclipse4 and it provides everything you expect from such a thing, it inherits the plugin/module concept and service modell from OSGi, adds a DI container, command and docking framework.

You can find more about it at http://efxclipse.org

Others i know of are afterburner.fx, griffon.fx and jacp.fx


问:
TDD: how to test file outputs?
I'm really new to TDD, so I guess this question is pretty basic.

We're building a website, and part of the functionality is generating some files (binary files: Excel, PDF, whatever). How should I test this feature?

I've think about creating some static files and compare those with the generated ones, but a binary comparison isn't reliable (the files can have the same content but different checksums), and, if I understood TDD correctly, a logic comparison isn't a good idea, since I should use basically the same algorithm I use to generate the files, so I wouldn't be really testing anything.

How are this kind of things usually dealt with?

答:
I've done this by using a library to parse the files.  Sounds like you already have one available so you should use this.

Even if you could compare the entirety of the binary files, I wouldn't recommend this.  Lets say you've got 100 tests that are testing various things by comparing the entire binary output.  Then a new requirement comes in that the title of each file should be changed from "Foo" to "Bar".  Assuming all your output files were outputting a title of "Foo", you've now got 100 broken tests you have to fix.

A better way is to only test one thing in a test that doesn't overlap with the other tests.  In this context, only a few tests should be responsible for checking the title.  Then if the same requirement comes in, only those few tests would need to be changed.

Title: TDD: how to test file outputs?


答:
How are this kind of things usually dealt with?

By not unit testing the files.

Generally, there's some intermediary format that defines the content of the file. You would test that the intermediary content you expect is being sent off to be PDF-ified. Basically, isolate everything but actually encoding your output to PDF. In an ideal world, that work will be done by some library, so you don't need to test it.

In a realistic world, you need humans to eyeball the PDFs to make sure that they're well formed and "look right" anyways (and load properly in Acrobat on different platforms, etc.), so have them check the content too. Not everything is a good fit for TDD.

Title: TDD: how to test file outputs?

Body:
I'm really new to TDD, so I guess this question is pretty basic.

We're building a website, and part of the functionality is generating some files (binary files: Excel, PDF, whatever). How should I test this feature?

I've think about creating some static files and compare those with the generated ones, but a binary comparison isn't reliable (the files can have the same content but different checksums), and, if I understood TDD correctly, a logic comparison isn't a good idea, since I should use basically the same algorithm I use to generate the files, so I wouldn't be really testing anything.

How are this kind of things usually dealt with?


答:
No.

Aside from structural issues of lack of pointers and access to hardware that is typically necessary for operating system design (fortran is too abstract), fortran also had a significant issue with different versions from different manufactures being, well, different.  Fortran 66 was the first industry standard version (before fortran 77), but even with these standards there were many other versions out there.

There were also other languages which did offer the necessary access to memory as memory, and hardware, and a bit less abstract. You had PL/I from '64 which was used to write Multix. BCPL and B  from '66 and '69 respectively were also used for operating system development. And then there was and C from '72. And one shouldn't forget the MCP for the Burroughs B5000 written in Algol in '61 (compare with Fortran being introduced in '58).

All of those better languages were better choices for operating system design - and were used for various operating systems.  They were standardized, cross platform and stable in a time when Fortran wasn't well standardized and programs that ran on IBM might not run on Digital equipment. They also were availabe very shortly after fortran and people started thinking about writing an OS in a language that was no longer seen as slow (compiler technology and optimizations were staring to catch up to hand coded assembly).

So, no.  There was no reason to write an operating system in Fortran when there were much better tools available for those who wanted to take it up.  As fortran as a systems language isn't recorded in the history while other ones are, and it certainly would have been notable it is probably safe to say that no serious operating system development has been done in Fortran.

From a Fortran 95 handout:

Not being a general-purpose language, there are some things Fortran is very bad at. Anyone trying to write a compiler or operating system in Fortran is probably mad or about to become mad. However the ‘old’ University Library electronic catalogue, which is soon to be replaced, is written in Fortran, even though this is far from the sort of application for which Fortran was designed.


问:
What is the rule for simplicity over complexity?
We have a site which is hugely complex in its implementation.   Conceptually, it is simple - a web-based catalog.  But the implementation has become a multi-layered nightmare.  </p>

<p>Can anyone indicate a "rule of thumb" for measuring when something has become too complex for the job it is doing?   </p>

答:
The rule of thumb I always employ is to code just enough to meet the requirements. Using a minimalist approach ensures you can grow organically rather than assuming what the user wants. Its what made google such a great website in my opinion. Keep it simple

Now if the implementation is too complex, you may want to use MVC more effectively


答:
A clean design is if you have a startDate and endDate for every price:

for a new product:

insert into price set product=X, startDate=now(), endDate=infinity

for a price change:

insert into price set product=X, startDate=now(), endDate=infinity

insert trigger fires: update price set endDate=now() where product=X and endDate=infinity

This way you can also easily model periods when there is no price.

Advanced: This can also be used for logging prices, so the real current price is in one table and you just update it and the logging table gets automatically filled by a trigger with the startDate and endDate as described above.


问:
Is there a particular coding standard with comments between function name and body?
I'm integrating with a shipping API built in php.

They have a strange coding standard where the comments are between the function name and the first curly bracket.. which - subjectively - makes the code really hard to read.

Is this a particular, albeit non-standard, commenting standard?

Here's an example of a such a function

```<code>public function qualityControlDescription($qcCode)
/*
Converts a Quality Control code (e.g. 'U') to a descriptive string.
Input parameters (case-insensitive):
    $qcCode = a Quality Control code, as returned by invokeWebService

Returned:
    Description string (e.g. 'UNSERVICEABLE'), or "" if not found
*/
{
    if (is_null($qcCode))
    {
        return "";
    }
    $descriptionMap = $this->qualityControlDescriptionMap();
    $returnVal = $descriptionMap[strtoupper($qcCode)];
    if (is_null($returnVal))
    {
        $returnVal = "";
    }
    return $returnVal;
}
</code>```

答:
PHP code tends to use a block before the function:

```<code>/**
 * Is the given array an associative array?
 */

function isAssoc($arr) {
    return array_keys($arr) !== range(0, count($arr) - 1);
}
</code>```

I have seen much C, Java, JavaScript, Perl, and other code that uses a similar block-before-function style. However other languages (Python comes to mind most quickly) do use this "between the definition and the code" style. E.g.:

```<code>def is_string(s):
    """
    Is the given value `s` a string type?
    """
    return isinstance(s, (str, unicode))
</code>```

There are a number of other conventions that tend to be language- and/or documentation-system specific for documenting the types, purposes, and default values for parameters and return types.

So that style is idiosyncratic for the PHP community, but not out of bounds considering all common documentation styles.

Here is more on the PHP DocBlock style.

Body:
PHP code tends to use a block before the function:

/**
 * Is the given array an associative array?
 */

function isAssoc($arr) {
    return array_keys($arr) !== range(0, count($arr) - 1);
}

I have seen much C, Java, JavaScript, Perl, and other code that uses a similar block-before-function style. However other languages (Python comes to mind most quickly) do use this "between the definition and the code" style. E.g.:

def is_string(s):
    """
    Is the given value `s` a string type?
    """
    return isinstance(s, (str, unicode))

There are a number of other conventions that tend to be language- and/or documentation-system specific for documenting the types, purposes, and default values for parameters and return types.

So that style is idiosyncratic for the PHP community, but not out of bounds considering all common documentation styles.

Here is more on the PHP DocBlock style.


答:
There are a few different ways of testing files:

Binary comparison. Output a "golden" result file for each test; manually confirm it's right; store it and compare it against future file outputs. Pros: Simple. Cons: Fragile. Prone to false negatives (esp if files contain metadata, like 'creation date' that change even when the 'payload' data does not.)

Parsing the file. Use a library to parse the (Excel, PDF, text, ...) file. Run assertions on the parsed data. Pro: Less fragile than binary comparison. Can easily avoid metadata flutter. Cons: More difficult and complex to code. Not all file formats are readily parsed, nor are the interesting features of the output amenable to a concise, descriptive set of test assertions.

Rendered comparison. Output the file; use a rendering engine to convert the file to a more comparable representation (such as a lossless image file). Pro: Can be less fragile than pure binary comparison, and easier to code than parsing plus assertions. Focuses easily on 'payload' rather than metadata. Cons: Dependent on renderer and rendering envionrment (including specific renderer version). Requires same "golden image" files as straightforward binary comparison. May require cropping, filtering, and sorting operations to align and compare only the relevant parts.

Title: TDD: how to test file outputs?


答:
A piece of software is a machine, with buttons, pipes, moving parts and everything else that might be part of a car, or some device at a factory, except that they're represented in code. Imagine your machine (the web site) if brought to life as physical device. Are there unnecessary extra parts? Too many (or the wrong kind of) knobs? A strange exhaust stack? What is it really supposed to do?

Every system is different, and things can't be measured the way they can in the physical world, so rules, ratios and formulae aren't always available to the software engineer. However, a few guidelines might help when analyzing of your system:

Is there an internal Wiki or FAQ with detailed steps that must be performed in order to add or change functionality? Are these steps really necessary, and if so, can they be automated?

Is there just one person that know how the whole system goes together? What if he/she leaves the company?

Are there layers of abstraction that have only one real usage? (i.e. interfaces with only one concrete implementation).

How many data transformations occur between endpoints of the system? In some applications, you could use JSON up and down the stack without problem. This isn't appropriate in every situation, but every time a data transformation occurs, evaluate if the layer requiring the transform is truly adding value.

Are certain technologies employed that were mandated for political, cost or other non-engineering reasons? (i.e. "We have to use Oracle because the CEO said it's the best")

For usability, have feedback been solicited from users (or people that didn't work on the project)? Are there too many clicks, cluttered pages?

If you had to identify one "secret sauce" area of the code, what would it be? Could this functionality be extracted into a separate module allowing other pieces to interact with it in a cleaner manner?

Finally, could you design a simpler system? Make a prototype, and gather feedback from your co-workers. This is the best test of all.

Title: What is the rule for simplicity over complexity?

Body:
We have a site which is hugely complex in its implementation.   Conceptually, it is simple - a web-based catalog.  But the implementation has become a multi-layered nightmare.  </p>

<p>Can anyone indicate a "rule of thumb" for measuring when something has become too complex for the job it is doing?   </p>


答:
When you encounter an Error, it typically means your program is now in an undefined state:  a .class file is corrupted, or memory is completely full, or you've run into an internal bug in the JVM, or something of similar severity.  Ask yourself:  even if you catch the Error to prevent an immediate crash, is it meaningful to continue running under these circumstances?  Can you trust the program to behave correctly afterward?  What can you do to actually handle an Error once you catch it?

If your "never crash" requirement means "never stop executing", then by all means, log and continue.  Clearly your client believes that a misbehaving program is better than a terminated one.  But if "never crash" means "never stop functioning", you should focus your defensive efforts elsewhere to prevent the Error from occurring in the first place, let it terminate the program if it somehow occurs anyway, and configure your server to automatically restart the program if that happens.

Title: Is it possible/good idea to reduce chance of crashing by catching Error?

Body:
I have a class the implements A which will run a certain method of class B. There is a requirement that this A should never crash when running this operation (which is not possible, right?).

To reduce the chance of crashing I'm catching Throwable around the operation, like so:

```<code>public void method(B b)
{
    try
    {
        b.operation
    }
    catch(Throwable e)
    {
        //Log e
        //Clean up stuff
    }
}
</code>```

My questions are:

Would this actually help in reducing crashes caused by any thrown Error?

Is it a good idea to ever catch an Error?