问:
Public API Facade with Micro Services
Consider a micro service infrastructure in which each service is responsible for one set of activities, and exposes a RESTful interface to its functionality. For example, assume a chat application.

We might have one service which is responsible for creating users, and a second service that is responsible for creating messages.

Now, we want to create a public-facing REST interface to the application. Are there any best practices for creating this public facade to the micro services? I'm interested in a couple of things, mainly:

Which layer should handle authentication/authorization (if the underlying services - do they share this data or each implement their own auth)

Clearly in this application messages are sent from users to users. However the message service can easily be written in such a way to be usable for anything. Should the public proxy be the one to determine the user information and then delegate to a message service?

答:
There are two authorization models that are common: trusted subsystems and delegation.

Trusted subsystems is an architecture in which the user creation & message creation services trust the API application to perform the user authentication & authorization. In this model, the API application is trusted (via network ACLs, tokens, x509 certificates, etc.) and can interact with both services in an unrestricted capacity.

Delegation is an alternative architecture where the API calls the microservice on behalf of the user; in such a model, both the API & the microservices would handle authorization, with the microservices validating both the identity of the API application and the claims of the user making the original request. The API validates that the user is authenticated & authorized to make the request, while the "message" microservice validates that both the application is trusted and the user is authorized to create messages.

There are tradeoffs between these two approaches; trusted subsystems is an easier architecture  easier to implement, but delegation enables more advanced security features. For your application, it is likely much easier to follow the trusted subsystem strategy, so I would strongly consider building authn/authz at the API "facade" (maybe gateway is a better word here?).

EDIT: The answer depends heavily on what the message service is doing, and what data is required for it to carry out its duties. If the message service is just routing messages in realtime to websockets, the requirements may be different than if the messages are persisted to a database. In general, though, it's possible that the service interacts with user IDs without being directly coupled to the user service (e.g. storing the messages in a table as sender_id, recipient_id, and message).

Check out this post for more on delegation and traversing layers.

Title: Public API Facade with Micro Services


问:
How do I fill in the BSD license template for multiple copyright holders?
I am involved in an open-source project with multiple copyright holders. The project is licensed under the 3-clause BSD license.  Unfortunately, the individual code files contain no reference back to their original owners (no copyright headers), but for the project as a whole a single file LICENSE.txt, which contains the BSD license text, is provided. The project also contains a separate file which identifies all copyright holders.

However, I am struggling with a pragmatic question: the first line of the BSD license is supposed to identify the copyright owner:

```<code>Copyright (c) <year>, <copyright holder>
</code>```

In our case, there is no single copyright owner (at least not for the project as a whole). So what should I put here, practically speaking? Obviously I can't just leave it out as the license itself refers to retaining "the above copyright notice". Is there a recommended way / format to list all copyright holders here, or perhaps to refer to an external list of copyright holders? We are talking 10 or more contributors by the way, some of them individuals, some companies, so it's not a short list.

I looked at how some other projects do this (e.g. Linux), but most I could find  use GPL, which does not contain the <copyright owner> bit in the license - and I have sofar failed to find a project that uses BSD and has multiple owners.

答:
In the United States, the US Government specifies in their publications the manner in which the copyright notice should be asserted.  The copyright notice shall consist of the
following three elements:

The word “Copyright”; and

the year of first publication of the work; and

the name of the owner of copyright in the work.

Since the date of publication should be the same for all authors, I would imagine that simply repeating all of the authors after the year of first publication (separated by commas) would be perfectly adequate.  That would also reinforce the idea that it is a collective work, created by multiple authors.

Full details can be found here: http://copyright.gov/title17/92chap4.pdf

Note that individual contributions to a collective work can still be copyrighted separately.  See §404 of the above linked article.  This is why contributors to the Mono Project are asked to assign copyright rights to Xamarin, so that there are no problems with subsequent assertion of copyright by individual contributors.

ContentLicense: CC BY-SA 3.0


问:
can a logic error happen way later than its cause?
For comparison, for a runtime fatal error, it is often that the cause of the error is way before the error crashes a program.

For a logic error, it doesn't crash a program. It happens when the state of the execution of the program isn't what we expect for the first time. The cause of a logic error in a program, I think, just like the cause of a runtime fatal error, is where you make correction and the program will not have the logic error. I wonder if the cause of a logic error must be where the error happens, or can be way before that?

Thanks.

答:
These are the same thing.  A runtime fatal error is (excluding malicious programmers and cosmic rays) always the result of a logic error -- somewhere, the program assumed something that wasn't true and then when trying to do simething based upon the false premise, causes a fatal error.

The assumption and its consequences can of course be widely seperated in both time and flow.


问:
Mapping multiple differing taxonomies to each other
At work we have a varied number of websites selling second-hand products. The bosses have noticed that there's often some overlap between the products sold on some of the websites and would like to syndicate content from one site to one or more of the others.

The main problem I'm having is that taxonomy on each site is different, so it's not a straight-forward task to put adverts from Site A into a known taxonomy location in Site B.

e.g. three sites sell second-hand bicycles but each site's each taxonomy is different...

Site A's taxonomy: For Sale > Sports Equipment > Bicycles

Site B's taxonomy: Bicycles > Mountain Bikes

Site C's taxonomy: Second-hand > Bicycles > Adults' Bikes > 26" Wheel

The notion is, for example, that all adverts placed on Site A would be pushed to a routing engine which would decide whether or not the advert should be pushed out to other sites, and it struck me this could be a place to do the taxonomy mapping... but I'm stumped as to an elegant way to go about it. I'm also conscious that although these taxonomies are fairly stable, they're not set in stone!

Anyone any ideas on how they'd go about approaching this problem?!

Cheers,

Adam

答:
This problem is a discipline of Information Management.
The people whom I know with skills in this area all hold PhDs which is overkill for your problem.
For a general overview of how to approach this problem, look at slides 10-15 of this presentation.
http://www.slideshare.net/HeatherHedden/mapping-merging-multilingualtaxonomies

If you are planning to merge the sites, create a one-off mapping e.g. in a spreadsheet and then restructure all the pages.
If you want to run the websites in parallel, firstly your system will need to support dynamic presentation of information, and secondly, you'll need to apply metadata to all the pages, and then configure your system to present the pages in the single new structure you want.
There are automatic tools to map, but they are intended for large projects.


问:
Are macros values, data types, identifiers, variables, constants, or ...?
Macros exist in many programming languages, for example, C.

A data type is a set of values with operations on the values. Are
macros values, or data types?

Are macros identifiers, variables, or constants?

Are macros something not belonging to a programming language,
and something that will be translated to the programming language in
the preprocessing step of compilation?

Thanks,

答:
macros have a very different meaning in C (or C++) than e.g. in Common Lisp or Scheme (or some homoiconic programming language).

In particular, in Lisp or Scheme you can have macros with some local binding scope. In C or C++ the scope is textual, always from the #define till the end of translation unit or some #undef. And C/C++ macros cannot define other macros (but you could do that in Lisp)

In C and C++, the preprocessor is the first phase of the compiler, and operates at a textual level (in particular, the C/C++ preprocessor does not see any abstract syntax tree, only lexical tokens). The compiler proper sees only preprocessed form (so your point 3 is true, and your points 1 and 2 become irrelevant). So macros are living in a different world than the values or variables. In particular, macros could be defined without even being a well formed expression or instruction, like in

```<code>int counter;
/// UGLY!
#define MY_BEGIN { counter++;
#define MY_END(N) N--; }
void myfun(void)
  MY_BEGIN printf("counter=%d\n", counter); MY_END(counter)
</code>```

But I feel that the above code is ugly!

A C or C++ compiler gives you the ability to get the preprocessed form. With GCC use e.g. gcc -C -E foo.c > foo.i to get into file foo.i (which you could inspect with some editor or pager) the preprocessed form of source file foo.c ... and read the documentation of cpp, i.e. of GCC preprocessor.

Notice that C/C++ macros are not able to generate easily any kind of code. For example, you cannot code parser generators like bison or ANTLR with only C/C++ macros (you need some external C code generating tool like bison). C++ has templates, but you cannot for instance easily code a printer generator (i.e. print all fields of some struct given as a template argument) or a serializer generator with them. Such things are possible in Lisp.

In Common Lisp, macros are homogeneous with the programming language, and are values. the evaluation and compilation process is very different from C. For example, with SBCL implementation of Common Lisp, the evaluator and compiler is part of every application, and applications in Lisp routinely build some Lisp expressions at runtime then compile them (at runtime also). So the code itself is changing at runtime!

Very grossly speaking, in Lisp macros are some kind of value (i.e. is a datatype); in Scheme or MELT (a domain specific language to extend and customize GCC), macro definitions introduce some kind of binding. (But things are in fact more subtle, so this is a simplification and is somehow "wrong"). Read about quasi-quotations.

C.Queinnec's book Lisp In Small Pieces explains that quite well. Scott's book Programming Language Pragmatics is also an interesting reading.

Body:
macros have a very different meaning in C (or C++) than e.g. in Common Lisp or Scheme (or some homoiconic programming language).

In particular, in Lisp or Scheme you can have macros with some local binding scope. In C or C++ the scope is textual, always from the #define till the end of translation unit or some #undef. And C/C++ macros cannot define other macros (but you could do that in Lisp)

In C and C++, the preprocessor is the first phase of the compiler, and operates at a textual level (in particular, the C/C++ preprocessor does not see any abstract syntax tree, only lexical tokens). The compiler proper sees only preprocessed form (so your point 3 is true, and your points 1 and 2 become irrelevant). So macros are living in a different world than the values or variables. In particular, macros could be defined without even being a well formed expression or instruction, like in

int counter;
/// UGLY!
#define MY_BEGIN { counter++;
#define MY_END(N) N--; }
void myfun(void)
  MY_BEGIN printf("counter=%d\n", counter); MY_END(counter)

But I feel that the above code is ugly!

A C or C++ compiler gives you the ability to get the preprocessed form. With GCC use e.g. gcc -C -E foo.c > foo.i to get into file foo.i (which you could inspect with some editor or pager) the preprocessed form of source file foo.c ... and read the documentation of cpp, i.e. of GCC preprocessor.

Notice that C/C++ macros are not able to generate easily any kind of code. For example, you cannot code parser generators like bison or ANTLR with only C/C++ macros (you need some external C code generating tool like bison). C++ has templates, but you cannot for instance easily code a printer generator (i.e. print all fields of some struct given as a template argument) or a serializer generator with them. Such things are possible in Lisp.

In Common Lisp, macros are homogeneous with the programming language, and are values. the evaluation and compilation process is very different from C. For example, with SBCL implementation of Common Lisp, the evaluator and compiler is part of every application, and applications in Lisp routinely build some Lisp expressions at runtime then compile them (at runtime also). So the code itself is changing at runtime!

Very grossly speaking, in Lisp macros are some kind of value (i.e. is a datatype); in Scheme or MELT (a domain specific language to extend and customize GCC), macro definitions introduce some kind of binding. (But things are in fact more subtle, so this is a simplification and is somehow "wrong"). Read about quasi-quotations.

C.Queinnec's book Lisp In Small Pieces explains that quite well. Scott's book Programming Language Pragmatics is also an interesting reading.


问:
Class hierarchy question - do you implement separate classes for the same behavior?
NOTE: The language I am using is C#.

I am currently working on a 'The Quest' mingame where there is a player and some enemies.
My design so far involves a base abstract class called 'Mover' and an interface called 'IAttacker', since the Player object and the Enemy object(s) both move and attack, albeit in different ways. However I also think this may be unnecessary because I could just create one big combination interface, 'IMoveAttack' or something like that.  Moreover, my friend who gave me the challenge recommeded that the Weapon class (the player can pick up weapons along the way which are lying on the floor) to be a subclass of Mover, even though the Weapons don't really need to move, they just need to spawn at random locations at every level.

What is the best design principle in this case?

答:
I'd suggest that you start by looking at Uncle Bob's SOLID principles.
Interface Segregation - Make sure no client has to depend on methods it doesn't use.
and Single Responsibility - Have one and only one reason to change. </p>

<p>If you can manage to implement those 5 design principles that's a good start on the way to writing good code.  The problems will be much easier to solve as well. </p>

Body:
I'd suggest that you start by looking at Uncle Bob's SOLID principles.
Interface Segregation - Make sure no client has to depend on methods it doesn't use.
and Single Responsibility - Have one and only one reason to change.

If you can manage to implement those 5 design principles that's a good start on the way to writing good code.  The problems will be much easier to solve as well.


问:
Is it bad practice to use Inheritance to associate methods with a basic container?
Basically, I have code that looks like this.  It's a typedef and a set of methods that revolve around that typedef.

```<code>class foo {
    // Foo stuff...

    // Registration Stuff
    private:
        typedef std::map<std::string, std::string> MTRegistrationParams;

        void DispatchRegistrationMessage (MTRegistrationParams const &, std::string destination_id);
        static std::string BuildRegistrationMessage (MTRegistrationParams const &, std::string message_id); // Only called by DispatchRegistrationMessage

    // more Foo stuff...
};
</code>```

I am thinking it might be clearer to just make a little mini-class, to help logically separate those methods from Foo's structure.

```<code>class foo {
    // Foo stuff...

    // Registration Stuff
    private:
        struct MTRegistrationParams : public std::map<std::string, std::string> {
            void DispatchRegistrationmessage (foo &, std::string const & destination_id);
            private:
                std::string BuildRegistrationMessage (std::string const & message_id);
    };

    // more Foo stuff...
};
</code>```

The thing is... I don't usually make derived classes unless for the sake of inheriting methods, and deriving from a standard container seems REALLY weird.

Am I being overly concerned, or is deriving from standard containers just to decorate them with methods genuinely bad practice?

答:
Deriving from a C++ standard container should look really weird, because they were never designed to be used as a base class.

The biggest source of problems is if your 'extended' container needs to override behavior of the underlying container (including the destructor!), or if your 'extended' container has additional constraints that don't exist for the underlying standard container.

When passing such an 'extended' container as a pointer/reference to a function that expects a standard container, that function can inadvertently break the invariants of the 'extended' container by calling the wrong functions of the base class. And if you happen to destruct an 'extended' container through a pointer to its base class, you land yourself in undefined behavior.

In the example of this question, the chances for such incorrect behavior are next to nil, but if you start using this pattern, it is easy to land in situations where it does matter. For that reason, it is strongly recommended not to derive from the standard containers.

Also, the DispatchRegistrationMessage method isn't that much easier to use, because now you need to pass in a Foo object and it is very inconvenient to use overloaded operators (like operator[] of std::map) on this.


答: it is fine. Because foo class is not associated logicaly with MTRegistrationParams. its is better to provide inner class. So if user want to use foo only then no need to expose MTRegistrationParams' functionalities. like iterator for list.</p>

Title: Is it bad practice to use Inheritance to associate methods with a basic container?

Body:
Basically, I have code that looks like this.  It's a typedef and a set of methods that revolve around that typedef.

```<code>class foo {
    // Foo stuff...

    // Registration Stuff
    private:
        typedef std::map<std::string, std::string> MTRegistrationParams;

        void DispatchRegistrationMessage (MTRegistrationParams const &, std::string destination_id);
        static std::string BuildRegistrationMessage (MTRegistrationParams const &, std::string message_id); // Only called by DispatchRegistrationMessage

    // more Foo stuff...
};
</code>```

I am thinking it might be clearer to just make a little mini-class, to help logically separate those methods from Foo's structure.

```<code>class foo {
    // Foo stuff...

    // Registration Stuff
    private:
        struct MTRegistrationParams : public std::map<std::string, std::string> {
            void DispatchRegistrationmessage (foo &, std::string const & destination_id);
            private:
                std::string BuildRegistrationMessage (std::string const & message_id);
    };

    // more Foo stuff...
};
</code>```

The thing is... I don't usually make derived classes unless for the sake of inheriting methods, and deriving from a standard container seems REALLY weird.

Am I being overly concerned, or is deriving from standard containers just to decorate them with methods genuinely bad practice?


答:
I guess your problem is more a linguistic one - the term "logic error" is very vague, and the term "time when it happens" can mean different things to different people.

Let's say you write a simple calculator program. It will allow you to enter something like "1+2" by the keyboard, calculate and display the result. Now you enter "1+2" and it displays not the expected value 3, but 4. So exactly "when" does this logic error happen? From the users point of view, it happens just when he or she sees the wrong result.

But the cause can be anywhere beforehand - the input data could be parsed wrong, the calculation itself could have gone wrong, or the display on the screen had a bug. So from the users point of view, the cause for the error is somewhere "before it happens". However, from a developers point of view who uses a debugger single-stepping through the program, the "state of the execution of the program" is wrong immediately at the time when the input parser delivers a wrong result, or the calculation delivers a wrong result, or the code bringing the result to the display does something wrong. So from this perspective, the logic error's cause is exactly where the internal state of the program deviates from the expected value.

Title: can a logic error happen way later than its cause?

Body:
For comparison, for a runtime fatal error, it is often that the cause of the error is way before the error crashes a program.

For a logic error, it doesn't crash a program. It happens when the state of the execution of the program isn't what we expect for the first time. The cause of a logic error in a program, I think, just like the cause of a runtime fatal error, is where you make correction and the program will not have the logic error. I wonder if the cause of a logic error must be where the error happens, or can be way before that?

Thanks.


答:
Am I being overly concerned, or is deriving from standard containers just to decorate them with methods genuinely bad practice?

No, you are right to be concerned. The std containers were not meant to be inherited, only encapsulated (and inheriting from them should be UB).

I think your final solution should be along these lines:

```<code>class MTRegistrationParams {
    std::map<std::string, std::string> data; // encapsulated
public:
    void DispatchRegistrationmessage (std::string const & destination_id);

    decltype(data.begin()) begin() { return data.begin(); }
    decltype(data.end()) end() { return data.end(); }
    decltype(data.size()) size() { return data.size(); }
    // forward ano other map methods you need, here
private:
    std::string BuildRegistrationMessage (std::string const & message_id);
};

class foo {
    // Foo stuff...

    // Registration Stuff
private:
    typedef MTRegistrationParams params;

    // more Foo stuff...
};
</code>```

Body:
Am I being overly concerned, or is deriving from standard containers just to decorate them with methods genuinely bad practice?

No, you are right to be concerned. The std containers were not meant to be inherited, only encapsulated (and inheriting from them should be UB).

I think your final solution should be along these lines:

class MTRegistrationParams {
    std::map<std::string, std::string> data; // encapsulated
public:
    void DispatchRegistrationmessage (std::string const & destination_id);

    decltype(data.begin()) begin() { return data.begin(); }
    decltype(data.end()) end() { return data.end(); }
    decltype(data.size()) size() { return data.size(); }
    // forward ano other map methods you need, here
private:
    std::string BuildRegistrationMessage (std::string const & message_id);
};

class foo {
    // Foo stuff...

    // Registration Stuff
private:
    typedef MTRegistrationParams params;

    // more Foo stuff...
};


问:
Is 'lazy' the correct term for timestamp-based skipping?
(1)

The oldmakeutility looks at timestamps, and if the output is newer than the input, it skips (pointless, time-consuming) re-compilation of e.g. C files.

The same is true for many languages and compilers. “Lazy” thumbnail generation in web aplications skips those thumbs that are newer than the source image.

“Smart” file syncing tools do the same, looking at time stamps, to reduce transfer volume.

I used to refer to this as “lazy”. However, looking at web citations, the term “lazy” in Computer Science seems to actually mean something different: „do something as late as possible“.

only load that extra part when it's necessary

initialize lazily, aka as late as needed

only evaluate that part of the equaption, when you get to it...

So is my term wrong? And what would be more correct, for all that „is-newer-based“ skip optimizations?

答:
"Lazy" usually means putting things off until the last possible moment, e.g. initializing a module only when it's actually needed, or computing only as many numbers of an infinite sequence as the user actually reads. Alternative terms are 'just-in-time' or 'on-demand'.

The key concept here is that this is only a good idea if you don't know exactly what the program will do at runtime. In practice that means that it's appropriate for interactive systems that depend on a stream of user input. If you knew exactly that a module will always be used, you might just as well initialize it on booting, because it's easier to code and doesn't make the user wait later when they're in full getting-things-done mode.

Not repeating compilations, as make does, isn't really comparable. First, whatever you want built is definitely going to be wanted - there isn't anything in the rule set that may or may not be necessary. Once you've given a target to make, you know that all preconditions will have to be satisfied. And no matter how long you wait, the source file is only going to get older, so the compilation will only get less and less necessary, so to speak.

So you don't have interactive functions, and you know exactly what is and isn't necessary to do (because knowing this is kind of make's job description. Therefore, I would say that not repeating compilations unnecessarily is just an instance of judicious caching - also a widespread practice, just a somewhat different one.


问:
Function only returns unchanged parameter, useless?
I just found this function in the project I'm working at:

```<code>  -- Just returns the text unchanged.
  -- Note: <text> may be nil, function must return nil in that case!
  function Widget:wtr(text)
      return text
  end
</code>```

Too sad, the coder does not work in the company anymore. Why would one make a function that does nothing, but returns the parameter it's called with?

Is there any use to such a function, not specified to this example, but overall in any case?

Due to

```<code>function aFunction(parameter)
    return parameter
end
</code>```

Ends in

```<code>aFunction(parameter) == parameter
</code>```

Why would I write something like

```<code>aFunction(parameter) == whatIWantToCheck
</code>```

instead of

```<code>parameter == whatIWantToCheck
</code>```

?

答:
Sure. Imagine an external API that allows you to retrieve things from somewhere that you absolutely need, but you have to specify filter criteria and output formatters for every query, even if you want all the results and want to get them exactly as stored.

Then you'd have to invent a trivial "accept everything" and a trivial "return unchanged" function to get at the data. wtr is precisely such a trivial pseudo-formatter. If you use that API a lot, it can be very useful to have this pseudo-helper function lying around rather than have to create an anonymous function whenever you query something. (You might consider calling it identity rather than wtr so that it's immediately clear it does nothing.)


问:
How to efficiently sort a recursively defined Stack?
I am trying to implement a recursively defined Stack and sort it in Java.
I don't have a particular usage of this program in mind. I found this approach of stack implementation a bit useful while implementing persistent stack.
I know Stacks are not made for sorting but one can consider using two stacks to implement a job scheduling queue which needs to be sorted for which stacks used for queue implementation must be sorted based on some resource parameters.

Is there any efficient method apart from copying the elements from Stack in array, sorting them and again pushing them on stack? (I know C/C++, Java)

```<code>//Stack definition:
Stack
{
    E element;
    Stack topOfSubStack;
}
</code>```

答:
You can use a derived mergesort

you can grab chunks of the stack and sort them separately (standard divide and conquer)

then you can simply merge as follows:

```<code>struct node{
int element;
node* next;
}

node* merge(node* begin1, node* end1, node* begin2, node* end2){

    node* head;
    node* tail;
    if(begin1==end1)return begin2;
    if(begin2==end2)return begin1;

    if(begin1->element < begin2->element){
       head = tail = begin1;
       begin1=begin1->next;
    }else{
       head = tail = begin1;
       begin2=begin2->next;
    }
    while(begin1!=end1 && begin2!=end2){

        if(begin1->element < begin2->element){
           tail->next = begin1;
           tail=tail.next;
           begin1=begin1->next;
        }else{
           tail->next = begin2;
           tail=tail.next;
           begin2=begin2->next;
        }

    }
    if(begin1==end1)tail->next=begin2;
    if(begin2==end2)tail->next=begin1;
    return head;
}
</code>```

You can split the array by starting at an increment of 1 and then grabbing chunks that large merging them 2 by 2, concatenating them and doubling the chunkLength each time.

Body:
You can use a derived mergesort

you can grab chunks of the stack and sort them separately (standard divide and conquer)

then you can simply merge as follows:

struct node{
int element;
node* next;
}

node* merge(node* begin1, node* end1, node* begin2, node* end2){

    node* head;
    node* tail;
    if(begin1==end1)return begin2;
    if(begin2==end2)return begin1;

    if(begin1->element < begin2->element){
       head = tail = begin1;
       begin1=begin1->next;
    }else{
       head = tail = begin1;
       begin2=begin2->next;
    }
    while(begin1!=end1 && begin2!=end2){

        if(begin1->element < begin2->element){
           tail->next = begin1;
           tail=tail.next;
           begin1=begin1->next;
        }else{
           tail->next = begin2;
           tail=tail.next;
           begin2=begin2->next;
        }

    }
    if(begin1==end1)tail->next=begin2;
    if(begin2==end2)tail->next=begin1;
    return head;
}

You can split the array by starting at an increment of 1 and then grabbing chunks that large merging them 2 by 2, concatenating them and doubling the chunkLength each time.


问:
Acceptable placement of the composition root using dependency injection (DI) and inversion of control (IoC) containers
I've read in several sources including Mark Seemann's 'Ploeh' blog about how the appropriate placement of the composition root of an IoC container is as close as possible to the entry point of an application.

In the .NET world, these applications seem to be commonly thought of as Web projects, WPF projects, console applications, things with a typical UI (read: not library projects).

Is it really going against this sage advice to place the composition root at the entry point of a library project, when it represents the logical entry point of a group of library projects, and the client of a project group such as this is someone else's work, whose author can't or won't add the composition root to their project (a UI project or yet another library project, even)?

I'm familiar with Ninject as an IoC container implementation, but I imagine many others work the same way in that they can scan for a module containing all the necessary binding configurations.  This means I could put a binding module in its own library project to compile with my main library project's output, and if the client wanted to change the configuration (an unlikely scenario in my case), they could drop in a replacement dll to replace the library with the binding module.

This seems to avoid the most common clients having to deal with dependency injection and composition roots at all, and would make for the cleanest API for the library project group.

Yet this seems to fly in the face of conventional wisdom on the issue.  Is it just that most of the advice out there makes the assumption that the developer has some coordination with the development of the UI project(s) as well, rather than my case, in which I'm just developing libraries for others to use?

答:
A library is supposed to be a black box with a clean domain-specific API. There's no problem with using any tools or patterns you need inside a library, including DI, as long as it does not leak to the client and constrain him in some way.

If there's a need to provide extensibility or library configuration changes, it still can be done without sharing a single composition root between the library and the client.

Whether you can justify your library depending on another 3rd party library just to implement DI in your library, is a different issue, but keep in mind that the DI pattern itself can be implemented without any dependencies.


问:
Design pattern for modifying state and notifying the other modifiers without a loop
The idea is that I have a set of properties that represent possible options in the app. These options can be modified through a variety of different ways, such as from the UI, remotely, third party, etc...

Each time one of these modifiers alters the state, the other modifiers need to be notified. E.g.: If the user marks a checkbox in the UI, the remote modifier and the third party need to be notified, so that they update their internal state.

There is no priority involved, and the state changes cannot be rejected. The only concern is to prevent the third party from receiving a notification when itself modifies the state.

Is there a good design pattern to solve these requirments?

答:
The question is a bit vague (e.g. what exactly do you mean by a third party?), but to try and answer anyway:

I think you're looking for the Observer pattern. The intent of the pattern is to allow entities to be notified when the state of some object changes, while decoupling the two sides. I.e., the observers don't know anything about the subject except that it is observable, and the subject knows nothing about the observers except that they can be notified.

You can register all the modifiers as observers to your app (whatever part of it makes the most sense and is relevant to your situation: the GUI, the Model facade if you have one, etc...), and then you can send them a notification whenever the app's state changes, while keeping all of them decoupled and keeping things flexible.

Edit: If you're using the MVC pattern, then the Model class (more accurately the facade class to the backend system) is probably your Subject that the observers will listen to, because it stores the state of the app and can notify the observers when anything changes.


问:
Long Keywords like `function` and `namespace`
In many English-based programming languages like C++ and JavaScript, there exist long keywords like function, namespace, exception (in OCaml languages) and such. Do you think shorter keywords like func should replace them? Why or why not? What about replacing them with digraph operators?

The long keywords we will be mainly talking about, but not limited to, are mainly from curly-brace imperative languages: function, namespace, implements, instanceof and synchronized (I always misspell that).
You should also show the examples from your favourite programming language.

答:
So you are proposing that we reduce code readability in exchange for saving some typing? Perhaps you might want to consider how much time you spend typing code and how much you spend reading/maintaining it.

If you are steadfast that we need concise unreadable code, I'd suggest Perl.

ContentLicense: CC BY-SA 2.5


问:
View model structuring best practise
What is the preferred convention for structuring view model properties? It is better to use generic or more specific property names?

Let's have a user, the page where this user will be displayed should be altered by user's permission. The view model could be written in two different ways:

```<code>{
    userName,
    userEmail,
    isAdmin // show/hide controls according the value of this property
}
</code>```

or

```<code>{
    userName,
    userEmail,
    enableDeleteBtn,
    showLogData,
    // many more show/enable properties which are set according user's permissions
}
</code>```

The first approach seems to smaller and easier to write, but it's less generic and the logic of displaying/hiding controls have to be changed if for example new type of user role will be introduced.

答:
I prefer the first one. Otherwise you are tying your view model to the implementation of your view, ie. putting display logic, which should live in your view into your view model.

Also the first shows why the delete button is enabled ie. it's in the language of the domain. If you look at the view and have to go through and track down why it is enabled somewhere else, then you have a bad abstraction.

Title: View model structuring best practise


问:
Changing message without redeploying / restarting application
Question: In java application, How to change error message or simple alert text without redeploying / restarting application

Closest answers  I could think up (1) is to have a new error messages in specific file in specific location say "\root\resources\messages.txt"and to create a file object for it like.

```<code>File msgFile = new File("\root\resources\messages.txt");
</code>```

msgFile.exist() will return true or false based on the result we can display pre-define message defined else where in application or use this message

(2) having a property file can sound the same but it'll be loaded only once when application is started so we have to restart

Is there anyother way to achieve this? what better place to ask than here..

答:
Obviously the message needs to be defined outside the application, so the simplest solution is to put it in a file. But you don't want to read a file every single time you want to display the alert; that's a lot of unnecessary IO. You can use Java's Watch Service API to check if the file containing the message has changed, otherwise you can continue displaying the same message from the last time you read the file.

You can find a tutorial here.


答:
Your question is sort of like asking what's the good of the number zero if whenever you add it to something you get the same value back.  An identity function is like the zero for functions.  Kind of useless by itself, but occasionally useful as part of an expression using higher-order functions, where you can take a function as a parameter or return it as a result.  That's why most functional programming languages have an id or identity in their standard library.

Put another way, it makes a handy default function.  Just like you might want to set offset = 0 as a default integer, even though that makes an offset do nothing, it might come in handy to be able to set filterFunction = identity as a default function, even though that makes the filter do nothing.

Title: Function only returns unchanged parameter, useless?

Body:
I just found this function in the project I'm working at:

```<code>  -- Just returns the text unchanged.
  -- Note: <text> may be nil, function must return nil in that case!
  function Widget:wtr(text)
      return text
  end
</code>```

Too sad, the coder does not work in the company anymore. Why would one make a function that does nothing, but returns the parameter it's called with?

Is there any use to such a function, not specified to this example, but overall in any case?

Due to

```<code>function aFunction(parameter)
    return parameter
end
</code>```

Ends in

```<code>aFunction(parameter) == parameter
</code>```

Why would I write something like

```<code>aFunction(parameter) == whatIWantToCheck
</code>```

instead of

```<code>parameter == whatIWantToCheck
</code>```

?


答:
Yes, make is lazy. It's avoiding doing work that it's determined it doesn't need to do.

From Wikipedia's page on lazy evaluation (added emphasis is mine):

lazy evaluation, or call-by-need is an evaluation strategy which delays the evaluation of an expression until its value is needed (non-strict evaluation) and which also avoids repeated evaluations

Re-running steps (compilers, linkers, loaders, preprocessors, or whatever) that have already determined to be suitably run is a clear "repeated evaluation." The whole point of the Makefile is to specify dependencies and determine what constitutes necessary or superfluous evaluation.

It's also fair to call it "incremental," "just-in-time," or "on-demand." But it's also, very much by design, lazy.

Title: Is 'lazy' the correct term for timestamp-based skipping?

Body:
(1)

The oldmakeutility looks at timestamps, and if the output is newer than the input, it skips (pointless, time-consuming) re-compilation of e.g. C files.

The same is true for many languages and compilers. “Lazy” thumbnail generation in web aplications skips those thumbs that are newer than the source image.

“Smart” file syncing tools do the same, looking at time stamps, to reduce transfer volume.

I used to refer to this as “lazy”. However, looking at web citations, the term “lazy” in Computer Science seems to actually mean something different: „do something as late as possible“.

only load that extra part when it's necessary

initialize lazily, aka as late as needed

only evaluate that part of the equaption, when you get to it...

So is my term wrong? And what would be more correct, for all that „is-newer-based“ skip optimizations?


答:
More interfaces are better than one big one.  Make sure your concrete classes do actually need the interface.  Weapon really isn't a mover.  I'd go for something like:</p>

```<code>IMover
ISpawner
IAttacker
IDefender

Character : IMover, ISpawner, IAttacker, IDefender
Player : Character
Enemy : Character
Weapon : ISpawner
</code>```

Title: Class hierarchy question - do you implement separate classes for the same behavior?

Body:
NOTE: The language I am using is C#.

I am currently working on a 'The Quest' mingame where there is a player and some enemies.
My design so far involves a base abstract class called 'Mover' and an interface called 'IAttacker', since the Player object and the Enemy object(s) both move and attack, albeit in different ways. However I also think this may be unnecessary because I could just create one big combination interface, 'IMoveAttack' or something like that.  Moreover, my friend who gave me the challenge recommeded that the Weapon class (the player can pick up weapons along the way which are lying on the floor) to be a subclass of Mover, even though the Weapons don't really need to move, they just need to spawn at random locations at every level.

What is the best design principle in this case?

Body:
More interfaces are better than one big one.  Make sure your concrete classes do actually need the interface.  Weapon really isn't a mover.  I'd go for something like:

IMover
ISpawner
IAttacker
IDefender

Character : IMover, ISpawner, IAttacker, IDefender
Player : Character
Enemy : Character
Weapon : ISpawner


答:
The most common way to handle updating messages without a redeploy/restart is via database or similar system like the file you proposed. Another option is to add functionality to the app itself to change messages, this would make use of the properties file.

Using a database is probably the best approach, especially if you already have one set up for your app the maintenance and scalability are just better here. You could use a file early on especially if you only have a few messages to store, there would be an IO hit, but it shouldn't be noticeably different than calls out to other methods of getting a dynamic message. The big problem with using a file is that the IO cost will increase as the file size increases if you store messages in a sequential manner, If you use multiple files managing the sheer number of files becomes difficult. Its possible to create a file with a fixed with for each message and keep track of the position of each message in the file to cut down IO costs of a large file (ie make a binary file), but at this point a database would be less work.

Title: Changing message without redeploying / restarting application

Body:
Question: In java application, How to change error message or simple alert text without redeploying / restarting application

Closest answers  I could think up (1) is to have a new error messages in specific file in specific location say "\root\resources\messages.txt"and to create a file object for it like.

```<code>File msgFile = new File("\root\resources\messages.txt");
</code>```

msgFile.exist() will return true or false based on the result we can display pre-define message defined else where in application or use this message

(2) having a property file can sound the same but it'll be loaded only once when application is started so we have to restart

Is there anyother way to achieve this? what better place to ask than here..


答:
It's not useless, actually it can be extremely useful, because it makes your code more uniform and flexible.

Say, for example, that you have a listing of people and a dropdown for the user to select if we wants to see "all" or just those that are "male" or "female".

You can either handle "all" as a special case, in which case you'll need an extra if and to check for this case explicitly, or you can have a filter function that just returns its parameter (e.g allows everything to pass), assigned to be used for the "all" case.


问:
How does contenteditable work?
I recently came across an article where if you enter

```<code>data:text/html,%20<html contenteditable>
</code>```

into the address bar of a browser that supports HTML5, you can type in the window.

I managed to figure out that with this you can basically write html in the address bar (it would be rather cumbersome) but
I do not understand how or why it works. What are the other functionalities of this command?

答:
The first part - data:text/html - is a Data URI that tells the browser that what follows is html, and it should parse it.

The second part -  - is the actual html, an editable html element. In HTML5 you can make any element editable with the contentEditable attribute.

Title: How does contenteditable work?

Body:
The first part - data:text/html - is a Data URI that tells the browser that what follows is html, and it should parse it.

The second part - <html contenteditable> - is the actual html, an editable html element. In HTML5 you can make any element editable with the contentEditable attribute.


答:
Whether a user role, such as admin, is allowed to see the some data (such as logs) is a business rule.

Business rules belong to the domain model.

The values of show/enable properties calculated within the domain model need to make it to the view somehow.

A viewmodel is an object designed just for that. It will contain pre-calculated values for things and decisions that should not be calculated in the presentation layer.

Title: View model structuring best practise

Body:
What is the preferred convention for structuring view model properties? It is better to use generic or more specific property names?

Let's have a user, the page where this user will be displayed should be altered by user's permission. The view model could be written in two different ways:

```<code>{
    userName,
    userEmail,
    isAdmin // show/hide controls according the value of this property
}
</code>```

or

```<code>{
    userName,
    userEmail,
    enableDeleteBtn,
    showLogData,
    // many more show/enable properties which are set according user's permissions
}
</code>```

The first approach seems to smaller and easier to write, but it's less generic and the logic of displaying/hiding controls have to be changed if for example new type of user role will be introduced.


答:
One additional scenario is similar to the use in python and C# of properties, but in languages that don't have the feature.

In general, you can declare something as just a member of the class; let's say, 'name' as a string. This means that you access it like this:

```<code>someobject.name
</code>```

Later, you decide that the name really needs to be dependent on what's in the object. So it should really be a function. Oops! Even with no arguments, that means all code that accesses it now has to be changed to

```<code>someobject.name()
</code>```

But if you have a lot of instances of this call, the chances of nothing going wrong with that is pretty low - somewhere this change won't be made, the program will crash when you get to that point, etc.

Properties in C#/Python allow you to substitute a function in for what used to be an attribute, while still allowing it to be accessed like an attribute i.e. with no change. You don't even have to have planned ahead.

If your language doesn't have that, you have to plan ahead, but you can still sort of support it the way people did before by making it a function from the beginning that doesn't do anything. In the beginning, it won't do anything interesting, and look like it should be removed, and many functions of this type are never changed. But later, if you realize that really whenever you call Widget.wtr you need to strip some special characters out, it's no big deal - it's already a function, you just add that in and you're done.

TL;DR This could just be a wise programmer planning ahead for future changes.

Body:
One additional scenario is similar to the use in python and C# of properties, but in languages that don't have the feature.

In general, you can declare something as just a member of the class; let's say, 'name' as a string. This means that you access it like this:

someobject.name

Later, you decide that the name really needs to be dependent on what's in the object. So it should really be a function. Oops! Even with no arguments, that means all code that accesses it now has to be changed to

someobject.name()

But if you have a lot of instances of this call, the chances of nothing going wrong with that is pretty low - somewhere this change won't be made, the program will crash when you get to that point, etc.

Properties in C#/Python allow you to substitute a function in for what used to be an attribute, while still allowing it to be accessed like an attribute i.e. with no change. You don't even have to have planned ahead.

If your language doesn't have that, you have to plan ahead, but you can still sort of support it the way people did before by making it a function from the beginning that doesn't do anything. In the beginning, it won't do anything interesting, and look like it should be removed, and many functions of this type are never changed. But later, if you realize that really whenever you call Widget.wtr you need to strip some special characters out, it's no big deal - it's already a function, you just add that in and you're done.

TL;DR This could just be a wise programmer planning ahead for future changes.


问:
Need help identifying a league scheduling algorithm
I am trying to create a sports league scheduler.  I am having trouble identifying an algorithm to help me efficiently fill in each slot.

Sample data to build the schedule would be:

10 teams

Each team plays each other 1 time (45 total games
required)

Each team plays no more than 1 time per day

In my testing I am using 9 days with 5 slots per day.

Combo Table (contains 45 combos)

ID

Team1ID

Team2ID

bitAssigned

Schedule Table (contains 45 time slots)

scheduleID

homeTeamID

awayTeamID

GameDate

GameTime

Right now my existing procedures fill about 90% of the slots leaving 10% of my slots empty to a scheduling conflict based off the rules above.

I loop over my schedule table in ascending date/time order.

My first slot could be Saturday at 8am.

I query a list of teams that haven't been scheduled yet.  I then make an array of possible combinations of those teams.  I then use that array to pull 1 random record from my combinations table from of combinations that haven't been scheduled yet and I place those teams on the schedule.  I then set that combination as used.

I repeat the loop over and over again and each time my list of available teams gets smaller and my array as a result is smaller too.

I'm finding that some days go fine, and on other days my final last 2 remaining teams have already played in a previous week so they are not added to the schedule again.

The only thing I havent tried yet is to "reset" the conflict days and try them over again to see if I get better placements.

Does anyone have any suggestions?

答: I think you are doing it backwards. Don't start with the schedule table, start with a table/array/whatever of all the game combinations (the 45 games). From there, it's a simple process to assign the games to a day, based on a team only playing once a day. And since matchups only happen once (Team A only plays Team B once) the scheduling is easy because you just need to make sure that the matchup hasn't already happened (the entries are "unique" that way).


问:
php make dollar optional
Is there any reason the PHP language could not be updated in a future version to make the $ prefix on variable names optional? Reasons that would break existing code?

I'm thinking it would still be required for string interpolation, like "Hello $name", but most of the time it would be optional.

For example,

```<code>$name = 'Bob';
echo "Hello $name";
</code>```

would still be valid, but so would

```<code>name = 'Bob';
echo "Hello $name";
</code>```

答: It would probably break tons of existing code. Using the sigil means variables may use the same names as keywords, functions (built-in or user-defined), classes, etc.

Title: php make dollar optional


问:
Should QA file 5 separate bugs or one bug with multiple parts in it?
The question might not be as simple as it sounds, as we have struggled with this a bit.
If there are 5 separate bugs, which can be taken care of with a single fix, then it is wasteful to take this approach. One bug might slip through the cracks, and would take away from a complete picture, or just be hidden for some time (we have several years worth of outstanding bugs, and our bug tracker sucks at searching :( ).

Now, if you file a bug of 100+ parts (such as help tooltips are missing from all 234 dialogs), then it should be treated as a project and be broken down. However, if it is a bug of 3-4 parts, then the developer would attempt to fix all 3 or 4 at once. This is where it gets interesting. What if the coder only fixes 3 or 3.5 out of 4? Should after testing a new bug be filed and old one closed? If yes, then this invites sloppy programming practices, where close enough is good enough. If the bug is to fail, then all of it has to be re-done and re-tested. Now ... what if part 1 is the size of a breadbox in terms of size and risk, part 2 is more like a car, part 3 is like a house, and so on :)

When sizing and prioritizing this bug (I must mention that we use Scrum), the house part was not noticed - who reads anything but a bug title anyway? So, it was deemed a low hanging fruit - low effort, low risk, happy user = high reward. But, we got bitten with one of them recently. What seemed to be logically the same area, was actually code in transitional state, where we are trying to deprecate one method of doing things, or one library for creating widgets with another, new and better. The problem is that we had to release mid-conversion, so we made two very different beasts look alike. Our QA folks did not know that, are not expected to know that, and so in their mind these are all the same issues.

We need to be QA-friendly - not to push back too hard or too often, but also try to give a set of heuristics which would help to decide whether to file one bug or many. I suppose the problem might lie with weak tools, where splitting and merging bugs is hard to do. However, how do you deal with this stuff in general?

P.S. In Scrum - once you committed to fixing something, it probably should be fixed. Break this rule too many times and discipline will degrade.

答: I agree that QA should not try to guess at the nature of the relationship between bugs.  If they find 5 bugs, open 5 bugs.  If they prove to have a common underlying cause and fix, they can be merged, or one can be made the canonical reference and the others closed, whatever.</p>


答:
A very common case for this is 'later added functionality'. So the programmer thought that there could be some change to that function later. Since you access it as a function and not as the parameter itself, you can easily globally change this. Lets say you have an index with:

```<code>function getIndex(index)
    return index
end
</code>```

and since your index starts at 0 this is all fine. You later change a component somewhere else, this component needs you to translate your index to start at 1. You would have to add hundreds of index+1 everywhere in your code. But with a method like this, simply say:

```<code> function getIndex(index)
    return index+1
end
</code>```

and you are fine. Functions like this can quickly lead to over-engineering but at some points they make a lot of sense!

Body:
A very common case for this is 'later added functionality'. So the programmer thought that there could be some change to that function later. Since you access it as a function and not as the parameter itself, you can easily globally change this. Lets say you have an index with:

function getIndex(index)
    return index
end

and since your index starts at 0 this is all fine. You later change a component somewhere else, this component needs you to translate your index to start at 1. You would have to add hundreds of index+1 everywhere in your code. But with a method like this, simply say:

 function getIndex(index)
    return index+1
end

and you are fine. Functions like this can quickly lead to over-engineering but at some points they make a lot of sense!


问:
Questions about UML in relation to the command pattern
http://www.oodesign.com/command-pattern.html
In reading through a tutorial about the command pattern, I came across a UML diagram that seems to omit some relationships. For the following diagram, the client instantiates a stock trade, an agent, and buy and sell stock orders. Why is it that the author omits the relationship arrow to the agent class? Why is the dashed line for <> used in place of a solid arrow like the one from Client to StockTrade?

I also compared the above diagram with the one below, which leaves out the Invoker/Agent class entirely and also uses the class CallbackTwo to aggregate Receivers.  The C# implementation has an invoker class, although the implementations in other languages don't. Does this mean the invoker relationship is implicit?

http://sourcemaking.com/design_patterns/command

http://sourcemaking.com/design_patterns/command/c-sharp-dot-net

答:
I recommend you don't take depicted diagrams too close. Depicted ones in GoF book should be referencing examples. Also, there are variations of patterns caused by environment where it is used.

The only thing we can do is formally validate it for UML and logic compliance.

At first diagram I see that designer wanted to show orders accumulation in agent instance, thus it uses "<>", but:

Inside big yellow box with code sample Client doesn't call agent.sell() and thus all holded in 'Agent' instance 'Order's (bsc, ssc) will never be processed.

Use of "<>" emphasizes that orders are holded inside 'Agent' and its relation is strong. Using of aggregation (<>) instead of simple association means more strong semantic, but I think in this certain case aggregation is not necessary. Hence, you're right, simple association (solid arrow) is good enough.

Omitting of relationship between 'Client' and 'Agent' instances is a bug. There must be dependency (dashed line with <> and\or <>) between them.

Moreover, designer was inconsistent in his decision. He redundantly placed field '+stock:StockTrace' in both 'BuyStockOrder' and 'SellStockOrder' and also added accociation between both 'BuyStockOrder' and 'SellStockOrder' and 'StockTrace'. But for similar case with 'Client' and 'StockTrace', 'Client' class doesn't contain '+stock:StockTrace' field.

At second diagram there are no invokers, thus it is assumed to be implicit :). The only thing I want to add that "also uses the class CallbackTwo to aggregate Receivers" is wrong. Word "also" is wrong.

Previous example depicted Invoker (Agent) holding Comamnds (Orders), but there Command (CallbackTwo) holds some data (Receiver).

Also, defining of both association and private field in CallbackTwo is redundant.


答: Stub functions like this are common in type-inheritance situations. The base class might do nothing useful, but derived classes might do various things with the inputs. Declaring the stub function in the base class allows all derived classes to have a function of that name, and individual derived classes to override it with something more elaborate and useful.


问:
What is a good design pattern to implement REST services on mobile?
It is easy to implement calls to API endpoints, then to parse JSON and handle the data - but what is a good design pattern for this?

Here are some ways I have tried but I feel like there should be a better way:

Create a singleton class that manages all networking code and all data parsing code for the entire application for all endpoints. Then any controller class can hit the singleton

Make network endpoint tasks straight from view controllers - using blocks within the view controller to manage responses

Consider an application that can hit an endpoint (GET) to download a list of appointments. Also consider an POST endpoint where you can send new appointments.

Data must be packaged/unpackaged in JSON and errors must be handled appropriately.

What is a good design pattern to accomplish this?

And before you downvote this post and say its too broad or subjective just look at this page:

https://softwareengineering.stackexchange.com/help/dont-ask

Some subjective questions are allowed, but “subjective” does not mean
  “anything goes”. All subjective questions are expected to be
  constructive.

A good answer to this common problem is hard to find.

答:
I would argue that the second method (direct endpoint calls from view controller) is not very future facing because of the possibility of having to extend the functionality to a bulk/automated api call that's separated from the view.

For example, what if a new requirement came up to post 100,000 appointments via your app, based on an excel input, for which the execution would have to be batched and scheduled to prevent api call limits on your target endpoint?  If your calling and handling code was baked into your view controller for a form (define and post a SINGLE appointment), you'd have to extract it into it's own class (likely singleton), extend it to ensure it can handle the bulk case, and handle responses.

Since the sending of requests is handled by a library, and the JSON parsing of the response is (perhaps?) handled by a library, the crux is determining whether to wrap all call-response logic for all endpoints into one class, or have one for each target system.

Instead of looking at get/post to an appointment api, consider a master CRM system that controls both the creation of an Invoice via ERP integration and entitlement via Product Server integration.  In this case, you have two SEPARATE apis being consumed by integration logic, but still utilizing the same library logic to request and parse the response.

My approach has been:

Separate all controller (and less importantly, view) logic for each system integration into it's own namespace within the application.  Eg)  ERP_Example, PS_Example

Abstract the contents (attributes of the request) of the integration call into a (possibly inline) class, then use JSON serialization, controlled by a dedicated, static integration class that is system-specific to make the call, parse the response, and route the success/fail logic appropriately.

Eg) ERP_InvoiceIntegration.class, PR_EntitlementIntegration.class

Then, when I need to bulkify the calls, I can simply create:

ERP_BatchableInvoiceActioner.class, PR_BatchableEntitlementsActioner.class

to handle the bulk case, and call the integration class from within each batch, knowing that the class itself will correctly route success/fail.

It also seems like this pattern can handle both synchronous and asynchronous api calls, though not as much in the bulk case, depending.

Shorter answer:  Singleton for each integration target, but not for each api call (get/post/etc)...


答:
Treat the REST API as any other data source, and create an abstraction (e.g. AppointmentRepository, etc.) that your controllers use. My examples are in Java, but I think you'll get the idea.

```<code>public interface AppointmentRepository {
    Appointment findById(String id) throws RepositoryAccessException;
    void create(Appointment appointment) throws RepositoryAccessException;
    void update(Appointment appointment) throws RepositoryAccessException;
    void delete(Appointment appointment) throws RepositoryAccessException;
}

public class RestAppointmentRepository {
    @Override
    public Appointment findById(String id) throws RepositoryAccessException {
        // make the API call
        // translate the JSON to an Appointment object
        return appointment;
    }
    // etc
}
</code>```

Using an abstraction in this way decouples your controller from the concrete source of data, so the two can change without affecting each other. Consider if in the future the REST API changes its representation of an appointment, which means your mapping code needs to change. When that mapping code is hidden behind an abstraction, there's no need to make any changes to the controller to handle the REST API change.

This approach also allows you to more easily unit-test your controller without having to worry about the REST API returning data to support your unit tests. In addition to the happy-path test, you should be testing that your controller reacts appropriately when the REST API is unavailable, i.e. when the repository method throws an exception. Take the repository interface as a dependency of the controller, and mock it in your unit test so that you can define its behavior easily.

```<code>public AppointmentController extends ViewController {
    private final AppointmentRepository appointmentRepository;

    public AppointmentController(final AppointmentRepository appointmentRepository) {
        Preconditions.checkNotNull(appointmentRepository);
        this.appointmentRepository = appointmentRepository;
    }
}
...
// unit test
AppointmentController appointmentController = new AppointmentController(mockAppointmentRepository);
</code>```

Title: What is a good design pattern to implement REST services on mobile?

Body:
It is easy to implement calls to API endpoints, then to parse JSON and handle the data - but what is a good design pattern for this?

Here are some ways I have tried but I feel like there should be a better way:

Create a singleton class that manages all networking code and all data parsing code for the entire application for all endpoints. Then any controller class can hit the singleton

Make network endpoint tasks straight from view controllers - using blocks within the view controller to manage responses

Consider an application that can hit an endpoint (GET) to download a list of appointments. Also consider an POST endpoint where you can send new appointments.

Data must be packaged/unpackaged in JSON and errors must be handled appropriately.

What is a good design pattern to accomplish this?

And before you downvote this post and say its too broad or subjective just look at this page:

https://softwareengineering.stackexchange.com/help/dont-ask

Some subjective questions are allowed, but “subjective” does not mean
  “anything goes”. All subjective questions are expected to be
  constructive.

A good answer to this common problem is hard to find.

Body:
Treat the REST API as any other data source, and create an abstraction (e.g. AppointmentRepository, etc.) that your controllers use. My examples are in Java, but I think you'll get the idea.

public interface AppointmentRepository {
    Appointment findById(String id) throws RepositoryAccessException;
    void create(Appointment appointment) throws RepositoryAccessException;
    void update(Appointment appointment) throws RepositoryAccessException;
    void delete(Appointment appointment) throws RepositoryAccessException;
}

public class RestAppointmentRepository {
    @Override
    public Appointment findById(String id) throws RepositoryAccessException {
        // make the API call
        // translate the JSON to an Appointment object
        return appointment;
    }
    // etc
}

Using an abstraction in this way decouples your controller from the concrete source of data, so the two can change without affecting each other. Consider if in the future the REST API changes its representation of an appointment, which means your mapping code needs to change. When that mapping code is hidden behind an abstraction, there's no need to make any changes to the controller to handle the REST API change.

This approach also allows you to more easily unit-test your controller without having to worry about the REST API returning data to support your unit tests. In addition to the happy-path test, you should be testing that your controller reacts appropriately when the REST API is unavailable, i.e. when the repository method throws an exception. Take the repository interface as a dependency of the controller, and mock it in your unit test so that you can define its behavior easily.

public AppointmentController extends ViewController {
    private final AppointmentRepository appointmentRepository;

    public AppointmentController(final AppointmentRepository appointmentRepository) {
        Preconditions.checkNotNull(appointmentRepository);
        this.appointmentRepository = appointmentRepository;
    }
}
...
// unit test
AppointmentController appointmentController = new AppointmentController(mockAppointmentRepository);


答:
In general, I agree with @Steven Lowe, but on the other hand I don't want to get 10 bug reports, one for each thing that's spelled wrong. I think that the right approach is for QA to use their heads - if they think it's likely that the things are all one big bug, they should be allowed to put them into one bug report. When the developer gets them, and finds out that some of them are one bug, and some are another, the developer can then issue a new bug report on the pieces he doesn't want to fix right now, and update the old bug report to just cover the bits that are fixed.

You'll have to go back and forth a bit with QA on this (because they really don't know for sure when things are related and when they aren't), but I think you'll get the best result (minimum administrative overhead) by having QA use their best judgement, and backfilling in development as needed.

Title: Should QA file 5 separate bugs or one bug with multiple parts in it?

Body:
The question might not be as simple as it sounds, as we have struggled with this a bit.
If there are 5 separate bugs, which can be taken care of with a single fix, then it is wasteful to take this approach. One bug might slip through the cracks, and would take away from a complete picture, or just be hidden for some time (we have several years worth of outstanding bugs, and our bug tracker sucks at searching :( ).

Now, if you file a bug of 100+ parts (such as help tooltips are missing from all 234 dialogs), then it should be treated as a project and be broken down. However, if it is a bug of 3-4 parts, then the developer would attempt to fix all 3 or 4 at once. This is where it gets interesting. What if the coder only fixes 3 or 3.5 out of 4? Should after testing a new bug be filed and old one closed? If yes, then this invites sloppy programming practices, where close enough is good enough. If the bug is to fail, then all of it has to be re-done and re-tested. Now ... what if part 1 is the size of a breadbox in terms of size and risk, part 2 is more like a car, part 3 is like a house, and so on :)

When sizing and prioritizing this bug (I must mention that we use Scrum), the house part was not noticed - who reads anything but a bug title anyway? So, it was deemed a low hanging fruit - low effort, low risk, happy user = high reward. But, we got bitten with one of them recently. What seemed to be logically the same area, was actually code in transitional state, where we are trying to deprecate one method of doing things, or one library for creating widgets with another, new and better. The problem is that we had to release mid-conversion, so we made two very different beasts look alike. Our QA folks did not know that, are not expected to know that, and so in their mind these are all the same issues.

We need to be QA-friendly - not to push back too hard or too often, but also try to give a set of heuristics which would help to decide whether to file one bug or many. I suppose the problem might lie with weak tools, where splitting and merging bugs is hard to do. However, how do you deal with this stuff in general?

P.S. In Scrum - once you committed to fixing something, it probably should be fixed. Break this rule too many times and discipline will degrade.


答:
The sigil for a variable in php is part of how the system works.  It conveys some information for the parser about what the thing actually is.  By keeping the variables and the functions in completely different name spaces, it allows one to have variable names that are function names without collision.

The without collision bit is kind of important in php, since it has been known to have quite a few standard functions.  This is further complicated but he fact that parentheses for functions are optional.  The parentheses are part of how other languages without sigils often separate if the identifier is a value or a function.

int foo() { return 42; }

int foo = 42;
int bar;

bar = foo;
bar = foo();
```

<p>In Java, (the code above) there is no ambiguity about which <code>foo</code> is being used in each line because the <code>()</code> are required on function calls.</p>

<p>This is not the case in php.</p>

<pre class="lang-php prettyprint-override"><code>$echo = "foo";
echo $echo;
echo($echo);
</code>```

Both of those are perfectly valid.  It is the sigil that says that one echo is a function call and the other is a variable.

So, no, the sigil for a variable cannot be made optional in php.  It is part of the type system and identifier lookup and parser.  It conveys necessary information that allows other things to be optional (like parentheses).

For fun, consider the following code (ideone) and the impact that sigils have on first class functions:

function greet($arg) { return "Hello $arg\n"; }

$greet = function($arg) { return "Greetings $arg\n"; };

echo $greet("Everyone");
echo greet("World");
```

And while there are ways of working around this in other languages that lack sigils that have first class functions, the combination of sigils and anonymous functions can be seen as making things a bit easier on the programmer and on the language designer at the same time.

Title: php make dollar optional

Body:
Is there any reason the PHP language could not be updated in a future version to make the $ prefix on variable names optional? Reasons that would break existing code?

I'm thinking it would still be required for string interpolation, like "Hello $name", but most of the time it would be optional.

For example,

```<code>$name = 'Bob';
echo "Hello $name";
</code>```

would still be valid, but so would

```<code>name = 'Bob';
echo "Hello $name";
</code>```

Body:
The sigil for a variable in php is part of how the system works.  It conveys some information for the parser about what the thing actually is.  By keeping the variables and the functions in completely different name spaces, it allows one to have variable names that are function names without collision.

The without collision bit is kind of important in php, since it has been known to have quite a few standard functions.  This is further complicated but he fact that parentheses for functions are optional.  The parentheses are part of how other languages without sigils often separate if the identifier is a value or a function.

int foo() { return 42; }

int foo = 42;
int bar;

bar = foo;
bar = foo();

In Java, (the code above) there is no ambiguity about which foo is being used in each line because the () are required on function calls.

This is not the case in php.

$echo = "foo";
echo $echo;
echo($echo);

Both of those are perfectly valid.  It is the sigil that says that one echo is a function call and the other is a variable.

So, no, the sigil for a variable cannot be made optional in php.  It is part of the type system and identifier lookup and parser.  It conveys necessary information that allows other things to be optional (like parentheses).

For fun, consider the following code (ideone) and the impact that sigils have on first class functions:

function greet($arg) { return "Hello $arg\n"; }

$greet = function($arg) { return "Greetings $arg\n"; };

echo $greet("Everyone");
echo greet("World");

And while there are ways of working around this in other languages that lack sigils that have first class functions, the combination of sigils and anonymous functions can be seen as making things a bit easier on the programmer and on the language designer at the same time.


问:
In AngularJS, why do we use scope instead of $scope in the directive link?
Just curious why whenever I see an example of a directive using a link, the parameter for scope is scope and not $scope?

This is always biting me because I'm so used to typing $scope, my brain auto-types it and I have to go back and correct it.

答:
For link, scope is not injected using Angular's dependency injection. Controllers, etc use dependency injection that relies on matching the function argument var names with something to be injected.

link has an expected function signature that has explicit arguments:

```<code>function link(scope, element, attrs) { ... }
</code>```

Whereas when you use it in a controller, angular analyzes the controllers function args explicitely by name and determines exactly how to inject the scope in the same way that angular services are injected. In the context of dependency inject, objects with a prefix of $ are considered angular provided services.

Contrasting with dependency injections use of variable names, there's nothing stopping you from calling the link arguments whatever you want just like any other function. You could call it

```<code>function link(cat, banana, aardvark) { ... }
</code>```

and it would still work...

However with controllers etc a $scope with any other name is not as sweet

```<code>angular.module('foo')
  .controller('blah', function (scope) {
  // doesn't work
...
}
</code>```

Body:
For link, scope is not injected using Angular's dependency injection. Controllers, etc use dependency injection that relies on matching the function argument var names with something to be injected.

link has an expected function signature that has explicit arguments:

function link(scope, element, attrs) { ... }

Whereas when you use it in a controller, angular analyzes the controllers function args explicitely by name and determines exactly how to inject the scope in the same way that angular services are injected. In the context of dependency inject, objects with a prefix of $ are considered angular provided services.

Contrasting with dependency injections use of variable names, there's nothing stopping you from calling the link arguments whatever you want just like any other function. You could call it

function link(cat, banana, aardvark) { ... }

and it would still work...

However with controllers etc a $scope with any other name is not as sweet

angular.module('foo')
  .controller('blah', function (scope) {
  // doesn't work
...
}


问:
Test-Driven Design is not Unit Testing
Ran across this statement by Martin Fowler circa 2002:

Unit testing in XP is often unlike classical unit testing, because in
  XP you're usually not testing each unit in isolation. You're testing
  each class and its immediate connections to its neighbors.

Is this still correct, and if so, why?

答:
11 years later I would state it this way:

Unit testing in Agile is often unlike classical unit testing, because in Agile you're usually not testing each unit in isolation. You're testing each class and its immediate connections to its neighbors.

Note: This is still distinct from integration testing where you are testing the code and its dependencies and required services.

Title: Test-Driven Design is not Unit Testing


问:
Providing friendly URLs for a website vs. realities of database IDs
We have a database of resources, be they products, blog posts or something. We need to design a URL scheme to address them, for the public website.

Here are two examples that are database ID bound:

https://www.youtube.com/watch?v=7FPS6llqhXw

http://www.amazon.co.uk/gp/product/B000NHOMSQ

Here's an example that's friendly:

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

(A little glimpse into my browsing life there)

I like the friendly URLs since you have an idea about what's on the end of the URL when you hover or see it in an email or document. It's better for SEO, or it used to be.

What happens when the document or product is renamed? Either because it changed (Wiki may not change but our resources could) or due to a typo, right? Our resources are very technical, long words and error prone.

Also, we have a database ID, which is a number. Let's look at an idea for an address of a video using a pretend rental store:

http://vidsyeah.com/video/sliding-doors/287171

The ID is obvious and is used in the DB look-up. Fine.

The sliding-doors bit is non-unique and just generated from the video title, it could be verified on GET, so if gliding-doors was entered and doesn't match what's really in doc 287171 it responds 404.

Or maybe it could be ignored, allowing humans to stick whatever they like in there, if someone ever cared to. So this URL would also work:

http://vidsyeah.com/video/anything-at_all/287171

The issue with verifying the friendly part is, as mentioned, the problem of renaming or typo correction. If the name changed, and in our domain that does happen, we don't want to break the URLs that are out there, so should we:

Just not verify the friendly part.

Verify, but add a 'history' of friendly parts to the database record so any previous friendly IDs still work!

Your thoughts and ideas are welcome.

Luke

答:
I have used two different scenario's in the past.

/id/some-slug where the id is used to lookup, the slug not. Thus the slug can be anything. But, when the slug does not match with the actual slug, the user is redirected to the current version.

/permalink for cases where we didn't want an id in the url or where the url should never change, even though there is an id available (see [1] and [2]). Of course, in this case the permalink is used for the lookup. Both the current slug and the permalink (the first slug) are stored in the database.

In neither of these ways you need to keep a history of slugs in your database, which would get problematic very soon.

ps: In the second case you'll need some very specific routing to keep social credits:

if you want, redirect users to the current (non permalink) url

have the permalink used as the url in the social buttons

always redirect the facebook crawler to the permalink

See [1] and [2] again.


问:
How to tell the View to create a cookie?
I have a LoginService class with loginUser($email, $password, $remember = false) method in the application layer of my model layer.

Now, if $remember is true it needs to create a persistent user login cookie on the client's browser, but since that is the responsibility of the View, what is a good way of reaching the view through the controller to let it know it should create the cookie for it?

答:
A View should not touch cookies. The place of the stored data (cookie, database, user table) is an implementation detail that a view should not know about, basically a CRUD object.

Also registerUser($email, $remember = false) is not a good method signature. What if you have to pass more data for one of the cases later? This is hard to extend. Write different methods for different actions instead, register_permanent( $email ) and register_temporary( $email ) in this case.

The registration model should not know about cookies either, because cookies are a details of a web request, and the output layer (web, console, whatever) is another implementation detail that should not affect other business rules.
The registration knows only what checks to apply for a registration. The CRUD object should be passed as an abstract dependency (an interface), so you can mock it easily in your unit tests.

An overly simplified solution could look like this:

```<code>interface Login_Status
{
    public function log_in( $name, $data );

    public function log_out( $name );

    public function get_data( $name );
}

class Login_Cookie implements Login_Status
{
    public function log_in( $name, $data )
    {
        setcookie( $name, $data, time() + 3600 * 24 * 30 );
    }

    public function log_out( $name )
    {
        setcookie( $name, '', time() + 3600 * 24 * 30 );
    }

    public function get_data( $name )
    {
        if ( ! empty ( $_COOKIE[ $name ] ) )
            return $_COOKIE[ $name ];

        return '';
    }
}

class User_Registration
{
    /**
     * @type Login_Status
     */
    private $login_Status;

    public function __construct( Login_Status $login_Status )
    {
        $this->login_Status = $login_Status;
    }

    public function register_permanent( $email )
    {
        // do something with $email, maybe this:
        $hash = hash( 'whirlpool', $email . 'some_salt' );
        // then …
        $this->login_Status->log_in( 'login', $hash );
    }
}
</code>```

These models are controlled by … well … the controller. The view is not involved at all.

You could say that HTTP headers are output and therefore views. This is usually correct. But in this case, the view would just be a thin wrapper around setcookie() with some overhead (a dependency on a model). For the sake of simplicity, I would not separate out setcookie().

Body:
A View should not touch cookies. The place of the stored data (cookie, database, user table) is an implementation detail that a view should not know about, basically a CRUD object.

Also registerUser($email, $remember = false) is not a good method signature. What if you have to pass more data for one of the cases later? This is hard to extend. Write different methods for different actions instead, register_permanent( $email ) and register_temporary( $email ) in this case.

The registration model should not know about cookies either, because cookies are a details of a web request, and the output layer (web, console, whatever) is another implementation detail that should not affect other business rules.
The registration knows only what checks to apply for a registration. The CRUD object should be passed as an abstract dependency (an interface), so you can mock it easily in your unit tests.

An overly simplified solution could look like this:

interface Login_Status
{
    public function log_in( $name, $data );

    public function log_out( $name );

    public function get_data( $name );
}

class Login_Cookie implements Login_Status
{
    public function log_in( $name, $data )
    {
        setcookie( $name, $data, time() + 3600 * 24 * 30 );
    }

    public function log_out( $name )
    {
        setcookie( $name, '', time() + 3600 * 24 * 30 );
    }

    public function get_data( $name )
    {
        if ( ! empty ( $_COOKIE[ $name ] ) )
            return $_COOKIE[ $name ];

        return '';
    }
}

class User_Registration
{
    /**
     * @type Login_Status
     */
    private $login_Status;

    public function __construct( Login_Status $login_Status )
    {
        $this->login_Status = $login_Status;
    }

    public function register_permanent( $email )
    {
        // do something with $email, maybe this:
        $hash = hash( 'whirlpool', $email . 'some_salt' );
        // then …
        $this->login_Status->log_in( 'login', $hash );
    }
}

These models are controlled by … well … the controller. The view is not involved at all.

You could say that HTTP headers are output and therefore views. This is usually correct. But in this case, the view would just be a thin wrapper around setcookie() with some overhead (a dependency on a model). For the sake of simplicity, I would not separate out setcookie().


答: TDD or Test-Driven Development is where you would create a failed unit test on a method first, write the method code second, then see if the test passes. If it doesn't, you refactor the code until it passes and then move on to your next unit test of the same method. You don't have to use TDD to create unit tests. You can write the method first and then create unit tests for it second making sure each test passes. If you're testing a class, you run in to integration testing because it may call out to a data layer which communicates with the database. To avoid that you'll need to use a mocking framework so that your tests can be automated and not rely on connections outside of your application.</p>

Title: Test-Driven Design is not Unit Testing

Body:
Ran across this statement by Martin Fowler circa 2002:

Unit testing in XP is often unlike classical unit testing, because in
  XP you're usually not testing each unit in isolation. You're testing
  each class and its immediate connections to its neighbors.

Is this still correct, and if so, why?


问:
Is a long list of parameter checks an anti-pattern?
Background:  I'm working on an application that will manage backup generators.  These generators need to be able to be "linked" together.  For example, Generator B might serve as a backup for Generator A.  If A fails, then the software turns B on.  Or they might be linked in a load-sharing configuration, where Generator A and B run together, and share the load.

I'm making a function that will make the link, given 2 generators and the type of link desired.

```<code>public void LinkGenerators(Generator A, Generator B, Type linkType);
</code>```

In writing my tests, I've come with a large number of invalid parameter configurations.  My LinkGenerators function looks like this:

```<code>public void LinkGenerators(Generator A, Generator B, Type linkType)
{
     if (linkType.BaseType != typeof(Link))
     {
        throw new ArgumentException("linkType is not a valid link type");
     }
     if (linkAlreadyExistsFor(A, B))
     {
        throw new InvalidOperationException("Link for A and B already exists");
     }
     if (A.Equals(B) || B.Equals(A))
     {
        throw new InvalidOperationException("A and B cannot be the same generator");
     }
     if (A == null || B == null || linkType == null)
     {
        throw new ArgumentException("Cannot pass a null argument");
     }
     .....
     //Actually make the link after making sure all the arguments are valid.
}
</code>```

Most of the LinkGenerator functions consists of verifying that the parameters are good.  The actual link creation takes 2 lines of code.  There's a bit of business logic (verifying that link doesn't already exist and that the generators are not the same) mixed in with a bit functional logic (making sure that the linkType derives from Link, arguments aren't null...), and makes me.......uncomfortable.

Is a long list of parameter checks an anti-pattern or a code smell?  And if so, what can one do about it?

(Just to make this clear to close-voters probably misunderstanding the question: this is not a question about "coding style for conditions" like this one).

答:
I don't think what you've done here is that bad, although it could be moved to a separate procedure to keep things neater:</p>

```<code>public void LinkGenerators(Generator A, Generator B, Type linkType)
{
     //simplest way to refactor is to just not catch the exception that's
     // thrown by the validation function.
     validateLinkGeneratorArgs(A, B, linkType);
     .....
     //Actually make the link after making sure all the arguments are valid.
}

private void validateLinkGeneratorArgs(Generator A, Generator B, Type linkType)
{
     if (linkType.BaseType != typeof(Link))
     {
        throw new ArgumentException("linkType is not a valid link type");
     }
     if (linkAlreadyExistsFor(A, B))
     {
        throw new InvalidOperationException("Link for A and B already exists");
     }
     if (A.Equals(B) || B.Equals(A))
     {
        throw new InvalidOperationException("A and B cannot be the same generator");
     }
     if (A == null || B == null || linkType == null)
     {
        throw new ArgumentException("Cannot pass a null argument");
     }
 }
</code>```

Body:
I don't think what you've done here is that bad, although it could be moved to a separate procedure to keep things neater:

public void LinkGenerators(Generator A, Generator B, Type linkType)
{
     //simplest way to refactor is to just not catch the exception that's
     // thrown by the validation function.
     validateLinkGeneratorArgs(A, B, linkType);
     .....
     //Actually make the link after making sure all the arguments are valid.
}

private void validateLinkGeneratorArgs(Generator A, Generator B, Type linkType)
{
     if (linkType.BaseType != typeof(Link))
     {
        throw new ArgumentException("linkType is not a valid link type");
     }
     if (linkAlreadyExistsFor(A, B))
     {
        throw new InvalidOperationException("Link for A and B already exists");
     }
     if (A.Equals(B) || B.Equals(A))
     {
        throw new InvalidOperationException("A and B cannot be the same generator");
     }
     if (A == null || B == null || linkType == null)
     {
        throw new ArgumentException("Cannot pass a null argument");
     }
 }