答:
I recently solved a similar problem with a third-party library.  Allow me to restate to make sure I'm not misinterpreting your situation.  You know how to work around it, but you don't like the repetition of the workaround, and you feel it obscures your actual code?

I solved my problem using a python decorator that catches an exception and handles it appropriately.  That way, it's only one additional @handle_errors to my function definitions, not a bulky try-catch block that's repeated everywhere.  I'm not very familiar with the .net product line, but I know there are aspect-oriented programming libraries you can get, or you can use the decorator pattern to achieve a similar reduction in boilerplate.

Unfortunately, there's not much beyond that you can do.  It's just the price of vendor lock in.  However, this seems to be a low probability, low impact situation, with validation routines that ought to be mostly stateless and relatively easy to test thoroughly.  Also, the exceptions are hardly "hidden" if they're presented to the user.  This isn't the situation described in Jeff Atwood's blog.

Title: How to handle exceptions that get absorbed by a 3rd party library?

Body:
I'm currently having an issue with a 3rd party control library provider. They have an exception occulting culture that gets in the way of my general fail-fast approach when developing software.

An example: their grid control proposes a RowValidating event in which it's possible to check user data input before it's committed to the underlying object. The event argument has a IsValid boolean property and an ErrorText string property. If the handler had  the IsValid property set to False, the grid will treat the row as invalid, present the error text followed by "Do you want to correct the value?" in a yes / no dialog box.

The problem is that if the handler throws an actual Exception during the validation process, the grid catches it and will behave exactly like described above - only it will use the caught exception's Message property as the validation error text. The exception instance, even though it's actually MY code that caused it, can't ever be caught afterwards. There's no way for me to handle it other than wrapping my validation code in a try/catch block that catches everything.

Of course I don't want my code to throw any exceptions, but hey... errare humanum est! If that ever happens, I'd much prefer having the app crash and burn than hiding the exception away! For these scenarios I have a global handler that will log the unhandled exception right before the app crashes. This is where I'd expect any of them to end up.

Since my company made a huge investment in this particular 3rd party provider (both from learning and actual code running with it), I can't just run to another vendor - much less making my own grid control.

I tried talking to the vendor so that this gets fixed but they won't do anything in fear of causing breaking changes for other customers (understandable). They also won't introduce any kind of boolean flag to circumvent the behavior (less understandable).

Right now I'm uncomfortable deploying an app in which I know there's a chance for it to run in a corrupted state. I also hate having to wrap my event code in a try/catch block that may encounter an Exception from which it's impossible to gracefully recover from.

What kind of solution can I use to prevent or fix this problem?

TL;DR: 3rd party vendor takes away Exception instances thrown from my own code, workarounds are ugly and unsatisfying, don't know what to do with this.


问:
operator"" in modern C++
I took an example I found on-line whereby a constexpr of the form _binary could be evaluated at compile time as an unsigned long long and then I tried to generalize it for any base from 2 to 36.  For instance, 17b1234_baseChange would be evaluated from base 17 as ((1*17 +2)*17 + 3)*17 + 4 = 5624.

I realize this is kind of a contrived example but I was wondering what the limits are for operator"".  Is seems like the compiler when parser is creating separate tokens for numbers and letters.  I was curious if this was a bug or expected behavior.  (In addition to 'b', I have tried other separators with no luck.)
Thanks for your insight.

Command line within http://coliru.stacked-crooked.com/:
g++-4.9 -std=c++14 -O3 -Wall -Wextra -pedantic -pthread -pedantic-errors main.cpp -lm  && ./a.out

Code:

```<code>#include <iostream>

const char Delimiter = 'b';
typedef unsigned long long ULL;

/// Extract one "digit" from a digit string and then recurse.
template<unsigned short NumericBase, char Head, char... Rest>
struct baseChange_helper
{
  constexpr ULL operator()(ULL result) const;
};

/// Teminate recursion when interpreting a numeric string.
template<unsigned short NumericBase, char Head> struct
baseChange_helper<NumericBase, Head>
{
   constexpr ULL operator()(ULL result) const;
};

template<unsigned short NumericBase, char Head, char... Rest>
constexpr ULL baseChange_helper<NumericBase, Head, Rest...>::operator()
(ULL result) const
{
   static_assert(   (Head >= '0' && (Head <= '0' + std::min(NumericBase-1, 9)))
                 || (NumericBase > 10 && (Head >= 'A' && Head <= 'A' +
                     std::min(NumericBase-10, 25)))
                 , "not a valid number in this base");
    return baseChange_helper<Rest...>{}(result = result * (NumericBase -1)
                         + ((Head > 'A') ? (10 + Head - 'A') : (Head - '0')));
}

template<unsigned short NumericBase, char Head>
constexpr ULL
baseChange_helper<NumericBase, Head>::operator()(ULL result) const
{
    static_assert(   (Head >= '0' && (Head <= '0' + std::min(NumericBase-1, 9)))
                 || (NumericBase > 10 && (Head >= 'A' &&
                     Head <= 'A' + std::min(NumericBase-10, 25)))
                 , "not a valid number in this base");
   return  result * (NumericBase -1)  +
           ((Head > 'A') ? (10 + Head - 'A') : (Head - '0'));
}

template<unsigned short NumericBase, char Head, char... Rest> struct
baseChange_parser
{
   constexpr ULL operator()() const;
};
template<unsigned short NumericBase, char Head, char... Rest>
constexpr ULL baseChange_parser<NumericBase, Head, Rest...>::operator()()
const
{
   static_assert( (Head == Delimiter && NumericBase > 1 && NumericBase < 36) ||
                  (Head >= '0' && Head <= '9'),
                  "not a valid base");
   return ( Head == Delimiter ? baseChange_helper<NumericBase, Rest...>((ULL)0)
                    : baseChange_parser<NumericBase*10 + Head - '0', Rest...>()
          );
}
template<char... Chars> constexpr ULL operator"" _baseChange()
{
   return baseChange_parser<0, Chars...>{}();
}

int main() {
    const ULL v = 17b1234_baseChange;
    std::cout << v << std::endl;
}
</code>```

答:
The input to your user-defined literal operator is one of two things: either it's a number, of it's a string.

For it to be a number, it must be something the normal C++ lexer/parser can recognize as a number. It reads the text of the program, converts that token to a number, and passes the number to your routine.

Otherwise, it can be a string. In this case, you need to enclose the string in quote marks, just like any other string literal. As far as the compiler cares, it's just a string literal so it can be formatted any way you choose as long as its contents are legitimate characters (e.g., if it contains a back-slash, the next character must form one of the standard escape sequences, unless you use a raw string literal).

Since 17b1234 isn't something the compiler can/will recognized as a number, it can't be passed to a user-defined literal operator as a number. If you really insist on this format, you're pretty much stuck with passing it as a string:

```<code>"17b1234"_baseChange
</code>```

In this case, your operator will (of course) need to receive its argument as a string, not a number.

ContentLicense: CC BY-SA 3.0

Title: operator"" in modern C++

Body:
The input to your user-defined literal operator is one of two things: either it's a number, of it's a string.

For it to be a number, it must be something the normal C++ lexer/parser can recognize as a number. It reads the text of the program, converts that token to a number, and passes the number to your routine.

Otherwise, it can be a string. In this case, you need to enclose the string in quote marks, just like any other string literal. As far as the compiler cares, it's just a string literal so it can be formatted any way you choose as long as its contents are legitimate characters (e.g., if it contains a back-slash, the next character must form one of the standard escape sequences, unless you use a raw string literal).

Since 17b1234 isn't something the compiler can/will recognized as a number, it can't be passed to a user-defined literal operator as a number. If you really insist on this format, you're pretty much stuck with passing it as a string:

"17b1234"_baseChange

In this case, your operator will (of course) need to receive its argument as a string, not a number.


问:
Should I use Strategy Pattern for this task?
I'm setting up a data validator that will iterate through the rows of a spreadsheet, and for each column, perform a validation check.  I was thinking that this might be an appropriate task for the Strategy Pattern as follows:

interface IValidator:

```<code>public function isValid(rng as range) as boolean
end function
</code>```

implementation validator_Number:

```<code>'checks whether or not value is a number
implements IValidator
public function IValidator_isValid(rng as range) as boolean
    IValidator_isValid=isnumeric(rng.value)
end function
</code>```

implementation validator_Capitalized:

```<code>'checks whether all letters are capitalized in value
implements IValidator
public function IValidator_isValid(rng as range) as boolean
   IValidator_isValid=isnumeric(rng.value) and (ucase(rng.value)=rng.value)
end function
</code>```

validation checker:

```<code>'iterates through worksheet cells, validating them and
public sub validationChecker()

dim headerRow as long
dim validator as IValidator

headerRow=1

for row=2 to maxRow
    for column=1 to maxColumn
        'check the column header name and instantiate
        'validator using the appropriate implementation
        select case sheet.cells(headerRow,column).value
            case "NAME"
                set validator=new validator_Capitalized
            case "AGE"
                set validator=new validator_Number
            'etc.
         end select
         if validator.isValid(sheet.cells(row,column)) then
             doSomething()
         endif
     next
next
</code>```

I previously asked another question about using Strategy to validate Excel data, and the response was that I didn't need to do that because there were only a few types of tests and so the rules could be held in a data store.  But here there are going to be many different kinds of validation tests, some of which have several lines of code.  Is the Strategy implementation that I outlined above the most appropriate pattern to use here?

答:
isValid() could be a method implemented in a Strategy pattern. IMO, the benefit of the pattern is future modifiability. That is, there will be a future need for new implementations of isValid() and you don't want to change your code that iterates and validates. In the definition of Strategy, that's the Context class.

Your select block, which I believe would be in the Context class, isn't flexible the way you proposed it, mainly because it "knows" the concrete implementations:

```<code>    select case sheet.cells(headerRow,column).value
        case "NAME"
            set validator=new validator_Capitalized
        case "AGE"
            set validator=new validator_Number
        'etc.
     end select
</code>```

To make Strategy work the way you want, you probably need a Simple Factory that encapsulates the new XXX. So, instead of a select/case, you just do:

```<code>    set validator = Factory.create(sheet.cells(headerRow,column).value)
</code>```

which effectively calls a create method with the argument "NAME", "AGE", etc. which will return the appropriate validator. The create() encapsulates the select/case logic.

The benefit of this is that you can add new validators without having to change the code in Context. Of course, you do have to update the Factory.create() method (essentially the new case for a new validator) and write a new IValidator implementation.

Here's an updated diagram:

The factory class as well as the separate implementation classes are a lot of extra code which IMO won't "pay off" if you only have two validators and a single Context. If you plan on adding lots of validators and really want the flexibility of keeping the details hidden from Context (which may appear in several places), then go for it!

If you aren't "feeling pain" from repetition in maintaining code, then probably you don't need a pattern.

Body:
isValid() could be a method implemented in a Strategy pattern. IMO, the benefit of the pattern is future modifiability. That is, there will be a future need for new implementations of isValid() and you don't want to change your code that iterates and validates. In the definition of Strategy, that's the Context class.

Your select block, which I believe would be in the Context class, isn't flexible the way you proposed it, mainly because it "knows" the concrete implementations:

    select case sheet.cells(headerRow,column).value
        case "NAME"
            set validator=new validator_Capitalized
        case "AGE"
            set validator=new validator_Number
        'etc.
     end select

To make Strategy work the way you want, you probably need a Simple Factory that encapsulates the new XXX. So, instead of a select/case, you just do:

    set validator = Factory.create(sheet.cells(headerRow,column).value)

which effectively calls a create method with the argument "NAME", "AGE", etc. which will return the appropriate validator. The create() encapsulates the select/case logic.

The benefit of this is that you can add new validators without having to change the code in Context. Of course, you do have to update the Factory.create() method (essentially the new case for a new validator) and write a new IValidator implementation.

Here's an updated diagram:

The factory class as well as the separate implementation classes are a lot of extra code which IMO won't "pay off" if you only have two validators and a single Context. If you plan on adding lots of validators and really want the flexibility of keeping the details hidden from Context (which may appear in several places), then go for it!

If you aren't "feeling pain" from repetition in maintaining code, then probably you don't need a pattern.


问:
How much to "automatically" do?
I'm reading Code Complete 2, and I'm at the chapter where it says to (paraphrasing) "avoid programming through the interface."  Why is it bad to program "through" the interface?

A more concrete example: if I have a method of a class that submits a funny picture, what's wrong with it logging me in also?  Should I simply provide more "helper" methods that do it automatically?

Would it be preferred to break it up into:

set_login(username, password)

login()

submit_picture(funny_picture)

easy_submit(funny_picture) # where it will log in (if not already) and submit

答: It's elementary, my dear Watson! Code Reuse. When you separate the task of login and sending picture, some one else can also use your login, and someone else can also use your send_picture. Moreover if you have login and send_picture separate, how difficult is it to create easy_submit? </p>

ContentLicense: CC BY-SA 2.5

Title: How much to "automatically" do?


问:
Where is the evidence for the performance of Node.js?
A lot of developers, especially ones who haven't used Node.js in production, seem to believe that Node.js is faster than other interpreted languages such as PHP, Python, and Ruby.

These claims include:

Node.js/V8 is x times faster than y language.

The JavaScript reactor pattern will always handle concurrency better than any multi-threaded application.

I can certainly believe the first claim, yet I am unable to find any satisfactory benchmarks showing this.  The second claim seems unfounded, or at least too absolute.

What are the characteristics of Node.JS and V8 that justify such claims?

答:
I've implemented SCrypt libraries both on the clientside and serverside using js-scrypt and CryptSharp, and found the results shocking.

With chrome, execution time was over twice as fast as the .net implementation.

I never really paid much attention to the V8 engine until I observed these performance results, but now I have a very healthy respect for javascript executing on V8.

As for multi-threading, JS is single threaded and non-blocking, so code must be written async by default.
On a single processing core, javascript is basically forcing your code execution to be as processor efficient as possible, whereas serverside code can eat up threads and wait while other things are happening. So there are situations where there is work to be done and a core isn't doing work.

For well written multithreaded code with many cores, and enough work to keep them all busy, js's non-blocking single threaded code may not be able to compete. For example when simulating a universe on a super-computer.

However, thats not what Node.js is for. The vast majority of server code isn't multi-thread optimized or even necessary, so non-blocking wins.


问:
What does that mean? SOAP operation represents logic and REST Resources that represent data
I am trying to understand the different between SOAP and REST so one of these differences is. SOAP exposes operation that represents logic and REST exposes Resources that represent data. What does that mean? Can someone clarify that with examples?</p>

答:
SOAP is a standardized communications protocol.

A SOAP request:
```<code>POST /InStock HTTP/1.1
Host: www.example.org
Content-Type: application/soap+xml; charset=utf-8
Content-Length: nnn

<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">

<soap:Body xmlns:m="http://www.example.org/stock">
  <m:GetStockPrice>
    <m:StockName>IBM</m:StockName>
  </m:GetStockPrice>
</soap:Body>

</soap:Envelope>
</code>```

The SOAP response:

```<code>HTTP/1.1 200 OK
Content-Type: application/soap+xml; charset=utf-8
Content-Length: nnn

<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">

<soap:Body xmlns:m="http://www.example.org/stock">
  <m:GetStockPriceResponse>
    <m:Price>34.5</m:Price>
  </m:GetStockPriceResponse>
</soap:Body>
</soap:Envelope>
</code>```

Notice that you're passing data to a SOAP endpoint, and it's returning data in response.  The action is governed entirely by the XML that defines the SOAP protocol.  Also notice that a POST is being used, so this could, in fact, be a REST-style endpoint.

REST is an architectural style, not a communications protocol.

REST is an understanding that endpoints represent resources, and some mechanisms that promote that understanding.  REST endpoints are entirely agnostic about the kind of data that is passed back and forth between them; you can have SOAP data, XML data associated with AJAX, JSON, or pretty much anything else.

Further Reading

What is REST?

SOAP Example

How I Explained REST to my Wife

Body:
SOAP is a standardized communications protocol.

A SOAP request:

POST /InStock HTTP/1.1
Host: www.example.org
Content-Type: application/soap+xml; charset=utf-8
Content-Length: nnn

<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">

<soap:Body xmlns:m="http://www.example.org/stock">
  <m:GetStockPrice>
    <m:StockName>IBM</m:StockName>
  </m:GetStockPrice>
</soap:Body>

</soap:Envelope>

The SOAP response:

HTTP/1.1 200 OK
Content-Type: application/soap+xml; charset=utf-8
Content-Length: nnn

<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">

<soap:Body xmlns:m="http://www.example.org/stock">
  <m:GetStockPriceResponse>
    <m:Price>34.5</m:Price>
  </m:GetStockPriceResponse>
</soap:Body>
</soap:Envelope>

Notice that you're passing data to a SOAP endpoint, and it's returning data in response.  The action is governed entirely by the XML that defines the SOAP protocol.  Also notice that a POST is being used, so this could, in fact, be a REST-style endpoint.

REST is an architectural style, not a communications protocol.

REST is an understanding that endpoints represent resources, and some mechanisms that promote that understanding.  REST endpoints are entirely agnostic about the kind of data that is passed back and forth between them; you can have SOAP data, XML data associated with AJAX, JSON, or pretty much anything else.

Further Reading

What is REST?

SOAP Example

How I Explained REST to my Wife


问:
Should I keep font assets in git repo?
Switched from svn to git, and I can feel that several repos with heavy assets feel, well, heavy.

I never noticed this heaviness with svn. There is a huge difference when checking out whole history of mostly static assets vs just head.

That got me into optimization. And I'm trying to lean repos up, removing all what is content.

I've cleaned up mostly everything, but fonts.

I wonder if fonts should be kept in the git repo, many of my repos actually contain same fonts.

My thinking is to make a private font server, fonts.company.com use that as a CDN and remove all font-assets from repos.

What is your take on this?

I keep laravel / wordpress / ci / ror web projects under git.

答: Given the relative size of fonts, it's hard to imagine this making an appreciable difference on the performance of a repo. Compare that to having to remember to check the fonts repo for an updated version of the font (or new fonts that are needed), and it seems like it wouldn't be worth the hassle. However, YMMV.</p>

Title: Should I keep font assets in git repo?


答:
Commit until proven guilty.

My preference is to keep everything that's needed in the repo unless there is a strong argument against having it there.

Even if the version control aspect of the repository is not really needed for a given asset, having it come packaged with everything else when a developer clones the repo, or when the repo is deployed to a remote server, confers an advantage that housing those files elsewhere does not.

Putting all the files in the repo eliminates extra provisioning steps when attempting to get the project up and running on a new host.

Title: Should I keep font assets in git repo?

Body:
Switched from svn to git, and I can feel that several repos with heavy assets feel, well, heavy.

I never noticed this heaviness with svn. There is a huge difference when checking out whole history of mostly static assets vs just head.

That got me into optimization. And I'm trying to lean repos up, removing all what is content.

I've cleaned up mostly everything, but fonts.

I wonder if fonts should be kept in the git repo, many of my repos actually contain same fonts.

My thinking is to make a private font server, fonts.company.com use that as a CDN and remove all font-assets from repos.

What is your take on this?

I keep laravel / wordpress / ci / ror web projects under git.


问:
How to handle exceptions that get absorbed by a 3rd party library?
I'm currently having an issue with a 3rd party control library provider. They have an exception occulting culture that gets in the way of my general fail-fast approach when developing software.

An example: their grid control proposes a RowValidating event in which it's possible to check user data input before it's committed to the underlying object. The event argument has a IsValid boolean property and an ErrorText string property. If the handler had  the IsValid property set to False, the grid will treat the row as invalid, present the error text followed by "Do you want to correct the value?" in a yes / no dialog box.

The problem is that if the handler throws an actual Exception during the validation process, the grid catches it and will behave exactly like described above - only it will use the caught exception's Message property as the validation error text. The exception instance, even though it's actually MY code that caused it, can't ever be caught afterwards. There's no way for me to handle it other than wrapping my validation code in a try/catch block that catches everything.

Of course I don't want my code to throw any exceptions, but hey... errare humanum est! If that ever happens, I'd much prefer having the app crash and burn than hiding the exception away! For these scenarios I have a global handler that will log the unhandled exception right before the app crashes. This is where I'd expect any of them to end up.

Since my company made a huge investment in this particular 3rd party provider (both from learning and actual code running with it), I can't just run to another vendor - much less making my own grid control.

I tried talking to the vendor so that this gets fixed but they won't do anything in fear of causing breaking changes for other customers (understandable). They also won't introduce any kind of boolean flag to circumvent the behavior (less understandable).

Right now I'm uncomfortable deploying an app in which I know there's a chance for it to run in a corrupted state. I also hate having to wrap my event code in a try/catch block that may encounter an Exception from which it's impossible to gracefully recover from.

What kind of solution can I use to prevent or fix this problem?

TL;DR: 3rd party vendor takes away Exception instances thrown from my own code, workarounds are ugly and unsatisfying, don't know what to do with this.

答:
I am very fond of hard error & fail fast, I believe they are the one true and right way to go, but I try not to be dogmatic about them.

There are cases where the best thing to do with an unexpected exception is to log it and swallow it.  I will give you an example which is more simple than your situation: suppose you have an observable collection which, when changed, issues a notification to a list of registered observers. And suppose that one of the observers throws an exception. Is it the collection's fault? No, as it has no control over who registers with it. Is it the fault of the code that modified the collection? Certainly not, that code probably did not even know that the collection that it was modifying was an observable one. Is it the fault of any of the remaining observers that are registered and also expect to receive their notifications? Also no, as each of them has no knowledge of other observers, and no control over who will be notified first. So, clearly, the only thing that makes sense for the observable collection to do is to log the exception, swallow it, and keep invoking the remaining observers in the list as if nothing happened.

So, the creator of that library is in a similar situation, and has had to make the same decision.

What I would do in your shoes is that I would surround all my entry points with try-catch so as to be sure that a meaningful error message will always be returned to the library that calls me.

It would be nice to have support by the language for doing things like that, (automatically generated decorators that catch exceptions and invoke an overridable to handle them,) and Karl Bielefeldt's answer seems to indicate that python does have such a mechanism, but those of us who don't have such niceties at our disposal are stuck with doing it by hand.

EDIT:

Your need as a developer to know that a non-fatal exception has occurred should mostly be covered by logging the exception. (You do watch your log while debugging your application, don't you?)

Now, if, like me, you want to eliminate the possibility of any non-fatal exception ever scrolling by the log and going unnoticed, you can do what I do:

I have a centralized utility method for swallowing exceptions which, immediately after logging the exception, performs the following extremely useful call:

```<code>System.Diagnostics.Debugger.Break();
</code>```

On the field, this does nothing.  But in a development environment, (while running under the debugger,) this breaks into the debugger, which theoretically allows me to examine the state of the machine and gain more information about the cause of the exception, but even more importantly, it makes sure that I notice that the exception was thrown.

Of course this presumes that while developing your application you never run it, you always debug it.  That's the correct mode of operation.  If by any chance you do not already have that habit, I would strongly recommend that you acquire it.

Body:
I am very fond of hard error & fail fast, I believe they are the one true and right way to go, but I try not to be dogmatic about them.

There are cases where the best thing to do with an unexpected exception is to log it and swallow it.  I will give you an example which is more simple than your situation: suppose you have an observable collection which, when changed, issues a notification to a list of registered observers. And suppose that one of the observers throws an exception. Is it the collection's fault? No, as it has no control over who registers with it. Is it the fault of the code that modified the collection? Certainly not, that code probably did not even know that the collection that it was modifying was an observable one. Is it the fault of any of the remaining observers that are registered and also expect to receive their notifications? Also no, as each of them has no knowledge of other observers, and no control over who will be notified first. So, clearly, the only thing that makes sense for the observable collection to do is to log the exception, swallow it, and keep invoking the remaining observers in the list as if nothing happened.

So, the creator of that library is in a similar situation, and has had to make the same decision.

What I would do in your shoes is that I would surround all my entry points with try-catch so as to be sure that a meaningful error message will always be returned to the library that calls me.

It would be nice to have support by the language for doing things like that, (automatically generated decorators that catch exceptions and invoke an overridable to handle them,) and Karl Bielefeldt's answer seems to indicate that python does have such a mechanism, but those of us who don't have such niceties at our disposal are stuck with doing it by hand.

EDIT:

Your need as a developer to know that a non-fatal exception has occurred should mostly be covered by logging the exception. (You do watch your log while debugging your application, don't you?)

Now, if, like me, you want to eliminate the possibility of any non-fatal exception ever scrolling by the log and going unnoticed, you can do what I do:

I have a centralized utility method for swallowing exceptions which, immediately after logging the exception, performs the following extremely useful call:

System.Diagnostics.Debugger.Break();

On the field, this does nothing.  But in a development environment, (while running under the debugger,) this breaks into the debugger, which theoretically allows me to examine the state of the machine and gain more information about the cause of the exception, but even more importantly, it makes sure that I notice that the exception was thrown.

Of course this presumes that while developing your application you never run it, you always debug it.  That's the correct mode of operation.  If by any chance you do not already have that habit, I would strongly recommend that you acquire it.


问:
What to do when time estimation goes wrong?
Let’s say you estimated time for a case to be 3 days.
In day two you notice that the case is growing and new scenarios are popping up which were not counted when the time estimation where done.  The new finding leads to 2 days extra (total 5 days). This is a typical problem that you will face sooner or later as developer.

Which strategy can be used when you are going to notify project leader the new time of delivery?

Often you get the question why? How do you motivate the new time of delivery?

The fact is that many projects don’t put much time on analysis & design during SDLC.

EDIT:
In very complex projects no matter how much reasonable time you put on Analysis & Design there are always surprises since the business rules are too complex. However in such cases I believe the project leader must be aware of the complexity and have right attitude when unexpected surprises comes up. The question is how to tackle project leaders who don’t understand the complexity.

答:
This happens so often that no experienced project mananger will make much of a deal of it. Just be honest about it and don't make too optimistic new estimations; when you see it will take much longer, say it. Don't say "I need a bit more time" on a daily basis.

You will have to explain to the manager: was the estimate wrong in the first place or were adverse circumstances (spent a day hunting a bug) the reason for the delay? In the first case, something is wrong with the estimation process, maybe it's too optimistic or naive. In the second case, it's a case for the buffer that was hopefully included in the project plan.


答:
Since the .NET framework standard UI controls do not catch unhandled exceptions by themselves, and offer you some mechanisms to catch those exceptions in a central place, I agree that it is questionable why a 3rd party control should behave differently.

Lets assume, from the nature of your application, in case of a severe failure, you are 100% sure you can safely exit the application at any time, even in an arbitrary GUI event, without the risk of letting behind too much inconsistent data. Then you might consider to create a functional wrapper like this:

```<code>public class MyExit
{
  public void WhenUnhandledException(Action action)
  {
    try
    {
        action();
    }
    catch(Exception ex)
    {
         // ... do some additional logging, if you like ...
         Environment.FailFast(ex.Message+"\n"+ex.StackTrace);
    }
  }
}
</code>```

and use this function throughout you code like this:

```<code>  void MyGUIExceptionHandler(object o, EventArgs e)
  {
     MyExit.WhenUnhandledException(() => {
       // add code, maybe using o and e
     });
  }
</code>```

That way, you don't need to repeat the same try/catch/log/FailFast code more than once, and you can change your fail-fast and logging strategy afterwards, if you like.

Body:
Since the .NET framework standard UI controls do not catch unhandled exceptions by themselves, and offer you some mechanisms to catch those exceptions in a central place, I agree that it is questionable why a 3rd party control should behave differently.

Lets assume, from the nature of your application, in case of a severe failure, you are 100% sure you can safely exit the application at any time, even in an arbitrary GUI event, without the risk of letting behind too much inconsistent data. Then you might consider to create a functional wrapper like this:

public class MyExit
{
  public void WhenUnhandledException(Action action)
  {
    try
    {
        action();
    }
    catch(Exception ex)
    {
         // ... do some additional logging, if you like ...
         Environment.FailFast(ex.Message+"\n"+ex.StackTrace);
    }
  }
}

and use this function throughout you code like this:

  void MyGUIExceptionHandler(object o, EventArgs e)
  {
     MyExit.WhenUnhandledException(() => {
       // add code, maybe using o and e
     });
  }

That way, you don't need to repeat the same try/catch/log/FailFast code more than once, and you can change your fail-fast and logging strategy afterwards, if you like.


问:
Advantages and drawbacks of different ways using Either-types
I am writing software for compiling programs. Therefore have a Compiler that compiles a given sourcecode. It then returns a CompileResult that is similiar to an Either type (it is actually internally delegating to an Either object). Now there can be 2 (non-exceptional) cases:

The compile is successfull (CompileSuccess)

The compile failed (CompileFailure)

Let's assume the compile was successfull. I have seen two or maybe three ways to handle it:

return new CompileResult( new CompileSuccess("success info") ) where CompileResult contains a CompileSuccess.

return new CompileSuccess("success info") where CompileSuccess implements CompileResult.

CompileResult.from( CompileSuccess("success info") ) which could possibly implemented to return either a CompileResult object or a CompileSuccess object (as in 2.)

Are there other ways to accomplish what I want to do? I saw the 2. "inheritation" way in Google guavas Either and in Scalas Either. In guava the 3. way is used for the Option type. What are the differences and when to choose what?

答:
The major issue with your two first solutions is that you couple the compile phase and the creation/instancing of the result. Your third way add a dependency of your class with an unique way to create the result (CompileResult).
Let's solve the first point (delegating Result creation):

```<code>class SuccessDetails {
    private String description;
    public SuccessDetails (String description) {
        this.description = description;
    }
}
class FailureDetails {
    private String description;
    public FailureDetails (String description) {
        this.description = description;
    }
}
class FailResultDetailed extends Result {
    private FailureDetails details;
    public FailResultDetailed (FailureDetails details) { this.details = details; }
}
class SuccessResultDetailed extends Result {
    private SuccessDetails details;
    public SuccessResultDetailed (SuccessDetails details) { this.details = details; }
}
class Result {}
class SuccessResult extends Result {
    private String description;
    public SuccessResult (String description) { this.description = description; }
}
class FailResult extends Result {
    private String description;
    public FailResult (String description) { this.description = description; }
}
interface IResultFactory {
    public SuccessResultDetailed success (SuccessDetails details);
    public FailResultDetailed fail (FailureDetails details);
}
class ResultFactory implements IResultFactory {
    public ResultFactory () { }
    public SuccessResultDetailed success (SuccessDetails details) { return new SuccessResultDetailed(details); }
    public FailResultDetailed fail (FailureDetails details) { return new FailResultDetailed(details); }
}
class Compiler {
    private IResultFactory resultFactory;
    public Compiler (IResultFactory resultFactory) { this.resultFactory = resultFactory; }
    public Result compile (String code, Boolean result) {
        if (result)
            return resultFactory.success(new SuccessDetails("Ok"));
        else
            return resultFactory.fail(new FailureDetails("You've made a mistake"));
    }
}
</code>```

Now your are free to change the way you handle and create the Result object, but you might want to add some details.
The most intuitive way to solve it (for a OO developer) is to extract the details in a bunch of other classes:

```<code>class SuccessWithWarningsDetails extends SuccessDetails {
    private int[] lines;
    public SuccessWithWarningsDetails (String description, int[] lines) {
        super(description);
        this.lines = lines;
    }
}
class CompilerThatThrowsWarnings {
    private IResultFactory resultFactory;
    public CompilerThatThrowsWarnings (IResultFactory resultFactory) { this.resultFactory = resultFactory; }
    public Result compile (String code, Boolean result) {
        if (result)
            return resultFactory.success(new SuccessWithWarningsDetails("Ok", new int[] {1, 2, 3}));
        else
            return resultFactory.fail(new FailureDetails("You've made a mistake"));
    }
}
</code>```

But again, we couple the compile phase and the creation/instancing of the result.
We can try to apply the same process we have done the first time:

```<code>interface IResultDetailsFactory {
    public SuccessDetails success (String description);
    public SuccessWithWarningsDetails successWithWarnings (String description, int[] lines);
    public FailureDetails failure (String description);
}
class ResultDetailsFactory implements IResultDetailsFactory{
    public ResultDetailsFactory () { }
    public SuccessDetails success (String description) { return new SuccessDetails(description); }
    public SuccessWithWarningsDetails successWithWarnings (String description, int[] lines) { return new SuccessWithWarningsDetails(description, lines); }
    public FailureDetails failure (String description) { return new FailureDetails(description); }
}
class CompilerThatThrowsWarningsWithoutCreation {
    private IResultFactory resultFactory;
    private IResultDetailsFactory resultDetailsFactory;
    public CompilerThatThrowsWarningsWithoutCreation (IResultFactory resultFactory, IResultDetailsFactory resultDetailsFactory) {
        this.resultFactory = resultFactory;
        this.resultDetailsFactory = resultDetailsFactory;
    }
    public Result compile (String code, Boolean result) {
        if (result)
            return resultFactory.success(resultDetailsFactory.successWithWarnings("Ok", new int[] {1, 2, 3}));
        else
            return resultFactory.fail(resultDetailsFactory.failure("You've made a mistake"));
    }
}
</code>```

We are so close to the ending, if only we hadn't the resultFactory depency...
Why? because we only care about producing Result, not how they are arranged.

```<code>interface IResultDetailsAndResultFactory {
    public SuccessResultDetailed success (String description);
    public SuccessResultDetailed successWithWarnings (String description, int[] lines);
    public FailResultDetailed failure (String description);
}
class ResultDetailsAndResultFactory implements IResultDetailsAndResultFactory {
    private IResultFactory resultFactory;
    public ResultDetailsAndResultFactory (IResultFactory resultFactory) { this.resultFactory = resultFactory; }
    public SuccessResultDetailed success (String description) { return resultFactory.success(new SuccessDetails(description)); }
    public SuccessResultDetailed successWithWarnings (String description, int[] lines) { return resultFactory.success(new SuccessWithWarningsDetails(description, lines)); }
    public FailResultDetailed failure (String description) { return resultFactory.fail(new FailureDetails(description)); }
}
class CompilerThatThrowsWarningsWithoutCreationAndResult {
    private IResultDetailsAndResultFactory resultFactory;
    public CompilerThatThrowsWarningsWithoutCreationAndResult  (IResultDetailsAndResultFactory resultFactory) {
        this.resultFactory = resultFactory;
    }
    public Result compile (String code, Boolean result) {
        if (result)
            return resultFactory.successWithWarnings("Ok", new int[] {1, 2, 3});
        else
            return resultFactory.failure("You've made a mistake");
    }
}
</code>```

Now we have not only a Compile phase that only depends on a factory to build detailed Results, but we also have results that only depends on a factory to handle the way they will be processed.

Body:
The major issue with your two first solutions is that you couple the compile phase and the creation/instancing of the result. Your third way add a dependency of your class with an unique way to create the result (CompileResult).
Let's solve the first point (delegating Result creation):

class SuccessDetails {
    private String description;
    public SuccessDetails (String description) {
        this.description = description;
    }
}
class FailureDetails {
    private String description;
    public FailureDetails (String description) {
        this.description = description;
    }
}
class FailResultDetailed extends Result {
    private FailureDetails details;
    public FailResultDetailed (FailureDetails details) { this.details = details; }
}
class SuccessResultDetailed extends Result {
    private SuccessDetails details;
    public SuccessResultDetailed (SuccessDetails details) { this.details = details; }
}
class Result {}
class SuccessResult extends Result {
    private String description;
    public SuccessResult (String description) { this.description = description; }
}
class FailResult extends Result {
    private String description;
    public FailResult (String description) { this.description = description; }
}
interface IResultFactory {
    public SuccessResultDetailed success (SuccessDetails details);
    public FailResultDetailed fail (FailureDetails details);
}
class ResultFactory implements IResultFactory {
    public ResultFactory () { }
    public SuccessResultDetailed success (SuccessDetails details) { return new SuccessResultDetailed(details); }
    public FailResultDetailed fail (FailureDetails details) { return new FailResultDetailed(details); }
}
class Compiler {
    private IResultFactory resultFactory;
    public Compiler (IResultFactory resultFactory) { this.resultFactory = resultFactory; }
    public Result compile (String code, Boolean result) {
        if (result)
            return resultFactory.success(new SuccessDetails("Ok"));
        else
            return resultFactory.fail(new FailureDetails("You've made a mistake"));
    }
}

Now your are free to change the way you handle and create the Result object, but you might want to add some details.
The most intuitive way to solve it (for a OO developer) is to extract the details in a bunch of other classes:

class SuccessWithWarningsDetails extends SuccessDetails {
    private int[] lines;
    public SuccessWithWarningsDetails (String description, int[] lines) {
        super(description);
        this.lines = lines;
    }
}
class CompilerThatThrowsWarnings {
    private IResultFactory resultFactory;
    public CompilerThatThrowsWarnings (IResultFactory resultFactory) { this.resultFactory = resultFactory; }
    public Result compile (String code, Boolean result) {
        if (result)
            return resultFactory.success(new SuccessWithWarningsDetails("Ok", new int[] {1, 2, 3}));
        else
            return resultFactory.fail(new FailureDetails("You've made a mistake"));
    }
}

But again, we couple the compile phase and the creation/instancing of the result.
We can try to apply the same process we have done the first time:

interface IResultDetailsFactory {
    public SuccessDetails success (String description);
    public SuccessWithWarningsDetails successWithWarnings (String description, int[] lines);
    public FailureDetails failure (String description);
}
class ResultDetailsFactory implements IResultDetailsFactory{
    public ResultDetailsFactory () { }
    public SuccessDetails success (String description) { return new SuccessDetails(description); }
    public SuccessWithWarningsDetails successWithWarnings (String description, int[] lines) { return new SuccessWithWarningsDetails(description, lines); }
    public FailureDetails failure (String description) { return new FailureDetails(description); }
}
class CompilerThatThrowsWarningsWithoutCreation {
    private IResultFactory resultFactory;
    private IResultDetailsFactory resultDetailsFactory;
    public CompilerThatThrowsWarningsWithoutCreation (IResultFactory resultFactory, IResultDetailsFactory resultDetailsFactory) {
        this.resultFactory = resultFactory;
        this.resultDetailsFactory = resultDetailsFactory;
    }
    public Result compile (String code, Boolean result) {
        if (result)
            return resultFactory.success(resultDetailsFactory.successWithWarnings("Ok", new int[] {1, 2, 3}));
        else
            return resultFactory.fail(resultDetailsFactory.failure("You've made a mistake"));
    }
}

We are so close to the ending, if only we hadn't the resultFactory depency...
Why? because we only care about producing Result, not how they are arranged.

interface IResultDetailsAndResultFactory {
    public SuccessResultDetailed success (String description);
    public SuccessResultDetailed successWithWarnings (String description, int[] lines);
    public FailResultDetailed failure (String description);
}
class ResultDetailsAndResultFactory implements IResultDetailsAndResultFactory {
    private IResultFactory resultFactory;
    public ResultDetailsAndResultFactory (IResultFactory resultFactory) { this.resultFactory = resultFactory; }
    public SuccessResultDetailed success (String description) { return resultFactory.success(new SuccessDetails(description)); }
    public SuccessResultDetailed successWithWarnings (String description, int[] lines) { return resultFactory.success(new SuccessWithWarningsDetails(description, lines)); }
    public FailResultDetailed failure (String description) { return resultFactory.fail(new FailureDetails(description)); }
}
class CompilerThatThrowsWarningsWithoutCreationAndResult {
    private IResultDetailsAndResultFactory resultFactory;
    public CompilerThatThrowsWarningsWithoutCreationAndResult  (IResultDetailsAndResultFactory resultFactory) {
        this.resultFactory = resultFactory;
    }
    public Result compile (String code, Boolean result) {
        if (result)
            return resultFactory.successWithWarnings("Ok", new int[] {1, 2, 3});
        else
            return resultFactory.failure("You've made a mistake");
    }
}

Now we have not only a Compile phase that only depends on a factory to build detailed Results, but we also have results that only depends on a factory to handle the way they will be processed.


问:
Why isn't `length` generic by default?
Haskell often provides two versions of a given function f, i.e:

```<code>f :: Int ...
genericF :: Integral i => i ...
</code>```

There exist many standard library functions with those two versions: length, take, drop, etc.

Quoting the description of genericLength:

The genericLength function is an overloaded version of length. In particular, instead of returning an Int, it returns any type which is an instance of Num. It is, however, less efficient than length.

My question is: where does the efficiency loss comes from? Can't the compiler detect that we are using genericLength as an Int and therefore us length for better performance? Why isn't length generic by default?

答:
Aside from usability, the reason seems to indeed be to avoid performance degradation. In the recent Foldable in GHC7.10 Prelude's FAQ

length is left ungeneralized with regards to the numeric type primarily because genericLength has absolutely abysmal performance. One of the pragmatic guidelines we followed is that we can't make code slower.

By looking at the implementation:

length

```<code>{-# NOINLINE [1] length #-}
length                  :: [a] -> Int
length l                =  lenAcc l 0#

lenAcc :: [a] -> Int# -> Int
lenAcc []     a# = I# a#
lenAcc (_:xs) a# = lenAcc xs (a# +# 1#)
</code>```

genericLength

```<code>genericLength           :: (Num i) => [a] -> i
{-# NOINLINE [1] genericLength #-}
genericLength []        =  0
genericLength (_:l)     =  1 + genericLength l
</code>```

length has a tail-recursive implementation, and the helper function lenAcc can probably be inlined. This might explain the difference, but I'm not sure if there's more to it.

Title: Why isn't `length` generic by default?

Body:
Aside from usability, the reason seems to indeed be to avoid performance degradation. In the recent Foldable in GHC7.10 Prelude's FAQ

length is left ungeneralized with regards to the numeric type primarily because genericLength has absolutely abysmal performance. One of the pragmatic guidelines we followed is that we can't make code slower.

By looking at the implementation:

length

{-# NOINLINE [1] length #-}
length                  :: [a] -> Int
length l                =  lenAcc l 0#

lenAcc :: [a] -> Int# -> Int
lenAcc []     a# = I# a#
lenAcc (_:xs) a# = lenAcc xs (a# +# 1#)

genericLength

genericLength           :: (Num i) => [a] -> i
{-# NOINLINE [1] genericLength #-}
genericLength []        =  0
genericLength (_:l)     =  1 + genericLength l

length has a tail-recursive implementation, and the helper function lenAcc can probably be inlined. This might explain the difference, but I'm not sure if there's more to it.


问:
How do you check that code has been covered automatically?
I am in the process of setting up a Bamboo server for some new projects for a push to TDD in a CI/CD workflow. Sure, unit testing is great, but only as log as it is there.

Now this might be better off in a GIT pre-recieve hook on certain branches (i.e: develop and main release branches) but how should code coverage be enforced, if at all. I am happy to trust committers to ensure code is covered, but how are these things upheld without any slippage apart from diligence and consistency?

In short, I would like to see how others enforce test coverage as an automatic process during either commit or build stages.

答:
You should't enforce code coverage automatically.

This is like enforcing the maximum lines of code per method: agreed, most methods should be less than, say, 20 LOC, but there are valid cases where methods would be longer than that.

In the same way, targeting a given percentage of code coverage per class may lead to unwanted consequences. For instance:

Boilerplate code classes or classes created by code generators may not be tested at all. Forcing developers to test them won't have any benefit and will have a substantial cost in terms of time spent doing it.

Simple code handling unimportant parts of the application doesn't necessarily have to be tested.

In some languages, some code cannot be tested. I had this case in C# with anonymous methods on a library where I really wanted to have 100% code coverage. Those cases may be demoralizing for developers.

More importantly, code coverage should be proportional to two aspects of the code: how critical and how complicated it is:

A piece of code with a complicated logic which is a part of the major feature of an application would better be tested thoughtfully, because failures or regressions can have important consequences.

A simple piece of code which handles a feature nobody uses may have basic tests which cover only basic cases.

Of course, you can still use code coverage as a measurement, especially to compare how different teams achieve code coverage: there may be teams which are less disciplined and more reluctant when it comes to testing. In those cases, you may want to combine this metric with others, such as the number of bugs, the time spent resolving bugs or the number of remarks during code reviews.

You may also want to enforce at least some code coverage, say 60%¹, on individual projects where it makes sense (be careful to exclude prototypes, generated code, CRUD, etc.) Making it possible for developers to mark specific classes as excluded from code coverage is also nice². In this case, this may be done under a form of a check which fails a build if code coverage is below the required minimum. I would do it at build stage, not commit stage, since you are not expected to run unit tests during commit.

¹ I would consider 60% as a reasonable minimum based on my code base: nearly every project or class which has less than 60% code coverage is really untested. This may vary a lot from a language to another and from a company to another (in some companies, 0% is a standard). Make sure to discuss with your team what is normal and what is too high for them. Maybe they are constantly hitting 95% and can easily target 99%, or maybe they struggle to increase their code coverage from 70% to 75%.

² Given that eventual abuse will be detected during code reviews, you shouldn't be afraid to give this possibility to developers. This is similar to the possibility to exclude some parts of the code from the checks by the linters or style checkers. JSLint, StyleCop and Code Analysis are three examples where exclusion is supported and is actually useful without encouraging abuse.


答:
Options:

Cut features

Cut quality (leave bug fixes for later)

Increase productivity

Find and remove blockers

Break/rest

Cut personal/sleep time

Get more workforce

Get better tools

Training

Increase motivation

Free food

[Promise of] raise/promotion/vacation/bonus/etc.

Threats

Improve working conditions (better hardware, furniture, etc.)

Change environment - work from a coffee shop or move the whole team somewhere cool - a mountain lodge or a lake house?

Title: What to do when time estimation goes wrong?

Body:
Let’s say you estimated time for a case to be 3 days.
In day two you notice that the case is growing and new scenarios are popping up which were not counted when the time estimation where done.  The new finding leads to 2 days extra (total 5 days). This is a typical problem that you will face sooner or later as developer.

Which strategy can be used when you are going to notify project leader the new time of delivery?

Often you get the question why? How do you motivate the new time of delivery?

The fact is that many projects don’t put much time on analysis & design during SDLC.

EDIT:
In very complex projects no matter how much reasonable time you put on Analysis & Design there are always surprises since the business rules are too complex. However in such cases I believe the project leader must be aware of the complexity and have right attitude when unexpected surprises comes up. The question is how to tackle project leaders who don’t understand the complexity.

OwnerDisplayName: xyzzer


问:
How would I isolate changes to mutable state if I need to run two queries to get the final result?
I'm working on some code that takes search criteria from a Rest API and uses it to query a remote API to return results.  As an exercise, I wanted to try to separate all state changes to one place, as a language like Haskell would force you to (even though I'm programming in Java in this example).

At first this was straight forward:  Separate the code that generates the query from the code that executes the query.  The code that executes the query can be ignorant of the query it gets.

But now I have a new requirement that works like this:  If someone searches for all things under a parent folder, then I need to run two queries.  One to find the path of that parent folder then another to find all things that start with that path.  I cannot use subqueries to do this in one query, the remote api does not allow it.

I can't figure out how I could cleanly design this.  For this special case, the first query needs to get outside the "pure" code, be executed, then the result needs to be passed in to different "pure" code so the result can be executed as the second query.

How would this be cleanly designed in a functional programming language?  Keep in mind, tomorrow I may get a new requirement that requires me to run 3 queries to get the final result.

答:
The most common pattern I see in these types of situations is to use a CompletableFuture, which most FP languages just call a plain Future.  It allows you to execute something long-running like a query, then specify actions to take later.  If the query succeeds, the result is passed to the next action in the chain.  If it fails, all the subsequent actions are skipped, and a failure action is called instead.

I haven't personally done this in Java, so I can't speak to the ease of use of this particular implementation, but it's a lifesaver in JavaScript.


问:
Are websites hosted in distant servers slower?
I live in Brazil and I'm planning on hosting my website in either DreamHost or Digital Ocean, which don't have any servers in my country. Will that affect the loading speed of my site?

Thanks!!!

答:
The speed of light is 299 792 458 m/s. The circumference of Earth is 40 075 000 m. This means that if the data center is at the opposite side of the Earth, the delay will be at least 0.067 s., that is 67 ms. Noticeable for critical applications where every millisecond counts, such at the home page of Google or a financial sector app; not noticeable for a personal blog or a forum.

The closest Amazon data center, for instance, would be probably in Jacksonville, Florida, USA. The distance is approximately 6 000 km to the center of Brazil (if you're in the south of Brazil, you're out of luck), which translates into 20 ms.

You should also take in account that the time the packets are spent traveling through routers, which may increase the waiting time, and that they hardly travel in a straight line. This being said, the additional time is still probably not too much for an ordinary website.

Conclusion: if the hosting company has several data centers around the world (such as Amazon AWS), hosting a web app in geographical proximity to the customers can be nice. But for most web apps, it's not what will make a radical change in the perceived speed of your app.


问:
Do I need to use cloud services (EC2 / GAE) for my web app?
Noobie to deploying any kind of web app. I have a Java (Play Framework) and MySQL server app running locally. I know that I can deploy it to EC2 (have once as a test), and that I can download some kind of module to get it to run on Google App Engine. But my question is -- do I need to?

I suppose I don't understand what my other options are -- are there other options besides these typical cloud offerings where I get my own server VM, get SSH access and run a Java application / install MySQL with admin access? If so, why would I choose EC2 / GAE over these other options?

I know that they are robust (mainly Amazon) and that's one reason. But I am fairly certain I do not need hardly anything that Amazon offers with their cloud packages other than the ability to run an EC2 instance. But then, I do need some level of customization, as I'm running a custom Java application and will need root level admin access, so from what I'e heard of GAE I probably would not use it.

答:
Do you expect a situation where you would need to scale your application, and do it fast?

If yes, that's the point of cloud computing in general and Amazon's Elastic Compute Cloud in particular. You start small and you pay a small fee. But if your service is successful and you need to increase its capacity per ten, or hundred, or thousand in a matter of minutes, you can do it, eventually relatively easily.

If no, you may use an ordinary hosting, <s>or host the service yourself</s>¹. However, make sure to compare carefully the prices of ordinary hosting companies with the prices of Amazon or Azure: cloud hosting is quite competitive nowadays.

¹ Don't. If you love playing with hardware and have enough money for up-front costs and have a reliable ISP and can afford paying higher electricity bills and have place for noisy servers in your garage and understand the risks of hosting something yourself (including the risk of having all servers with all your data stolen one day), then feel free to do it.


问:
What is the difference between a helper and a convenience function?
The two seem the same to me:

a convenience is a helper

a helper is a convenience

When is it good to use the one or the other term?

答:
Functions have two main purposes: aiding code reusability and breaking down a task into smaller logical units. Functions that do not aid code reusability are helper functions; their sole purpose is to "help" a single function by cleaning the code and making the logic clearer. The opposite of a helper function is a library function, which focuses on code reuse.

Source: Cunningham & Cunningham

whereas:

A convenience function is a non-essential subroutine in a programming library or framework which is intended to ease commonly performed tasks.

Source: Wikipedia

So:

A helper function which is not a convenience function would be any function which breaks down a task into smaller logical units without aiding code reusability and without having a goal of easing a commonly performed task.

For example, a specific task T may require to perform action A and action B. Refactoring may lead to three functions: T(), A() and B(), given that it may not make too much sense to call A() without calling B() just after that.

A convenience function which is not a helper function would ease commonly performed tasks without breaking down a task into smaller logical units.

For instance, if many persons are calling the task T₁ immediately followed by the task T₂, a convenience function would be T₃ which will simply call T₁, then T₂. Here, T₃() doesn't "help" a single function, and doesn't break down any task into smaller logical units: it simply regroups two currently used tasks.


答:
They're just terms. In most scenarios, they are interchangeable.

In general though, a convinience function is one that just helps you do something you can already do, albeit with less typing. An overload that forwards with the usual defaults for example.

A helper often is some new functionality that doesn't really belong somewhere so it's off on its own, but still helps out.

Title: What is the difference between a helper and a convenience function?

Body:
The two seem the same to me:

a convenience is a helper

a helper is a convenience

When is it good to use the one or the other term?


答:
At least as I'd use them, the two are actually more or less opposites.

A convenience function is (at least close to) a pure interface function--something that only provides a nicer, more convenient interface for client code to use. A classic example would be a front-end for a recursive function such as a Quicksort:

```<code>Quicksort(array a) {
    QuicksortImplementation(a, 0, a.size());
}
</code>```

A helper function, by contrast, normally isn't visible at all. In object oriented programming, for example, it'll typically be implemented as a private method/member function.

```<code>class X {
    public void foo() {

        // beginning of `foo`

        if (some_condition)
            helper();

        // remainder of foo
    }

    private void helper() {
        // do some relatively minor service for foo()
    }
};
</code>```

In both cases, however, there is usually the basic idea that the helper/convenience function provides only a small part of the overall functionality. There is also at least the connotation that the helper/convenience function is really only intended to be used in conjunction with one other primary function. It's usually not particularly general or reusable, just a part of its primary function that needs to be (or is more convenient when) written as a separate function for one reason or another.

Body:
At least as I'd use them, the two are actually more or less opposites.

A convenience function is (at least close to) a pure interface function--something that only provides a nicer, more convenient interface for client code to use. A classic example would be a front-end for a recursive function such as a Quicksort:

Quicksort(array a) {
    QuicksortImplementation(a, 0, a.size());
}

A helper function, by contrast, normally isn't visible at all. In object oriented programming, for example, it'll typically be implemented as a private method/member function.

class X {
    public void foo() {

        // beginning of `foo`

        if (some_condition)
            helper();

        // remainder of foo
    }

    private void helper() {
        // do some relatively minor service for foo()
    }
};

In both cases, however, there is usually the basic idea that the helper/convenience function provides only a small part of the overall functionality. There is also at least the connotation that the helper/convenience function is really only intended to be used in conjunction with one other primary function. It's usually not particularly general or reusable, just a part of its primary function that needs to be (or is more convenient when) written as a separate function for one reason or another.


问:
Do RESTful API controllers typically only provide resources related to their own type?
Let's say my API has the following routes:

```<code>GET /theaters
GET /theaters/:id
GET /theaters/:id/movies
GET /movies
GET /movies/:id
GET /movies/:id/theaters
</code>```

And then I have the following controllers with the listed methods:

```<code>TheaterController
    list
    show

MovieController
    list
    show
</code>```

I'm trying to decide in which controllers the remaining requests would best be handled from a strict RESTful perspective. Would this

```<code>TheaterController
    listMoviesByTheater (handles GET /theaters/:id/movies)

MovieController
    showTheatersByMovie (handles GET /movies/:id/theaters)
</code>```

or this

```<code>TheaterController
    listByMovie (handles GET /movies/:id/theaters)

MovieController
    listByTheater (handles GET /theaters/:id/movies)
</code>```

be more RESTful? If neither is more RESTful, which is a more common approach?

Basically, the question boils down to whether TheaterController should only provide access to Theater resources and MovieController should only provide access to Movie resources.

答:
REST doesn't have anything to say about which controller services which URL.

From a purely hierarchical perspective, your first example makes more sense because the first (most general) level in the URL is being handled by its respective controller.

i.e.

```<code>/theaters/:id/movies -- belongs in the Theaters controller, and

/movies/:id/theaters -- belongs in the Movies controller.
</code>```

But that has nothing to do with REST.  The whole point of REST is that a resource identified by a specific URL can be located anywhere.

Body:
REST doesn't have anything to say about which controller services which URL.

From a purely hierarchical perspective, your first example makes more sense because the first (most general) level in the URL is being handled by its respective controller.

i.e.

/theaters/:id/movies -- belongs in the Theaters controller, and

/movies/:id/theaters -- belongs in the Movies controller.

But that has nothing to do with REST.  The whole point of REST is that a resource identified by a specific URL can be located anywhere.


答:
Consider the following code:

```<code>rsq = a*a + b*b;
if (rsq >= 0.0) {
    r = sqrt(rsq);
}
else {
    handle_this_impossible_event();
}
</code>```

There is no way to create a test case that will reach that else branch. Yet if this was safety critical flight software, people would be all over the author's case if that protection against sending a negative value to sqrt was not present. Typically the computation of rsq = a*a + b*b and the extraction of the square root are separated by multiple lines of code. In the interim, a cosmic ray can flip the sign bit on rsq.

In fact, flight software has invoked the equivalent of handle_this_impossible_event(), multiple times. Usually this involves switching control over to a redundant computer, gracefully shutting down the suspect computer, restarting the suspect computer, and finally the suspect computer taking the role of the backup. That's much better than the primary flight computer going whacko.

Even in flight software, it's impossible to achieve 100% code coverage. The people who claim they have achieved this either have trivial code or they don't have enough tests against these impossible events.

Title: How do you check that code has been covered automatically?

Body:
I am in the process of setting up a Bamboo server for some new projects for a push to TDD in a CI/CD workflow. Sure, unit testing is great, but only as log as it is there.

Now this might be better off in a GIT pre-recieve hook on certain branches (i.e: develop and main release branches) but how should code coverage be enforced, if at all. I am happy to trust committers to ensure code is covered, but how are these things upheld without any slippage apart from diligence and consistency?

In short, I would like to see how others enforce test coverage as an automatic process during either commit or build stages.

Body:
Consider the following code:

rsq = a*a + b*b;
if (rsq >= 0.0) {
    r = sqrt(rsq);
}
else {
    handle_this_impossible_event();
}

There is no way to create a test case that will reach that else branch. Yet if this was safety critical flight software, people would be all over the author's case if that protection against sending a negative value to sqrt was not present. Typically the computation of rsq = a*a + b*b and the extraction of the square root are separated by multiple lines of code. In the interim, a cosmic ray can flip the sign bit on rsq.

In fact, flight software has invoked the equivalent of handle_this_impossible_event(), multiple times. Usually this involves switching control over to a redundant computer, gracefully shutting down the suspect computer, restarting the suspect computer, and finally the suspect computer taking the role of the backup. That's much better than the primary flight computer going whacko.

Even in flight software, it's impossible to achieve 100% code coverage. The people who claim they have achieved this either have trivial code or they don't have enough tests against these impossible events.


答: In general, shorter methods are more readable and easier to test with unit tests. Even if you do not plan to reuse the login and/or submit method, breaking it down makes testing and maintenance easier.</p>

Title: How much to "automatically" do?

Body:
I'm reading Code Complete 2, and I'm at the chapter where it says to (paraphrasing) "avoid programming through the interface."  Why is it bad to program "through" the interface?

A more concrete example: if I have a method of a class that submits a funny picture, what's wrong with it logging me in also?  Should I simply provide more "helper" methods that do it automatically?

Would it be preferred to break it up into:

set_login(username, password)

login()

submit_picture(funny_picture)

easy_submit(funny_picture) # where it will log in (if not already) and submit


答:
Yes, it matters.  The signals may travel at light speed (or a reasonable fraction) but there are many rest stops called routers along the way. Your data gets stopped, buffered, and stuffed down another pipe, competing with other traffic for bandwidth.  The fewer routers in the path, and the fatter the pipes, the better your site will load.

That said, unless your site is a twitch-level shooter, or you're sending gigabytes of data,
your users probably won't notice.  The main thing that matters will be the bandwidth
available from your actual host.  Cheap connections may not provide much (you get what you
pay for).

Title: Are websites hosted in distant servers slower?

Body:
I live in Brazil and I'm planning on hosting my website in either DreamHost or Digital Ocean, which don't have any servers in my country. Will that affect the loading speed of my site?

Thanks!!!


问:
When should we use weak entities when modelling a database?
This is basically a question about what are weak entities? When should we use them? How should they be modeled?

What is the main difference between normal entities and weak entities? Does weak entities correspond to value objects when doing Domain Driven Design?

To help keep the question on topic here is an example taken from Wikipedia that people can use to answer these question:

In this example OrderItem was modeled as a weak entity, but I can't understand why it can't be modeled as a normal entity.

Another question is what if I want to track the order history (i.e. the changes in it status) would that be a normal or weak entity?

答:
According to my understanding in the above diagram they have included the two entities/tables instead of one i.e orders and order item so that accessing the information becomes easy when two entities are designed. And order item is dependent on orders entity so it is considered as an weak entity. because the characteristic of weak entity is it depends on another entity. Suppose if you do not include order item entity how will you be able to know order item's price,discount. and as jgauffin said If you for instance remove the order you have no way of knowing where the item should be shipped. Or if you remove the product you don't know what to ship.

The ER diagram is to be designed according to the business requirement.


问:
"Read user input": Could it be a step of an algorithm?
Based on this definition of algorithm from Wikipedia:

In mathematics and computer science, an algorithm is a self-contained step-by-step set of operations to be performed. Algorithms exist that perform calculation, data processing, and automated reasoning.

An algorithm is an effective method expressed as a finite list of well-defined instructions for calculating a function. Starting from an initial state and initial input (perhaps empty), the instructions describe a computation that, when executed, proceeds through a finite number of well-defined successive states, eventually producing "output" and terminating at a final ending state.

Is "Wait for user input" or simply read() counted an step of algorithm?

I thought for the following reasons it may not fit in the definition:

It seems it's not an step which can be executed as an operation is executed.

It should wait for an external signal to get finished, it could be against of the self-contained in the definition.

Moreover the definition talks about an initial input, so I suppose the input should be already provided.

Am I correct?

Update: If it's not an step, then how would you represent the following sequence, is it an algorithm?

X = 5

Y = X + 4

if ( Y > 10) Z = Read() // get the user input

else Z = 1

if (Z > 2) Z = Z + X

Please note reading occurs conditionally, then we may not suppose the input should be already provided.

答:
No. It is not.

Like a mathematical function, an algoritim transforms elements from a source set of information to a destination set. That works independently from the origins of the source set: Whether it stems from user (keyboard or otherwise) input, from a file containing the information or from punchcards. The input belongs to the preconditions of an algortihm: without input no need for calculation; but the method of gathering the input is neglectable and does not belong to the algorithm itself.

Update:
You could substitute the reading-part itself with access to an array a[0]. The data retrieved/result by reading is part of the algorithm, the reading itself not. As I said: the source doesn't matter.
Though the reading is part of your program's logic.

Take for example a sorting algorithm. A sorting algorithm is a well defined number of steps on a set to be sorted. Where the set originates has nothing to do with the algorithm - although every implementation has to take care of the problem, where to retrieve the data from.

That is of course a bit academic or one might say: philosophical.


问:
Staying productive by keeping focus on a feature while developing
As a hobbyist developer I'm quite keen on the git-flow way of working.

But I keep having a problem that I can only blame myself for: while developing a new feature, I keep getting sidetracked by small things that I can "quickly" do. Such things range from small refactoring, writing a particular piece of code in a more pythonic way, adding comments, decoupling, writing an extra test, etc.

Of course, next to the fact that these small things are unrelated to the feature I'm developing, they also tend to grow in size. What appears to be a small thing to do turns out to be something that you spend 2 hours on.

Are there any best practices to keep myself from doing this? I have tried forcing myself to switch to the development branch and do the fixes in a seperate hotfix branch, but I always fool myself into thinking that "for this little change, it's unnecessary to bother with a new branch". Is this just a question of discipline?

(Bonus question: I'm a sole developer, but how on earth would a team of developers handle someone like me? In other words: I'd be changing code all over the place, all the time, which would mean my co-developers would have to keep checking out code and keep trying to get their heads around the new changes).

答:
I can't help you stay focused, but in a team you'd quickly fail code reviews. When you fix a bug or implement a feature on a branch and it comes to review, your reviewer will quickly be saying "WTF did you do that for". I imagine at first you'd be told to stop doing it and the gold plating would be let through "this time", but if you kept doing it, your reviews would fail and they'd be sent back for the extras to be removed.

This may still apply to refactoring changes. If they're not necessary to the code change, then they would rightly be rejected as a clean history where you can see what was modified is more important than anything else - if it goes wrong, how else can you see why it went wrong if you've cluttered the diffs up. (this is most obvious for refactorings such as changing bracket placements - massive diff changes for no benefit)

Maybe this discipline is what you need though, until you have your changes rejected and sent back for rework, you'll never quite get the reality of working in branches. Until then, if you are going to do this, then you might as well stop working like this and simply make all changes on big 'rollup' branches that contain several fixes, features or similar. Only creating new branches for major work that you might not want to keep, or that would clutter the history of a single development trunk.

EDIT: After reading Neil's comment I can't help thinking that maybe the problem is a lack of up-front design. If you're refactoring all the time because you keep finding things that need changing (and not quick bugfixes) then perhaps the underlying problem is that the codebase does not have a firm plan to follow. IF it is that you keep finding bugs, then perhaps TDD would help you more (and TDD that makes you write tests before code, also helps with design)


答:
I think its pretty common to get sidetracked on smaller tasks. I actually think its a good habit. It lets to get away from a problem that your facing for a bit so you can later look at it with fresh eyes. But everything in moderation. I don't think you should stop taking on small changes, however I think you need to focus more on developing that feature before you branch off into other things. Break tasks down into manageable pieces, then set a goal before you allow yourself to get sidetracked.

As for refactoring code I might assume you're methods are too complicated and need to be broken down. You might want to settle for a set of conventions and code design patterns. It might also be worth using a linter before committing, to prevent a lot of problems from even making it into your code base. Monitoring code quality and fixing bugs before implementing features is a good practice, and allows you to refactor before things get out of hand. You shouldn't be rewriting code that often. Simply put you should be writing better code originally, and though humans are not perfect there are plenty of tools that you can use to aid in this(I'll list a few at the end).

A good way to manage refactoring is to make sure you have unit tests for the code your refactoring to make sure your changes behave the same as previously. You should also have some kind of task management software which will allow you to see who is working on what, therefore you can make sure you're not merging over someones work with refactored code. Likely when you work on a team its up to the project manager(who ever assigns tasks) to keep track of everyone's work and this would entitle making sure tasks aren't going to interfere with each other.

Some tools you may find useful:

Pylint To assure code quality before each commit.

unittest pythons unittest framework

JIRA project management software for teams.

Landscape Code Quality and Metrics

nose unittest made easier

Title: Staying productive by keeping focus on a feature while developing

Body:
As a hobbyist developer I'm quite keen on the git-flow way of working.

But I keep having a problem that I can only blame myself for: while developing a new feature, I keep getting sidetracked by small things that I can "quickly" do. Such things range from small refactoring, writing a particular piece of code in a more pythonic way, adding comments, decoupling, writing an extra test, etc.

Of course, next to the fact that these small things are unrelated to the feature I'm developing, they also tend to grow in size. What appears to be a small thing to do turns out to be something that you spend 2 hours on.

Are there any best practices to keep myself from doing this? I have tried forcing myself to switch to the development branch and do the fixes in a seperate hotfix branch, but I always fool myself into thinking that "for this little change, it's unnecessary to bother with a new branch". Is this just a question of discipline?

(Bonus question: I'm a sole developer, but how on earth would a team of developers handle someone like me? In other words: I'd be changing code all over the place, all the time, which would mean my co-developers would have to keep checking out code and keep trying to get their heads around the new changes).


答:
So here, you're writing the handler that throws the exception and the grid manages that exception itself.

I see this as fair enough - after all, you're writing the library code that throws on error states, and the caller (ie the grid) catches and manages the exception how it likes, in this case showing a message to the user in a dialog (which is perfectly understandable given its a UI control).

Now I can understand that you'd like some exceptions to pass through and crash the app, or allow you to catch them, and they might have only caught exceptions based on their own hierarchy instead of catching all exceptions, but they made that choice. You'll just have to live with not being able to catch exceptions and handle them inside the handler (possibly setting some state elsewhere or sending an alternative message to notify your application).

Body:
I'm currently having an issue with a 3rd party control library provider. They have an exception occulting culture that gets in the way of my general fail-fast approach when developing software.

An example: their grid control proposes a RowValidating event in which it's possible to check user data input before it's committed to the underlying object. The event argument has a IsValid boolean property and an ErrorText string property. If the handler had  the IsValid property set to False, the grid will treat the row as invalid, present the error text followed by "Do you want to correct the value?" in a yes / no dialog box.

The problem is that if the handler throws an actual Exception during the validation process, the grid catches it and will behave exactly like described above - only it will use the caught exception's Message property as the validation error text. The exception instance, even though it's actually MY code that caused it, can't ever be caught afterwards. There's no way for me to handle it other than wrapping my validation code in a try/catch block that catches everything.

Of course I don't want my code to throw any exceptions, but hey... errare humanum est! If that ever happens, I'd much prefer having the app crash and burn than hiding the exception away! For these scenarios I have a global handler that will log the unhandled exception right before the app crashes. This is where I'd expect any of them to end up.

Since my company made a huge investment in this particular 3rd party provider (both from learning and actual code running with it), I can't just run to another vendor - much less making my own grid control.

I tried talking to the vendor so that this gets fixed but they won't do anything in fear of causing breaking changes for other customers (understandable). They also won't introduce any kind of boolean flag to circumvent the behavior (less understandable).

Right now I'm uncomfortable deploying an app in which I know there's a chance for it to run in a corrupted state. I also hate having to wrap my event code in a try/catch block that may encounter an Exception from which it's impossible to gracefully recover from.

What kind of solution can I use to prevent or fix this problem?

TL;DR: 3rd party vendor takes away Exception instances thrown from my own code, workarounds are ugly and unsatisfying, don't know what to do with this.


问:
How can I ask my boss (in a polite way) to comment his code?
I am being taught by my boss (I just finished school and he wanted someone with a little programming experience, so he chose me to train me on what that company specializes in) and started working with ASP.NET MVC applications, some HTML and CSS. I'm fine with the web design stuff he gives me (it is pretty simple to understand without clarification).

But for instance, he gives me a task to do with ASP.NET MVC, he explains it really well. But he doesn't explain anything in the code he has just given me. (We use source control in Visual Studio 2013), so it's literally hundreds of lines of code, without any background on what it is supposed to do. The kind of code that I'm seeing is code I've never seen before, so it is really difficult to try and figure out.

I would try and ask him more questions, but he is always working (it's his own business), and I feel as though he might get annoyed with all these questions I have on my hands.

So just something that will help my out until I get a grip on things, how can I ask my boss to put comments into his code that he gives me, but politely?

答:
If you want comments in the code to understand why something has been written then most likely (considering you are new) you don't yet understand the business needs. I'm sure you know all the syntax and can read code but unless you know the purpose of some code then you will feel a bit lost.

One thing that springs to mind is pair-programming. You say your boss is impressed with your progress so you could suggest working alongside him. This will help both of you in the long run. Your boss will find himself having to explain things he takes for granted and you'll learn more about the business.


答:
Code coverage data can of course be obtained automatically, but no automatic decisions should be made based on them, for reasons that others have already explained.  (Too fuzzy, too much room for error.)

However, the next best thing is to have an established process whereby the current state of the project in terms of code coverage gets regularly checked by human beings, possibly with daily reports arriving in the project manager's inbox.

In enterprise environments this is achieved with Continuous Integration tools such as Hudson, Jenkins, etc.  These tools are configured to regularly check out the entire project from the source code repository, build it, run the tests, and generate reports.  Of course, they can be configured to run the tests in code coverage mode and include the results in these reports.

Jetbrains also makes TeamCity, which seems to me a bit more lightweight and suitable for smaller software shops.

So, the project manager receives regular code coverage reports, uses his own good judgement, and acts as the enforcer if needed.


答:
Code coverage can be checked automatically, despite popular opinion, Rational's Purify suite of tools included a code coverage feature. It relied on instrumenting all functions (it worked on the binaries, updating each function or call with a bit of extra code) so it could write out data that was then displayed to the user. Pretty cool technology, especially at the time.

However, even when we tried really, really hard to get 100% coverage we only managed 70% or so! So its a bit of a pointless exercise.

In the situation of writing unit tests however, I think 100% unit test coverage is even more pointless. Unit test those methods that require unit testing, not every getter or setter! Unit testing should be about verifying the tricky functions (or classes TBH) and not trying to tick boxes in some process or tool that shows nice green ticks.


问:
Game architecture - connecting different parts of the game
I do a bit of solo game development and always get stuck on some part of the architecture where I can't decide what the best way to tackle a problem is. I've just run into a good architecture problem, and I'm hoping I'll be able to use lessons learned from it down the road.  I'll abstract it down a bit to a theoretical problem:

Say my game has two abilities, "Heal Player" and "Stun Enemies". Each of the abilities is reusable with a cooldown. The game will need a separate button to activate each of the abilities.

The core class for gameplay is called GameplayCore. My GUI is all contained in an HUD class, and the enemies are all controlled by an EnemyManager. The Player class contains the player's health. GameplayCore creates and stores the HUD instance, EnemyManager instance, and Player instance.

Obviously I want to separate the UI code from the functionality code. So say on the GUI side I've got HealButton, StunButton, and HealthBar classes that define the appearance and behavior of those controls. On the functionality side, I've got the Player class with a health property, an AbstractAbility class that defines shared ability behavior including cooldown, and the HealAbility and StunAbility classes that extend it to define concrete implementations.

To keep GameplayCore from getting too bloated, I make an AbilitySet class to create and manage the HealAbility and StunAbility instances, and make an instance of AbilitySet in GameplayCore.

Here's where things start to fall apart. I want to be able to change the appearance of the buttons as their cooldowns elapse. I want the cooldown code to be self-contained in AbstractAbility, so HealAbility and StunAbility need references to their corresponding buttons. Now I need to pass those references back from HUD to GameplayCore and then into the constructor of AbilitySet so they can be passed into the constructors for the ability buttons. HealAbility needs references to the HealthBar (in HUD) and the Player (in GameplayCore). StunAbility needs a reference to EnemyManager so it can retrieve the collection of enemies to loop through and stun them. But HUD needs references to the HealAbility and StunAbility so it can call them when the buttons are pressed.

Everything has gotten pretty tangled; there is too much coupling and I'm honestly not sure where the best place to construct the ability classes is. I'm very tempted to merge all of the ability code into the ability buttons, which would greatly simplify everything, but then I'd have important functionality code mixed into a UI class.

What's a good organizational approach to this problem? What are some good architectural strategies I could use to keep the code from getting too tangled? Is my entire approach heavily flawed?

edit: I should note this particular project is in ActionScript 3, which does include an event system (with its own quirks and limitations).

答:
I have actually written a large scale game gui that implements (among many other things) precisely those actions that you are talking about. The way it worked is that the gui was completely separated from the game logic, so you could, in theory, play the game without the gui, or instantiate two guis on the same gamelogic.  Nobody ever tried that, but it was theoretically possible, and the fact that it was possible reveals an important characteristic of the design:

The gui must know the gamelogic.

The gamelogic should know absolutely nothing about the gui.

The way this is accomplished is by making everything in the gamelogic observable, and making the gui register various observers to receive notifications from the gamelogic.

So, when the user clicks the button, the button tells the gamelogic to perform the corresponding action.

The action does whatever it is supposed to do, and then it sets its own time-to-unblock to 100%.  Since the state of the action object has now changed, it issues a notification to that effect.

The gui has registered with the gamelogic to receive events about the action, so it receives this notification, it retrieves the new state of the action, and it paints the button as fully disabled.

Then on the next tick (the next iteration of the main loop of the game) the action reduces the time-to-unblock to, say, 95%, and issues another event about that change.

The gui receives this event and repaints the button to show it partially disabled.  And so on, and so forth.


问:
Naming conventions: camelCase versus underscore_case ? what are your thoughts about it?
I've been using underscore_case for about 2 years and I recently switched to camelCase because of the new job (been using the later one for about 2 months and I still think underscore_case is better suited for large projects where there are alot of programmers involved, mainly because the code is easier to read).

Now everybody at work uses camelCase because (so they say) the code looks more elegant .

What are you're thoughts about camelCase or underscore_case

p.s. please excuse my bad english

Edit

Some update first:

platform used is PHP (but I'm not expecting strict PHP platform related answers , anybody can share their thoughts on which would be the best to use , that's why I came here in the first place)

I use camelCase just as everibody else in the team (just as most of you recomend)

we use Zend Framework which also recommends camelCase

Some examples (related to PHP) :

Codeigniter framework recommends underscore_case , and honestly the code is easier to read .

ZF recomends camelCase and I'm not the only one who thinks ZF code is a tad harder to follow through.

So my question would be rephrased:

Let's take a case where you have the platform Foo which doesn't recommend any naming conventions and it's the team leader's choice to pick one. You are that team leader, why would you pick camelCase or why underscore_case?

p.s. thanks everybody for the prompt answers so far

答:
It is an interesting question, I have thought on this many times. But there is no a definite answer, I think.

Following the "cultural" conventions it a good choice. "Cultural" in this case means conventions set up in the team/company and they basically carry the language/platform conventions as well. It helps others to read/use your code easily and doesn't require additional efforts and time to get into the way of understanding your code.

Sometimes it is interesting to break accepted notations. One of my small projects (on Python) I used underscored_names for utility functions/"protected" methods, and Java-style methodNames for methods. My team was happy with it :)