问:
What is SteppedPattern?
I read this article on Jon Skeet's blog where he delves into the topic of performance on object pooling & thread safety.

In the article he makes a reference to SteppedPattern:

Most of our formatting goes through something called SteppedPattern – that’s basically one multicast delegate (with lots of actions) for formatting, and a list of delegates for parsing.

He demonstrates the above-mentioned format method:

```<code>public string Format(TResult value)
{
    StringBuilder builder = new StringBuilder();
    // This will call all the actions in the multicast delegate.
    formatActions(value, builder);
    return builder.ToString();
}
</code>```

I've never heard of the term before and can't really find any information available online for SteppedPattern (most searched have lead me to Wikipedia's Software design pattern page)

Does anybody have more information on SteppedPattern, specifically:

how it is defined, and

where it would be applied?

答:
It's just a class within Noda Time. It's not a specific design pattern that I could name.

It's used to build up a text parsing/formatting pattern which consists of a number of steps. When formatting a value, we basically start off with a value (e.g. a date) and an empty StringBuilder, then apply each step in turn, supplying each step with the current builder and the date. So for example, to come up with a value of "2015-02-24" you'd have stepped pattern with five format actions:

Append the year as a four-digit value

Append the literal '-'

Append the month-of-year as a two-digit value

Append the literal '-'

Append the day-of-month as a two-digit value

The parser works in the exact same manner, but it starts off with a cursor over the supplied text value (which each parse step advances) and a bucket for the parse steps to store data in (e.g. it first parses the year and remembers that, then skips over the '-', etc). Finally, it converts the bucket into a LocalDate (or whatever).

I have pattern parsers to convert something like "yyyy-MM-dd" into a stepped pattern (containing both parse and format actions) - the idea is that you parse the pattern specifier once, and then you can reuse the parse/format actions multiple times efficiently.

Title: What is SteppedPattern?


问:
Is it premature optimization to add database indices?
A colleague of mine today suggested that we go through all of the queries in our application and to add indices accordingly.

I feel this is premature optimisation because our application is not even released yet. I suggested to monitor for slow queries once we go live and then add indices accordingly.

What is the general consensus when designing your database, should you add a matching index every time you write a new query? Or is it better to just monitor and see how it goes?

答:
Following proven patterns for known problems (like finding a record by its ID) isn't premature anything. It's just sensible.

That said, indexes aren't always a straightforward business. It's often tough to know during the design phase which indexes your traffic will depend on and which will bottleneck write-operations. So, I'd argue for leveraging some "obvious" schema design best practices (use PK's appropriate for the designed read/write patterns and index FK's); but, don't put an index on anything else until your stress testing demands it.

ContentLicense: CC BY-SA 3.0


问:
Confused about ASP.NET Ajax, jQuery and JavaScript
Yesterday, I read couple of chapters on ASP.NET Ajax and jQuery from my ASP.NET 4 book and I found those frameworks pretty interesting and decide to learn more about them.

Today, I borrowed some books from library on Ajax and JavaScript. It seems ASP.NET Ajax is different from Ajax and jQuery seems like the "new" JavaScript.

Does it mean that I can skip JavaScript and learn jQuery directly?

On the other hand, the non-ASP.NET Ajax book I borrowed seems to apply to the client side web programming only and looks quite different from what I learned from ASP.NET Ajax. If I'm an ASP.NET developer, I guess I should stick with ASP.NET Ajax instead of client side Ajax right? What about PHP? Is there a "PHP Ajax" similar to ASP.NET Ajax?

It's not that I'm lazy to learn other tools, but I just want to focus on the right ones.

答:
There are many ways to do AJAX, and if you're doing ASP.NET, ASP.NET AJAX is one of those ways.  In recent years, I personally have gotten away from doing it that way in favor of jQuery and its implementation of AJAX.

If I'm a ASP.NET developer I guess I should stick with ASP.NET AJAX instead of client side AJAX right?

ASP.NET AJAX is still client-side ajax.  Look for the (enormous) JavaScript libraries generated for you by ASP.NET AJAX (you'll see them while running in ScriptResource.axd or WebResource.axd.

Is that means I can skip javascript and learn jQUERY directly?

jQuery is just a library of JavaScript functions.  You'll still need an understanding of JavaScript to use jQuery properly.  jQuery does abstract away some tricky JavaScript, so jQuery is, in my opinion, a good way to start using and learning JavaScript (though you'd better at least know some JavaScript before you start using it).

Is there a "PHP AJAX" similar to ASP.NET AJAX?

There are a lot of JavaScript libraries to abstract AJAX away for you.  jQuery is just one of them, but it is a very popular one, and a very robust one.

ContentLicense: CC BY-SA 2.5


问:
Is it reasonable to assume that any physical quantity can be represented by a 64-bit integer without overflow or underflow?
The original binary search algorithm in the JDK used 32-bit integers and had an overflow bug if (low + high) > INT_MAX (http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html).

If we rewrote the same binary search algorithm using (signed) 64-bit integers, can we assume that low + high will never exceed INT64_MAX because it's physically impossible to have 10^18 bytes of memory?

When using (signed) 64-bit integers to represent physical quantities, is it reasonable to assume underflow and overflow can't happen?

答:
Is it POSSIBLE for a physical quantity to not fit in 64 bits? Of course. Others have pointed out counting the number of atoms in the sun or the number of millimeters to the next galaxy. Whether such cases are relevant to your application depends on what your application is. If you're counting the number of items in any given bin in your warehouse, 16 bits would likely be sufficient. If you're compiling statistics about number of people in the world meeting various conditions, you need to be able to record billions, so you'll need more than 32 bits, at which point you'd presumably go to 64 (as few computers have built-in support for 37 bit numbers, etc). If this is a chemistry application that's counting moles worth of atoms, 64 bits will not be sufficient.

Technically, just because no computer today has 2^64 bytes of memory doesn't necessarily mean that an array index could never be more than 2^64. There's a concept called a "sparse array" where many of the elements of the array are not physically stored anywhere, and such unstored values are assumed to have some default value like null or zero. But I suppose that if you are writing a function to search an array or list of some kind, and the size of the field you are using to hold the index into the array is more than double the largest possible address, then checking for overflow when adding two indexes would not be strictly necessary.


答: You don't even need to go cosmic when combinatorics are involved. There are 2^95 possible deals in a game of bridge and that's on the small side of complexity.</p>

Title: Is it reasonable to assume that any physical quantity can be represented by a 64-bit integer without overflow or underflow?

Body:
The original binary search algorithm in the JDK used 32-bit integers and had an overflow bug if (low + high) > INT_MAX (http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html).

If we rewrote the same binary search algorithm using (signed) 64-bit integers, can we assume that low + high will never exceed INT64_MAX because it's physically impossible to have 10^18 bytes of memory?

When using (signed) 64-bit integers to represent physical quantities, is it reasonable to assume underflow and overflow can't happen?


问:
Best way to offer team member help?
I've been having a problem recently. In my recent sprints, I have found myself finishing my work well before the sprint ends (several hours in a 2 week sprint).

I am left with a lot of time and nothing to work on. I approach my team members and ask them if I can help them, but they always refuse.

I am bored during this time, and need something to do. If I finish my work early, I would like to help other people who are still working.

Is there any way I can get them to accept help so I have something to work on?

Thanks

答:
Is there any way I can get them to accept help so I have something to work on?

If you're near the end of the sprint, then the rest of your peers should be doing testing. Very few developers like doing testing, and testing doesn't require a ton of information exchange. By offering to do that stuff, you should get some help.

If you're in one of the many companies doing sorta-agile, and you're still doing development near the end of the sprint, there's likely not much you can do. Your peers are in a rush to hit their deadline and don't want to spend time telling you what needs to be done instead of just doing it.

But you should still try. During standup, offer to help out with stuff. This gives your peers (and manager and project manager) an opportunity to get your help and provides visibility to get you more work next sprint. If they do not take advantage of it (and there's no quicky bugs in the backlog) then enjoy the free time. Maybe watch some training videos or read a book. Browse the web to see what new advancements have come up. Maybe mock up a prototype for something interesting.

Or just relax and recoup your energy/morale/motivation so you can hit the next sprint at your best.

Title: Best way to offer team member help?


答:
Your problem is that you're not doing Agile. What is this "my work" you speak of, as if its been allocated to you?

In an agile environment, you should have a backlog of tasks that the team works on, individual members of the team, pick up a task, work them and then go back for more until either you run out of time or you run out of tasks (what you do then is debatable, either declare the sprint finished early, or go get some more tasks to include.. up to you).

So, the easiest way around this is t fix your processes so that you all are involved in all the tasks. If that's not the case, you can test your work, and then test it again, or declare your lack of work to all in the standups (you have them, right) so your manager can fix the problem possibly by re-allocating outstanding work.

Or, my favourite - ask to "work from home" at the end of the sprint to "get the remaining work done wthout any distractions so you can achieve the deadline". Managers like that kind of commitment ;)

Title: Best way to offer team member help?

Body:
I've been having a problem recently. In my recent sprints, I have found myself finishing my work well before the sprint ends (several hours in a 2 week sprint).

I am left with a lot of time and nothing to work on. I approach my team members and ask them if I can help them, but they always refuse.

I am bored during this time, and need something to do. If I finish my work early, I would like to help other people who are still working.

Is there any way I can get them to accept help so I have something to work on?

Thanks


问:
Do you plan to rewrite?
Whenever I work on some fairly significant piece of code, often I find that the I go through a phase of high level designing (aside: I like to use pencil and paper for this), followed by mental walkthroughs to highlight flaws and make refinements.

I see coding as another level (and finest grained) of mental walkthrough - you have to consider and cover every eventuality and this often results in further refinement of the design. Usually I find at the end of the process that enough has been learned that if I were designing and writing the code again there are things I could do better. And some of those things are perhaps too 'baked in' to the structure of the code to warrant spending the time to make the changes.

It often seems to me that in an ideal world I would always plan to go through the above process with the intention of using it as a learning process, and to plan to rewrite. Noting that much of the nuts and bolts of the code (e.g. low level subroutines) will be re-usable, so it's not a full bottom up re-write.

答:
Everything you say in your question is absolutely true, though I have a feeling that many companies don't actually go through quite the same thought process as you.

Your thought process is (more or less, for any significant piece of code) "I need a day to write it, a day to debug it, and a day to refactor it."  Your company is saying "You need a day to write it."

Your company knows that time to market is everything; a marginal piece of software that strikes gold first often wins market share over the highly-polished latecomer.  It's even worse than that; the first to market isn't always the one that strikes gold; often, a company has to go through many iterations of a product before people like it and embrace it.  King wrote almost a hundred games before Candy Crush came out, and Candy Crush represents something like 75% of their revenue.

Consequently, companies will almost always push to get the product out the door at the expense of clarity and elegance of code.  It's not the most comfortable position to be in as a software developer, but it is a challenge met by those who can balance the need to meet deadlines with the need to reduce technical debt as much as possible.

Also, remember that customer feedback is paramount.  Unreleased software doesn't get customer feedback and it doesn't make any money.  The sooner that a product gets released (consistent with stability and a reasonable feature set), the sooner you can find out what the customer really wants.  This is the big reason that agile methodologies that get early customer feedback are now favored over "big design up front" methodologies like waterfall.

Title: Do you plan to rewrite?


答:
You are describing a core component of clean coding.

No matter how well you think you design something up front, development is an iterative process that demands change. You start with the high level overview of a system and design accordingly. Maybe you go through several ideas before settling on the right idea.

Then you start diving into slightly more detail. Maybe you see that your original design needs to be changed. Maybe it needs to be replaced entirely. This is a natural consequence of a top-down approach to design that is so common in our industry.

If you develop using an iterative approach (who uses Waterfall anymore?), the details necessarily move from coarse (early sprints) to detailed (later sprints) as you code more and more functionality. This may involve changing earlier code to work better with requirements implemented in later iterations.

This is natural and good: embrace the change.

Title: Do you plan to rewrite?

Body:
Whenever I work on some fairly significant piece of code, often I find that the I go through a phase of high level designing (aside: I like to use pencil and paper for this), followed by mental walkthroughs to highlight flaws and make refinements.

I see coding as another level (and finest grained) of mental walkthrough - you have to consider and cover every eventuality and this often results in further refinement of the design. Usually I find at the end of the process that enough has been learned that if I were designing and writing the code again there are things I could do better. And some of those things are perhaps too 'baked in' to the structure of the code to warrant spending the time to make the changes.

It often seems to me that in an ideal world I would always plan to go through the above process with the intention of using it as a learning process, and to plan to rewrite. Noting that much of the nuts and bolts of the code (e.g. low level subroutines) will be re-usable, so it's not a full bottom up re-write.


答:
I feel this is premature optimisation because our application is not even released yet. I suggested to monitor for slow queries once we go live and then add indices accordingly.

You can't treat your end-users and production environment like quality-assurance.  In more words, you're saying that you'll figure it out in production.  I don't think that's the right way, and I see that approach go horribly wrong every day.

You need to keep one thing in mind, as you can't paint this with a broad brush.

What is your common workload?

That might sound obvious or dull, but it's significant in practice.  If you have 10 queries that make up 98% of your workload (quite common, believe it or not), my recommendation would be a hard analysis before production.  With realistic and representative data, make sure those 10 queries are as good as they possibly can be (perfect is a waste of valuable time, and almost not achievable).

For the other 200 queries that make up the 2% of the workload, those are ones that most likely aren't worth a ton of effort, and will make up the corner-case perf troubleshooting oddities in production.  That's also a reality, and not a terribly bad thing.  But that doesn't mean ignore indexing best practices or make estimated assumptions about data retrieval.

It is common and good practice to figure out database performance prior to production.  In fact, there is a relatively common position for this type of thing called a development DBA.

But...

Some take that too far and go crazy adding indexes "just in case".  Somebody recommends this is a missing index?  Add it, and four other variations.  Also a bad idea.  You need to not only think about your data retrieval, but what about data modification?  The more indexes you have on a table, generally speaking the more overhead you have when you modify data.

Like most things, there is a healthy balance.

As a fun little side note...  The pluralization of "Index"

"Indices" are for financial people

"Indexes" are for us

Title: Is it premature optimization to add database indices?

Body:
A colleague of mine today suggested that we go through all of the queries in our application and to add indices accordingly.

I feel this is premature optimisation because our application is not even released yet. I suggested to monitor for slow queries once we go live and then add indices accordingly.

What is the general consensus when designing your database, should you add a matching index every time you write a new query? Or is it better to just monitor and see how it goes?


答:
This is a question you need to ask on a case-by-case basis. You should not be using a general assumption that 64-bit arithmetic will not overflow, because even when correct quantities will be in a much smaller range, a malicious data source could end up giving you unreasonable quantities which could overflow, and it's better to be prepared for this situation than to be hit by it unexpectedly.

There are some cases where it makes sense to write code that depends on non-overflow of 64-bit numbers. The main class of example I know is counters, where the counter is incremented each time it's used. Even at a rate of one increment per nanosecond (not practical) it would take more than a century to overflow.

Note that while it may at first seem "always wrong in principle" to rely on "time until failure" for the correctness of a system, we do this all the time with authentication/login. Given enough time (for brute forcing), any such system (whether based on passwords, private keys, session tokens, etc.) is broken.


答:
It also depends on how many users you expect.  You should definitely do some load testing and make sure your database can keep up with 10s to 100s to 1000s of simultaneous requests. Again, it depends on how much traffic you expect, and what areas you expect to be used more than others.

In general, I would fine tune the areas that I expect the user to hit the most first. Then i'd fine tune anything that's slow from the user experience standpoint. Whenever user has to wait for something, they get a bad experience and might get turned down. Not good!


问:
Is it OK to replace html on resize?
I was asked to take over a web project. It is supposed to be a responsive website, but the former programmer didn't write the HTML/CSS with responsivity in mind and adding code to make it responsive would be a nightmare. Mobile version on m.domain.ltd is not acceptable by the client for some reason. Is it OK to just replace whole page (ajax call to server) with another content when the window is resized or loaded in, say, <780px?
Thanks</p>

答:
Replace the whole content with an ajax call?  Nevar!  That is an insane idea!

CSS3 now supports what's called "media queries" which figures out the width and height of your viewport and can set new CSS rules.

Here's a sample from one of my current projects

```<code>@media only screen and (max-width: 1260px) {
    #left_wrap {
        visibility: hidden;
    }
    #usercard {
        background: magenta;
    }
    #right_wrap {
        margin-left: 10px;
        width: 926px;
    }
    #shortWidthUserCard {
        visibility: visible;
    }
}
</code>```

Earlier rules set different values, when the width is less than 1260px for the viewport, these rules above are applied.

Be nice to the guy who's going to maintain the code after you.

Title: Is it OK to replace html on resize?

Body:
Replace the whole content with an ajax call?  Nevar!  That is an insane idea!

CSS3 now supports what's called "media queries" which figures out the width and height of your viewport and can set new CSS rules.

Here's a sample from one of my current projects

@media only screen and (max-width: 1260px) {
    #left_wrap {
        visibility: hidden;
    }
    #usercard {
        background: magenta;
    }
    #right_wrap {
        margin-left: 10px;
        width: 926px;
    }
    #shortWidthUserCard {
        visibility: visible;
    }
}

Earlier rules set different values, when the width is less than 1260px for the viewport, these rules above are applied.

Be nice to the guy who's going to maintain the code after you.


答:
No, it is not premature optimization, but it must be done correctly as any optimization should be.

Here is what I would do:

Load the database with enough test data to mimic a production load. You cannot get this 100% accurate but that is fine: just put enough data in. Does one table have a fixed amount of data? Load it up. Do you have one table that holds a lot of data, e.g. whatever table holds questions on this site? Load a few million records even if just dummy data.

Turn on profiling in your database server.

Bang away at the application using a combination of automated scripts (provides volume) and real users (they know how to break things).

Review the profiling data. Are specific queries slow? Check the explain plans and see if the database server is telling you it wants an index but it does not exist.

Database servers are complex and intelligent pieces of software. They can tell you how to optimize them if you know how to listen.

The keys are to measure performance before and after optimizing and and let the database tell you what it needs.


问:
Free Standing Functions in Global Namespace
When writing non-member, free functions, can they be placed in the global namespace so long as the signature specifies a namespace-scoped object?  For example, in the code below, is "Example 2" acceptable design?  Which is better, Example 1 or Example 2?  Does your answer change if the function is an operator overload?

Research:  I don't think this question was addressed when I took a C++ programming class (or it may have been addressed before I was ready to understand it).  I tried searching for the answer with a few different permutations of the keywords but did not get any quality hits.

```<code>#include <iostream>
#include <string>
#include <sstream>

/* Example 1 */
namespace myapp
{
    namespace xyz
    {
        class Thing
        {
        public:
            Thing( int value ) : myValue( value ) {}
            void setValue( int value ) { myValue = value; }
            int getValue() const { return myValue; }
        private:
            int myValue;
        };
        std::string toString( const Thing& thing )
        {
            std::stringstream ss;
            ss << thing.getValue();
            return ss.str();
        }
    }
}

/* Example 2 */
namespace myapp
{
    namespace xyz
    {
        class AnotherThing
        {
        public:
            AnotherThing( int value ) : myValue( value ) {}
            void setValue( int value ) { myValue = value; }
            int getValue() const { return myValue; }
        private:
            int myValue;
        };
    }
}
std::string toString( const myapp::xyz::AnotherThing& thing )
{
    std::stringstream ss;
    ss << thing.getValue();
    return ss.str();
}

int main(int argc, const char * argv[])
{
    /* Example 1 */
    myapp::xyz::Thing t( 1 );
    std::cout << myapp::xyz::toString( t ) << std::endl;

    /* Example 2 */
    myapp::xyz::AnotherThing a( 2 );
    std::cout << toString( a ) << std::endl;

    return 0;
}
</code>```

答:
boost uses a lot of free functions (free functions are a good thing). The free functions are maintained close to the namespace that involves the objects or other related classes associated with the free function. Then the free function definitions are hoisted to upper namespaces as required.

This technique gives control over the scope of free functions. “Utility” free functions can be defined in a namespace then not hoisted treating them as “private-like” functions.

In this case, Example 1 is more appropriate choice but adding hoisting declarations in the outer namespaces will allow the functions to be more easily referenced.


问:
Is it wise for a high level developer to spend time studying assembly?
It is clear that the knowledge of low level stuff is very important in our work.

But in a situation where you're already developing commercial software on a high level, and when you already have a chosen direction but don't have any assembly skill, isn't it more reasonable to focus on studying stuff related to your direction? Or is there a reason you should spend some time to learn the low-level basics anyway?

When is it too late, and when it is not? And if it is not too late, then how would one go about learning optimally (in the sense of not spending excessive time to get some depth and understanding)?

答:
Yes - Continuous, life-long learning is an essential component of a career in Software development. If you are interested in continuing to learn about programming and how to improve your craft then yes, at some point you should learn assembly as it will expose you to a completely new language and way of writing code. For the same reason, I recommend experimenting with many languages / programming styles including Ruby/Python (dynamic language), Haskell/F# (pure functional language), Lisp/Scheme (functional language), etc...

I would say that it is too late if you are no longer interested in learning more about the programming craft. For example, if you have reached the point in your career where you may soon be moving on from programming into another area such as Management, Systems Engineering, Sales/Marketing, etc. If you think you might want to move into a new area in the next few years then I would focus more on the skills necessary to develop in that area, instead of on the programming craft.


答:
Put the function in the same namespace as the classes it operates on.

This way, it does not clutter the global namespace and is properly grouped for easy understanding, but will easily be found by ADL (argument-dependent-lookup).

As an aside, that's the way swap should be implemented and used:

The standard provides the generic std::swap and various specialized variants in the namespace of the objects it operates on, and depends on the overload-set consisting of the generic version, and whatever ones are found by ADL giving the right one.

Title: Free Standing Functions in Global Namespace

Body:
When writing non-member, free functions, can they be placed in the global namespace so long as the signature specifies a namespace-scoped object?  For example, in the code below, is "Example 2" acceptable design?  Which is better, Example 1 or Example 2?  Does your answer change if the function is an operator overload?

Research:  I don't think this question was addressed when I took a C++ programming class (or it may have been addressed before I was ready to understand it).  I tried searching for the answer with a few different permutations of the keywords but did not get any quality hits.

```<code>#include <iostream>
#include <string>
#include <sstream>

/* Example 1 */
namespace myapp
{
    namespace xyz
    {
        class Thing
        {
        public:
            Thing( int value ) : myValue( value ) {}
            void setValue( int value ) { myValue = value; }
            int getValue() const { return myValue; }
        private:
            int myValue;
        };
        std::string toString( const Thing& thing )
        {
            std::stringstream ss;
            ss << thing.getValue();
            return ss.str();
        }
    }
}

/* Example 2 */
namespace myapp
{
    namespace xyz
    {
        class AnotherThing
        {
        public:
            AnotherThing( int value ) : myValue( value ) {}
            void setValue( int value ) { myValue = value; }
            int getValue() const { return myValue; }
        private:
            int myValue;
        };
    }
}
std::string toString( const myapp::xyz::AnotherThing& thing )
{
    std::stringstream ss;
    ss << thing.getValue();
    return ss.str();
}

int main(int argc, const char * argv[])
{
    /* Example 1 */
    myapp::xyz::Thing t( 1 );
    std::cout << myapp::xyz::toString( t ) << std::endl;

    /* Example 2 */
    myapp::xyz::AnotherThing a( 2 );
    std::cout << toString( a ) << std::endl;

    return 0;
}
</code>```


问:
How to connect mean.js to AWS S3
I am trying see how I can upload images and file to aws S3 via the mean.js framework. I am not sure how  the backend is linked to S3. There are no resources online about this specific framework and how it can be integrated with s3. Anyone cares to explain how?</p>

答:
MEAN.JS is a full-stack JavaScript solution that helps you build fast, robust and maintainble production web applications using MongoDB, Express, AngularJS, and Node.js.
So, I suggest looking for the right node module (use npm) which can handle the S3 connection with your node.js app</p>

Title: How to connect mean.js to AWS S3


问:
Java has the JVM, what does C have?
I know that C has a compiler but what determines execution performance?

For example in an if else block, what if the code just had all ifs instead of if elses, what determines that all the ifs will be ran? In Java it would be the JVM, but in C what is the execution compiler thing?

答:
In Java the virtual machine executes your code, but C compilers generate code that the real machine executes. To be precise, in both cases your program ends up being converted into real machine code, but in the case of Java there's a middle step of compiling to JVM bytecode.

So Java programs are converted to real instructions by the JVM when you load them, whereas C programs are already converted to real instructions by the compiler before they're run.

Title: Java has the JVM, what does C have?


问:
How do I write a REStful API's functional specifications?
I've been looking for answers about writing functional specifications for a software for a while now but I can't seem to find an answer to my specific case.

I think I understand the difference between technical and functional specs but it's still hard for me to be clear about that when I write those for a RESTful API.
To me a RESTful API is a simple bridge between databases and HTTP-based clients to access data in those databases. When it comes to define the functional specs of such an API I can't seem to be correct and to me the only way is to go into details but I know I'm wrong.

When I try not to go into details there are a lot of repetitions like "Accessing [database table here] informations...." or "Modyfing [database table here] informations...." maybe there will be something like "Authenticate client using OAUTH" but that is it.
I'm probably missing something here and right now I feel like I'm completely lost when it comes to write such specs about that kind of API.

Is there a specific way to write them when it comes to such an API or is it just me completely misunderstanding the concept of functional specifications?

答: For me functional specification of WS is just use case diagram for your backend. You can describe it as set of features like ability to authenticate user, get messages list, finish user's sesion, demand something. Functional specification should describe what (bussiness) services are available through your WS and what is it built for.</p>


问:
Domain Modeling - Offerings vs. Usages
I have a question about an issue I always seem to run into when building a domain model. The issue comes up whenever a domain object is used in what I am calling an "offering" scenario and in a "usage" scenario. For example, let's take a small school.

This school offers programs of study. Each program requires that a student enroll in and complete a certain number of classess of a certain type. In other words, one program may require 2 "general education" type classess, and one "math" type coruse. Here is the domain model for this:

This is all fine so far. Now, let's consider the student enrolling in this program. The student has the option to select from 2 "general education" classess and one "math" class. Once these classes are selected they need to be associated with the program the student is enrolled in. Here is a domain model for this:

Both of these domain models seem fine. However, when you add them together you get something that is not clear at all. You get the following:

This is confusing because you cannot tell what relationships apply to which scenario (the "offering" or the "usage", in other words, the offered programs and the ones that a student has enrolled in). It looks like programs that the school offers might already have selected classes. Alternatively you might think that even after a student is enrolled in a class there are still class options.

Is there a general way to deal with this issue? I find that it presents itself in most businesses and therefore software projects. Are there domain modeling "patterns" for things like this?

Thanks for any help that can be provided.

答:
Actually, you discovered what Fowler would probably call a Bounded Context - the idea of splitting one domain model into two different sub-models, one for the "class options" and one for the students' choices.

Just take your third model as a blueprint for your database schema, and keep the other two models as part of the spec. Or try to draw some fences around your objects like this:

Title: Domain Modeling - Offerings vs. Usages


答:
This is a complicated subject but here's my attempt to distill what all of these things are and how they relate.

AJAX: This is a concept that involves pulling data asynchronously into a web application without reloading the entire page.  It allows for dynamic UIs such as Google Mail that act like desktop applications but run in a browser.

ASP.NET AJAX: This is a library authored by Microsoft that attempts to make the AJAX concept accessible to developers that have an ASP.NET background.  It provides methods that are similar to .NET Framework methods such as String.Format and others.  It has some overlap with JQuery but they can both be used in harmony together as they have different strengths and weaknesses.  It is important to remember that this is a client-side library and doesn't actually have a dependency on ASP.NET.  You could use ASP.NET AJAX with any server-side technology.

jQuery: This is a JavaScript library that provides a framework to make AJAX applications easy to write.  It provides a powerful selection model using a CSS-like syntax for interacting with the browser DOM.  It also abstracts away many of the differences between the different browsers and versions.  So you are almost always better off coding against jQuery as opposed to browser-specific DOM or AJAX APIs.  There is a rich ecology of jQuery plugins available which can add all sorts of powerful behavior to your web applications, without a lot of work on your part.

JavaScript: This is an interpreted language implemented by all major browsers that allows for dynamic, client-side behavior on web sites.  The language itself is pretty solid, but the different APIs that the different browsers provide make it complicated to write "raw" JavaScript effectively.  That is why there are all these libraries on top of it.

Now, as to the question of what you should learn as an ASP.NET developer.  I would recommend getting familiar with the functionality of both ASP.NET AJAX and jQuery.  Microsoft endorses both, and both are included with VS 2010.  They have different strengths and weaknesses and if you understand what those are you will be more effective with using them.

You don't have to use AJAX to do ASP.NET websites, but your websites will be more powerful and more user-friendly if you do.  And if you develop a sense for when AJAX is effective and when it isn't, you will be a better web developer.

Oh, and stay away from UpdatePanels.  That was MS's first answer to AJAX, but they are generally bad and go against a lot of the concepts that make AJAX good.  They give you a short term benefit but in the long term they are a maintainability nightmare in my experience.

Title: Confused about ASP.NET Ajax, jQuery and JavaScript

Body:
Yesterday, I read couple of chapters on ASP.NET Ajax and jQuery from my ASP.NET 4 book and I found those frameworks pretty interesting and decide to learn more about them.

Today, I borrowed some books from library on Ajax and JavaScript. It seems ASP.NET Ajax is different from Ajax and jQuery seems like the "new" JavaScript.

Does it mean that I can skip JavaScript and learn jQuery directly?

On the other hand, the non-ASP.NET Ajax book I borrowed seems to apply to the client side web programming only and looks quite different from what I learned from ASP.NET Ajax. If I'm an ASP.NET developer, I guess I should stick with ASP.NET Ajax instead of client side Ajax right? What about PHP? Is there a "PHP Ajax" similar to ASP.NET Ajax?

It's not that I'm lazy to learn other tools, but I just want to focus on the right ones.


问:
What an application should do when there is an error notifying the user of an error?
Say I have an application, and it writes (among other things) errors to a log file. It's the first place the user would be asked to go and look if there was a problem. Let's also assume that this is a critical application that cannot be allowed to just crash.

For the sake of argument we'll also say that all exceptions are being logged as well. I'm in the boat that says this is a bad idea, but we'll run with it for the sake of this fictional problem.

How should the application ideally handle the situation where it is completely unable to write to its log? Say due to a lack of disk space, exhausted file handle count, or a permissions/access issue.

Depending on the exact reason of course it may be able to partially resolve itself. If there was no free disk space for example it might be reasonable for it to trash the current log to write out a line saying its out of disk space, at the expense of losing the log contents. Although this is very unhelpful if something external is eating space and would just result in logs being emptied.

It may be prudent for it to log to an internal buffer, so that once the situation is resolved no data is lost - but left too long this'd simply munch on memory.

So what do you think, how should a fault notifying the user of an error be handled? Especially with an eye to headless/unattended applications that'd normally just monitored by looking at their logs.

答:
If Dan's comment had been an answer then I would have voted for it, but since it isn't...

There are 2 kinds of errors where recovery is pure luck, if you can even get far enough to attempt recovery. "Out of Memory" and "Out of Disk Space".  Thus, most applications don't even try to recover if either of these happen. They simply crash.

Like Dan's comment said, the only way for applications to safely and reliably handle these types of errors is by ensuring that they never occur. That requires monitoring the status of disk space and memory and when it gets below a certain threshold then the application can try to free up space. If that doesn't work (because the application isn't responsible for the loss of memory) then the application needs to perform an orderly exit before memory is exhausted.

As for what to do when writing a log entry fails. My logging always runs in a background thread and makes use of message queues. If writing the log entry fails then the LogThread will push the LogEntry back into the front of the message queue and then attempt to open a new log file for writing. If a new file is opened then proceed processing log entries from the queue as normal. If not then wait a while and try again. Not much more you can do other than keep trying.  You also want to limit the number of entries you allow in your message queue or you will eventually hit the "Out of Memory" error because all of your Log Entries are stored in memory.

I suppose other possible options include:

Write to some other type of log (e.g. Windows Application Log).

Send data out a serial port

Connect to an external error server and send messages to it

Ensure your system has backup storage (or check if any additional storage is attached) and write to it.

Check if a printer is attached and write to it.

Some boards have NVRAM, write to that.


问:
Is there any reason to use the "var" keyword in ES6?
Babel's guide to ES6 says:

let is the new var.

Apparently the only difference is that var gets scoped to the current function, while let gets scoped to the current block. There are some good examples in  this answer.

I can't see any reason to use var in ES6 code. Even if you want to scope a given variable to the whole function, you can do so with let by putting the declaration at the top of the function block, which is what you should be doing with var anyway to indicate the actual scope. And if you want to scope something more finely in an for block or something, then you can do that too.

So my instinct is to stop using var altogether when writing ES6 code.

My question is, am I wrong about this? Is there any legitimate case where var would be preferable over let?

答: I don't necessarily think you're wrong but there are caveats to using var.  Essentially, let should help developers get around JavaScript's stupidity, particularly with naming conflicts.  var, it seems, has a larger scope since it wants to go to the closes function scope.  There will be times when you need var, like when you need a temp variable to be available within the scope of a block inside of a function, otherwise, preferring let over var will help developers with naming conflicts.  On a lighter note, it's about time that ES6 introduced let.


答: In addition to what Doc Brown mentioned regarding Bounded Contexts, you might want to consider that you're colluding two different events regarding the student. They enroll in a program, but the selection of a class does not flow through the program itself. That is, You have a ProgramEnrollment for a Student and there is a separate concept of a ClassEnrollment for the Student. The Program defines a set of required courses or categories of courses that the student can select from but the enrollment is separate from the program itself.</p>

Title: Domain Modeling - Offerings vs. Usages

Body:
I have a question about an issue I always seem to run into when building a domain model. The issue comes up whenever a domain object is used in what I am calling an "offering" scenario and in a "usage" scenario. For example, let's take a small school.

This school offers programs of study. Each program requires that a student enroll in and complete a certain number of classess of a certain type. In other words, one program may require 2 "general education" type classess, and one "math" type coruse. Here is the domain model for this:

This is all fine so far. Now, let's consider the student enrolling in this program. The student has the option to select from 2 "general education" classess and one "math" class. Once these classes are selected they need to be associated with the program the student is enrolled in. Here is a domain model for this:

Both of these domain models seem fine. However, when you add them together you get something that is not clear at all. You get the following:

This is confusing because you cannot tell what relationships apply to which scenario (the "offering" or the "usage", in other words, the offered programs and the ones that a student has enrolled in). It looks like programs that the school offers might already have selected classes. Alternatively you might think that even after a student is enrolled in a class there are still class options.

Is there a general way to deal with this issue? I find that it presents itself in most businesses and therefore software projects. Are there domain modeling "patterns" for things like this?

Thanks for any help that can be provided.


答:
Apart from machine code, there is no programming language in existence which executes directly on hardware, in the sense that you can't feed it the literal source text. All real implementations must translate the source program into the language of the "machine".

For some implementations, it's translated statically. We usually call these implementations "compiled". For others, it's translated into some intermediate form, which is then translated dynamically as the program is run. We usually call these implementations "interpreted". There is a continuum of possibilities between these, and even many modern CPUs do dynamic translation as part of its execution core.

Even when your program is statically compiled long before execution, unless you're writing firmware, it's rare that the compiled code runs directly on the bare metal with nothing supporting it. The operating system provides a virtual machine for user-space programs, often providing such features as the illusion that you have a CPU all to yourself. The illusion of a flat memory space which could be larger than the physical RAM attached to the machine is even called "virtual memory".

On top of that, even when you're programming in C, there is a C virtual machine! It is traditionally referred to as "the C runtime", or CRT for short.

Because C is mostly translated directly into assembly/machine code well ahead of time (on some platforms, there may also be some threaded code, and that can be considered part of the virtual machine), the virtual machine usually only has to handle startup and shutdown.

Startup typically involves setting up the stack and heap; the operating system rarely provides these for you, and it's the job of the programming language to provide these to the programmer. On some platforms there may be some initialisation of signal handling, setting up the "main" thread in a multi-threaded environment, running global constructors on the off chance that the program has been linked to C++ code, handling dynamically linked libraries, or there may be some processing required to set up argc/argv and envp. Finally, CRT transfers control to main.

As for shutdown, many operating systems can kill a process uncleanly, so shutdown doesn't need to do very much. The main thing is to process atexit() calls for the case where the program does exit cleanly.

Title: Java has the JVM, what does C have?

Body:
I know that C has a compiler but what determines execution performance?

For example in an if else block, what if the code just had all ifs instead of if elses, what determines that all the ifs will be ran? In Java it would be the JVM, but in C what is the execution compiler thing?


答:
Doug Crockford discusses let at this point in his talk, "The Better Parts".

The point is, let avoids a source of misunderstanding, esp. for programmers with expectations set by languages with block-scope. A var has function scope (it declares a variable that's visible throughout the function) even though it looks like it has block scope.

var might possibly still be useful in an extreme case like machine-generated code, but I'm stretching hard there.

(const is also new and has block scope. After let x = {'hi': 'SE'} you can reassign to x, while after const y = x you cannot reassign to y. That's often preferrable since it keeps something from accidentally changing out from under you. But to be clear, you can still modify the object y.hi = 'SO' unless you freeze it.)

Realistically, your impression is right on for ES6: Adopt let and const. Stop using var.

(In another performance of "The Better Parts", Doug says why === was added rather than fixing the problems of ==. == produces some "surprising" results, so just adopt ===.)

A Revealing Example

Mozilla Developer Network gives an example where var does not work as intended. Their example is a realistic one that sets onclick handlers in a web page. Here's a smaller test case:

var a = [];
(function () {
   'use strict';
   for (let i = 0; i < 5; ++i) { // *** `let` works as expected ***
     a.push( function() {return i;} );
   }
} ());
console.log(a.map( function(f) {return f();} ));
// prints [0, 1, 2, 3, 4]

// Start over, but change `let` to `var`.
// prints [5, 5, 5, 5, 5]
```

<p><code>var</code> trips us up because all loop iterations share the same function-scoped <code>i</code> variable, which has the value <code>5</code> after the loop finishes.</p>

<p><br/>
<strong>Another Telling Example</strong></p>

<pre class="lang-js prettyprint-override"><code>function f(x) {
    let y = 1;
    if (x > 0) {
        let y = 2;  // `let` declares a variable in this block
    }
    return y;
}
[f(1), f(-1)]  // --> [1, 1]

// Start over, but change `let` to `var`.
// --> [2, 1]
</code>```

let declares block-scoped variables.
var confuses us by referring to the same variable throughout the function.

Title: Is there any reason to use the "var" keyword in ES6?

Body:
Babel's guide to ES6 says:

let is the new var.

Apparently the only difference is that var gets scoped to the current function, while let gets scoped to the current block. There are some good examples in  this answer.

I can't see any reason to use var in ES6 code. Even if you want to scope a given variable to the whole function, you can do so with let by putting the declaration at the top of the function block, which is what you should be doing with var anyway to indicate the actual scope. And if you want to scope something more finely in an for block or something, then you can do that too.

So my instinct is to stop using var altogether when writing ES6 code.

My question is, am I wrong about this? Is there any legitimate case where var would be preferable over let?

Body:
Doug Crockford discusses let at this point in his talk, "The Better Parts".

The point is, let avoids a source of misunderstanding, esp. for programmers with expectations set by languages with block-scope. A var has function scope (it declares a variable that's visible throughout the function) even though it looks like it has block scope.

var might possibly still be useful in an extreme case like machine-generated code, but I'm stretching hard there.

(const is also new and has block scope. After let x = {'hi': 'SE'} you can reassign to x, while after const y = x you cannot reassign to y. That's often preferrable since it keeps something from accidentally changing out from under you. But to be clear, you can still modify the object y.hi = 'SO' unless you freeze it.)

Realistically, your impression is right on for ES6: Adopt let and const. Stop using var.

(In another performance of "The Better Parts", Doug says why === was added rather than fixing the problems of ==. == produces some "surprising" results, so just adopt ===.)

A Revealing Example

Mozilla Developer Network gives an example where var does not work as intended. Their example is a realistic one that sets onclick handlers in a web page. Here's a smaller test case:

var a = [];
(function () {
   'use strict';
   for (let i = 0; i < 5; ++i) { // *** `let` works as expected ***
     a.push( function() {return i;} );
   }
} ());
console.log(a.map( function(f) {return f();} ));
// prints [0, 1, 2, 3, 4]

// Start over, but change `let` to `var`.
// prints [5, 5, 5, 5, 5]

var trips us up because all loop iterations share the same function-scoped i variable, which has the value 5 after the loop finishes.

Another Telling Example

function f(x) {
    let y = 1;
    if (x > 0) {
        let y = 2;  // `let` declares a variable in this block
    }
    return y;
}
[f(1), f(-1)]  // --> [1, 1]

// Start over, but change `let` to `var`.
// --> [2, 1]

let declares block-scoped variables.
var confuses us by referring to the same variable throughout the function.

ContentLicense: CC BY-SA 4.0


问:
How "Best" to capture State Transitions in a formal software requirements specification
Suppose you have a state transition diagram. What is the best way to "Formally" write requirement(s) that capture the state transitions depicted in the diagram.  Over the years I have used two approaches and both work, but each time I work with new people there seems to be disagreements on how best to "Formally" capture the state transitions. "Formally" capture is required because traceability matrices are used that map to "Test Cases" and "Software Units (ie. Classes and/or Modules)".

Method 1

The system shall transition between states as depicted in Figure 1 XYZ Transition Diagram.

OR

Method 2

Look at the diagram and write a requirement for each transition.

Upon power up the system shall start in the Comms-Init State.

Upon establishing communications the system shall transition to the Initialization State.

(ie. A requirement for each state transition)

The benefit to method 1 is that it is one requirement and very easy to write.

The con to method 1 is that pictures don't work well with traceability matrices and it is more difficult to verify that you've covered all the transitions.

The benefit to method 2 is that each transition can be mapped to the explicit test cases and modules in their respective traceability matrices.

The con is that it is more work writing all the extra requirements and sometimes putting into clear and accurate words what the picture clearly shows is not as easy as it sounds. Also, the additional requirements seem to add more clutter as opposed to value, which makes reading the requirements less understandable rather than more.

While I suspect the answer in the simple case like I described is that it depends on the project or it doesn't really matter. The issue on my new project is that things are slightly more complicated (there are modes in addition to states that interplay). Thus, method 2 will potentially explode into a lot of requirements.

So I am asking the question because this is one of those "practices" that I have been doing without really knowing "Why".  I don't generally like to work that way, so I am hoping that someone can point out valid reasons why one approach is "more proper" than the other and in the process I will learn the "Why", which will let me understand how best to tailor for the slightly more complicated scenarios.

答:
Only the very simplest software systems can be usefully specified:

solely in English

with one testable fact per sentence.

Most realistic software systems are going to have some user-level requirements that correspond to tens, hundreds or thousands of test cases. One example is where some external standard is referenced (e.g. 'must support all HTML 5 markup tags', or implement this standard internet routing protocol, or whatever).

This is where experience and analogy with hardware testing, even of digital electronics, can be misleading; no-one implements HTML 5 in hardware.

If you are not careful, you end up with a specification that has literally 10s of thousands of 'requirements'. Almost none of which the customer would have any idea of what they mean, in the unlikely event they were to read them. Perhaps easy to test, but that testing tells you little about whether it is correct, let alone fit for purpose.

So something has to be done, if you want to be able to deal with any system more complex than a toaster at a cost less than developing a fighter jet.

One approach is to keep the top level user requirements in English, but have them reference lower level specifications that may or may not be. So the requirement is 'you must follow this specification', where the specification can be an industry standard, another document, or a model. A model may well be displayed as a diagram, but would be understood by the tools you are using at a high-enough level to, for example, generate test cases. So you don't need to manage traceability manually.

Another is to have the English specification automatically generated from a model; this is kind of pointless, but very straightforward to do. It may even be the best approach for systems that are generally trivial but have just one complex area.


问:
Should I implement many RSS feeds or rely on the category field?
When creating a RSS feeds, one can specify categories for the feed, but also for the items. I have a situation where more than 30 categories should be used for content.

I am wondering whether I should implement 30 RSS feeds, or whether I should create 1 feed and set one the 30 category values for each item.

My concern is for end users: do RSS readers usually provide category filters, or not? Most users will only be interested in a couple of categories.

答:
As a user I'd prefer if you'd only send me what I'm interested in, so that favors the first option. Furthermore, if you have to register for your service, i'd love to see a customization feature, i.e. a personal feed.

Having only one feed makes it much obviously less work to implement, but the user will have to set up its own filters. Usually, users are reluctant to put in that much work if they are not fully convinced of the value it adds. However, most are more willing to add an rss feed, rather than register as a user.

I see how that could be seen as a discussion, but I see some value in listing pros and cons here. In the end, I'd see it as a low priority problem. Start with one feed, then add personalization features to it.


问:
Many small requests vs. few large requests (API Design)
I'm currently working on a project with an organization as follows:

Client - Gets data from the main server via REST api.

Server - Requests data from various other servers via third-party APIs

Third-party APIs - Services out of my control that provide data to the server (Reddit, Hackernews, Quora, etc.)

For the sake of argument, let's say the client first needs a list of items from each of the third-party APIs. From this list, an item will be chosen at which point the client needs to see the full content of the item as well as responses (i.e. comments) to the item. I'm trying to decide between three options:

A la Carte

In this approach, I would have 3 separate endpoints on my server: one to get the list of items, one to get the main content for an item, and one to get the responses of the item.

Pros: I never make more requests than I need to, requests should be small so generally they should be faster.

Cons: I have to make a lot of requests. After choosing an item from the list, the user may have to wait before seeing the main content and then wait even longer to see the responses

Server-side cache

In this request, I would make a single call to my server to "fetch" all the data for all sources. The data would then be cached on the server. The client would then have the same REST endpoints as before, except there wouldn't be much waiting between calls since my server already has the data and just has to feed it to the client.

Pros: Still easy to implement on the client side, but without the latency issues

Cons: A bit more involved server side, and the first call could take really really long.

Client-side cache

This scenario is similar to the previous one except the client only ever makes one request to the server: give me all of the data. From here it's the client's responsibility to save the data and use it appropriately.

Pros: Easy server implementation, very speedy after the first call

Cons: First call will be very slow, more complicated client-side implementation

I'm not sure which is the best approach, or if maybe I'm missing the obvious solution. Any advice would be greatly appreciated!

答: I have always found a few large requests to be better performing and more scalable. But there are tradeoffs in all approaches, so it depends on the needs of the server and client. You may wish to use another option, which is to have the client specify a whole range or set of data to retrieve -- not necessarily all the data, but some range, which is tuned over time to match the bandwidth available.</p>


问:
Should I use an open source client framework or create my own?
I am working at a medium sized internet company, and I was handed the task of implementing the framework for our sites rebranding.

It's quite an old (and ugly) site, and we want to update its look and feel (UI/UX) as fast as possible, but also with a good foundation for the future.

I started to check out Zurb's Foundation and Twitter's Bootstrap, and I was impressed with the features they hold (like responsiveness).

My only reservations were that we have designers made a design that will be impossible to create without massive customization, and the fact that we have some important (and ancient) HTML and JS that will be prohibitively difficult to remake with a ready made framework. So I was wondering if I should make a basic lean framework myself, that over time we can add features to, without starting to override designs and code structures that were made for similar, but different things.

答:
When you use Bootstrap you can use parts of the framework - such as responsive grid without using rest of it. It also allows you to do quite significant customization with less/scss variables. You can then merge it with your own custom parts.

Great thing about framework is that it's tested, robust, and in case of bootstrap, very comprehensive. It will take you weeks or even months to get your code to the same robustness level.

My suggestion- get bootstrap, pick parts you want (you can use their customization page or compile from source) and add only the things that bootstrap doesn't already have.


问:
Metric by which to hold developers accountable
I asked a question on lines of code per hour and got torn a new one.  So my matured follow-up question is this:

If not lines of code, then what is a good metric by which to measure (by the hour/day/unit-of-time) the effectiveness of remote programmers?

答:
Another interesting way to measure productivity would be to count automatable tests reviewed by a manager per day. The developer gets:

a point for writing an automatable test (and passing review) and adding it to the regression test suite,

a point for making them pass, while not causing any other regression test failures.

The developer and manager can jointly improve the system by:

jointly agreeing on the important areas of development and testing

independently reviewing and running the test suite.

deciding not to build a feature that has limited business benefit but requires lots of development and testing required to deliver that feature. (The most productive line of code is one that you decided not to write because it delivers no business benefit).

partitioning the system into an architecture (such as model-view-controller) which facilitates incremental feature development without breaking the whole system.

The developer cannot game the metric because:

redundant tests will be blocked by manager review.

fine-grained tests may be blocked by manager review.

fine-grained tests will improve the quality of the system.

The manager cannot game the metric because:

rejecting too many tests will lead to developer attrition.

requesting too many tests will make it hard to refuse a later deadline.

The developer cannot screw the manager because

Each delivered unit of functionality with tests must also pass the regression suite. i.e. This forces the developer to develop carefully without breaking other code.

Any claim of work must be provable by passing new tests and regression tests.

The manager cannot screw the developer because.

Each requested unit of functionality must include key test cases, and an estimate of the number of test cases needed to finish the work.

It's hard to ask for an aggressive schedule and/or free overtime when you are obviously asking for a lot of work.

Another big benefit to the manager is that he can bring on new developers and know that they will not be able to deliver code that silently breaks the system (because the regression test suite catches that).

The big downside to the manager is that it forces him to admit that his system is more complex than it seems on the 1-page description of the feature. The other downside is that the transparency of this method will make it hard to blame developers for business failure.


问:
Are deadlines Agile?
For clarity, a deadline is:

A time limit or deadline is a narrow field of time, or particular point in time, by which an objective or task must be accomplished.

From wikipedia

My whole software development career I have been doing "Agile" which everywhere has seemed to mean at least the following practices were adhered to:

Weekly or Bi-Weekly sprints

Retrospectives Sprint planning

A product owner

Scrum

User Stories

However, every project I have ever been on has insisted on setting a deadline. Given that Agile attempts to focus on adaptive planning, flexibility and change; are deadlines Agile?

My own opinion is that they are not, as I see deadlines leading to a lack of flexibility and lack of quality. Instead, I think it provides more value to focus on Sprints and early deliveries. It seems however, in every circle I have been in, this is not the case, and deadlines are viewed to go hand in hand with Agile development.

答:
TL;DR

Are deadlines [a]gile?...[D]eadlines are viewed to go hand in hand with [a]gile development.

Many answers here are likely to focus on the engineering aspects of the question. Instead, I will address this from a project management perspective.

A deadline implies a great deal of up-front planning which is not in line with agile principles. Instead, iterative development models rely on time-boxes, cadence, and release cycles that include just-in-time planning, but not the "big, up-front planning" that is generally associated with traditional project management deadlines.

It is still possible to do release planning with agile methodologies, but the plans are generally based on an estimate of the number of iterations required to meet a goal rather than management targets set by fiat. That isn't to say that shipping dates can't be set, or that goals can't be met, but the way that they are defined and met is quite different than in traditional project management methodologies.

Think Time-Boxes, Not Deadlines

However, every project I have ever been on has insisted on setting a deadline. Given that Agile attempts to focus on adaptive planning, flexibility and change; are deadlines Agile?

This is a common misunderstanding of the agile principles. Agile frameworks such as Scrum and Kanban are not focused on deadlines, but rather on time-boxing and a sustainable cadence of delivery.

In Scrum, for example, the Sprint is not a "deadline." It is a time-box which is filled with the amount of work the team estimates will fit within the time-box without overflowing it, and is then either "done" or "not done" when the time-box expires. Once gone, the time-box is gone forever; any work that is not done must be re-planned and re-estimated within a new, equally ephemeral time-box based on then-current (rather than historical) needs of the project.

The importance of the time-box is that it creates both a predictable cadence for stakeholders to review progress, and a sustainable pace for the team in which to deliver potentially-shippable increments of value. The work is incremental, and follows the cadence; the concept of a big, up-front deadline is therefore not in line with agile principles.

Release Planning Based on Time-Boxes

Perhaps the one area where people have the most difficulty mapping agile processes to traditional frameworks is in release planning. Release planning often involves either fixed-scope or fixed-date deliverables. In agile frameworks, release planning is usually done through an estimation process where scope is explicitly defined as a mutable variable, while release dates are estimated in iterations.

For example, a project may be committed to releasing v1.0 of a project at the end of 20 iterations; the scope of what is released may change over the life of the project (as scope, features, and priorities can change at the start of every Sprint), but the target dates for each release is fixed in the project plan. The team strives to deliver a potentially-shippable increment each Sprint, and the Definition of Done includes quality checks such as continuous integration to ensure that the project is in a releasable state at the end of each Sprint.

Occasionally, you will see agile projects where the scope is fixed, but because scope is the mutable variable in agile projects, the release date may change over time as the scope of each iteration adjusts, changes, or adapts to the evolving needs of the project. I certainly don't recommend the fixed-scope approach to agile teams, especially inexperienced teams, but there are times when it's the right approach.

See Also

How to Perform Agile Release Planning

Title: Are deadlines Agile?


问:
Is there a canonical book on Ruby on Rails?
I'm an experienced developer with .NET, and understand core computing concepts well (OOP, design patterns, etc) but would like to also learn rails.

Is there a book out there that's the de-facto standard for describing best practices, design methodologies, and other helpful information on Ruby on Rails? What about that book makes it special?

答:
I found the Head First book on Rails to be very useful.  I come from a .NET background as well and I was able to follow the book with very little knowledge of Ruby and no knowledge of Rails.

http://www.amazon.com/Head-First-Rails-Learners-Companion/dp/0596515774


问:
DDD - Aggregate root with large number of children
I'll preface this question by saying I am relatively new to DDD so I may be making some fundamental mistakes here!

I working on a project which involves the concepts of Accounts and Transactions (in the financial sense). An Account can have many Transactions entered against it.

It seems to me that Account and Transaction are both Entities, and that Account is an Aggregate root containing Transactions since a Transaction cannot exist without the Account.

However when I come to apply this in code I immediately hit a problem. In many situations it's not especially useful for me to have a list of every Transaction in an Account at all times. I am interested in being able to do things like calculating Account balance and enforcing invariants such as a credit limit, but I also want to be able to easily work with a subset of Transactions (eg displaying those which fall within a date range).

In the latter case, if I was using a TransactionRepository I could efficiently access just those objects I need without loading the whole (potentially very large) list. However this would allow things other than the Account to work with Transactions which means I have broken the concept of Account as aggregate root.

How do people handle this kind of situation? Do you just accept the memory and performance implications of loading a potentially huge number of children for an aggregate root?

答:
tl;dr - break the rules if you need to. DDD can't solve all problems; in fact the object ideas it gives are good advice and a good start, but really bad choices for some business problems. Consider it a hint for how to do things.

For the issue of loading all children (transaction) with the parent (account) - Looks like you've run into the n+1 problem (something to google) which many ORMs have solved.

You can solve it by lazy loading the children (transaction) - only when needed.

But is sounds like you already know that by mentioning that you can use a TransactionRepository to solve the problem.

To 'conceal' that data so that only Account can use it, you'd need to not even store it where anybody else would no how to deserialize it, like a public relational table. You could have it stored with the 'document' of account in a document DB. Either way if somebody tried hard enough they could still see the data. And 'work' with it. And when you're not looking, they will!

So you could set up permissions, but then, you have to run 'account' as a separate process.

What you really realize here is that DDD and pure use of the object model will sometimes back you into a corner. Truthfully, of course, you don't have to use the 'composition'/aggregate root to benefit from the design principles of DDD. It's just one thing you can use when you have a situation that fits in its constraints.

Somebody may say 'don't early optimize'. Here in this case, though, you know the answer - there will be enough transactions to bog down a method that will keep them all forever with the account.

The real answer is to begin standing up SOA. At my workplace we watched the Udi Dahan 'Distributed computing' videos and bought nServiceBus (just our choice). Make a service for accounts - with its own process, message queues, access to a relation database only it can see, and ... viola, you could hardcode SQL statements in the program and even throw in a couple of Cobol transaction scripts (kidding of course) but seriously have more separation of concerns than the smartest OO/Java snob could ever dream of.

I'd recommend modeling it well anyway; you can just have the benefits of aggregate root here without the problems by treating the service as a mini-bounded countext.

This has a drawback, of course. You can not just RPC (webservice, SOAP, or REST) in and out of services and between them or you get an SOA antipattern called 'the knot' due to temporal coupling. You have to use the inversion of communication pattern, a.k.a. 'Pub-Sub' which it just like event handlers and event raisers, but (1) between processes (which you can put on separate machines if they are getting overloaded on one).

the real issue is you don't want a service that needs to get data from another service to 'block' or wait - you have to fire and forget the message and let a handler elsewhere in your program pick it up to complete processing. This means you have to do your logic differently. nServicebus automates the 'saga' pattern to help with some of this, but in the end, you have to develop a different coding style. You can still do it all, just have to do it differently!

The book "SOA Patterns" by Arnon Rotem-Gal-Oz answers many questions about this. Including the usage of 'active service pattern' to periodically replicate data from outside services to your own when the need arises (many RPC would have been needed, or link is unreliable/not in the publish/subscribe ecosystem).

Just to preview, UIs do have to RPC into services. Reports are generated from a reporting database that's fed by the services' databases. Some people say reports are not needed and that the problem should be solved another way. Be skeptical of that talk.

In the end though, not all things can properly be classified into a single service. The world does not run on ravioli code! So you will have to break rules. Even if you would never have to, new devs to the project will do it when you leave it. But don't worry, if you do what you can, the 85% that follows the rules will make a program that's far more maintainable.

Wow, that was long.


问:
What layer generates commands for dependent services?
Our business works with truck drivers making pickups/deliveries of containers. The location of containers needs to be tracked.

The drivers use mobile devices to generate a "DriverReport" (a log of their trip locations, times, container pickup/drop-offs, etc.). This is currently working with a mostly CRUD design.

We wanted to maintain good SoC so we built two services:

DriverService

InventoryService

We've had the DriverService take a dependency on the InventoryService. When a new DriverReport was inserted, it would generate DTO's (based off the reports data) that could be sent to the InventoryService.

We're not using CQRS yet, but we're considering transitioning to it.

I'm struggling to understand the relationship between the services, commands and BLL. I seem to have lots of questions.

Who would be responsible for calling the inventory service?

Would it be good design for a NewTripCommandHandler to generate and send an UpdateContainerInventory command?

Or, would updating inventory for a new Trip be considered business logic? If yes, should a a domain entity for Trip generate and send an UpdateContainer command?

Or, should the mobile client generate both trip and inventory specific commands to send to the appropriate service?

Would it make more sense to take the parts specific to DriverReport inventory and merge it into the DriverService (so the dependency is broken)? Is that still good SoC? If we did this, at what layer might we start to think about the inventory? Would updating the inventory simply become a DB repository concern, or should there still be inventory specific commands and/or business logic?

I'm getting lost in the details, and it seems the more I read on the topics, the more confused I get.

答: You could consider SOA if you want to. The thing is here you're only dealing with Commands. If you add the Publish/Subscribe pattern (message queues, service bus), you can have the serives publish events/messages, and not have to know who the subscribers were; the subscribers would all get the news and operate off the message contents. </p>


问:
Why are there no java compiler alternatives to allow new functionality?
For example, a new java compiler could allow for some breaking backwards compatibility to allow for things like overloading on generic types like:

```<code>void foo(List<String> arr);
void foo(List<Integer> arr);
</code>```

Or to allow things like generics over primitive types

```<code>void foo(List<int> arr);
</code>```

Now I am not suggesting these are trivial changes, or that everyone would even use such a compiler, but I was curious why I could not find ANY alternatives to javac. Even if you never modified the bytecode spec, some of these changes (and others) could be implemented purely at compile time. If nothing else, it could allow a nice testbed to merge changes back to mainline in some fashion (I get that changing the semantics of the language means it is no longer "Java", but let's call it J++ or something).

I like Java's backwards compatibility first mentality, but I was surprised this is not an approach people have taken over completely new languages like Kotlin/Ceylon/etc.

Is there more going on here that prevents this from happening?

答: Back in 2004 Microsoft did have a product called J++. It got Microsoft involved in a bitter court battle with Sun Microsystems which Microsoft lost. A ton of stuff in the Java eco-system is heavily protected by intellectual property and trademark law, and Oracle has an army of lawyers to enforce it. One of Java's big selling points has been cross platform/cross-vendor compatibility. As someone who is currently trying to get a thick stack of libraries to all build nicely on Linux using GCC and on OS X using Clang I kind of see the value in that.</p>


问:
Implement multiple separate interfaces or interface hierarchy
I've been refactoring one of my projects recently and ran into a decision I have to make.

I have several interfaces:

Entity: Something in the game world

Actor: An Entity that can perform actions

Character: An Actor that has a name (as well as some other features I haven't determined yet

Player: A Character that is played by a human being.

The type hierarchy is currently

```<code>public interface Entity { }
public interface Actor extends Entity { }
public interface Character extends Actor { }
public interface Player extends Character { }
</code>```

The reason I have it designed this way is because a big portion of functionality will come from community-driven mods that add functionality to the game, and I want it to be as modular as possible.

Now, the decision I ran into is: Should I keep this type hierarchy, or, to allow for more robust design (possibly, I can't think of an example), implement each individually?

The current implementation details are

```<code>public class BaseEntity implements Entity { }
public class BaseActor extends BaseEntity implements Actor { }
public class BaseCharacter extends BaseActor implements Character { }
public class BasePlayer extends BaseCharacter implements Player { }
</code>```

My question is, would there be any benefit (from a design perspective) of doing something like this instead

```<code>public interface Entity { }
public interface Actor { }
public interface Character { }
public interface Player { }

public class BaseEntity implements Entity { }
public class BaseActor implements Entity, Actor { }
public class BaseCharacter implements Entity, Actor, Character { }
public class BasePlayer implements Entity, Actor, Character, Player { }
</code>```

I can't think of a good reason to do this, but someone who would use my API to make their own mod may have their own

```<code>public class FooPlayer implements Player, Foo { }
</code>```

And not want/care about the methods defined in Entity, Actor, or Character.

答: I have to imagine that your first way, that is, where BaseActor extends BaseEntity and implements Actor, would be the preferable choice. Having your implementations extend an implementation of the parent interface would allow you to reduce code duplication, since, for example, BaseActor can inherit basic implementations of the methods in Entity from BaseEntity. If there's no reason to change what they're doing from how they're defined in BaseEntity, why redefine them again and again in every class in the hierarchy?</p>


问:
What is a "Business Intelligence" Developer?
What traits / skills does the Business Intelligence Developer role expect over a traditional Web Developer role?</p>

答:
As experts shared their opinion here what BI is.I want to digress here a bit by explaining what are the basic elements and skills they should posses to work in this area.Though I'm not expert but tried to share few ideas what I come across and past few years.Please make your counter idea and let me correct if there is difference in opinion.

A BI developer/consultant should posses these:
Must be aware of few BI tools and be expertise in one of them that he/she can claim his/her hands on experience on that.
Preferably Tableau Desktop is better to start for beginner as it's easy to learn and demanding these days.Focus on getting knowledge on tool interface then all functions and charts provided.

Later on SAS,Roambi(for ipads),Microstartegy,OBIEE,Cognos,pentaho,Tibco,Qlikview -choose any of them later on.
Apart of that learn a database(prerequisite here is DBMS and Basic SQL queries),prefer to learn DB which is best suited to play with large amount of data,learn any of Oracle,Postgre SQL,SAP HANA,MS SQL Server and last but not least Mongo DB.

One who wants to expand his career in ETL,Informatica is best tool.
Guys who is interested in analytics should be aware of m/c learning,AI,statistics,complex SQL queries,ability to write stored procs etc,as a tool SPSS is best to start with.Later learn "R"(language dedicated for statistics).

Apart of all these get basic awareness of DWH(dataware housing) like cubes,star schema,fact,dimension,OLAP vs OLTP concepts,Objectivse of a BI,ERP,CRM,DWH.

Also learn how to better use MS-Excel because clients usually keep thier data on this spreadsheet and we need to manipulate/model them to make it adeqaute to use.
Integrating/Importing/Exporting data and connecting Excel,DB(MS SQL server),Tableau.Using theobald software for SAP connection to tableau.

And most importantly better communication and interpreting skills to make other understand the things in lucid way.Business domain knowledge helps while developing project which helps you to observe things closely as you are there to make CEO reports,KPI dashboards,quick visuals and better insights.
Above all try to understand data,what they are trying to say that you can transform them in better insights using tools.After all,this is your objective as a BI developer.Along with these keep brush up with SQL area,because its equally important for all related sectors what I mentioned above.

According to me,these are the lethal combination a BI consultant/developer should be.


问:
Distributing Libraries
How are libraries typically distributed?  Because they have to be compiled with the same compiler under the same settings as the project using it, distributing the .dll, .lib, etc. seems  impractical.  Is the source code just made available for download?

答: If you are going to distribute Libraries or Applications written in C++, you will need to provide a different binary for each platform you are going to support. For example, Windows, Linux, Mac, etc. You may also need to provide different versions for each architecture, for example 32-bit Windows vs 64-bit.</p>

Title: Distributing Libraries


答:
I think this is the sort of thing you are positing does not exist:

http://pizzacompiler.sourceforge.net/

it is an existence proof of what you're looking for (but from 12 years ago -- many of the features in that "extended Java compiler" eventually migrated into the real Java compiler).  In fact, Java keeps evolving at a reasonable (okay, that's debatable) pace, so "extensions" to the language get considered and implemented in Java (see https://en.wikipedia.org/wiki/Java_version_history)

But more broadly, I think you could argue that Scala (http://www.scala-lang.org/) meets your definition.  Its broken backwards compatibility at the source level (the language is totally different), but generates output that runs on a vanilla JVM, and, more impressively, it is interoperable with standard Java libraries.

All the other JVM-based languages (like groovy, jruby, jpython, etc) also fall in this category.  See https://en.wikipedia.org/wiki/List_of_JVM_languages for a more comprehensive list.  (Note that there are a couple entries on that Wikipedia page that claim to be supersets of Java, even.)

I think anyone that would take the time to implement a Java++ would probably want to fix a lot of stuff.  And would end up creating something completely different.  A lot has been learned about language design in the last 20 years, and the JVM provides a compatibility mechanism that doesn't require source code compatibility.

Title: Why are there no java compiler alternatives to allow new functionality?

Body:
For example, a new java compiler could allow for some breaking backwards compatibility to allow for things like overloading on generic types like:

```<code>void foo(List<String> arr);
void foo(List<Integer> arr);
</code>```

Or to allow things like generics over primitive types

```<code>void foo(List<int> arr);
</code>```

Now I am not suggesting these are trivial changes, or that everyone would even use such a compiler, but I was curious why I could not find ANY alternatives to javac. Even if you never modified the bytecode spec, some of these changes (and others) could be implemented purely at compile time. If nothing else, it could allow a nice testbed to merge changes back to mainline in some fashion (I get that changing the semantics of the language means it is no longer "Java", but let's call it J++ or something).

I like Java's backwards compatibility first mentality, but I was surprised this is not an approach people have taken over completely new languages like Kotlin/Ceylon/etc.

Is there more going on here that prevents this from happening?


问:
Should a "secret access code" use the same security as a normal password?
Obviously, when you store a password, you should use something similar to bcrypt before you store it in in the database.

But I have a client who wants to add the ability to add a "secret code" to each database entry that a user will have to enter before gaining access to that entry.

The "secret key" isn't exactly as critical as a password, so should I bcrypt this secret code, or does it even need it?

答:
It looks like your client wants to use those "secret codes" as a fine-grained authorization scheme: Only people who are authorized to access those entries should know the corresponding secret code.

If that is the case, then those secret codes serve a similar purpose to passwords and should be subject to the same security standards.


答:
It depends. What is the benefit of not using encryption?

Under some circumstances, it can be cheaper to implement and debug.

Easier for admins and others to figure out a password / secret access code.

What are the drawbacks of not using encryption?

Potential legal liability, depending on the context.

Easier for admins and others to figure out a password / secret access code.

Unless this is for an environment where the security must be weak and multiple users must have access to each others passwords (these environments do exist), I think using encryption is clearly the better option.

Title: Should a "secret access code" use the same security as a normal password?

Body:
Obviously, when you store a password, you should use something similar to bcrypt before you store it in in the database.

But I have a client who wants to add the ability to add a "secret code" to each database entry that a user will have to enter before gaining access to that entry.

The "secret key" isn't exactly as critical as a password, so should I bcrypt this secret code, or does it even need it?


答:
This depends on what methods are on Player and whether or not you would have to add methods which are better on other interfaces.

E.g. getName().  If you want to call getName() on a Player, you would need to define the method there as well as in Character.

If this isn't the case then you should question whether Player //is a// Character after all.

Overall it is best if your classes model the domain properly and I would only break the hierarchy if it isn't really in the domain (if a Player isn't really a Character).

An example of when this might happen is when an inheritance exists just to save code.

For example, you may want a Vehicle which can drive so you extend BaseActor to get some of the action behaviour  when really a car is just an entity as it is the Actor using it that has does actions. (So you should probably compose an Actor inside your Vehicle which extends BaseEntity).

Title: Implement multiple separate interfaces or interface hierarchy

Body:
I've been refactoring one of my projects recently and ran into a decision I have to make.

I have several interfaces:

Entity: Something in the game world

Actor: An Entity that can perform actions

Character: An Actor that has a name (as well as some other features I haven't determined yet

Player: A Character that is played by a human being.

The type hierarchy is currently

```<code>public interface Entity { }
public interface Actor extends Entity { }
public interface Character extends Actor { }
public interface Player extends Character { }
</code>```

The reason I have it designed this way is because a big portion of functionality will come from community-driven mods that add functionality to the game, and I want it to be as modular as possible.

Now, the decision I ran into is: Should I keep this type hierarchy, or, to allow for more robust design (possibly, I can't think of an example), implement each individually?

The current implementation details are

```<code>public class BaseEntity implements Entity { }
public class BaseActor extends BaseEntity implements Actor { }
public class BaseCharacter extends BaseActor implements Character { }
public class BasePlayer extends BaseCharacter implements Player { }
</code>```

My question is, would there be any benefit (from a design perspective) of doing something like this instead

```<code>public interface Entity { }
public interface Actor { }
public interface Character { }
public interface Player { }

public class BaseEntity implements Entity { }
public class BaseActor implements Entity, Actor { }
public class BaseCharacter implements Entity, Actor, Character { }
public class BasePlayer implements Entity, Actor, Character, Player { }
</code>```

I can't think of a good reason to do this, but someone who would use my API to make their own mod may have their own

```<code>public class FooPlayer implements Player, Foo { }
</code>```

And not want/care about the methods defined in Entity, Actor, or Character.


问:
Does the usage of LINQ and Lambda Expressions lead to less readable code?
I'm having a discussion with a co-worker on Linq, I'll copy here:

Co-Worker: Lets be honest here. Linq
syntax sucks. It's confusing and
non-intuitive.

Me: oh come on, more
confusing than T-SQL?

Co-Worker: uh,
yes.

Me: it has the same basic
parts, select, where, and from

Co-Worker: Linq, to me, is a
bastardization of relational + OO.
Co-Worker: Don't get me wrong - it's
incredibly powerful, but they
repurposed SQL to use agains object
collections.

I'm of the opinion that using Linq + Lamda's is very powerful (he agrees), and also makes code easier to read (he disagrees on that point):

pickFiles = from f in pickFolder.GetFiles("*.txt")
where ValidAuditFileName.IsMatch(f.Name)
select f;
```
<p>or</p>
<pre class="lang-cs prettyprint-override"><code>var existing = from s in ActiveRecordLinq.AsQueryable<ScannedEntity>()
where s.FileName == f.FullName && s.DocumentType != "Unknown"
select s;
</code>```

or (VB code here)

   Dim notVerified = From image In images.AsParallel
     Group Join verifyFile In verifyFolder.GetFiles("*.vfy").AsParallel.Where(
      Function(v) v.Length > 0
      ).AsParallel
   On image.Name.Replace(image.Extension, ".vfy") Equals verifyFile.Name
     Into verifyList = Group
    From verify In verifyList.DefaultIfEmpty
    Where verify Is Nothing
    Select verify
```

To me this is clean and easy (at least easier than the alternatives) to read, what are your opinions on it?

答:
It depends. Obviously, T-SQL uniquely provides some DB-relational solutions. Obviously LINQ uniquely provides some OO solutions.

However; "more confusing than T-SQL?" - is discussed/asked in the initial question. This clearly implies some features that none of the existing answers address, instead accusing the (obviously SQL-acquainted) criticizer of being stuck in the past.

So although I appreciate LINQ for certain qualities, and don't greatly disagree with the existing answers here, I feel the counterpoint deserves representation:

Years after becoming familiar with LINQ, performing certain types of group operations, outer joins and non-equijoins, working with composite keys, and other operations in LINQ still make me cringe. (Especially when targeting a relational back-end with performance-sensitive questions.)

```<code>from c in categories
join p in products on c equals p.Category into ps
from p in ps.DefaultIfEmpty()
</code>```

If you think that's intuitive, more power to you. ;)

Body:
It depends. Obviously, T-SQL uniquely provides some DB-relational solutions. Obviously LINQ uniquely provides some OO solutions.

However; "more confusing than T-SQL?" - is discussed/asked in the initial question. This clearly implies some features that none of the existing answers address, instead accusing the (obviously SQL-acquainted) criticizer of being stuck in the past.

So although I appreciate LINQ for certain qualities, and don't greatly disagree with the existing answers here, I feel the counterpoint deserves representation:

Years after becoming familiar with LINQ, performing certain types of group operations, outer joins and non-equijoins, working with composite keys, and other operations in LINQ still make me cringe. (Especially when targeting a relational back-end with performance-sensitive questions.)

from c in categories
join p in products on c equals p.Category into ps
from p in ps.DefaultIfEmpty()

If you think that's intuitive, more power to you. ;)


答:
The "something like this instead" approach won't even work:

If you pass a Player interface to a function, the function will not have access to the Character, or the Actor, or the Entity functionality.  Presumably the Entity contains very important stuff, like the location of the entity in the world, so you will have a Player in your hands and you won't be able to tell where in the world it is.

Your initial approach is a very good way to go.

Interface hierarchies paralleled by object hierarchies are quite common. For example, see java's collections interfaces and implementing classes.  The NavigableMap interface extends the SortedMap interface, which in turn extends the Map interface. (And in languages which are slightly better thought out, like C#, the Map interface does not shy from extending the Collection interface.)  It is perfectly fine and very usable.

Amendment

If you would like to examine an alternative approach, consider studying the object model of Unity, which is not so heavily based on object inheritance and interface hierarchies, and instead uses the concept of components. Here is an introduction: http://gamedevelopment.tutsplus.com/articles/unity-now-youre-thinking-with-components--gamedev-12492