答:
Stick to the fundies; they are fundamental for a reason.

<scheme>://<user>:<password>@<server.tld>:<port>/path;parameter?query#fragment

(note that the usage of user:password to identify userinfo is deprecated and is a generally bad practice. They are included for completeness' sake as they are still technically valid segments of a URI)

Those are your fundamental blocks for building URIs.
You may be opposed to the aesthetics of your URI because you aren't adequately using the tools at your disposal.  There is nothing particularly wrong with your URI snippets. But if your data is not hierarchical -I can think of no particular reason why a person and a pet should naturally be hierarchical data in a generic domain- your objection likely stems from the fact that that is the exact relationship you have modeled; a hierarchical one.

Keep in mind here that with the proper understanding, you can craft your URIs to read as prosaically as you wish.  So -first- let me import some details from the URI spec.

3.3.  Path

The path component contains data, usually organized in hierarchical
    form

...

URI producing applications
     often use the reserved characters allowed in a segment to delimit
     scheme-specific or dereference-handler-specific subcomponents.  For
     example, the semicolon (";") and equals ("=") reserved characters are
     often used to delimit parameters and parameter values applicable to
     that segment.  The comma (",") reserved character is often used for
     similar purposes.

That part about path parameters is usually glossed over and underutilized

3.4.  Query

The query component contains non-hierarchical data

The query is very well utilized (over-utilized in my opinion and usually while ignoring that little detail about "non-hierarchical" data)

3.5.  Fragment

The fragment identifier component of a URI allows indirect

  identification of a secondary resource by reference to a primary

  resource and additional identifying information.  The identified

  secondary resource may be some portion or subset of the primary

  resource, some view on representations of the primary resource, or

  some other resource defined or described by those representations.  A
  fragment identifier component is indicated by the presence of a

  number sign ("#") character and terminated by the end of the URI.

The fragment is in widespread use, but usually within a narrow scope of identifying specific representations or switching out view fragments.

With that information brought into discussion, what kind of relationship between people and pets are you trying to model with your API?  I personally feel it is very clunky and unnatural to use the "traditional" approach of drilling down the hierarchy as you have with /users/1/pets/2 even without considering the identifiers.  There is nothing inherently hierarchical in the relationship between users and pets by my understanding.  If a hierarchical relationship is what you are going for, then that is exactly what you have modeled and my opinion does not add value; in that case, you already have what you want.

But, lets assume you want to model a relationship between users and pets that is non-hierarchical.  I can think of three basic usages here that would result in two different looking types of URIs.

Let's say that you don't want to consider "pets" and "people" to be distinct entities.  Let's say you are using the name of a pet to find a person. You could model that like so

/customers?pet=Zeus

Perhaps say you are modeling a pet shop and you consider customers to be a core domain object. By using this structure, you will unsurprisingly retrieve customers having a pet named Zeus.

Let's say that you want to use the name of a person to find pets

/pets?owner=Alan

Perhaps you are modeling a veterinary clinic and pets are the core domain object of your medication tracking system. Using this structure will unsurprisingly retrieve pets owned by Alan.

For the final set of examples, let's assume that you want to model a close relationship between "owners" and "pets" without modeling the relationship hierarchically. You want to use a context defined in the path to retrieve some piece of data that is related to but not semantically coupled to the structure of the path. You can use the fragment for that (before using this, seek a definition of predefined semantics for your representation's media type to see if this usage is valid.  In absence of predefined semantics, the fragment's usage is unconstrained and left to the design of the server. In that event, this would be valid.)

```<code>Retrieve the pet named Zeus for user Alan
/users;name=Alan#pet=Zeus

Retrieve the owner of pet named Zeus
/pets/Zeus#owner

/veterinary/patients;owner=Alan#pet=Zeus
</code>```

For the final one, you are searching veterinary records by using the entity with name=Alan to retrieve a pet named Zeus, or more succinctly you are taking Alan's dog.

Ooooohhhhh noooooooeeeee.

Title: REST API: Resource Ownership

Body:
Stick to the fundies; they are fundamental for a reason.

<scheme>://<user>:<password>@<server.tld>:<port>/path;parameter?query#fragment

(note that the usage of user:password to identify userinfo is deprecated and is a generally bad practice. They are included for completeness' sake as they are still technically valid segments of a URI)

Those are your fundamental blocks for building URIs.
You may be opposed to the aesthetics of your URI because you aren't adequately using the tools at your disposal.  There is nothing particularly wrong with your URI snippets. But if your data is not hierarchical -I can think of no particular reason why a person and a pet should naturally be hierarchical data in a generic domain- your objection likely stems from the fact that that is the exact relationship you have modeled; a hierarchical one.

Keep in mind here that with the proper understanding, you can craft your URIs to read as prosaically as you wish.  So -first- let me import some details from the URI spec.

3.3.  Path

The path component contains data, usually organized in hierarchical
    form

...

URI producing applications
     often use the reserved characters allowed in a segment to delimit
     scheme-specific or dereference-handler-specific subcomponents.  For
     example, the semicolon (";") and equals ("=") reserved characters are
     often used to delimit parameters and parameter values applicable to
     that segment.  The comma (",") reserved character is often used for
     similar purposes.

That part about path parameters is usually glossed over and underutilized

3.4.  Query

The query component contains non-hierarchical data

The query is very well utilized (over-utilized in my opinion and usually while ignoring that little detail about "non-hierarchical" data)

3.5.  Fragment

The fragment identifier component of a URI allows indirect

  identification of a secondary resource by reference to a primary

  resource and additional identifying information.  The identified

  secondary resource may be some portion or subset of the primary

  resource, some view on representations of the primary resource, or

  some other resource defined or described by those representations.  A
  fragment identifier component is indicated by the presence of a

  number sign ("#") character and terminated by the end of the URI.

The fragment is in widespread use, but usually within a narrow scope of identifying specific representations or switching out view fragments.

With that information brought into discussion, what kind of relationship between people and pets are you trying to model with your API?  I personally feel it is very clunky and unnatural to use the "traditional" approach of drilling down the hierarchy as you have with /users/1/pets/2 even without considering the identifiers.  There is nothing inherently hierarchical in the relationship between users and pets by my understanding.  If a hierarchical relationship is what you are going for, then that is exactly what you have modeled and my opinion does not add value; in that case, you already have what you want.

But, lets assume you want to model a relationship between users and pets that is non-hierarchical.  I can think of three basic usages here that would result in two different looking types of URIs.

Let's say that you don't want to consider "pets" and "people" to be distinct entities.  Let's say you are using the name of a pet to find a person. You could model that like so

/customers?pet=Zeus

Perhaps say you are modeling a pet shop and you consider customers to be a core domain object. By using this structure, you will unsurprisingly retrieve customers having a pet named Zeus.

Let's say that you want to use the name of a person to find pets

/pets?owner=Alan

Perhaps you are modeling a veterinary clinic and pets are the core domain object of your medication tracking system. Using this structure will unsurprisingly retrieve pets owned by Alan.

For the final set of examples, let's assume that you want to model a close relationship between "owners" and "pets" without modeling the relationship hierarchically. You want to use a context defined in the path to retrieve some piece of data that is related to but not semantically coupled to the structure of the path. You can use the fragment for that (before using this, seek a definition of predefined semantics for your representation's media type to see if this usage is valid.  In absence of predefined semantics, the fragment's usage is unconstrained and left to the design of the server. In that event, this would be valid.)

Retrieve the pet named Zeus for user Alan
/users;name=Alan#pet=Zeus

Retrieve the owner of pet named Zeus
/pets/Zeus#owner

/veterinary/patients;owner=Alan#pet=Zeus

For the final one, you are searching veterinary records by using the entity with name=Alan to retrieve a pet named Zeus, or more succinctly you are taking Alan's dog.

Ooooohhhhh noooooooeeeee.


问:
Is anything in programming truly evil?
So, there are a bunch of questions appearing asking is X evil, is Y evil.

My view is that there are no language constructs, algorithms or whatever which are evil, just ones which are badly used.  Hell, if you look hard enough there are even valid uses of goto.

So does absolute evil, that is something which is utterly incompatible with best practice in all instances, exist in programming?  And if so what is it?  Or is it just bad programmers not knowing when something is appropriate?

Edit: To be clear, I'm not talking about things programmers do (such as not checking return codes or not using version control - they're choices made by bad programmers), I mean tools, languages, statements, whatever which are just bad...

答: Easy, IBM Rational ClearCase is an atrocity.</p>

ContentLicense: CC BY-SA 2.5

Title: Is anything in programming truly evil?


问:
Why different languages have different syntax?
Different programming language always/most of the time use different syntax.

For example take PHP, Java and Python.

In Php & Java semicolons are compulsory at the end of the line, yet Python gives an error if I put semicolon at the end of line.

In PHP & Java we must use brackets for more than 1 statement, whereas it is not required in Python.

In PHP variable should have $ sign while Java & Python does not
    have it.

Java & Python use + for concatenation of 2 strings whereas PHP uses ..

To import package JAVA uses import statement where as C# uses
    using statement.

And many, many more.

Why does this differentiation exists? What advantage it gives with different syntax?

Why can't there be a global standard to do all simple and common things?

I don't think this is a duplicate as I say Why is there Different syntax for different languages?. But that question answers Is there anything related to productivity when syntax changes.

答:
Why cant be a global Standard to do all Simple and Common things?

We tried that. The concept was called UNCOL, and the idea was that it would be ported to every architecture in the world, everyone would use it for everything. As you can tell, things didn't work out that way.

Why not? Because programming is a complex activity, and there is no single measure by which you can judge one program better than another, as long as both do their jobs. One is faster. The other takes up less RAM when running. The third one is immediately obvious for the maintenance programmer.

Also, people do not agree about what is obvious, easy to understand, well-structured etc. when it comes to source code. You can measure the runtime characteristics of a program, but quality of source code is a subjective matter. Any attempt by one side to impose a coding standard on the entire world because they consider it "the best" would be laughed off the table by a large opposing faction. This is why we will never have a universal programming language.

ContentLicense: CC BY-SA 3.0


答:
What matters about programming languages are the semantics, not the syntax. However, syntax is a vehicle for semantics. It is easy to show that two languages can have incompatible semantics (e.g. unrestricted pointers vs. memory safety, or differences in type systems). Let's focus on the syntax and semantics of variable declarations.

When we declare a variable in some language, this variable has a type, a scope, and a lifetime.

The lifetime of a variable determines how long the value in that variable exists. Afterwards, that value is freed. In many languages, the lifetime is unrestricted: a value may be used as long as it is accessible, the garbage collector takes care of freeing the associated memory. This means we do not statically know when a value is freed. But C++ guarantees deterministic destruction, and it is a frequent idiom to associate sides effects with destruction. This is not possible with garbage collection. This line has wildly different meaning in C++ and Java/C#:

```<code>Type variable = calculation();
</code>```

An universal syntax would need precise lifetime control syntax to be able to express a variety of languages.

Next up: scoping. Scope determines where an identifier is visible and the variable can be accessed. There are two kinds of scoping: lexical/static and dynamic. With dynamic scoping, a variable is accessible until a certain point in time, and it is accessible from any code that is executed during this time. Examples are Perl's package-global variables or Lisp's “special” variables. More common is lexical scoping, where the variable is only visible within a specific region of source code. There are three ways where the scope of a variable can start:

in the statement where the variable is declared, which allows the variable to be used within its definition. This is important if we are writing a recursive lambda expression.

after the statement where the variable is declared. This prevents recursive definitions.

at a different location, e.g. the start of the enclosing function or an enclosing block.

This statement has a different meaning in JavaScript (function scope) and C# (scope begins in statement):

```<code>var variable = calculation();
</code>```

Universal syntax would need to provide precise scope controls for a variety of scoping conventions.

Some languages don't make a syntactic difference between assignment and variable declaration. This is problematic when a language features closures, since this prevents us from assigning to closed-over variables.

Finally, typing. Many languages require explicit static typing, others support some kind of type inference, others have no static types. This line has different semantics in JavaScript and C#:

```<code>var variable = calculation();
</code>```

In JavaScript, variables do not have a fixed type, and we can freely assign a value of a different type to it at a later point. In C#, the var keyword triggers type inference, and the static type is determined by the result type of the assigning calculation. Aside from the scoping differences, the equivalent C# would be:

```<code>dynamic variable = calculation ();
</code>```

And there are various other properties such as reassignability, thread-safety guarantees, or constantness of values that might be reflected in a variable declaration. There is no way a simple statement such as Python's variable = value could be used in an universal syntax. Instead, we might be dealing with

```<code>let-in-function mutable thread-local dynamic* variable = value;
</code>```

And at that point, our universal syntax is so cumbersome and annoying that no one would want to use it. The solution cannot be to rule out some combinations in order to simplify the syntax, because some language will have used that combination by default. If our syntax cannot express the rich variety of programming language semantics, it is hardly an universal syntax.

Title: Why different languages have different syntax?

Body:
Different programming language always/most of the time use different syntax.

For example take PHP, Java and Python.

In Php & Java semicolons are compulsory at the end of the line, yet Python gives an error if I put semicolon at the end of line.

In PHP & Java we must use brackets for more than 1 statement, whereas it is not required in Python.

In PHP variable should have $ sign while Java & Python does not
    have it.

Java & Python use + for concatenation of 2 strings whereas PHP uses ..

To import package JAVA uses import statement where as C# uses
    using statement.

And many, many more.

Why does this differentiation exists? What advantage it gives with different syntax?

Why can't there be a global standard to do all simple and common things?

I don't think this is a duplicate as I say Why is there Different syntax for different languages?. But that question answers Is there anything related to productivity when syntax changes.

Body:
What matters about programming languages are the semantics, not the syntax. However, syntax is a vehicle for semantics. It is easy to show that two languages can have incompatible semantics (e.g. unrestricted pointers vs. memory safety, or differences in type systems). Let's focus on the syntax and semantics of variable declarations.

When we declare a variable in some language, this variable has a type, a scope, and a lifetime.

The lifetime of a variable determines how long the value in that variable exists. Afterwards, that value is freed. In many languages, the lifetime is unrestricted: a value may be used as long as it is accessible, the garbage collector takes care of freeing the associated memory. This means we do not statically know when a value is freed. But C++ guarantees deterministic destruction, and it is a frequent idiom to associate sides effects with destruction. This is not possible with garbage collection. This line has wildly different meaning in C++ and Java/C#:

Type variable = calculation();

An universal syntax would need precise lifetime control syntax to be able to express a variety of languages.

Next up: scoping. Scope determines where an identifier is visible and the variable can be accessed. There are two kinds of scoping: lexical/static and dynamic. With dynamic scoping, a variable is accessible until a certain point in time, and it is accessible from any code that is executed during this time. Examples are Perl's package-global variables or Lisp's “special” variables. More common is lexical scoping, where the variable is only visible within a specific region of source code. There are three ways where the scope of a variable can start:

in the statement where the variable is declared, which allows the variable to be used within its definition. This is important if we are writing a recursive lambda expression.

after the statement where the variable is declared. This prevents recursive definitions.

at a different location, e.g. the start of the enclosing function or an enclosing block.

This statement has a different meaning in JavaScript (function scope) and C# (scope begins in statement):

var variable = calculation();

Universal syntax would need to provide precise scope controls for a variety of scoping conventions.

Some languages don't make a syntactic difference between assignment and variable declaration. This is problematic when a language features closures, since this prevents us from assigning to closed-over variables.

Finally, typing. Many languages require explicit static typing, others support some kind of type inference, others have no static types. This line has different semantics in JavaScript and C#:

var variable = calculation();

In JavaScript, variables do not have a fixed type, and we can freely assign a value of a different type to it at a later point. In C#, the var keyword triggers type inference, and the static type is determined by the result type of the assigning calculation. Aside from the scoping differences, the equivalent C# would be:

dynamic variable = calculation ();

And there are various other properties such as reassignability, thread-safety guarantees, or constantness of values that might be reflected in a variable declaration. There is no way a simple statement such as Python's variable = value could be used in an universal syntax. Instead, we might be dealing with

let-in-function mutable thread-local dynamic* variable = value;

And at that point, our universal syntax is so cumbersome and annoying that no one would want to use it. The solution cannot be to rule out some combinations in order to simplify the syntax, because some language will have used that combination by default. If our syntax cannot express the rich variety of programming language semantics, it is hardly an universal syntax.


问:
Idiomaticy of macros in C++
Macros are considered a good thing by one and evil by another.

Is there a rule of thumb when to and when not to use macros in C++?

When are macros idiomatic and when should they be avoided?

答:
As a rule, you should only use macros, when a better alternative does not exist.

They should not be used to generate code; you should simply write the code instead (if the code is type-agnostic, write a template instead).

They should not be used to define constants; constants should be defined using one of these: (static) constexpr/const variables, anonymous enumerations, named enumerations, enum classes (depending on what you want to use them for).

They should be used for conditional compilation (include guards are one of these cases).

Ideally, they should not be used to conditionally change the API of a module at compilation (that is, ideally you should declare the same functions in all configurations, then use conditional compilation in the implementation file.

In all* other cases, macros should be avoided.

(*) - Sometimes, there are exceptions to "all other cases" (for example, you may have third party code that requires you to use macros; that's life :-) ).

Title: Idiomaticy of macros in C++


问:
Is functional language without runtime written in C possible?
Every functional language that compiles to native code relies on quite big runtime written in C programming language (well at least ones that I know of, for example Haskell, OCaml, Gambit/Chicken Scheme, SBCL, Mercury). Basically C is used to implement all the low level stuff like garbage collection, lazyness, OS abstraction layer and etc.

I'm interested if it is even possible to implement functional programming language all in itself, without doing anything in other programming language like C? If it is possible how for example garbage collection would need to be implemented?

I know that there are some projects that somehow compile OCaml, Haskell and Erlang to run on bare bones Xen hypervisor. Does the Xen provide low level features like garbage collection or there is still some C layer involved in these projects?

Is there still any functional programming language that doesn't rely on C runtime?

答:
Is there still any functional programming language that doesn't rely on C runtime?

Yes, at least if you consider (like I do) that Lisp variants are functional languages (because they have the application and abstraction operators of the lambda-calculus), and that any language with closures and abstraction is functional:

Bones is an implementation of Scheme, compiled to x86-64 assembly code in nasm syntax, which can be built without using any C compiler (but uses gcc as a linker only; with enough knowledge, you could replace that with ld).

Scheme48 is another implementation of Scheme which is entirely compiled to C; AFAIK its runtime system (including its GC) is coded in a subset of Scheme called PreScheme, and is translated to C (so IIUC no human written C code exist in it)

Jacques Pitrat's CAIA system is a declarative language bootstrapped artificial intelligence system (and all of its C code is generated by itself), so contains no human-written C code (but uses C as a target object language, like many other implementations)

Lissac is an object oriented language with some functional abilities (AFAIK it has closures so can count as functional programming language) entirely compiled to the x86-64 code.

old LISP machines from the 1980s did not rely on C at all.

You are probably asking: how can be a runtime system written in a high-level functional language (sort of chicken and egg problem, called bootstrapping compilers). The answer is "simple" in principle; you need to ensure that the lower part of your runtime does not need any runtime (e.g. any garbage collection) when it runs. This may be tricky to code (if you don't have tools ensuring that property) and generally need some knowledge about implementation details of the compiler, and uses some basic unsafe construct (e.g. the one requesting memory from the OS, e.g. thru POSIX mmap function or the underlying mmap(2) system call)

I know that there are some projects that somehow compile OCaml (...) to run on bare bones Xen hypervisor

You are probably thinking of MirageOS, an unikernel coded mostly in Ocaml. But it uses an adaptation of Ocaml runtime (notably the GC) ported to Xen and hand-coded in C. Xen is an hypervisor emulating (in a VM) some kind of x86-64 hardware system, so don't provide any garbage collector (but abstracts some common hardware devices and perhaps very low level drivers).

Notice that C is widely used as a "portable assembler". You could use LLVM (or C-- by S.Peyton Jones & Norman Ramsey, which unfortunately stalled) for that role (but LLVM is written in C++).


问:
Single source of truth within an enterprise distributed system
Within an enterprise distributed system I have many services - an E-commerce service, a CRM, support desk, finance, billing. Many of these services share common data, such as Customer data.

These services communicate with each other using an Enterprise Service Bus (ESB) to ensure that data in all systems is eventually consistent with one another.

My question is this: Is it better to ensure that only one system can update any one part of data? To have a single source of truth. E.g. Only the billing system can update the Customer's billing information. Only the CRM can update the Customer's contact details?

To me this sounds cumbersome and confusing to locate the correct system for the data that you wish to update. I can see it better to have multiple sources for updates and the ESB communicates these updates to subscribed services.

I can see that some data will have a single source of truth (SSOT) as it would be quite niche, such as Customer's credit card information, for example.

What is an commonly adopted technique for dealing with common data that could potentially be updated from different services? Is a SSOT needed in an enterprise distributed system?

答:
The most architecturally sound approach I know of is to put that single source of truth behind a microservice. It is perfectly okay for multiple parts of the system to update that data, as long as they do it through something like a microservice that can ensure it's always done correctly and predictably.

So for instance, Customer data is probably already in a database, but all reads and writes of Customer data should go through a single service whose sole purpose is to provide a limited interface for manipulating Customer data. This provides a common place for things like validation logic and query optimization, and ensures that changes to the data always happen in very specific ways you've thought about in advance and are sure will be okay. For instance, you may provide a deleteCustomer request that ensures all credit card data for that customer also gets deleted when the customer does. This also makes it much easier to change the underlying database tables in the future.

Finding the correct microservice should be no harder than finding the correct database tables, and the microservice's API should be significantly easier to use correctly than a database schema. Also, it should be a very thin wrapper; most of the ones I use and write at work simply map each request to a single SQL statement. More interesting logic like using credit card details to charge someone or setting up delivery of their item belong elsewhere.


问:
Is the use of set / get prefix discouraged for methods if they don't actually mutate / access fields
This could be a quirk of the IDE I am using, Android Studio, or it could be something more nuanced that I don't understand.

I have a method setCustomFont that appears as a property in the Structure view in my IDE. It appears that AS is making this decision to class it as a property based on its signature and the set / get prefix of the method name. The field that it thinks I am mutating is customFont however this does not exist.

I changed the method name to applyCustomFont and now the Structure view in AS reflects something closer to the truth in my class.

I was wondering if this is by design? Should I try and stay clear of set / get unless I have an associated field?

Edit: I am also wondering about sensible method names regardless of whether the IDE has a Structure view.

答:
That's not a quirk of your IDE - that's part of the Java Beans convention. There are many other Java tools and libraries(ORMs, serializers, configuration readers etc.) that rely on these conventions and will not work(or work poorly) if you disobey them.

That being said - getters should not always be restricted to physical fields. If you have a class Circle with a radius field, then in addition to the getRadius() method you can also have a getArea() field that calculates the area from the radius. As long as you can calculate the result in a fast, side-effects-free manner, there is no problem with getters that aren't directly mapped to member fields. Sure, that means that your IDE will show you the area in addition to the radius - and this shouldn't be a problem.

Setters are a different story, because some tools/libraries might be using reflection to invoke all your setters, which may alter the state of the object in unexpected ways. For example, in your class a serializer might call getCustomFont(), receive null(because there is no custom font), serialize it, and when reading it'll call setCustomFont(null) and override the non-custom font.


答:
The only time I'd consider macros are for compile time constants, typically ones that affect the compilation (as opposed to constant application values, which are better modelled as const types).

However, I have modelled utility routines such as calls to logging functions in a macro just so they will be compiled out, but I think even this is unnecessary today - the compiler should be clever enough to realise a logging function that does nothing due to conditional compilation will be optimised away, but old habits die hard :)

Title: Idiomaticy of macros in C++

Body:
Macros are considered a good thing by one and evil by another.

Is there a rule of thumb when to and when not to use macros in C++?

When are macros idiomatic and when should they be avoided?


问:
How to determine if a class meets the single responsibility principle?
The Single Responsibility Principle is based on the high cohesion principle. The difference between the two is that a highly cohesive classes features a set of responsibilities that are strongly related, while classes adhering to SRP have just one responsibility. </p>

<p>But how do we determine whether a particular class features a set of responsibilities and is thus just highly cohesive, or whether it has only one responsibility and thus adheres to SRP? In other words, isn't it more or less subjective, since some may consider a class very granular (and as such will believe the class adheres to SRP), while others may consider it not granular enough? </p>

答:
A concrete way can be done, based on what you said - that high cohesion leads single responsibility you can measure cohesion. A maximal cohesive class has all the fields used in all the methods. While a maximal cohesive class is not always possible nor desirable to have it's still best to reach to this. Having this class design goal it's pretty easy to deduce that your class cannot have many methods or fields (some say at most 7).

Another way is from the pure basics of OOP - model after real objects. Its much more easier to see the responsibility of the real objects. However, if the real object is too complex break it into multiple containg objects each of has its own responsibility.


问:
Dual licensed (LGPL, commercial) library and contributions
I have dual-licensed library, LGPL 3 and commercial license. Someone downloads the LGPL version, makes some improvements and sends back few patches. So far so good. But what now? It's legal to just merge those patches into code base and use them under commercial license?

I know some project (Qt, Canonical) have contributor agreements to handle exactly this cases. But what's the situation if this library doesn't have contributor agreements?

Thanks

答: IANAL, but as far as I understand you should ask the contributer to assign the copyrights of the changes to you, refusing to merge if they doesn't. Once the copyrights are you, you can distribute in whatever license you want.</p>


问:
Should you write your back-end as an API?
I had a heated discussion today about our MVC application. We have a website written in MVC (ASP.NET), and it usually follows the pattern of do something in the view -> hit the controller -> controller builds a model (calls a Manager that gets the data, builds the model in the controller method itself) -> model goes to view -> rinse & repeat.

He said that our code was too tightly coupled. For example, if we wanted a desktop application as well, we would not be able to use our existing code.

The solution and best practice he said is to build an API, and then build your website on top of your API, and then building a desktop application, mobile app, etc. is very simple.

This seems like a bad idea to me for various reasons.

Anyway I can't seem to find anything by googling that might discuss this practice. Does anyone have any information about pros, cons, why you should, why you shouldn't or further reading?

Some reasons I think it's a bad idea:

It's way too abstract to run your backend off an API. You're trying to make it too flexible which will make it an unmanagable mess.

All the stuff built into MVC seems useless, like roles and authentication. For example, [Authorize] attributes and security; you will have to roll your own.

All your API calls will require security information attached, and you will have to develop a token system and whatnot.

You will have to write complete API calls for every single function your program will ever do. Pretty much every method you want to implement will need to be ran off an API. A Get/Update/Delete for every user, plus a variant for each other operation eg update user name, add user to a group, etc. etc. and each one would be a distinct API call.

You lose all kinds of tools like interfaces and abstract classes when it comes to APIs. Stuff like WCF has very tenuous support for interfaces.

You have a method that creates a user, or performs some task. If you want to create 50 users, you can just call it 50 times. When you decide to do this method as an API your local webserver can named-pipes connect to it and no problem - your desktop client can hit it too, but suddenly your bulk user creation will involve hammering the API over the Internet 50 times which isn't good. So you have to create a bulk method, but really you're just creating it for desktop clients. This way, you end up having to a) modify your API based on what's integrating with it, and you can't just directly integrate with it, b) do a lot more work to create an extra function.

YAGNI. Unless you're specifically planning to write two identically functioning applications, one web and one Windows application for example, it is a huge amount of extra development work.

Debugging is much harder when you can't step through end-to-end.

Lots of independent operations that will require lots of back and forth, for example some code might get the current user, check the user is in the administrator role, get the company the user belongs to, get a list of other members, send them all an email. That would require a lot of API calls, or writing a bespoke method the specific task you want, where that bespoke method's only benefit would be speed yet the downside would be it would be inflexible.

Probably some more reasons these are just off the top of my head.

It just seems to me like unless you really need two identical applications, then it's really not worth it. I've never seen an ASP.NET application built like this either, you'd have to write two separate applications (the API and your code) and version control them both as well (if your user page gets a new field, you'd have to update the API and your consuming code simultaneously to ensure no ill-effects or put lots of extra work into keeping it robust).

Edit: Some great responses, really starting to get a good idea of what this all means now. So to expand on my question, how would you structure an MVC app to follow this API structure?

For example, you have a website that displays info about a user. Under MVC, you have:

View - (CS)HTML page that displays a UserViewModel
Controller - Calls GetUser() and creates a UserViewModel that it passes to the view
Manager class (sort of your API) that has a GetUser method.

The controller does GetUser() but you want a desktop app too. This means your GetUser needs to be exposed via some kind of API. You might want a TCP connection, either WCF, or perhaps Remoting. You also want a mobile app which will be RESTful since persistent connections are flaky.

So would you then write an API for each one, a WCF web service that has a method GetUser() and the code just does return new UserManager().GetUser() ? And an mvc 4 web api method that does the same thing? While continuing to call GetUser directly in your MVC controller method?

Or would you choose the solution that would work for all three (web api REST service) and build everything on that, so all three apps make API calls (the mvc ones, to the local machine).

And is this just a theoretical perfect scenario? I can see large overheads in developing this way, especially if you have to develop in a way that will let you do operations in a RESTful manner. I think some of this has been covered in the replies.

Edit 2: After reading more stuff, I've put a comment below that I think might explain it. The question is a bit of a trick question I think. Should you write your back-end as an API had me confused thinking there should be a single webservice that everything (mvc app, desktop app, mobile app) calls to do stuff.

The conclusion I have come to is that what you should really do is make sure your business logic layer is correctly decoupled. Looking at my code, I do this already - the controller will call GetUser() on a manager, then create a view model from it to render with a View. So really, the business logic layer is an API. If you want to call it from a desktop app though, you'll need to write something like a WCF service to facilitate calling it. Even just having a WCF method called GetUser() that contains the code return MyBusinessLayer.GetUser() would be sufficient. So the API is the business logic, and WCF / web api etc. are just titbits of code to let external applications in to call it.

So there is some overhead, in that you have to wrap your business logic layer in different APIs depending on what you need, and you will have to write an API method for each operation you want your other apps to do, plus you will need to sort out a way to do authentication, but for the most part it's the same. Stick your business logic in a separate project (class library), and you will probably have no issue!

Hopefully this interpretation is correct. Thanks for all the discussion/comments it has generated.

答:
Short Version: Your controller effectively an API no matter what; though ASP.NET may be obscuring that.

Longer Version:

Think about a basic MVC Web App that provides information about beer and optionally sells you one.  What do the routes look like?

```<code>/sign_in
/sign_out
/beer
/beer/{beer_name}
/order
/order/{order_number}
</code>```

In a normal web-app, there are likely a few ancillary routes like:

```<code>/beer/new
/beer/{beer_name}/edit
/beer/{beer_name}/delete
/order/new
/order/{order_number}/edit
/order/{order_number}/delete
</code>```

In a Web API those are not required, as they're inferred from the HTTP method.

Given the above symmetry, I think this makes a pretty compelling case that your API and Controller are so close that they may as well be the same thing.

After doing some digging, I've determined that this might be the state of things for you depending on which version of ASP.NET you're using.  The older MVC 5 and before lack the conventions and interface to soundly unify the two implementations.  In old versions, Web App returns populates a View  whereas the API gives an HttpResponse.  In either case, though, they're generating the exact same response semantically.

If you're using MVC 6, you get both in a unified controller class that can be smart about what it returns.  I haven't found any good ASP example code for this model, but I've found some Rails code with the same pattern.  Consider this controller for "likes" from the Diaspora project.  Each controller method has routes defined by a "resourceful convention" here that amount to the LCRUD in an API.

If you read the implementations, though, each can possibly respond to HTML, Mobile HTML, or JSON.  This, combined with a convention for finding the views, completely unifies the Web App and Web API.  You'll also note that not all methods actually provide each response (which makes sense, as the UI may require methods that the API won't, and vice versa).

This is an impedance mismatch because ASP.NET kind of figured all of this out late whereas Rails has embraced the symmetry for some time and makes it very clear.

Speculation:

Your coworker is probably both right and wrong, depending on which ASP version you're using.  Under the old MVC version, the difference between the API and App probably did make it a "best practice" to build the API up-front because ASP.NET's model didn't really allow for good code reuse there.

With the newer one, it makes more sense to use unified code because it's been made easier to re-use code with the unified controller base class.

In either case, though, the Controller is effectively the API.

Body:
Short Version: Your controller effectively an API no matter what; though ASP.NET may be obscuring that.

Longer Version:

Think about a basic MVC Web App that provides information about beer and optionally sells you one.  What do the routes look like?

/sign_in
/sign_out
/beer
/beer/{beer_name}
/order
/order/{order_number}

In a normal web-app, there are likely a few ancillary routes like:

/beer/new
/beer/{beer_name}/edit
/beer/{beer_name}/delete
/order/new
/order/{order_number}/edit
/order/{order_number}/delete

In a Web API those are not required, as they're inferred from the HTTP method.

Given the above symmetry, I think this makes a pretty compelling case that your API and Controller are so close that they may as well be the same thing.

After doing some digging, I've determined that this might be the state of things for you depending on which version of ASP.NET you're using.  The older MVC 5 and before lack the conventions and interface to soundly unify the two implementations.  In old versions, Web App returns populates a View  whereas the API gives an HttpResponse.  In either case, though, they're generating the exact same response semantically.

If you're using MVC 6, you get both in a unified controller class that can be smart about what it returns.  I haven't found any good ASP example code for this model, but I've found some Rails code with the same pattern.  Consider this controller for "likes" from the Diaspora project.  Each controller method has routes defined by a "resourceful convention" here that amount to the LCRUD in an API.

If you read the implementations, though, each can possibly respond to HTML, Mobile HTML, or JSON.  This, combined with a convention for finding the views, completely unifies the Web App and Web API.  You'll also note that not all methods actually provide each response (which makes sense, as the UI may require methods that the API won't, and vice versa).

This is an impedance mismatch because ASP.NET kind of figured all of this out late whereas Rails has embraced the symmetry for some time and makes it very clear.

Speculation:

Your coworker is probably both right and wrong, depending on which ASP version you're using.  Under the old MVC version, the difference between the API and App probably did make it a "best practice" to build the API up-front because ASP.NET's model didn't really allow for good code reuse there.

With the newer one, it makes more sense to use unified code because it's been made easier to re-use code with the unified controller base class.

In either case, though, the Controller is effectively the API.


问:
Can I take a GPL program and relicense my changes under the AGPL?
Can I take a GPL program and relicense my changes under the AGPL?

Say I clone a GPL project, make some changes, can I only allow people to use my changes under the AGPL license?

答:
Can I take a GPL program and resilience my changes under the AGPL?

No, you are not allowed to change the licence. GPL code has to contain the GPL, and it is not allowed to change the licence.

Say I clone a GPL project, make some changes, can I only allow people to use my changes under the AGPL license?

See above : you are not allowed to modify the licence. If you clone the project, you can publish your changes only under GPL conditions.


答:
According to the FSF, you cannot:

Please note that the GNU AGPL is not compatible with GPLv2. It is also
  technically not compatible with GPLv3 in a strict sense: you cannot
  take code released under the GNU AGPL and convey or modify it however
  you like under the terms of GPLv3, or vice versa. However, you are
  allowed to combine separate modules or source files released under
  both of those licenses in a single project, which will provide many
  programmers with all the permission they need to make the programs
  they want. See section 13 of both licenses for details.

I believe the "vice versa" covers the exact case you're asking about.

If I'm reading that FAQ item and section 13 of the AGPLv3 correctly, the closest thing that you are allowed to do is combine GPL'd code with AGPL'd code into a single product. But even in that case the two pieces of code retain their respective licenses.

Body:
Can I take a GPL program and relicense my changes under the AGPL?

Say I clone a GPL project, make some changes, can I only allow people to use my changes under the AGPL license?


答:
When are macros idiomatic and when should they be avoided?

Macros are idiomatic only when there is no alternative to their use. Examples are include guards (they are the only portable form), embedded domain-specific languages, special compiler support not available through other language features (embedding built-in macros like __FILE__, stringifying and concatenating identifiers), and a few other places.

Macros should be avoided whenever possible. That's because they follow their own very simplistic syntax and know nothing about C++, dumbly trampling over any and all namespaces.

It has always been one of Stroustrup's goals to eliminate the preprocessor as much as possible. Function inlining, templates, and constants are a prime example, as are modules (to replace #include), which have been chewed on by the standardization committee for years. The language features created to avoid having to use macros are all very much better than the macros they replace. Make use of them whenever possible.

Title: Idiomaticy of macros in C++


问:
Why are regular expressions so morbidly attractive?
Exhibit 1, Exhibit 2, I guess you won't find it hard to recall other examples.

Thing is: if there is more than one way to solve a problem, the PHP programmer (I usually browse the PHP tag on StackOverflow) will ask for help on the solution involving regular expressions.

Even when it will be less economic, even when the php manual suggests (link) to use str_replace instead of any preg_* or ereg_* function when no fancy substitution rules are required.

Does somebody have a clue about why this happens?

Don't get me wrong, some of my best friends are regular expressions and I don't despise Perl. What I don't get is why there is no looking for alternatives whatsoever, even when the overkill is obvious (regex to switch strings) or the code complexity rises exponentially (regex for getting data from html in PHP)

答:
Regular expressions are very attractive because they wield power.  You can do a very complicated piece of work in very few characters.

The problem is that the standard regular expression construct is not Turing-complete which means that there are programs you simply cannot implement with a regular expression, and people don't KNOW that when they are lured by the apparent power of regular expressions.

This - I guess - is the reason for the jwz-quote of "now they have two problems".

I would guess that Perl regular expressions are Turing-complete, but apparently it has not been decisively proved or disproved yet.


问:
Relationship between user story, feature, and epic?
As someone who's still new to agile, I'm not sure I completely understand the relationship or difference between user story, feature, and epic.

According to this question, a feature is a collection of stories.  One of the answers suggests that a feature is actually an epic. So are features and epics considered the same thing, that is basically a collection of related user stories?

Our project manager insists that there's a hierarchical structure:

Epic -> Features -> User stories

And that basically all user stories must fall within this structure.  Therefore all user stories must fall under an umbrella feature and all features must fall under an epic.

To me, that sounds awkward.  Can someone please clarify how user stories, features, and epics are related?  Or is there an article that clearly outlines the differences?

答:
The way we work with Epics, Stories and Features is as follows

Early in the project cycle, we come up with Epics. These are very high-level, almost marketing-centric, bullet-points of functionality. The sort of thing that you can use in an executive summary, such as,

Our new web site will allow customers to browse products, view availability and pricing, place orders and see their past order history

This leads to Epics such as

Browse Product Catalog

View Availability

View Pricing

Place Order

View Order History

These are written up as user stories (e.g. As a customer, I want to browse the product catalog, so that I can make an informed purchase decision), but serve only as a starter for ten for what will be actually developed and released.

These Epics are then further broken down into User Stories. These are actual end-to-end user journeys, very limited in scope and defined in a way that can be estimated and planned independently, and developed, tested, and released in one release cycle.

The User Story is the unit of delivery. It is the user story that is complete or not complete, goes live or does not go live.

An Epic may result in a large number of user stories, not all will be developed or released at the same time.

As an example, the Browse Product Catalog epic may break down into

Navigate Category Hierarchy

Search by Keyword

Filter by Product Attributes (e.g. price range, brand, colour, size, etc.)

Again, each of these would be written up in the format, e.g. As a customer, I want to navigate the category hierarchy, so that I can browse products and drill down to the product most suitable for my needs.

Generally, for most of our projects, we have tens of Epics and hundreds of stories.

Now, as we go through the story life cycle, we tag these stories with Features. For example, all the browse and search and stock and pricing stories will be tagged with, say, 'product-catalog'. Place Order stories to do with paying by Credit Card may be tagged with a 'credit-card' label and those to do with paying by PayPal will be tagged with a 'paypal' label.

These labels serve to group together stories that belong together, not because they are different types of performing the same activity (e.g. all the place order stories) but because they ought to be released together.

For example, the "placing an order paying by credit card" story belongs under the same epic as the "placing an order paying by PayPal" story, but they need not be released together.

Whereas, the "placing an order paying by credit card" story, the "processing a return refunding onto a credit card" story, and the "allowing customers to manage their saved credit cards on their account" story do seem to belong to one another. They would all have been tagged with the 'credit-card' feature label. i.e. they would all belong to the "Credit Card" feature. It is not very helpful releasing the ability to place an order paying by Credit Card, if it is not possible to process a return refunding on to PayPal, or if it is not possible to manage your saved Credit Cards on your account

Note: As a general rule, that is. This is, in the end, a business decision. If time-to-market is important, there may be a legitimate reason to go live with one of these and not the other.

Thus Epics serve to break down into (related, but separate) stories that can be developed independently, while Features serve to group together stories that should be released together.

You could say that Epics decompose into User Stories, and User Stories get composed into Features. The stories that belong to a feature are usually across Epics. Thus Epics and Features are orthogonal, not in a strict hierarchy.

In our way of working, once the Epics have been broken down into stories, they lose their purpose. We do not estimate, or plan Epics. We do not track progress on Epics. We do not release Epics. We estimate, plan, and track User Stories. And we release Features.


答:
When I started my career in 2006 this type of architecture was all the rage in the .NET world. I worked on 3 separate projects conceived in the mid 2000s with a web service between the business logic layer and the web frontend. Of course these days the web services were SOAP but it is still the same architecture. The supposed benefits were the ability to switch either front or backend and even develop desktop program. Ultimately YAGNI proved to be true. I never ever saw any of this happen. All this time I only saw cost of splitting the project this way. I even ended up ripping the web service out of one of the projects (took half an year to remove it step by step while doing other things) and the whole team was happy. I never tried that approach since and I will not unless given a very specific reason. 5 years of experience trying this architecture taught me that I ain't gonna need it and no amount of experts telling me the opposite is going to convince me I will. Only a project where I need it may do that.

Now that being said I do try hard to develop a layer between the business logic and the controllers/presenters. For example I have a service layer, I never expose queriables, use interfaces for all my services and inject them in controllers with IoC. If I ever need a web service in my architecture I will be able to introduce it with a reasonable cost. I just don't want to pay this cost in advance.

Also I quite like the idea of microservices but my understanding is that microservices means vertical modules rather than horizontal layers. For example if you are building facebook the chat feature will be a separate service deployed separately on its own servers, etc. This is the type of independent services I would encourage.

Title: Should you write your back-end as an API?

Body:
I had a heated discussion today about our MVC application. We have a website written in MVC (ASP.NET), and it usually follows the pattern of do something in the view -> hit the controller -> controller builds a model (calls a Manager that gets the data, builds the model in the controller method itself) -> model goes to view -> rinse & repeat.

He said that our code was too tightly coupled. For example, if we wanted a desktop application as well, we would not be able to use our existing code.

The solution and best practice he said is to build an API, and then build your website on top of your API, and then building a desktop application, mobile app, etc. is very simple.

This seems like a bad idea to me for various reasons.

Anyway I can't seem to find anything by googling that might discuss this practice. Does anyone have any information about pros, cons, why you should, why you shouldn't or further reading?

Some reasons I think it's a bad idea:

It's way too abstract to run your backend off an API. You're trying to make it too flexible which will make it an unmanagable mess.

All the stuff built into MVC seems useless, like roles and authentication. For example, [Authorize] attributes and security; you will have to roll your own.

All your API calls will require security information attached, and you will have to develop a token system and whatnot.

You will have to write complete API calls for every single function your program will ever do. Pretty much every method you want to implement will need to be ran off an API. A Get/Update/Delete for every user, plus a variant for each other operation eg update user name, add user to a group, etc. etc. and each one would be a distinct API call.

You lose all kinds of tools like interfaces and abstract classes when it comes to APIs. Stuff like WCF has very tenuous support for interfaces.

You have a method that creates a user, or performs some task. If you want to create 50 users, you can just call it 50 times. When you decide to do this method as an API your local webserver can named-pipes connect to it and no problem - your desktop client can hit it too, but suddenly your bulk user creation will involve hammering the API over the Internet 50 times which isn't good. So you have to create a bulk method, but really you're just creating it for desktop clients. This way, you end up having to a) modify your API based on what's integrating with it, and you can't just directly integrate with it, b) do a lot more work to create an extra function.

YAGNI. Unless you're specifically planning to write two identically functioning applications, one web and one Windows application for example, it is a huge amount of extra development work.

Debugging is much harder when you can't step through end-to-end.

Lots of independent operations that will require lots of back and forth, for example some code might get the current user, check the user is in the administrator role, get the company the user belongs to, get a list of other members, send them all an email. That would require a lot of API calls, or writing a bespoke method the specific task you want, where that bespoke method's only benefit would be speed yet the downside would be it would be inflexible.

Probably some more reasons these are just off the top of my head.

It just seems to me like unless you really need two identical applications, then it's really not worth it. I've never seen an ASP.NET application built like this either, you'd have to write two separate applications (the API and your code) and version control them both as well (if your user page gets a new field, you'd have to update the API and your consuming code simultaneously to ensure no ill-effects or put lots of extra work into keeping it robust).

Edit: Some great responses, really starting to get a good idea of what this all means now. So to expand on my question, how would you structure an MVC app to follow this API structure?

For example, you have a website that displays info about a user. Under MVC, you have:

View - (CS)HTML page that displays a UserViewModel
Controller - Calls GetUser() and creates a UserViewModel that it passes to the view
Manager class (sort of your API) that has a GetUser method.

The controller does GetUser() but you want a desktop app too. This means your GetUser needs to be exposed via some kind of API. You might want a TCP connection, either WCF, or perhaps Remoting. You also want a mobile app which will be RESTful since persistent connections are flaky.

So would you then write an API for each one, a WCF web service that has a method GetUser() and the code just does return new UserManager().GetUser() ? And an mvc 4 web api method that does the same thing? While continuing to call GetUser directly in your MVC controller method?

Or would you choose the solution that would work for all three (web api REST service) and build everything on that, so all three apps make API calls (the mvc ones, to the local machine).

And is this just a theoretical perfect scenario? I can see large overheads in developing this way, especially if you have to develop in a way that will let you do operations in a RESTful manner. I think some of this has been covered in the replies.

Edit 2: After reading more stuff, I've put a comment below that I think might explain it. The question is a bit of a trick question I think. Should you write your back-end as an API had me confused thinking there should be a single webservice that everything (mvc app, desktop app, mobile app) calls to do stuff.

The conclusion I have come to is that what you should really do is make sure your business logic layer is correctly decoupled. Looking at my code, I do this already - the controller will call GetUser() on a manager, then create a view model from it to render with a View. So really, the business logic layer is an API. If you want to call it from a desktop app though, you'll need to write something like a WCF service to facilitate calling it. Even just having a WCF method called GetUser() that contains the code return MyBusinessLayer.GetUser() would be sufficient. So the API is the business logic, and WCF / web api etc. are just titbits of code to let external applications in to call it.

So there is some overhead, in that you have to wrap your business logic layer in different APIs depending on what you need, and you will have to write an API method for each operation you want your other apps to do, plus you will need to sort out a way to do authentication, but for the most part it's the same. Stick your business logic in a separate project (class library), and you will probably have no issue!

Hopefully this interpretation is correct. Thanks for all the discussion/comments it has generated.


问:
Status transitions with extra information in RESTful interfaces
How would you design a REST interface that triggers a status change of an object, but requires additional properties in that moment? For example, the deliverer of a package needs to change the status of the package from in transport to delivered, but also specify how it was delivered (letterbox or in person).

I see two possibilities:

POST /packages/:id/deliver with deliveredTo as request body

PATCH /packages/:id with status=delivered&deliveredTo=... as request body

It is generally considered best practice to use the methods POST, PUT or PATCH to update the state of resources in a RESTful API. RPC-style Actions should be avoided.

The problem I see with the second approach is that validation is hard. The initial POST /packages must not accept the deliveredTo field, but the PATCH request that includes status=delivered requires it. This is not only cumbersome to implement (as the frameworks do not usually support it), but also makes for a complicated  API.

So is this a case where custom actions are appropriate?

答:
REST affects a single resource, it does not mean you can only update a single property on that resource.

Some RESTful interfaces (eg SMTP) have a single property putting system, where you repeatedly call a custom verb with a single property until your resource is fully populated with all your data. Others send a blob of data in a single packet (XML, query string, form data, doesn't matter which) to update all properties in one go.

I think the distinction of which to use depends on the latency of your communication channel - so calling a REST interface over http is quite slow, so you'd send all properties in a single message.


问:
IoC/DI design for class library
I am refactoring and introducing unit tests in a large application.

It's currently a collection of static classes with static methods that return data, like such:

```<code>// in data access project
public static class DataStock {
     public static Stock GetStock(int operation) { return my data; }
}

// in business layer project
public static class Stock {
     public static Stock GetStock(int operation) {
         var stock = DataStock.GetStock(operation);
         // do something with the data
         return stock;
     }
}

// in forms project
public class FrmDisplayStock {
     public void LoadStock() {
         var stock = Stock.GetStock(this.selectorOperation);
         // display the stock
     }
}
</code>```

I am redesigning the app like this:

```<code>// in data access project
public class DataStock : IDataStock {
     public Stock GetStock(int operation) { return my data; }
}

// in business layer project
public class Stock : IStock {
     private IDataStock data;

     public Stock() { this.data = new DataStock(); }
     public Stock(IDataStock data) { this.data = data; }

     public Stock GetStock(int operation) {
         var stock = data.GetStock(operation);
         // do something with the data
         return stock;
     }
}

// in forms project
public class FrmDisplayStock {
     private IStock stockbll;

     public FrmDisplayStock() { this.stockbll = new Stock(); }
     public FrmDisplayStock(IStock stockbll) { this.stockbll = stockbll; }

     public void LoadStock() {
         var stock = stockbll.GetStock(this.selectorOperation);
         // display the stock
     }
}
</code>```

This allows me to write tests for the business and forms layers, mocking the underlying layer (I am not yet testing the data access layer, but it's both more complicated to test and less interesting).

I would like to use a IoC container so that I don't have to manually wire the interfaces to concrete types every time; with deep nesting and many tests to write, it's becoming quite annoying and error-prone.

The problem is that I don't grasp how to implement it, technically.

Shall I write a bootstrapper for each project that wires the underlying layer ?

Shall I change my constructors to get the container's instance like such ? public Stock() { this.data = myContainer.GetInstance<IDataStock>(); }

Is it working differently than I am assuming ?

答:
You want all dependencies to be injected from the absolute top layer, so you should have a dependency graph with a root, and the root has a reference to the concrete implementation of the deps at every node, registers that concretion for the interface in a container, and then grabs just the first level deps it needs from the container. But in doing so, that layer has deps the container constructs which has deps the container constructs...

Think of your dependency graph being constructed by the container like this:

```<code>public void main()
{
    var frmDisplayStock = new FrmDisplayStock(
      new Stock(
        new DataStock()
      )
    );
}
</code>```

Except instead of you manually constructing each dependency at each layer of the graph, you just register the types with a container (or however the container you choose requires you to register them). For example:

```<code>public void main()
{
    var container = new SomeIocContainer();
    container.Register<IDataStock>(typeof(DataStock));
    container.Register<IStock>(typeof(Stock));
    container.Register<IDataStock>(typeof(DataStock));
    var frmDisplayStock = container.Get<FrmDisplayStock>();
}
</code>```

In the above example, the final .Get call is going to use the types it knows about, and the container will presumably figure out what types are required to fulfill the whole dependency graph, identically so what was done in our previous example without a container.

So in conclusion, you want to go to the highest point in your stack you can and let it decide all the concretions. You don't want to have those default public constructors that know the concretions, because that causes tightly-coupled references between things when an interface would more than suffice. You never know when you'll want to use an IDataStock that works off a high performance cache, or 3rd party webservice, or local file, so don't presume DataStock is the only implementation you'll use. The key point of making this decision at the top layer is, if you do it below that, you'll find some layer of dependencies above that point and now you'll what- reference up the stack to define it?

Dependencies should be a directed graph with no loops (DAG) and a single root (tree), in a tree you never let peers know about each other, and you never let children know their parents. So where but at the root can you reference all dependencies without breaking the rules of a tree?

Another larger example that may make this all clearer since your example merely has 2 dependencies, not much of a sample for illustrating a concept.

```<code>public void Main()
{
    var myWidgetsService = new WidgetService(
      new WidgetEventsProcessor(
        new MessageQueueSubscriber(ConfigurationManager.AppSettings["MQConnectionString"])
      ),
      new WidgetInProcessCacheStore(),
      new WidgetSerializerService(
        new JsonSerializer()
      ),
      new WidgetAccessControlService(
        new AccessRightsProcessor(
          new AccessRightsServiceClient(ConfigurationManager.AppSettings["AccessRightsServiceUri"])
        ),
        new AuthenticationProcessor(
          new WindowsAuthenticationChecker(ConfigurationManager.AppSettings["DomainController"]),
          new EMailClient(ConfigurationManager.AppSettings["SMTPService"]) // for auth failure warnings
        )
      )
    );
}
</code>```

Given the above dependencies tree, you would just make the registrations, and let the container manage the construction (totally made-up IoC API, not a real or suggested IoC framework API):

```<code>public void Main()
{
    var container = new SomeIocContainer();
    container.Register<IWindowsAuthenticationChecker>(typeof(WindowsAuthenticationChecker), ConfigurationManager.AppSettings["DomainController"]);
    container.Register<IEMailClient>(typeof(EMailClient), ConfigurationManager.AppSettings["SMTPService"]);
    container.Register<IAuthenticationProcessor>(typeof(AuthenticationProcessor));
    container.Register<IAccessRightsServiceClient>(typeof(AccessRightsServiceClient), ConfigurationManager.AppSettings["AccessRightsServiceUri"]);
    container.Register<IAccessRightsProcessor>(typeof(AccessRightsProcessor));
    container.Register<IWidgetAccessControlService>(typeof(WidgetAccessControlService));
    container.Register<IJsonSerializer>(typeof(JsonSerializer));
    container.Register<IWidgetSerializerService>(typeof(WidgetSerializerService));
    container.Register<IWidgetStore>(typeof(WidgetInProcessCacheStore));
    container.Register<IWidgetSerializerService>(typeof(WidgetSerializerService));
    container.Register<IMessageQueueSubscriber>(typeof(MessageQueueSubscriber), ConfigurationManager.AppSettings["MQConnectionString"]));
    container.Register<IWidgetEventsProcessor>(typeof(WidgetEventsProcessor));

    var myWidgetsService = container.Get<WidgetService>();
}
</code>```

Title: IoC/DI design for class library

Body:
You want all dependencies to be injected from the absolute top layer, so you should have a dependency graph with a root, and the root has a reference to the concrete implementation of the deps at every node, registers that concretion for the interface in a container, and then grabs just the first level deps it needs from the container. But in doing so, that layer has deps the container constructs which has deps the container constructs...

Think of your dependency graph being constructed by the container like this:

public void main()
{
    var frmDisplayStock = new FrmDisplayStock(
      new Stock(
        new DataStock()
      )
    );
}

Except instead of you manually constructing each dependency at each layer of the graph, you just register the types with a container (or however the container you choose requires you to register them). For example:

public void main()
{
    var container = new SomeIocContainer();
    container.Register<IDataStock>(typeof(DataStock));
    container.Register<IStock>(typeof(Stock));
    container.Register<IDataStock>(typeof(DataStock));
    var frmDisplayStock = container.Get<FrmDisplayStock>();
}

In the above example, the final .Get call is going to use the types it knows about, and the container will presumably figure out what types are required to fulfill the whole dependency graph, identically so what was done in our previous example without a container.

So in conclusion, you want to go to the highest point in your stack you can and let it decide all the concretions. You don't want to have those default public constructors that know the concretions, because that causes tightly-coupled references between things when an interface would more than suffice. You never know when you'll want to use an IDataStock that works off a high performance cache, or 3rd party webservice, or local file, so don't presume DataStock is the only implementation you'll use. The key point of making this decision at the top layer is, if you do it below that, you'll find some layer of dependencies above that point and now you'll what- reference up the stack to define it?

Dependencies should be a directed graph with no loops (DAG) and a single root (tree), in a tree you never let peers know about each other, and you never let children know their parents. So where but at the root can you reference all dependencies without breaking the rules of a tree?

Another larger example that may make this all clearer since your example merely has 2 dependencies, not much of a sample for illustrating a concept.

public void Main()
{
    var myWidgetsService = new WidgetService(
      new WidgetEventsProcessor(
        new MessageQueueSubscriber(ConfigurationManager.AppSettings["MQConnectionString"])
      ),
      new WidgetInProcessCacheStore(),
      new WidgetSerializerService(
        new JsonSerializer()
      ),
      new WidgetAccessControlService(
        new AccessRightsProcessor(
          new AccessRightsServiceClient(ConfigurationManager.AppSettings["AccessRightsServiceUri"])
        ),
        new AuthenticationProcessor(
          new WindowsAuthenticationChecker(ConfigurationManager.AppSettings["DomainController"]),
          new EMailClient(ConfigurationManager.AppSettings["SMTPService"]) // for auth failure warnings
        )
      )
    );
}

Given the above dependencies tree, you would just make the registrations, and let the container manage the construction (totally made-up IoC API, not a real or suggested IoC framework API):

public void Main()
{
    var container = new SomeIocContainer();
    container.Register<IWindowsAuthenticationChecker>(typeof(WindowsAuthenticationChecker), ConfigurationManager.AppSettings["DomainController"]);
    container.Register<IEMailClient>(typeof(EMailClient), ConfigurationManager.AppSettings["SMTPService"]);
    container.Register<IAuthenticationProcessor>(typeof(AuthenticationProcessor));
    container.Register<IAccessRightsServiceClient>(typeof(AccessRightsServiceClient), ConfigurationManager.AppSettings["AccessRightsServiceUri"]);
    container.Register<IAccessRightsProcessor>(typeof(AccessRightsProcessor));
    container.Register<IWidgetAccessControlService>(typeof(WidgetAccessControlService));
    container.Register<IJsonSerializer>(typeof(JsonSerializer));
    container.Register<IWidgetSerializerService>(typeof(WidgetSerializerService));
    container.Register<IWidgetStore>(typeof(WidgetInProcessCacheStore));
    container.Register<IWidgetSerializerService>(typeof(WidgetSerializerService));
    container.Register<IMessageQueueSubscriber>(typeof(MessageQueueSubscriber), ConfigurationManager.AppSettings["MQConnectionString"]));
    container.Register<IWidgetEventsProcessor>(typeof(WidgetEventsProcessor));

    var myWidgetsService = container.Get<WidgetService>();
}


问:
Using GNU GPL with classpath exception licensed library in a GNU GPL licensed project
I am working on a project that uses ABCL. License of ABCL is GNU GPL with classpath exception, which means we can link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice.

So I know that we dont have to enforce license of ABCL to my project, but what about otherwise,
Would license of the project that is GNU GPL without classpath exception be enforced to ABCL to make is GNU GPL withOUT classpath exception as well ?

PROJECT (GNU GPL)    -----> ABCL (GNU GPL with class path exception)

A --- >> B
Now we know that license of B doesnot effect license of A, but is A going to effect license of B?

ABCL is used to compile and load lisp code files written by myself, on which I DO NOT WANT TO ENFORCE GNU.
these lisp files are not the part of the main project executable. But the main project uses ABCL to load these files. Would GNU GPL (license of main project) be now enforced on these lisp files? ABCL has classpath exception for ABCL license will NOT be enforced on lisp code files.

答:
This is so straightforward I'm not even going to bother writing "IANAL". The fact that you have a project that depends on ABCL can not in any way alter the license of ABCL itself. ABCL does not depend on your project and therefore doesn't need to comply to your license - or even be aware of it.

Think of the implications if licenses worked that way - some kid in a basement will write a GPL licensed project that depends on ABCL, and suddenly ABCL will lose it's class path exception and every proprietary project in the world that depends on it will become illegal. Does this make sense?


答:
The short answer is no, it does not work that way. To clear up the confusion, I find it helps to think of licenses as applying to distributions of software, rather than the software directly (as far as I know, this is actually closer to the truth).

I'll pretend your project is called DEFM. If you release DEFM under GPLv3, then someone downloads it and uses parts of it to build their own program GHIN (even just the ABCL part), then they are using your code under the terms of the GPLv3, regardless of the "original" licenses that applied to each part. However, ABCL is already being distributed under GPL with classpath exception, so the GHIN guy can simply go use that distribution instead if he prefers that license (assuming the ABCL part was all they cared about). Nothing you do with ABCL can retroactively change the license that its distributors used. You can only change the license on your own redistribution of ABCL (and of course, ABCL's license restricts what you can change it to).

Similarly, you're allowed to change your license at any time, use different licenses on different versions of your code, or even distribute the same version of your code under different licenses depending on the client (it's common to have a free version with a copyleft license and a paid version with a more permissive or proprietary license). In all of these cases, the person using your software gets to use it under the terms of the license that was applied to the particular distribution they received at the time they received it.

Title: Using GNU GPL with classpath exception licensed library in a GNU GPL licensed project

Body:
I am working on a project that uses ABCL. License of ABCL is GNU GPL with classpath exception, which means we can link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice.

So I know that we dont have to enforce license of ABCL to my project, but what about otherwise,
Would license of the project that is GNU GPL without classpath exception be enforced to ABCL to make is GNU GPL withOUT classpath exception as well ?

PROJECT (GNU GPL)    -----> ABCL (GNU GPL with class path exception)

A --- >> B
Now we know that license of B doesnot effect license of A, but is A going to effect license of B?

ABCL is used to compile and load lisp code files written by myself, on which I DO NOT WANT TO ENFORCE GNU.
these lisp files are not the part of the main project executable. But the main project uses ABCL to load these files. Would GNU GPL (license of main project) be now enforced on these lisp files? ABCL has classpath exception for ABCL license will NOT be enforced on lisp code files.


问:
Is this a violation of the Liskov Substitution Principle?
Say we have a list of Task entities, and a ProjectTask sub type. Tasks can be closed at any time, except ProjectTasks which cannot be closed once they have a status of Started. The UI should ensure the option to close a started ProjectTask is never available, but some safeguards are present in the domain:

public class Task
{
     public Status Status { get; set; }

     public virtual void Close()
     {
         Status = Status.Closed;
     }
}

public class ProjectTask : Task
{
     public override void Close()
     {
          if (Status == Status.Started)
              throw new Exception("Cannot close a started Project Task");

          base.Close();
     }
}
```

Now when calling Close() on a Task, there is a chance the call will fail if it is a ProjectTask with the started status, when it wouldn't if it was a base Task. But this is the business requirements. It should fail. Can this be regarded as a violation of the Liskov substitution principle?

答:
This may or may not be a violation of the LSP.

Seriously.  Hear me out.

If you follow the LSP, objects of type ProjectTask must behave as objects of type Task are expected to behave.

The problem with your code is that you have not documented how objects of type Task are expected to behave. You have written code, but no contracts.  I'll add a contract for Task.Close.  Depending on the contract I add, the code for ProjectTask.Close either does or does not follow the LSP.

Given the following contract for Task.Close, the code for ProjectTask.Close  does not follow the LSP:

     // Behaviour: Moves the task to the closed state
     // and does not throw any Exception.
     // Default behaviour: Moves the task to the closed state
     // and does not throw any Exception.
     public virtual void Close()
     {
         Status = Status.Closed;
     }
```

<p>Given the following contract for Task.Close, the code for <code>ProjectTask.Close</code>  <strong>does</strong> follow the LSP:</p>

```     // Behaviour: Moves the task to the closed status if possible.
     // If this is not possible, this method throws an Exception
     // and leaves the status unchanged.
     // Default behaviour: Moves the task to the closed state
     // and does not throw any Exception.
     public virtual void Close()
     {
         Status = Status.Closed;
     }
```

Methods that may be overridden should be documented in two ways:

The "Behaviour" documents what can be relied on by a client who knows the recipient object is a Task, but doesn't know what class it is a direct instance of. It also tells designers of subclasses which overrides are reasonable and which are not reasonable.

The "Default behaviour" documents what can be relied on by a client who knows that the recipient object is a direct instance of Task (i.e. what you get if you use new Task().  It also tells designers of subclasses what behaviour will be inherited if they don't override the method.

Now the following relations should hold:

If S is a subtype of T, the documented behaviour of S should refine the documented behaviour of T.

If S is a subtype of (or equal to) T, the behaviour of S's code should refine the documented behaviour of T.

If S is a subtype of (or equal to) T, the default behaviour of S should refine the documented behaviour of T.

The actual behaviour of the code for a class should refine its documented default behaviour.

Body:
This may or may not be a violation of the LSP.

Seriously.  Hear me out.

If you follow the LSP, objects of type ProjectTask must behave as objects of type Task are expected to behave.

The problem with your code is that you have not documented how objects of type Task are expected to behave. You have written code, but no contracts.  I'll add a contract for Task.Close.  Depending on the contract I add, the code for ProjectTask.Close either does or does not follow the LSP.

Given the following contract for Task.Close, the code for ProjectTask.Close  does not follow the LSP:

     // Behaviour: Moves the task to the closed state
     // and does not throw any Exception.
     // Default behaviour: Moves the task to the closed state
     // and does not throw any Exception.
     public virtual void Close()
     {
         Status = Status.Closed;
     }

Given the following contract for Task.Close, the code for ProjectTask.Close  does follow the LSP:

     // Behaviour: Moves the task to the closed status if possible.
     // If this is not possible, this method throws an Exception
     // and leaves the status unchanged.
     // Default behaviour: Moves the task to the closed state
     // and does not throw any Exception.
     public virtual void Close()
     {
         Status = Status.Closed;
     }

Methods that may be overridden should be documented in two ways:

The "Behaviour" documents what can be relied on by a client who knows the recipient object is a Task, but doesn't know what class it is a direct instance of. It also tells designers of subclasses which overrides are reasonable and which are not reasonable.

The "Default behaviour" documents what can be relied on by a client who knows that the recipient object is a direct instance of Task (i.e. what you get if you use new Task().  It also tells designers of subclasses what behaviour will be inherited if they don't override the method.

Now the following relations should hold:

If S is a subtype of T, the documented behaviour of S should refine the documented behaviour of T.

If S is a subtype of (or equal to) T, the behaviour of S's code should refine the documented behaviour of T.

If S is a subtype of (or equal to) T, the default behaviour of S should refine the documented behaviour of T.

The actual behaviour of the code for a class should refine its documented default behaviour.


问:
Why create a Logger object instead of using static logging methods across an application?
Taking an example of a simple Ruby on Rails application. It creates a Logger object during application load process:

# in environment.rb
config.logger = Logger.new(<STDOUT | file | whatever>)

# and in our application we use this object
logger.warn "This process is taking too long to process. Optimization needed."
```

My question is, why don't we use class methods (or static methods) for logging? Won't Logger.warn scale than Logger.new.warn? Or atleast Logger.warn seems intuitive than Logger.new.warn.

Even if Logger.new is a singleton object, what advantages does it offer?

答:
Logger.new is a factory that will take where the result will be used (name of the class/file).

In the configuration files you can then decide what level to log to not logging at all for parts of the program without having to recompile the project.

Thus you can disable all but high-level logging (errors) for release builds and only activate the lowest level for the parts you are debugging.


答:
Here's an example that uses Java.  It's been a while since I've used log4j, but from what I remember, the whole log4j logging tool would initialize from an XML file.  The XML file itself could contain multiple loggers with different configurations(where you write to, what levels are written, etc).  So, in this case you would have logger objects rather than logger static methods in order to specify which logger you want to invoke.  Ie.

```<code>Logger logger = Logger.get("Network");
</code>```

would log things related to network connectivity, dropped packets, etc, or

```<code>Logger logger = Logger.get("Application");
</code>```

which would log things related to your business logic/application.  At least with log4j you could also configure which log levels actually get written out(info, trace, warn, error, debug being the default levels available).

If you had static methods, the best you could do is configure a single logger that would point to standard out, a file, etc, but everything you log would go to the same place.  With logger objects, it's easier to make it so your logging information is spread out to multiple files.

Title: Why create a Logger object instead of using static logging methods across an application?

Body:
Taking an example of a simple Ruby on Rails application. It creates a Logger object during application load process:

# in environment.rb
config.logger = Logger.new(<STDOUT | file | whatever>)

# and in our application we use this object
logger.warn "This process is taking too long to process. Optimization needed."
```

My question is, why don't we use class methods (or static methods) for logging? Won't Logger.warn scale than Logger.new.warn? Or atleast Logger.warn seems intuitive than Logger.new.warn.

Even if Logger.new is a singleton object, what advantages does it offer?

Body:
Here's an example that uses Java.  It's been a while since I've used log4j, but from what I remember, the whole log4j logging tool would initialize from an XML file.  The XML file itself could contain multiple loggers with different configurations(where you write to, what levels are written, etc).  So, in this case you would have logger objects rather than logger static methods in order to specify which logger you want to invoke.  Ie.

Logger logger = Logger.get("Network");

would log things related to network connectivity, dropped packets, etc, or

Logger logger = Logger.get("Application");

which would log things related to your business logic/application.  At least with log4j you could also configure which log levels actually get written out(info, trace, warn, error, debug being the default levels available).

If you had static methods, the best you could do is configure a single logger that would point to standard out, a file, etc, but everything you log would go to the same place.  With logger objects, it's easier to make it so your logging information is spread out to multiple files.


问:
Is this too much work for a Gateway to do?
I'm writing a Gateway class that wraps access to a web service which provides information about a player's item inventory in a video game. This web service returns a variety of information, however I do not need to use all of it.

The only thing I need to know from the web service is if a given game item is present in the player's inventory. This logic would be simple to implement: I would iterate over the player's items, trying to find a match. However, herein lies my primary concern: is this too much work for a Gateway to do? Would it be better practice to have the Gateway merely extract the list of items, and then handle the checking elsewhere? This would seem silly to me, because my program really only cares about the existence of a particular item and I don't really need a list of every item.

答:
In general, a gateway class should translate from the interface you have to the interface you want.  If the interface you want is a simple presence check, by all means write it that way.

I would just caution you as the requirements change and the application grows, to not be afraid to reevaluate that decision.  If your gateway class starts looking too large, or like it's forcing too many abstraction layers together, split it into one that retrieves the list and one that filters/searches the list.  Even if you have only one class, these should at least be separate functions.


问:
Why different languages have different syntax?
Different programming language always/most of the time use different syntax.

For example take PHP, Java and Python.

In Php & Java semicolons are compulsory at the end of the line, yet Python gives an error if I put semicolon at the end of line.

In PHP & Java we must use brackets for more than 1 statement, whereas it is not required in Python.

In PHP variable should have $ sign while Java & Python does not
    have it.

Java & Python use + for concatenation of 2 strings whereas PHP uses ..

To import package JAVA uses import statement where as C# uses
    using statement.

And many, many more.

Why does this differentiation exists? What advantage it gives with different syntax?

Why can't there be a global standard to do all simple and common things?

I don't think this is a duplicate as I say Why is there Different syntax for different languages?. But that question answers Is there anything related to productivity when syntax changes.

答: Every programming language is invented by different mind set, experience and objective, and there is no universal guideline setup for creating a language. So whenever a new language comes up it's their inventor choice to think about best naming/ syntax so this is all up to them what they think is best will add there. For example to add two numbers i will create function Like Add() and for me this will be best suitable but other may think Sum() will be best suitable. So it's all mind set they think on that time. </p>


问:
Loops to create nested loops
Is there a way to use a loop to create more nested loops? E.g. Doing this

```<code>for (int i = 0; i < iterations; i++)
            {
                //Do stuff
                for (int ii = 0; ii < iterations; ii++)
                {
                    // Do stuff
                    for (int iii = 0; iii < iterations; iii++)
                    {
                        //Do Stuff
                    }
                }
            }
</code>```

but allowing the user to change how many nested loops you want during run-time.

This allows me to know the depth I am on, while also resetting the "i" counter back to 0, allowing me to do the exact same thing over again, but with a different depth value.

答:
You've gotten some good answers here and on SO to your questions, but you're missing a non-recursive solution. Here's how I went about trying to solve the problem (Note that it is currently slightly broken!):

```<code>private static IEnumerable<string> GetPaths(int maxDepth, int iterations, string root)
{
    var depths = Enumerable.Range(0, maxDepth);
    var widths = Enumerable.Range(0, iterations);

    var thing = depths.Select(x => Path.Combine(
        depths
            .Reverse()
            .Skip(x + 1)
            .Select(y => y.ToString())
        .Reverse()
        .ToArray()));

    return thing.SelectMany(x => widths.Select(y => Path.Combine(root, x, y.ToString())));
}
</code>```

What this essentially does is create all the sets of combinations by joining collections, and then combines them into paths. The result is that every depth is covered, without any chance of blowing the stack. There is a bug currently: the variable thing (which should be renamed, should you take this route) contains (with an input of 10, 10, "temp" the paths:

```<code>0\1\2\3\4\5\6\7\8
0\1\2\3\4\5\6\7
0\1\2\3\4\5\6
0\1\2\3\4\5
0\1\2\3\4
0\1\2\3
0\1\2
0\1
0
string.Empty
</code>```

I'll leave it to you to figure out how to fix it, but it's very simple.

Title: Loops to create nested loops

Body:
You've gotten some good answers here and on SO to your questions, but you're missing a non-recursive solution. Here's how I went about trying to solve the problem (Note that it is currently slightly broken!):

private static IEnumerable<string> GetPaths(int maxDepth, int iterations, string root)
{
    var depths = Enumerable.Range(0, maxDepth);
    var widths = Enumerable.Range(0, iterations);

    var thing = depths.Select(x => Path.Combine(
        depths
            .Reverse()
            .Skip(x + 1)
            .Select(y => y.ToString())
        .Reverse()
        .ToArray()));

    return thing.SelectMany(x => widths.Select(y => Path.Combine(root, x, y.ToString())));
}

What this essentially does is create all the sets of combinations by joining collections, and then combines them into paths. The result is that every depth is covered, without any chance of blowing the stack. There is a bug currently: the variable thing (which should be renamed, should you take this route) contains (with an input of 10, 10, "temp" the paths:

0\1\2\3\4\5\6\7\8
0\1\2\3\4\5\6\7
0\1\2\3\4\5\6
0\1\2\3\4\5
0\1\2\3\4
0\1\2\3
0\1\2
0\1
0
string.Empty

I'll leave it to you to figure out how to fix it, but it's very simple.