问:
Is there something better than a StringBuilder for big blocks of SQL in the code
I'm just tired of making a big SQL statement, test it, and then paste the SQL into the code and adding all the sqlstmt.append(" at the beginning and the ") at the end.

It's 2011, isn't there a better way the handle a big chunk of strings inside code?

Please: don't suggest stored procedures or ORMs.

edit Found the answer using XML literals and CData. Thanks to all the people that actually tried to answer the question without questioning me for not using ORM, SPs and using VB

edit 2 the question leave me thinking that languages could try to make a better effort for using inline SQL with color syntax, etc. It will be cheaper that developing Linq2SQL.

Just something like:

```<code>dim sql = <sql>
          SELECT * ...
          </sql>
</code>```

答:
I agree with the approach @aaronnaught uses but with a slight change. Create a file with sql as the extension in the project and put your query text in there. Then add it as a resource (project properties, Resources tab, Add Resource, then go looking for the sql file you created) and reference it in code as My.Resources.Filename:

```<code>Dim cmd As New SqlClient.SqlCommand(My.Resources.Query)
</code>```

Because it's a sql file you can run the query, see results in VS and the text is nicely formatted.

Body:
I agree with the approach @aaronnaught uses but with a slight change. Create a file with sql as the extension in the project and put your query text in there. Then add it as a resource (project properties, Resources tab, Add Resource, then go looking for the sql file you created) and reference it in code as My.Resources.Filename:

Dim cmd As New SqlClient.SqlCommand(My.Resources.Query)

Because it's a sql file you can run the query, see results in VS and the text is nicely formatted.


问:
Creating variations of a property heavy class
What kind of pattern or design can prevent the creation of a class packed with properties that aren't always used?

Example

```<code>class Car{
   public string type;
   public string name;
   public DateTime manufactured;
   public int model;
   public Color color;
   public int VIN;
   // ..and on
}

public Car(string name, Color color){
    this.name = name;
    this.color = color;
}
</code>```

Sometimes you want to make a Car with just some info, like the make and model, but you always want it to have a few defaults. How do you avoid 20 children classes or constructor overloads in this case?

答:
Analyze what properties work closly together and make a class of each of these groups. They may group around the natural systems like electrical, engine, transmission; and notional groupings like performance, Identity, options.

As you work these groups look for redundant properties. These individual properties could be DRYed up to become a class that is used to minimally initialize any car. Other car aspect classes will have a reference to this as needed.

Given a minimally initialized car you can lazy load other car aspect objects as needed.

While all the above looks like just composition, thorough requirements and design analysis will yield complementary inheritance, composition, constructor overloads, and patterns like factory, builder, or even visitor to allow flexible construction and ensure object integrity.

Client code should not set individual car aspect-object properties. The client would need to know everything about the internal functionality of the car class in order to do it right. So besides a factory for initialization you might have builder classes that encapsulate/control injection of additional car aspect objects, the constructor parameters ensuring the car object will be in a valid state.

The above builder classes and factory may work by broad vehicle classifications like sports car, truck, luxury sedan, flying car, etc.

Finally, these car aspect classes should not be merely stupid DTO-type things - all state and no function. I find that even minimal things like overriding ToString, Equals, maybe implement IComparable, makes composition better and the levels of composition tend to stay simpler.

ContentLicense: CC BY-SA 3.0


问:
How to make a datatype for something that represents either itself or two other things

Background

Here's the actual problem I'm working on: I want a way to represent cards in the card game Magic: The Gathering.  Most cards in the game are normal-looking cards, but some of them are divided into two parts, each with its own name.  Each half of these two-part cards is treated as a card itself.  So for clarity, I'll use Card only to refer to something that's either a regular card, or half of a two-part card (in other words, something with only one name).

So we have a base type, Card.  The purpose of these objects is really just to hold properties of the card.  They don't really do anything by themselves.

```<code>interface Card {
    String name();
    String text();
    // etc
}
</code>```

There are two subclasses of Card, which I'm calling PartialCard (half of a two-part card) and WholeCard (a regular card).  PartialCard has two additional methods: PartialCard otherPart() and boolean isFirstPart().

Representatives

If I have a deck, it should be composed of WholeCards, not Cards, as a Card could be a PartialCard, and that wouldn't make sense.  So I want an object that represents a "physical card," that is, something that can represent one WholeCard, or two PartialCards. I'm tentatively calling this type Representative, and Card would have the method getRepresentative().  A Representative would provide almost no direct information on the card(s) it represents, it would only point to it/them.  Now, my brilliant/crazy/dumb idea (you decide) is that WholeCard inherits from both Card and Representative.  After all, they are cards that represent themselves!  WholeCards could implement getRepresentative as return this;.

As for PartialCards, they don't represent themselves, but they have an external Representative that is not a Card, but provides methods for accessing the two PartialCards.

I think this type hierarchy makes sense, but it's complicated.  If we think of Cards as "conceptual cards" and Representatives as "physical cards," well, most cards are both!  I think you could make an argument that physical cards do in fact contain conceptual cards, and that they're not the same thing, but I would argue that they are.

Necessity of Type-casting

Because PartialCards and WholeCards are both Cards, and there's usually no good reason to separate them out, I'd normally just be working with Collection<Card>.  So sometimes I'd need to cast PartialCards in order to access their additional methods.  Right now, I'm using the system described here because I really don't like explicit casts.  And like Card, Representative would need be cast to either a WholeCard or Composite, to access the actual Cards they represent.

So just for summary:

Base type Representative

Base type Card

Type WholeCard extends Card, Representative (no access needed, it represents itself)

Type PartialCard extends Card (gives access to other part)

Type Composite extends Representative (gives access to both parts)

Is this insane?  I think it actually makes a lot of sense, but I'm honestly not sure.

答:
It seems to me that you should have a class like

```<code>class PhysicalCard {
    List<LogicalCard> getLogicalCards();
}
</code>```

Code that's concerned with the physical card can deal with the physical card class, and code that's concerned with the logical card can deal with that.

I think you could make an argument that physical cards do in fact
  contain conceptual cards, and that they're not the same thing, but I
  would argue that they are.

It doesn't matter whether or not you think the the physical and logic card are the same thing. Don't assume that just because they are the same physical object, they should be the same object in your code. What matters is whether adopting that model makes the coder easier to read and write. The fact is, adopting a simpler model where every physical card is treated as a collection of logical card consistently, 100% of time, will result in simpler code.

Body:
It seems to me that you should have a class like

class PhysicalCard {
    List<LogicalCard> getLogicalCards();
}

Code that's concerned with the physical card can deal with the physical card class, and code that's concerned with the logical card can deal with that.

I think you could make an argument that physical cards do in fact
  contain conceptual cards, and that they're not the same thing, but I
  would argue that they are.

It doesn't matter whether or not you think the the physical and logic card are the same thing. Don't assume that just because they are the same physical object, they should be the same object in your code. What matters is whether adopting that model makes the coder easier to read and write. The fact is, adopting a simpler model where every physical card is treated as a collection of logical card consistently, 100% of time, will result in simpler code.


问:
Why are the sizes of programs so large?
If we look at the vintage program Netscape Navigator or an early version of Microsoft Word, those programs were less than 50 MB in size. Now when I install google chrome it is 200 MB and desktop version of Slack is 300 MB. I read about some rule that programs will take all available memory no matter how much it is but why?

Why are the current sizes of programs so large compared to 10 or 15 years ago? The programs are not doing significantly more functions and do not look very different. What is it that is the resource hog now?

答:
A lot of it boils down to developer time and the cost of that time. Back in the days when Visual Basic first arrived on the scene, it was competing with C/C++ and the big knock against it was that you could write 'Hello World' in ANSI C for Windows in maybe 15K. The problem with VB was you always had the albatross of the 300K runtime library.

Now, you could 10x the size of your VB program and it would still be just a few K more, but 10x the size of your C/C++ program and you're looking at a few MONTHS more development.

In the end the bloat of your applications is a small price to pay for the huge leaps in development production, reduction in price and sheer vastness of capabilities that would have never been possible in the old hand-crafted days of development; when programs were small and fast but also weak, incompatible with each other, under-featured and costly to develop.

Title: Why are the sizes of programs so large?


问:
Launching web-app with database without static ip
I have created a small web-app and want to deploy it. I have used struts2 and mysql for the database. The problem is that I do not have a static ip to run the app on my machine. Can anyone suggest me hosting services that host java pages and mysql?

Since this is a project I am not doing for money, I would prefer free servers even if they are allowing usage for a short period of time.

答:
what about takint a DynDns account?

This is a Dynamic DNS Service which consists of:

An executable which runs on your PC and sends notifications to DNS Server of your current IP

The Dynamic Server

You url would consist then of a subdomain of dyndns which ever you choose. Take a look !

ContentLicense: CC BY-SA 2.5


答:
The purpose of these objects is really just to hold properties of the card. They don't really do anything by themselves.

This sentence is a sign that there is something wrong in your design: in OOP, each class should have exactly one role, and the lack of behaviour reveals a potential Data Class, which is a bad smell in the code.

After all, they are cards that represent themselves!

IMHO, it sounds a little bit strange, and even a little bit weird. An object of type "Card" should represent a card. Period.

I know nothing about Magic: The gathering, but I guess you want to use your cards in a similar way, whatever their actual structure is: you want to display a string representation, you want to compute an attack value, etc.

For the problem you describe, I would recommend a Composit Design Pattern, despite the fact this DP is typically presented for solving a more general problem:

Create a Card interface, as you already did.

Create a ConcreteCard, that implements Card and defines a simple face card. Don't hesitate to put the behaviour of a normal card in this class.

Create a CompositeCard, that implements Card and has two additional (and a priori private) Cards. Lets call them leftCard and rightCard.

The elegance of the approach is that a CompositeCard contains two cards, which themselves can be either ConcreteCard or CompositeCard. In your game, leftCard and rightCard will probably systematically be ConcreteCards, but the Design Pattern allows you to design higher level compositions for free if you want. Your card manipulation will not take into account the real type of your cards, and therefore you don't need things such as casting to subclass.

CompositeCard must implement the methods specified in Card, of course, and will do it by taking into account the fact that such a card is made of 2 cards (plus, if you want, something specific to the CompositeCard card itself. For instance, you may want the following implementation:

```<code>public class CompositeCard implements Card
{
   private final Card leftCard, rightCard;
   private final double factor;

   @Override // Defined in Card
   public double attack(Player p){
      return factor * (leftCard.attack(p) + rightCard.attack(p));
   }

   @Override // idem
   public String name()
   {
       return leftCard.name() + " combined with " + rightCard.name();
   }

   ...
}
</code>```

By doing that, you can use a CompositeCard exactly as you do for any Card, and the specific behaviour is hidden thanks to polymorphism.

If you are sure a CompositeCard will always contain two normal Cards, you can keep the idea, and simply use ConcreateCard as a type for leftCard and rightCard.

Title: How to make a datatype for something that represents either itself or two other things

Body:
Background

Here's the actual problem I'm working on: I want a way to represent cards in the card game Magic: The Gathering.  Most cards in the game are normal-looking cards, but some of them are divided into two parts, each with its own name.  Each half of these two-part cards is treated as a card itself.  So for clarity, I'll use Card only to refer to something that's either a regular card, or half of a two-part card (in other words, something with only one name).

So we have a base type, Card.  The purpose of these objects is really just to hold properties of the card.  They don't really do anything by themselves.

```<code>interface Card {
    String name();
    String text();
    // etc
}
</code>```

There are two subclasses of Card, which I'm calling PartialCard (half of a two-part card) and WholeCard (a regular card).  PartialCard has two additional methods: PartialCard otherPart() and boolean isFirstPart().

Representatives

If I have a deck, it should be composed of WholeCards, not Cards, as a Card could be a PartialCard, and that wouldn't make sense.  So I want an object that represents a "physical card," that is, something that can represent one WholeCard, or two PartialCards. I'm tentatively calling this type Representative, and Card would have the method getRepresentative().  A Representative would provide almost no direct information on the card(s) it represents, it would only point to it/them.  Now, my brilliant/crazy/dumb idea (you decide) is that WholeCard inherits from both Card and Representative.  After all, they are cards that represent themselves!  WholeCards could implement getRepresentative as return this;.

As for PartialCards, they don't represent themselves, but they have an external Representative that is not a Card, but provides methods for accessing the two PartialCards.

I think this type hierarchy makes sense, but it's complicated.  If we think of Cards as "conceptual cards" and Representatives as "physical cards," well, most cards are both!  I think you could make an argument that physical cards do in fact contain conceptual cards, and that they're not the same thing, but I would argue that they are.

Necessity of Type-casting

Because PartialCards and WholeCards are both Cards, and there's usually no good reason to separate them out, I'd normally just be working with Collection<Card>.  So sometimes I'd need to cast PartialCards in order to access their additional methods.  Right now, I'm using the system described here because I really don't like explicit casts.  And like Card, Representative would need be cast to either a WholeCard or Composite, to access the actual Cards they represent.

So just for summary:

Base type Representative

Base type Card

Type WholeCard extends Card, Representative (no access needed, it represents itself)

Type PartialCard extends Card (gives access to other part)

Type Composite extends Representative (gives access to both parts)

Is this insane?  I think it actually makes a lot of sense, but I'm honestly not sure.

Body:
The purpose of these objects is really just to hold properties of the card. They don't really do anything by themselves.

This sentence is a sign that there is something wrong in your design: in OOP, each class should have exactly one role, and the lack of behaviour reveals a potential Data Class, which is a bad smell in the code.

After all, they are cards that represent themselves!

IMHO, it sounds a little bit strange, and even a little bit weird. An object of type "Card" should represent a card. Period.

I know nothing about Magic: The gathering, but I guess you want to use your cards in a similar way, whatever their actual structure is: you want to display a string representation, you want to compute an attack value, etc.

For the problem you describe, I would recommend a Composit Design Pattern, despite the fact this DP is typically presented for solving a more general problem:

Create a Card interface, as you already did.

Create a ConcreteCard, that implements Card and defines a simple face card. Don't hesitate to put the behaviour of a normal card in this class.

Create a CompositeCard, that implements Card and has two additional (and a priori private) Cards. Lets call them leftCard and rightCard.

The elegance of the approach is that a CompositeCard contains two cards, which themselves can be either ConcreteCard or CompositeCard. In your game, leftCard and rightCard will probably systematically be ConcreteCards, but the Design Pattern allows you to design higher level compositions for free if you want. Your card manipulation will not take into account the real type of your cards, and therefore you don't need things such as casting to subclass.

CompositeCard must implement the methods specified in Card, of course, and will do it by taking into account the fact that such a card is made of 2 cards (plus, if you want, something specific to the CompositeCard card itself. For instance, you may want the following implementation:

public class CompositeCard implements Card
{
   private final Card leftCard, rightCard;
   private final double factor;

   @Override // Defined in Card
   public double attack(Player p){
      return factor * (leftCard.attack(p) + rightCard.attack(p));
   }

   @Override // idem
   public String name()
   {
       return leftCard.name() + " combined with " + rightCard.name();
   }

   ...
}

By doing that, you can use a CompositeCard exactly as you do for any Card, and the specific behaviour is hidden thanks to polymorphism.

If you are sure a CompositeCard will always contain two normal Cards, you can keep the idea, and simply use ConcreateCard as a type for leftCard and rightCard.


问:
Is it wise to store a big lump of json on a database row
I have this project which stores product details from amazon into the database.

Just to give you an idea on how big it is:

```<code>[
  {
    "title": "Genetic Engineering (Opposing Viewpoints)",
    "short_title": "Genetic Engineering ...",
    "brand": "",
    "condition": "",
    "sales_rank": "7171426",
    "binding": "Book",
    "item_detail_url": "http://localhost/wordpress/product/?asin=0737705124",
    "node_list": "Books > Science & Math > Biological Sciences > Biotechnology",
    "node_category": "Books",
    "subcat": "",
    "model_number": "",
    "item_url": "http://localhost/wordpress/wp-content/ecom-plugin-redirects/ecom_redirector.php?id=128",
    "details_url": "http://localhost/wordpress/product/?asin=0737705124",
    "large_image": "http://localhost/wordpress/wp-content/plugins/ecom/img/large-notfound.png",
    "medium_image": "http://localhost/wordpress/wp-content/plugins/ecom/img/medium-notfound.png",
    "small_image": "http://localhost/wordpress/wp-content/plugins/ecom/img/small-notfound.png",
    "thumbnail_image": "http://localhost/wordpress/wp-content/plugins/ecom/img/thumbnail-notfound.png",
    "tiny_img": "http://localhost/wordpress/wp-content/plugins/ecom/img/tiny-notfound.png",
    "swatch_img": "http://localhost/wordpress/wp-content/plugins/ecom/img/swatch-notfound.png",
    "total_images": "6",
    "amount": "33.70",
    "currency": "$",
    "long_currency": "USD",
    "price": "$33.70",
    "price_type": "List Price",
    "show_price_type": "0",
    "stars_url": "",
    "product_review": "",
    "rating": "",
    "yellow_star_class": "",
    "white_star_class": "",
    "rating_text": " of 5",
    "reviews_url": "",
    "review_label": "",
    "reviews_label": "Read all ",
    "review_count": "",
    "create_review_url": "http://localhost/wordpress/wp-content/ecom-plugin-redirects/ecom_redirector.php?id=132",
    "create_review_label": "Write a review",
    "buy_url": "http://localhost/wordpress/wp-content/ecom-plugin-redirects/ecom_redirector.php?id=19186",
    "add_to_cart_action": "http://localhost/wordpress/wp-content/ecom-plugin-redirects/add_to_cart.php",
    "asin": "0737705124",
    "status": "Only 7 left in stock.",
    "snippet_condition": "in_stock",
    "status_class": "ninstck",
    "customer_images": [
      "http://localhost/wordpress/wp-content/uploads/2013/10/ecom_images/51M2vvFvs2BL.jpg",
      "http://localhost/wordpress/wp-content/uploads/2013/10/ecom_images/31FIM-YIUrL.jpg",
      "http://localhost/wordpress/wp-content/uploads/2013/10/ecom_images/51M2vvFvs2BL.jpg",
      "http://localhost/wordpress/wp-content/uploads/2013/10/ecom_images/51M2vvFvs2BL.jpg"
    ],
    "disclaimer": "",
    "item_attributes": [
      {
        "attr": "Author",
        "value": "Greenhaven Press"
      },
      {
        "attr": "Binding",
        "value": "Hardcover"
      },
      {
        "attr": "EAN",
        "value": "9780737705126"
      },
      {
        "attr": "Edition",
        "value": "1"
      },
      {
        "attr": "ISBN",
        "value": "0737705124"
      },
      {
        "attr": "Label",
        "value": "Greenhaven Press"
      },
      {
        "attr": "Manufacturer",
        "value": "Greenhaven Press"
      },
      {
        "attr": "NumberOfItems",
        "value": "1"
      },
      {
        "attr": "NumberOfPages",
        "value": "224"
      },
      {
        "attr": "ProductGroup",
        "value": "Book"
      },
      {
        "attr": "ProductTypeName",
        "value": "ABIS_BOOK"
      },
      {
        "attr": "PublicationDate",
        "value": "2000-06"
      },
      {
        "attr": "Publisher",
        "value": "Greenhaven Press"
      },
      {
        "attr": "SKU",
        "value": "G0737705124I2N00"
      },
      {
        "attr": "Studio",
        "value": "Greenhaven Press"
      },
      {
        "attr": "Title",
        "value": "Genetic Engineering (Opposing Viewpoints)"
      }
    ],
    "customer_review_url": "http://localhost/wordpress/wp-content/ecom-customer-reviews/0737705124.html",
    "flickr_results": [
      "http://localhost/wordpress/wp-content/uploads/2013/10/ecom_images/5105560852_06c7d06f14_m.jpg"
    ],
    "freebase_text": "No around the web data available yet",
    "freebase_image": "http://localhost/wordpress/wp-content/plugins/ecom/img/freebase-notfound.jpg",
    "ebay_related_items": [
      {
        "title": "Genetic Engineering (Introducing Issues With Opposing Viewpoints), , Good Book",
        "image": "http://localhost/wordpress/wp-content/uploads/2013/10/ecom_images/140.jpg",
        "url": "http://localhost/wordpress/wp-content/ecom-plugin-redirects/ecom_redirector.php?id=12165",
        "currency_id": "$",
        "current_price": "26.2"
      },
      {
        "title": "Genetic Engineering Opposing Viewpoints by DAVID BENDER - 1964 Hardcover",
        "image": "http://localhost/wordpress/wp-content/uploads/2013/10/ecom_images/140.jpg",
        "url": "http://localhost/wordpress/wp-content/ecom-plugin-redirects/ecom_redirector.php?id=130",
        "currency_id": "AUD",
        "current_price": "11.99"
      }
    ],
    "no_follow": "rel=\"nofollow\"",
    "new_tab": "target=\"_blank\"",
    "related_products": [],
    "super_saver_shipping": "",
    "shipping_availability": "",
    "total_offers": "7",
    "added_to_cart": ""
  }
]
</code>```

So the structure for the table is:

asin

title

details (the product details in json)

Will the performance suffer if I have to store like 10,000 products? Is there any other way of doing this? I'm thinking of the following, but the current setup is really the most convenient one since I also have to use the data on the client side:

store the product details in a file. So something like ASIN123.json

store the product details in one big file. (I'm guessing it will be a drag to extract data from this file)

store each of the fields in the details in its own table field

Thanks in advance!

UPDATE

Thanks for the answers! I just want to add some more details to my question.
First, the records are updated for a specific interval. Only specific data such as the price or the title are updated.

Second, I'm also using the json encoded data in the client-side so I thought at first it would be easier to just have it json encoded so I can easily use it in the client side without having to convert. Does this change your opinion about simply storing the fields in a regular table field in an RDBMS setup?

答:
It is sometimes a better fit for the application to store a complete document as one entity. It is not a coincidence that nosql and document databases are on the rise.

If you are aware of the drawbacks it can be an ok approack but you should also consider a real document database instead of inventing your own.

ContentLicense: CC BY-SA 4.0


问:
Should I share test code between different repositories
Suppose I have a Repo A that imports a Repo B.  I maintain both of them.

Currently, I have some convenience functions that are useful for testing of both repos.  They live in Repo B's test directory.  When you install Repo B, it includes it test directory so that Repo A has access to these convenience functions.

Is this a reasonable software pattern?

One alternative would be copy and pasting the convenience functions into Repo A and divorcing the test suites.

答:
Is it a pattern? No, this is called "reuse". And it has nothing to do with the fact you have test code in mind.

Is it reasonable? It depends, sometimes it is, sometimes not, key factor is how tight the life cycle of A and B is or should be coupled. Reuse avoids duplicate maintenance, but it comes fot the price of coupling A and B together.

Is there a third alternative? Of course: refactoring of the convenience functions to a third, independent package C and using C from A and B. But is this better? It depends, same as above.


答:
When constructing software, if you need function A, you will import a module A*.  A* can solve A, but A* can solve problems more than A, and A* could be large. All the large modules result in the large-sized software.

Maybe not the same case, but something like this: If you  just need to print "hello world" on console using Java, you need JRE(>60MB) installed.

If the example of Java is not good, try this one: If the software need to logging to file, it may use a logging module which can actually make logs to database, over network and some other features, but the functions are never used in the project.

Title: Why are the sizes of programs so large?

Body:
If we look at the vintage program Netscape Navigator or an early version of Microsoft Word, those programs were less than 50 MB in size. Now when I install google chrome it is 200 MB and desktop version of Slack is 300 MB. I read about some rule that programs will take all available memory no matter how much it is but why?

Why are the current sizes of programs so large compared to 10 or 15 years ago? The programs are not doing significantly more functions and do not look very different. What is it that is the resource hog now?


答:
This is definitely true concerning Android applications. Four years ago, a simple app took about 2-5 megabyte space.
Nowadays a simple app takes about 10-20 megabyte space.

The more space available, the bigger the app size.

I think that there are two main reasons in case of Android:

Google expanded the Android framework, added a lot of new functionality.

Developers do not care anymore. Images are included in a far higher resolution (of course the smartphone screen resolutions increased), third-party libraries are thoughtlessly included.

Title: Why are the sizes of programs so large?


问:
Is reinventing the wheel really all that bad?
Its common knowledge in programming that reinventing the wheel is bad or evil.

But why is that?

I am not suggesting that it's good. I believe it to be wrong. However, I once read an article that said, if someone is doing something wrong (programming wise) explain to them why its wrong, if you can't, then maybe you should be asking yourself if it is really wrong.

That leads me to this question:

If I see someone is clearly reinventing the wheel by building their own method of something that is already built into the language/framework. First, for arguments sake, lets assume that their method is just as efficient as the built in method. Also the developer, aware of the built in method, prefers his own method.

Why should he use the built in one over his own?

答:
I recently blogged my thoughts on this topic. To summarize:

It's almost always evil to build your own, especially true if its a function thats built into the language. But if you're evaluating an immature / questionably-maintained / badly-documented framework you found on the Internet against the possibility of writing your own, it could be a no-brainer.

I think reinventing the wheel is a pretty awful analogy for a software anti-pattern. It implies that the original solution can never be improved upon. That is nonsense. The so-called wheel can become obsolete overnight, or its owners could stop maintaining it. The wheel has a different value at each system where it's used. So, it's often entirely possible to invent a better wheel.

One major benefit of making your own framework is that you won't have to take responsibility for someone else's bugs. (This is Amazon's philosophy.) Think of it this way: which of these is better to tell a customer? -

"Our website broke. It was someone else's fault, and we've logged a bug with its creator. There is nothing we can do about it except wait. We'll keep you updated."

"Our website broke, and we were able to fix it immediately."


问:
API Server Client Setup
Suppose you have a setup where there is an API Server and all interaction revolve around the API. There is the admin, public and third party components that interact with the API server.

Suppose we have an e-commerce model, the components' have the following capabilities: Admin - ability to manage products, orders and customer information Public - ability to manage customer and order information belonging to the user Third Party - ability to retrieve list of products, view orders - create orders in behalf of the user (meaning must have authorization from user) - view customer info (need authorization from user)

My concern is regarding authorization. I'm familiar how to handle the third party through the OAuth workflow. But I'm confused with the Admin and Public components. The said two components doesn't seem to fit the OAuth workflow were there are typically 3 actors: the server, consumer and user.

For example for the public component, it's the front facing application where your users can manage their profiles, order and view products. Are we going to treat this component as special from the API authorization perspective. The same goes with the admin component which offers the ability to manage almost all aspect of your application, even set API keys.

Just like Facebook, Twitter, etc.. They offer an API. But internally do they communicate using some sort of API as well?

Should these core components (UI for admin and public) NOT be decoupled from the API Server in the first place?

答:
The OAuth 2.0 authorization framework enables a third-party application to obtain limited access to an HTTP service, either on behalf of a resource owner by orchestrating an approval interaction between the resource owner and the HTTP service, or by allowing the third-party application to obtain access on its own behalf.  This specification replaces and obsoletes the OAuth 1.0 protocol described in RFC 5849.

Thats the abstract to RFC 6749.

So the simple answer is that's what it's for.  The less facetious answer is stop thinking in terms of multiple interactions all at once. Despite all the object facade all code is sequential.

Treat this as a cascade of interactions; where your library acts as intermediary between 2 sides.  It's harder to be more specific without details of your app.

What I would do is the old unix philosophy: build a test program that takes one object call from 3rd party, stores it somehow and passes it to secondary thread/ object etc. And then that thing interacts with HTTP service. Then revisit design

Why old timers recommend this way is it may not do much, but it illuminates your understanding of the problem far deeper than use cases.  Also, now you can tell your boss you're 50% complete with about 70% to go.

Title: API Server Client Setup


问:
Is it possible to take a flexible agile approach to projects that require estimates of both time taken and time saved?
As someone who's worked effectively with Agile before, I am trying to convince my current employers of its benefits. However, management are insistent that we retain the ability to make upfront estimates in order to assess the business value of projects.

Most of my customers are internal, and I was recently tasked with going round teams and asking them for ideas on business processes to automate. I was then to find out how much time this was taking them, work out how much time the solution would save and estimate the total development time. That way, managers could attempt to measure how effective a solution was likely to be in terms of time saved.

However, it looks to me like there's no way to approach this requirement in an "Agile" way. Flexible requirements means that not only will estimates of time taken be wrong, so will estimates of potential time saved. I explained as much, explained why it was likely to be problematic, but was told it was non-negotiable.

The question How to sell Agile development to (waterfall) clients has some useful advice on how to "sell" Agile to external customers. I'm not trying to sell it to external clients: I'm trying to work out how I can best reconcile the demands of internal management while retaining a methodology I believe works well.

Is there any way to approach this task in a flexible manner which allows me to retain at least some Agile benefits?

答:
This is certainly one of the toughest part of introducing Agile

"Management still needs time estimates"

My approach is:

Pad 300%.  The old saying of 300% is useful when you are in a situation where being really agile at a management level isn't going to happen.  This is not an "agile approach" perhaps but is a compromise for this situation.  You'll be able to come in ahead a few times - but don't count on it!

Ask for a review based on work achieved at what would would be the 'half-way' point of the project.  Project when you would be complete based on work done.  Then talk to management and go over which they which to sacrifice - functionality or quality - given that time is fixed based on guesses at the start of the project.

Make sure you are collaborating on features done and quality with management so they actually make those decisions

Go with the flow for this project and allow the usual things to happen - missed deadlines, compromised quality, burned out and stressed (and possibly departed) employees that leave.  When the next project of phase comes up, discuss these 'side-effects'.

Focus and demonstrate the advantages of a "true" agile approach.  Talk about the improvement in quality.  Talk about the ability to make changes late in the day right up to and past them going into production.  Talked about less need for re-work.  Talk about less technical debt that will eventually bring development to a crawl.  Make analogies to the real world, for example, we can put off an oil change on any day, but put it off long enough and the engine suffers, performs poorly and eventually blows a rod.

Keep your resume and linkedIn profile up to date.  If you can't get management support after making your case a few times, move on.  Some organizations will not listed to your arguments so move to ones that do.  Called it Darwinism employment ;)


答:
I think you are making false assumptions about Agile development. Flexibility and changing requirements are literally baked into the Agile Manifesto.

Welcome changing requirements, even late in development. Agile
  processes harness change for the customer's competitive advantage.

Flexible (read: changing) requirements are welcome in Agile. Granted if you ask most developers they will add a caveat that the change must be reasonable. Asking a team to build a 3D game then changing the requirements to be "control system for a nuclear reactor" is a bit much. But adding, removing, or modifying requirements in the scope of the project is perfectly fine.

The question is how do you cope with changing requirements? The typical answer is to use short iterations so you can make course adjustments early on before you waste too much time. It also forces the team to decompose requirements into smaller pieces so everyone can better understand them and implement them in a reasonable amount of time and effort.

Simplicity--the art of maximizing the amount of work not done--is
  essential.

I also like this Agile principle. It normally is taken to mean that a team should strive to deliver only those things that are necessary through ruthless efficiency. For example: if the customer thinks they need something but it seems fishy, dig around. Maybe the end users really have no use for it, so the work should not be done.

However, I think your question hit on another aspect of this principle. Software generally serves the purpose of automating a manual process. The software itself exists to maximize the amount of work not done -- by the end users.

Measuring the amount of labor that software will save the end users is definitely a worthy metric. I have measured this myself in my career. It is actually a critical component of a cost/benefit analysis: how much effort will the software project take to implement, compared to how much effort the final product will save the end users.

This is absolutely compatible with the Agile (or any other) development philosophy and your management absolutely should buy into this.

Title: Is it possible to take a flexible agile approach to projects that require estimates of both time taken and time saved?

Body:
As someone who's worked effectively with Agile before, I am trying to convince my current employers of its benefits. However, management are insistent that we retain the ability to make upfront estimates in order to assess the business value of projects.

Most of my customers are internal, and I was recently tasked with going round teams and asking them for ideas on business processes to automate. I was then to find out how much time this was taking them, work out how much time the solution would save and estimate the total development time. That way, managers could attempt to measure how effective a solution was likely to be in terms of time saved.

However, it looks to me like there's no way to approach this requirement in an "Agile" way. Flexible requirements means that not only will estimates of time taken be wrong, so will estimates of potential time saved. I explained as much, explained why it was likely to be problematic, but was told it was non-negotiable.

The question How to sell Agile development to (waterfall) clients has some useful advice on how to "sell" Agile to external customers. I'm not trying to sell it to external clients: I'm trying to work out how I can best reconcile the demands of internal management while retaining a methodology I believe works well.

Is there any way to approach this task in a flexible manner which allows me to retain at least some Agile benefits?


问:
How to test the best combination of ratios to fit inside an overarching ratio?
We have a problem we are trying to solve where we have a number of different containers. Each container can hold a number of different items (call them "item A" through to "item H"). Each container can handle a different ratio of the items before it is full. So taking just three of the containers the ratios the can handle may be:

Container 1 may be able to hold the items in the ratio like below:

```<code>A  B  C  D  E  F  G  H
1  2  3  3  3  3  2  1
</code>```

Container 2 may be able to hold the items in the ratio like below:

```<code>A  B  C  D  E  F  G  H
1  2  3  4  4  3  2  1
</code>```

Container 3 may be able to hold the items in the ratio like below:

```<code>A  B  C  D  E  F  G  H
1  1  2  2  3  3  4  4
</code>```

What we need to try and find out is how to best fit packs of items with smaller ratios with a maximum number of items (say 5 or 6) into the containers. We can find all the different permutations of packs using combinatorics. We have a limit that out of all of the pack ratio permutations we can only select 3 or 4 different ones to use, so have to discard the worst fits and keep the best 3 or 4.

What we are struggling with is a technique that can test for the best of the smaller packs into the larger containers that is both accurate and performant. Currently we have one or the other!

Any maths geniuses out there that can help?

答:
This is a classic packing optimization problem and it belongs to the field of Computer Science, not Mathematics. The relevant literature is about algorithms for Packing Optimization or Container Optimization.

Take a look at the "Knapsack Problem" in wikipedia:

https://en.wikipedia.org/wiki/Knapsack_problem

Also, take a look at the "Bin Packing Problem" in wikipedia:

https://en.wikipedia.org/wiki/Bin_packing_problem

Related StackOveflow question about Bin Packing:

https://stackoverflow.com/questions/12056526/bin-packing-algorithm


答:
This is not a problem with "management".  It is an absolute requirement to be able to estimate the cost and benefit of any potential project before starting.  Otherwise, how would anyone know what is worth doing (or attempting)?

Then why Agile?

I would argue that to use Agile methods is not to choose uncertainty.  Rather, Agile is an argument that uncertainty is inevitable, and the detailed specifications and estimates of traditional methods introduce false certainty--which can be quite costly.

Some key points in terms of time estimation:

Changes to requirements throughout a project are inevitable; Agile takes this into account rather than pretending there will be no change.

Detailed specifications often contain design flaws that are not uncovered until well into the project.  This may mean bigger changes in a traditional project than an Agile one.

A time estimate based on "how big of a thing do I think this whole project is?" is likely to be just as accurate as adding up the estimated time for many detailed requirements.

The main thing that leads to good estimates is a cycle of estimating, measuring, and reviewing--which can be applied to any consistent process.

The "work saved" estimate is going to be driven by the primary requirements for the project rather than the details, so I doubt Agile would much harm the ability to estimate this.

Update:

Just to clarify, your response to your bosses seems to be "We can't estimate time saved or total development effort very well using Agile, because it is flexible."  I think this is mistaken.  I believe these estimates can be made just as well when using an Agile process, since the uncertainty is there anyway.
And of course Agile allows for a more flexible and responsive process as the project unfolds.


答:
Assuming you don't have an immediate need to query over those JSON fields, then there's nothing wrong with this approach, so long as the performance hit of deserializing/serializing isn't a problem for your program.

Later on, let's say the requirement comes in to order/filter based on that "sales_rank" JSON field. You'd write a program to run over the data and deserialize the object, copying out that field to a dedicated column in the table, which would then be indexed. You'll need a custom serialization/update routine to make sure you keep this discreet column maintained in sync w/ the JSON object, but that's not hard.

This kind of hybrid approach can be very useful when you are still figuring out the app's functionality, as you get the fast development speed of NoSQL, with the benefit of relational modeling for the fields that need it.

Title: Is it wise to store a big lump of json on a database row

Body:
I have this project which stores product details from amazon into the database.

Just to give you an idea on how big it is:

```<code>[
  {
    "title": "Genetic Engineering (Opposing Viewpoints)",
    "short_title": "Genetic Engineering ...",
    "brand": "",
    "condition": "",
    "sales_rank": "7171426",
    "binding": "Book",
    "item_detail_url": "http://localhost/wordpress/product/?asin=0737705124",
    "node_list": "Books > Science & Math > Biological Sciences > Biotechnology",
    "node_category": "Books",
    "subcat": "",
    "model_number": "",
    "item_url": "http://localhost/wordpress/wp-content/ecom-plugin-redirects/ecom_redirector.php?id=128",
    "details_url": "http://localhost/wordpress/product/?asin=0737705124",
    "large_image": "http://localhost/wordpress/wp-content/plugins/ecom/img/large-notfound.png",
    "medium_image": "http://localhost/wordpress/wp-content/plugins/ecom/img/medium-notfound.png",
    "small_image": "http://localhost/wordpress/wp-content/plugins/ecom/img/small-notfound.png",
    "thumbnail_image": "http://localhost/wordpress/wp-content/plugins/ecom/img/thumbnail-notfound.png",
    "tiny_img": "http://localhost/wordpress/wp-content/plugins/ecom/img/tiny-notfound.png",
    "swatch_img": "http://localhost/wordpress/wp-content/plugins/ecom/img/swatch-notfound.png",
    "total_images": "6",
    "amount": "33.70",
    "currency": "$",
    "long_currency": "USD",
    "price": "$33.70",
    "price_type": "List Price",
    "show_price_type": "0",
    "stars_url": "",
    "product_review": "",
    "rating": "",
    "yellow_star_class": "",
    "white_star_class": "",
    "rating_text": " of 5",
    "reviews_url": "",
    "review_label": "",
    "reviews_label": "Read all ",
    "review_count": "",
    "create_review_url": "http://localhost/wordpress/wp-content/ecom-plugin-redirects/ecom_redirector.php?id=132",
    "create_review_label": "Write a review",
    "buy_url": "http://localhost/wordpress/wp-content/ecom-plugin-redirects/ecom_redirector.php?id=19186",
    "add_to_cart_action": "http://localhost/wordpress/wp-content/ecom-plugin-redirects/add_to_cart.php",
    "asin": "0737705124",
    "status": "Only 7 left in stock.",
    "snippet_condition": "in_stock",
    "status_class": "ninstck",
    "customer_images": [
      "http://localhost/wordpress/wp-content/uploads/2013/10/ecom_images/51M2vvFvs2BL.jpg",
      "http://localhost/wordpress/wp-content/uploads/2013/10/ecom_images/31FIM-YIUrL.jpg",
      "http://localhost/wordpress/wp-content/uploads/2013/10/ecom_images/51M2vvFvs2BL.jpg",
      "http://localhost/wordpress/wp-content/uploads/2013/10/ecom_images/51M2vvFvs2BL.jpg"
    ],
    "disclaimer": "",
    "item_attributes": [
      {
        "attr": "Author",
        "value": "Greenhaven Press"
      },
      {
        "attr": "Binding",
        "value": "Hardcover"
      },
      {
        "attr": "EAN",
        "value": "9780737705126"
      },
      {
        "attr": "Edition",
        "value": "1"
      },
      {
        "attr": "ISBN",
        "value": "0737705124"
      },
      {
        "attr": "Label",
        "value": "Greenhaven Press"
      },
      {
        "attr": "Manufacturer",
        "value": "Greenhaven Press"
      },
      {
        "attr": "NumberOfItems",
        "value": "1"
      },
      {
        "attr": "NumberOfPages",
        "value": "224"
      },
      {
        "attr": "ProductGroup",
        "value": "Book"
      },
      {
        "attr": "ProductTypeName",
        "value": "ABIS_BOOK"
      },
      {
        "attr": "PublicationDate",
        "value": "2000-06"
      },
      {
        "attr": "Publisher",
        "value": "Greenhaven Press"
      },
      {
        "attr": "SKU",
        "value": "G0737705124I2N00"
      },
      {
        "attr": "Studio",
        "value": "Greenhaven Press"
      },
      {
        "attr": "Title",
        "value": "Genetic Engineering (Opposing Viewpoints)"
      }
    ],
    "customer_review_url": "http://localhost/wordpress/wp-content/ecom-customer-reviews/0737705124.html",
    "flickr_results": [
      "http://localhost/wordpress/wp-content/uploads/2013/10/ecom_images/5105560852_06c7d06f14_m.jpg"
    ],
    "freebase_text": "No around the web data available yet",
    "freebase_image": "http://localhost/wordpress/wp-content/plugins/ecom/img/freebase-notfound.jpg",
    "ebay_related_items": [
      {
        "title": "Genetic Engineering (Introducing Issues With Opposing Viewpoints), , Good Book",
        "image": "http://localhost/wordpress/wp-content/uploads/2013/10/ecom_images/140.jpg",
        "url": "http://localhost/wordpress/wp-content/ecom-plugin-redirects/ecom_redirector.php?id=12165",
        "currency_id": "$",
        "current_price": "26.2"
      },
      {
        "title": "Genetic Engineering Opposing Viewpoints by DAVID BENDER - 1964 Hardcover",
        "image": "http://localhost/wordpress/wp-content/uploads/2013/10/ecom_images/140.jpg",
        "url": "http://localhost/wordpress/wp-content/ecom-plugin-redirects/ecom_redirector.php?id=130",
        "currency_id": "AUD",
        "current_price": "11.99"
      }
    ],
    "no_follow": "rel=\"nofollow\"",
    "new_tab": "target=\"_blank\"",
    "related_products": [],
    "super_saver_shipping": "",
    "shipping_availability": "",
    "total_offers": "7",
    "added_to_cart": ""
  }
]
</code>```

So the structure for the table is:

asin

title

details (the product details in json)

Will the performance suffer if I have to store like 10,000 products? Is there any other way of doing this? I'm thinking of the following, but the current setup is really the most convenient one since I also have to use the data on the client side:

store the product details in a file. So something like ASIN123.json

store the product details in one big file. (I'm guessing it will be a drag to extract data from this file)

store each of the fields in the details in its own table field

Thanks in advance!

UPDATE

Thanks for the answers! I just want to add some more details to my question.
First, the records are updated for a specific interval. Only specific data such as the price or the title are updated.

Second, I'm also using the json encoded data in the client-side so I thought at first it would be easier to just have it json encoded so I can easily use it in the client side without having to convert. Does this change your opinion about simply storing the fields in a regular table field in an RDBMS setup?


问:
Why can we not insert into files without the additional writes? (I neither mean append, nor over-write)
This occurs as a programming language independent problem to me.

I have a file with the content

```<code>aaabddd
</code>```

When I want to insert C behind b then my code needs to rewrite ddd to get

```<code>aaabCddd
</code>```

Why can I not just insert C at this position?

I can not do this in Java, Python, ... . I can not do this in Linux, Windows, ... . Am I right?

I do not understand why C can't simply be inserted without the additional writes.  Would someone please explain why this is so?

答:
The most efficient way to insert a block of bytes in the middle of a file would be to:

Map the file to memory

Append the bytes at the end of the memory image of the file

Rotate these files into place (with a standard algorithm available in the C++ Standard Library, for instance)

Let the OS take care of writing dirty blocks to disk


答:
I've never worked in any company that was able to have consistently good time estimates, nor have I ever worked with anyone who claims to have done so either. Searching will show you that estimation is an unsolved problem across the industry.

I'd try to get buy-in about measuring velocity based on abstract story points, and if you can't do that, I'd pad your estimates more.


答:
As other answers have stated, Management has every right to get a high level estimate upfront of a project.  They are not unreasonable for trying to determine ROI.

One of the approaches that I like about Agile however is that the scope of a project is not fixed.  It can be initially sized out at the Feature and Epic level, then business can determine ROI based on what are the most important features.  Maybe the fancy UI with bells and whistles has low business value, but the workflow engine for handling claims has a high ROI.

When you lump the whole project together then it harder to meet ROI than if you focus on the critical business functionality that is desired.

Here is a way that I have done this:

Take your WBS milestones and turn each of these into a deliverable feature

This allows you to categorize your project into mini subprojects that have varying business value.  Each of these should stand on their own in terms of business value.

T-Shirt Size the Effort on Features

This is a very easy way to get a rough idea about how big or involved a particular feature might be.  Perhaps low value features still have a great ROI if they look like easy wins.

Break Down a Feature into Stories

Go through the exercise to find a small feature that is well understood and break it down into stories initially.  Estimate these stories by points.  Now you have a basis where

Small -> 40 points

This will be a basis of comparison to other features

Associate story point effort to all Features

Compare your Small Feature to other features.  For example,

Medium Feature Y feels like it is twice the size and effort of Small Feature X of 40 story points.

Medium Feature Y is probably 80 story points.  Continue this until you have story points estimated at a high level for all features.

Estimate your Team Velocity

Looking at your development team, try to determine how many story points could this team effectively deliver in a given sprint.  If you have previous Agile projects as an example with this team that is a great place to start.  If you do not have such history behind the team then go through a mock Sprint Planning with your team where you start looking at your Small feature that you have detailed out.  What kinds of hourly estimates are people giving for their tasks on these stories?

Based on how much work the team thinks they can deliver in 2 weeks, use that total story point number as the average potential velocity of your team!

Find your Projected Completion Date

If your team in mock sprint planning feels comfortable delivering 25 story points in a sprint, and your total backlog looks like 300 story points for the gold Cadillac version of your project, then it looks like your team would ideally take 12 sprints or 24 weeks to complete everything.

Now it is trivial to turn cost of resources on your team into dollars per week to arrive at a cost for ROI vs. Business Value.  The negotiation can continue on what the most important features are and then your project management becomes basically a Knapsack Problem.


问:
automatic database fill up in sql script tests

The problem

I am working on an application with ~ 1000 tables in a sql server database. I am having a recurring issue with a sql script.

The script is used by the consulting team to "clean" some part of the database and sometimes it will fail because a new table with a foreign key constraint was added a few month ago and until this moment no one ran the script with any data in this new table. A foreign key violation is raised and everyone yells at the devs for their crappy tools.

There is a CI test on this script, but no ones updates the data provided in the test. So the test never fails because the new tables are left empty, but the script still fails in real environments.

The possible solution

I would like to make sure that every table in the database contains at least a few rows when the script CI test is run. I could try to maintain a manual script to fill up the data and add a test that checks that every table contains some rows but I fear that it will be a maintenance nightmare.

Another solution is to have another powershell/sql that script analyses the schema and creates rows according to the column types with constant/random values in all tables ordered using a topological ordering based on the foreign keys relation graph. The script would first fill table without relations, then tables with relations to the already filled tables, etc

I have two questions:

does this solution seems reasonable?

am I overcomplicating things? is there simpler way to make sure a sql script won't fail because  of foreign key constraint violations?

I checked existing tools but the static analysis tools don't seem to have the required features and the data generation tools are used to specify "realistic" data which I don't care about.

答:
You need to throw this back on the developers who are breaking the SQL. They are in the best position to update the SQL as they make changes which are fresh in their minds.

The simplest way to accomplish this is to use continuous integration.

Set up a test DB. Periodically, a CI build server will look at the source code repository for new check-ins. If it finds one, it runs the build.

Aside from compilation, the build should also deploy your application and test stuff like does it produce a valid executable file, do the SQL scripts run against a test DB, etc.

During the build, the DB should be rebuilt (backup, created from script, whatever is appropriate). Some process such as a stored procedure built for this purpose should ensure that data exists in all tables: that is, no table is empty.

Whenever a developer checks in a change that breaks your SQL script, it will break the build because a table is empty (no test data) or the clean procedure was not updated, or both. Eventually, developers will have to update the SQL when checking in their changes because without a functioning build, it cannot be deployed or tested and they are paid to produce a functional piece of software.


问:
Designing my classes with relationships
I need to build a UI for entering values to the database. I am stuck with my class design to achieve it.

I need a UI where I am able to enter the name of the system. Each system can have many options. Each option is associated with a TC(Technical chara). Each TC has another set of values which is described as TCset. For instance, let's say Tcset for a TC (TC1) has values: TC1.1, TC1.2, TC1.3. (There other variables describing each row in the TCset, I have mentioned the name property alone for simplicity. Now again coming back to the system, the option defined in each system can have multiple option values.  For each option value I should be able to enter a value for the name property in TCset associated with the TC of that option.)

What I would like to achieve would be something similar to this.

Adding a system and defining the Options:

Adding Value for Option and value for SetVal:

Based on my understanding I have designed the following class diagram. But still I can't find the exact mapping between the Option and SetVal. I am unable to design a class where I could add values for the Tcset in a particular option

```<code>public class Lsystem
{
    public int LsystemID { get; set; }
    public string LsystemName { get; set; }
    public virtual ICollection<Option> Options { get; set; }
    public int OptionId { get; set; }

}

public class Option
{
    public int OptionID { get; set; }
    public string OptionName { get; set; }
    public int TCID { get; set; }
    public virtual TC tc { get; set; }
    public virtual Lsystem Lsystem { get; set; }
    public int LsystemID { get; set; }
    public virtual ICollection<OptionValue> OptionValues { get; set; }
}

public class OptionValue
{
    public int OptionValueID { get; set; }
    public string ValName { get; set; }
   //public int TCsetID { get; set; }
    public int OptionID { get; set; }
    public int SetValID { get; set; }
    public virtual Option Option { get; set; }
  //public virtual TCset TCset { get; set; }
    public virtual SetVal SetVal { get; set; }
}

public class TC
{
    public int TCID { get; set; }
    public string TCName { get; set; }
    public virtual ICollection<TCset> TCsets { get; set; }
}

public class SetVal
{
    public int SetValId { get; set; }
    public double Value { get; set; }
    public int OptionID { get; set; }
    public int TCsetID { get; set; }
    public virtual OptionValue OptionValue { get; set; }
    public virtual TCset TCset { get; set; }
}

public class TCset
{
    public int TCsetID { get; set; }
    public string TCsetName { get; set; }
    public string PhysicalUnit { get; set; }
    public int TCID { get; set;}
    public virtual TC TC { get; set; }

}
</code>```

Is there something I am missing to get it right. But the current class model doesn't work because foreign key conflicts. That made me add another class SetVal but did not solve my problem. I have tried a lot to get all the relationships right but nothing worked out.

Just for a briefing, the relationships that I have used here:

```<code>  System - Option : One to Many
  Option - OptionValue : One to Many
  Option - TC : Many to One
  TC - TCset : One to many
  OptionValue - SetVal : One to One
  TCset - Setval : One to One
</code>```

Edit

The point where i am stuck is generating a table which would take option value id and give an option to add values for the tcset.

That is Under Option Value Ab1, i need a table to give values like the following

Option Value Ab1

ABC1    -    45
ABC2    -    34

Option Value Pq1

PQR1   -    67
Pqr2   -    34
pqr3   -    56

Option Value Pq2

PQR1  -    67
pqr2  -    34
pqr3  -    67

This connection is what i am missing. i realized this when i was trying to make tables the way it was made in the answer

Edit : 2 Adding example

```<code>     +--------------------------+
     |  SystemId  | System Name |
     +------------+-------------+
     |     1      |   DCC - 050 |
     |____________|_____________|
     |     2      |   DCC - 070 |
     |____________|_____________|

     ____________________________
     |  TCID      | TCName      |
     |____________|_____________|
     |    1       | Screw       |
     |____________|_____________|
     |    2       |  Motor      |
     |____________|_____________|

     __________________________________________________________
     | TCSetID   | TCsetname|PhysicalUnit | DataUsage | TCID   |
     |___________|__________|_____________|___________|________|
     |    1      | speed    | m/sec       | Prelimina |   1    |
     |___________|__________|_____________|___________|________|
     |    2      | d_0      | mm          | final     |   1    |
     |___________|__________|_____________|___________|________|
     |    3      | d_1      | m           | final     |   1    |
     |___________|__________|_____________|___________|________|
     |    4      | torque   |  mm         | final     |   2    |
     |___________|__________|_____________|___________|________|

     ____________________________________
     |OptionID | SystemID | TCID |OpName |
     |_________|__________|______|_______|
     |    1    |     1    |  1   |Screw  |
     |_________|__________|______|_______|
     |    2    |     1    |  2   |Motor  |
     |_________|__________|______|_______|

     _______________________________________________
     |OptionvalID | SystemID|OptionID | OptionValue|
     |____________|_________|_________|____________|
     |    1       |    1    |    1    |    01      |
     |____________|_________|_________|____________|
     |    2       |    1    |    1    |    02      |
     |____________|_________|_________|____________|
     |    3       |    1    |    1    |    03      |
     |____________|_________|_________|____________|
     |    4       |    1    |    2    |    01      |
     |____________|_________|_________|____________|
     |    5       |    1    |    2    |    02      |
     |____________|_________|_________|____________|
</code>```

Now the main issue is, i want to give values for the TCsetname in each option. My resulting table would be the following (This is not the database schema)

SCREW

```<code>     __________________________________________
     |TCSet |     01   |    02    |    03     | => Option values for Screw
     |______|__________|__________|___________|
     |speed |    12    |    14    |     16    |
     |______|__________|__________|___________|
     |d_0   |    34    |    56    |     56    |
     |______|__________|__________|___________|
     |d_1   |    2     |     5    |     6     |
     |______|__________|__________|___________|
</code>```

MOTOR

```<code>     ______________________________
     |TCSet |     01   |    02    | => Option Values for the Option Motor
     |______|__________|__________|
     |Torqu |    12    |    14    |
     |______|__________|__________|
</code>```

I am looking to correct the datamodel which accepts the last table

答:
User story

Based on my current understanding of your program, it's dealing with information about various systems, where different systems can have different properties. Each property has a limited set of possible values. However, users must be able to define new properties and must be able to modify their set of possible values.

Let's assume we'll use it to track spare engine parts, just to make things more concrete. Pretty much every spare part (system) has a name and a manufacturer. For some parts, it's important to know their weight, while for others, we need to know their color. So far, we've got 4 different properties: Name, Manufacturer, Weight and Color (but we'll assume that every part has a name so that's the only property that won't be configurable).

Let's also assume we're only dealing with 2 different manufacturers (Wheelers and BigCorp), only 3 weight classes (Light, Medium and Heavy) and 3 different colors (Red, Blue and Green).

Spare part 'Large wheel' is made by Wheelers and has a Medium weight, but we don't care about its color. Spare part 'Front window' is made by BigCorp and it's Green, but we don't care about its weight.

Database schema

We need to store information about options and their available values (Manufacturer -> Wheelers and BigCorp, Weight -> Light, Medium and Heavy, Color -> Red, Blue and Green). This is what I called 'blueprint data'. It describes what options and values a user can choose from, but does not store any actual system data.

```<code>option table:
+----+--------------+
| id | name         |
+----+--------------+
| 1  | Manufacturer |
| 2  | Weight       |
| 3  | Color        |
+----+--------------+

option_value table:
+----+-----------+----------+
| id | option_id | value    |
+----+-----------+----------+
| 1  | 1         | Wheelers |
| 2  | 1         | BigCorp  |
| 3  | 2         | Light    |
| 4  | 2         | Medium   |
| 5  | 2         | Heavy    |
| 6  | 3         | Red      |
| 7  | 3         | Blue     |
| 8  | 3         | Green    |
+----+-----------+----------+
</code>```

We also need to store information about actual systems, which properties are relevant to them and what values are selected for those properties ('Large Wheel', made by Wheelers, Medium weight, and 'Front window', made by BigCorp, Green color).

```<code>system table:
+----+--------------+
| id | name         |
+----+--------------+
| 1  | Large wheel  |
| 2  | Front window |
+----+--------------+

system_property table:
+-----------+-----------+-----------------+
| system_id | option_id | option_value_id |
+-----------+-----------+-----------------+
| 1         | 1         | 1               | // Large Wheel is made by Wheelers
| 1         | 2         | 4               | // Large Wheel has Medium weight
| 2         | 1         | 2               |
| 2         | 3         | 8               |
+-----------+-----------+-----------------+
</code>```

Code

We can represent this with the following classes:

```<code>public class Option
{
    public string Name { get; set; }
    public ICollection<OptionValue> AvailableValues { get; set; }

    // Database-related fields:
    public int ID { get; set; }
}

public class OptionValue
{
    public string Value { get; set; }

    // Database-related fields:
    public int OptionID { get; set; }
    public int ID { get; set; }

    // Parenting:
    public Option Parent { get; set; }
}

public class System
{
    public string Name { get; set; }
    public ICollection<SystemProperty> Properties { get; set; }

    // Database-related fields:
    public int ID { get; set; }
}

public class SystemProperty
{
    public Option Option { get; set; }
    public OptionValue SelectedValue { get; set; }

    // Database-related fields:
    public int SystemID { get; set; }
    public int OptionID { get; set; }
    public int OptionValueID { get; set; }

    // Parenting:
    public System Parent { get; set; }
}
</code>```

Conclusion

Glancing at the screenshot, you'd also need an IsEnabled property in SystemOption. Physical units and double values are also missing, but it's not clear to me where those should fit in. Still, the above contains only 4 classes as opposed to 6, and the emerging relationships seem to be fairly straightforward:

The program can contain multiple options, where each option can have multiple possible values.

The program can also contain multiple systems, where each system can have multiple properties.

A property refers to a specific value for a specific option.

I've also given different names to a few things, which I hope will clear up some of the confusion.

Title: Designing my classes with relationships

Body:
User story

Based on my current understanding of your program, it's dealing with information about various systems, where different systems can have different properties. Each property has a limited set of possible values. However, users must be able to define new properties and must be able to modify their set of possible values.

Let's assume we'll use it to track spare engine parts, just to make things more concrete. Pretty much every spare part (system) has a name and a manufacturer. For some parts, it's important to know their weight, while for others, we need to know their color. So far, we've got 4 different properties: Name, Manufacturer, Weight and Color (but we'll assume that every part has a name so that's the only property that won't be configurable).

Let's also assume we're only dealing with 2 different manufacturers (Wheelers and BigCorp), only 3 weight classes (Light, Medium and Heavy) and 3 different colors (Red, Blue and Green).

Spare part 'Large wheel' is made by Wheelers and has a Medium weight, but we don't care about its color. Spare part 'Front window' is made by BigCorp and it's Green, but we don't care about its weight.

Database schema

We need to store information about options and their available values (Manufacturer -> Wheelers and BigCorp, Weight -> Light, Medium and Heavy, Color -> Red, Blue and Green). This is what I called 'blueprint data'. It describes what options and values a user can choose from, but does not store any actual system data.

option table:
+----+--------------+
| id | name         |
+----+--------------+
| 1  | Manufacturer |
| 2  | Weight       |
| 3  | Color        |
+----+--------------+

option_value table:
+----+-----------+----------+
| id | option_id | value    |
+----+-----------+----------+
| 1  | 1         | Wheelers |
| 2  | 1         | BigCorp  |
| 3  | 2         | Light    |
| 4  | 2         | Medium   |
| 5  | 2         | Heavy    |
| 6  | 3         | Red      |
| 7  | 3         | Blue     |
| 8  | 3         | Green    |
+----+-----------+----------+

We also need to store information about actual systems, which properties are relevant to them and what values are selected for those properties ('Large Wheel', made by Wheelers, Medium weight, and 'Front window', made by BigCorp, Green color).

system table:
+----+--------------+
| id | name         |
+----+--------------+
| 1  | Large wheel  |
| 2  | Front window |
+----+--------------+

system_property table:
+-----------+-----------+-----------------+
| system_id | option_id | option_value_id |
+-----------+-----------+-----------------+
| 1         | 1         | 1               | // Large Wheel is made by Wheelers
| 1         | 2         | 4               | // Large Wheel has Medium weight
| 2         | 1         | 2               |
| 2         | 3         | 8               |
+-----------+-----------+-----------------+

Code

We can represent this with the following classes:

public class Option
{
    public string Name { get; set; }
    public ICollection<OptionValue> AvailableValues { get; set; }

    // Database-related fields:
    public int ID { get; set; }
}

public class OptionValue
{
    public string Value { get; set; }

    // Database-related fields:
    public int OptionID { get; set; }
    public int ID { get; set; }

    // Parenting:
    public Option Parent { get; set; }
}

public class System
{
    public string Name { get; set; }
    public ICollection<SystemProperty> Properties { get; set; }

    // Database-related fields:
    public int ID { get; set; }
}

public class SystemProperty
{
    public Option Option { get; set; }
    public OptionValue SelectedValue { get; set; }

    // Database-related fields:
    public int SystemID { get; set; }
    public int OptionID { get; set; }
    public int OptionValueID { get; set; }

    // Parenting:
    public System Parent { get; set; }
}

Conclusion

Glancing at the screenshot, you'd also need an IsEnabled property in SystemOption. Physical units and double values are also missing, but it's not clear to me where those should fit in. Still, the above contains only 4 classes as opposed to 6, and the emerging relationships seem to be fairly straightforward:

The program can contain multiple options, where each option can have multiple possible values.

The program can also contain multiple systems, where each system can have multiple properties.

A property refers to a specific value for a specific option.

I've also given different names to a few things, which I hope will clear up some of the confusion.


问:
What is the difference between WCF service and a simple Web service in developing using .NET Framework?
My questions are:

What is the difference between WCF service and a simple Web service in .NET Framework?

What a WCF Service can do which a .NET Web service cant? In other words, what are the limitation of .NET Web services which were overcome in WCF services?

I understand that WCF are REST based and .NET web services are SOAP based. But I need to know more than that. How a developer will make a design decision whether to developer a Web service or a WCF service?

答:
The major difference is that things like binding are configurable through the config files - you can change from http to tcp or anything else just by editing your config. Same with a lot of parameters (buffer sizes etc).

There is absolutely no reason to create simple web services if you have the option of using WCF.


答:
It sounds to me like you've got at least 3 environments; dev, ci, and production,  and that the ci environment's database isn't being kept in a realistic condition.

Given that, I would say that the first option you offer, "I could try to maintain a manual script to fill up the data" is non-optimal - a CI server should be as fully-automated as possible, no "manual" scripts.

That said, we do use a process that creates data at the beginning of every CI run. We also use it in our dev and test environments and it's the responsibility of the development team (which in our case includes both "development" and "testing" tasks) to keep it up-to-date. As developers, we often (sometimes multiple times/day) wipe our local db and use this process to ensure we have a valid environment.

note: we consider that process to be just as important as test code, which is just as important as "real" code - so it's maintained and under source control.

Title: automatic database fill up in sql script tests

Body:
The problem

I am working on an application with ~ 1000 tables in a sql server database. I am having a recurring issue with a sql script.

The script is used by the consulting team to "clean" some part of the database and sometimes it will fail because a new table with a foreign key constraint was added a few month ago and until this moment no one ran the script with any data in this new table. A foreign key violation is raised and everyone yells at the devs for their crappy tools.

There is a CI test on this script, but no ones updates the data provided in the test. So the test never fails because the new tables are left empty, but the script still fails in real environments.

The possible solution

I would like to make sure that every table in the database contains at least a few rows when the script CI test is run. I could try to maintain a manual script to fill up the data and add a test that checks that every table contains some rows but I fear that it will be a maintenance nightmare.

Another solution is to have another powershell/sql that script analyses the schema and creates rows according to the column types with constant/random values in all tables ordered using a topological ordering based on the foreign keys relation graph. The script would first fill table without relations, then tables with relations to the already filled tables, etc

I have two questions:

does this solution seems reasonable?

am I overcomplicating things? is there simpler way to make sure a sql script won't fail because  of foreign key constraint violations?

I checked existing tools but the static analysis tools don't seem to have the required features and the data generation tools are used to specify "realistic" data which I don't care about.


问:
How should I pass login data from client to server using REST API
I want to create a new session, the new session will be created by logging in (naturally).

Should I pass the username and password:

via URL (POST request to session?username=:username&password=:password)

or should I use a header instead (for instance - Authorization?)?

I want to stress that the session is not existent, I want to create it.

答:
I recommend keeping your RESTful interface stateless.  This means for every request, you must pass in all authentication information.  I have used Basic Authentication (credential in HTTP headers) with great success.

Keeping your RESTful interface stateless greatly simplifies your server logic and your client's logic.  Every request is autonomous, and you do not have a temporal coupling on your authentication mechanism.  It makes your application easier to test, and you will not run into scenarios where the session expires and the client doesn't expect it.


答:
I will propose an entirely different way of doing things:

You should have one "database-creation" script which creates the database from scratch, starting on a completely empty schema/catalog and creating all the tables, with all necessary relations, and all necessary immutable initial data.  Immutable initial data are, for example, the days of the week (Sun,Mon,Tue, etc.) in the days_of_week table.

This script must always be committed and checked out together with the rest of the code, (assuming you are also using some other language besides SQL in the shop,) because the code relies on this script. This way, developers and testers can forget about keeping old databases around and amending them with changes. The database should be a throw-away entity, always created from scratch, and populated with data as needed.  The state of your system is described entirely by what is committed in the version control system, and you avoid the constant headache of whether the version of the database is the same as the version of the database-creation script and the version of the code. Also, this way, each developer can have a local instance of the database for development and testing purposes, always being thrown away and recreated with every iteration of the checkout-develop-test-commit cycle.

So, my recommendation is to not have any script which creates test data.  Each test should temporarily create the data that it needs in order to run, possibly in a transaction which gets rolled back instead of being committed, so as to leave the database empty, or each test should create a temporary schema/catalog, create the database in it, fill it with data, perform the test, and then drop the entire schema/catalog.  If the test cannot create the data due to some constraint violation, then someone made a change to the database-creation script and committed it without first bothering to run the tests. It is their fault.

If you really insist on having a test-data-creation script, then it, too, should be committed and checked out together with the database-creation script and the rest of the code. That will also work.

Operations should maintain whatever older-version databases they need, and it is their problem to migrate the contents of old databases to new databases released by the developers.


问:
What should a Dependency Injector look like in JavaScript?
I'm studying Dependency Injection in JavaScript. I've learned what I need to accomplish, according to Wikipedia,

The client delegates to external code (the injector) the
responsibility of providing its dependencies. The client is not
allowed to call the injector code.[2] It is the injecting code that
constructs the services and calls the client to inject them. This
means the client code does not need to know about the injecting code.
The client does not need to know how to construct the services. The
client does not need to know which actual services it is using. The
client only needs to know about the intrinsic interfaces of the
services because these define how the client may use the services.

But I'm not sure how this should be done in JavaScript. I could probably set out to create all sorts of ways to inject dependencies in JavaScript, matching "services" to "clients" in the code structure and technically satisfy the terms of the Dependency Inversion Principle. But that doesn't mean it would be the best/correct way.

For example lets say I have a wheel (service) which every car (client) needs, along with services: gasPedal, break, clutch, and stick.

What should a proper dependency injector look like in JavaScript?

How does one inject the dependency without calling on the injection code from the client?

Note: None of the answers so far cover doing this manually. I know I can use libraries to do it, what I'm asking about - the challenging aspect of injectors - is how to create them from scratch, what the structure of one would actually look like, not how to use a library which supports them.

I'm trying to learn what the function for an injector would be structured like for the sake of truly understanding dependency injection at its core - the function that implements injection. I'm not asking for a complete function or working code, just a good explanation or even an overly simplified pseudo-code example.

答:
There are a number of existing solutions you should look at before reinventing the wheel.  One is Asynchronous Module Definition (AMD), which is shared by a few frameworks and usable by several others.  Pretty much all frameworks of any note have solved this problem.

The big difference with JavaScript compared to other languages is the idea that you usually want to be able to load dependencies asynchronously over the web on demand, and only those you need, and cache it for later use.  On the other hand, you also want the ability to sort of compile all your dependencies into one minified file that is quick to download for production use, but have that version be semantically identical to the asynchronous on-demand version you used during development.


答:
Agile is a great solution to a whole range of problems, but despite what some evangelicals would suggest, it is not the only solution and it is not always the right solution.

Your stated case is simply not an agile problem:

I was recently tasked with going round teams and asking them for ideas on business processes to automate. I was then to find out how much time this was taking them, work out how much time the solution would save and estimate the total development time. That way, managers could attempt to measure how effective a solution was likely to be in terms of time saved.

You are tasked with determining the cost and benefit of automating some business processes, that is not an agile task subject to change, it is a specific problem with specific solution. You will produce a list with an arbitrary number of business processes and for each, there will be an estimated cost of automating, an estimated cost of not automating and an estimated benefit of automating. Management will match this against their budgets, resources, requirements and strategic goals and determine which (if any) of these processes to automate. If you are conscientious, then you will have highlighted selected tasks which have potentially lower ROI's in themselves but which will reduce the cost of other phases so improving the total ROI. You may also have identified different ways of achieving the automation including in-house and outsourced bespoke development (using agile and/or waterfall techniques), buying off the shelf solutions, using third party service providers and so on. This whole process was very fashionable in the 90's when it was known as business process re-engineering.


答:
How it "should" be done is a subject of debate, but I can provide you an example that works well from a pretty common library -- angularjs:

```<code>(function() { // wrap in anonymous function to not pollute global scope
    angular
        .module('mymodule') // which module to register this object with
        // register 'someSvc' identifier to inject someSvc object
        // for testing, provide a replacement object
        .service('someSvc', someSvc);

    // the object that will be injected
    function someSvc() {
        var privateVar = '';
        this.publicVar = '';
        this.publicMethod = function() { ... };
    }
})();
</code>```

When I later use someSvc in another component (which will also be registered with the dependency injector)...:

```<code>(function() { // wrap in anonymous function to not pollute global scope
    angular
        .module('mymodule') // which module to register this object with
        // register someCtrl object with identifier 'someCtrl'
        .controller('someCtrl', someCtrl);

    // tell angular which dependencies this object requires
    // this method of injection survives javascript minification
    someCtrl.$inject = ['someSvc']

    // constructor inject dependencies
    // name someSvc doesn't have to match (since we used $inject above)
    // but kept same for clarity
    function someCtrl(someSvc) {
        this.doSomething = function () {
            someSvc.publicMethod();
        }
    }
    // javascript functions are "hoisted", so it's available even if declared last
})();
</code>```

Scopes

There are several registration methods on angular which essentially provide different scopes like a standard DI container. .service news up the object only once (singleton). .factory expects a function which returns the object and only calls said function once (singleton). .controller is per object lifetime scope and generally used for page template controllers.

JS Minification

You must also keep in mind that variable names can and will be changed by minification process, so your method of injection must still work when variable names change. In angular, this is accomplished by specifying the string identifier of the dependency (via $inject or array syntax on the module registration).

Injection

The above syntax registers dependencies with the injector. The dependencies are injected by the injector like so:

```<code>// create an injector
var $injector = angular.injector(['ng']);

// use the injector to kick off your application
// use the type inference to auto inject arguments, or use implicit injection
$injector.invoke(function($rootScope, $compile, $document) {
  $compile($document)($rootScope);
  $rootScope.$digest();
});
</code>```

Example pulled from this link. The injector reads the parameter names (or the $inject property) of the invoked function and tries to find matching dependency names in its registry. If it cannot, then it crashes. Obviously, it is your responsibility to make sure the appropriate modules are registered before calling the injector. (Angular automatically calls the injector during it's startup process as it scans and finds registered components specified in the HTML DOM.)

More information on angular DI can be found here.

Title: What should a Dependency Injector look like in JavaScript?

Body:
I'm studying Dependency Injection in JavaScript. I've learned what I need to accomplish, according to Wikipedia,

The client delegates to external code (the injector) the
responsibility of providing its dependencies. The client is not
allowed to call the injector code.[2] It is the injecting code that
constructs the services and calls the client to inject them. This
means the client code does not need to know about the injecting code.
The client does not need to know how to construct the services. The
client does not need to know which actual services it is using. The
client only needs to know about the intrinsic interfaces of the
services because these define how the client may use the services.

But I'm not sure how this should be done in JavaScript. I could probably set out to create all sorts of ways to inject dependencies in JavaScript, matching "services" to "clients" in the code structure and technically satisfy the terms of the Dependency Inversion Principle. But that doesn't mean it would be the best/correct way.

For example lets say I have a wheel (service) which every car (client) needs, along with services: gasPedal, break, clutch, and stick.

What should a proper dependency injector look like in JavaScript?

How does one inject the dependency without calling on the injection code from the client?

Note: None of the answers so far cover doing this manually. I know I can use libraries to do it, what I'm asking about - the challenging aspect of injectors - is how to create them from scratch, what the structure of one would actually look like, not how to use a library which supports them.

I'm trying to learn what the function for an injector would be structured like for the sake of truly understanding dependency injection at its core - the function that implements injection. I'm not asking for a complete function or working code, just a good explanation or even an overly simplified pseudo-code example.

Body:
How it "should" be done is a subject of debate, but I can provide you an example that works well from a pretty common library -- angularjs:

(function() { // wrap in anonymous function to not pollute global scope
    angular
        .module('mymodule') // which module to register this object with
        // register 'someSvc' identifier to inject someSvc object
        // for testing, provide a replacement object
        .service('someSvc', someSvc);

    // the object that will be injected
    function someSvc() {
        var privateVar = '';
        this.publicVar = '';
        this.publicMethod = function() { ... };
    }
})();

When I later use someSvc in another component (which will also be registered with the dependency injector)...:

(function() { // wrap in anonymous function to not pollute global scope
    angular
        .module('mymodule') // which module to register this object with
        // register someCtrl object with identifier 'someCtrl'
        .controller('someCtrl', someCtrl);

    // tell angular which dependencies this object requires
    // this method of injection survives javascript minification
    someCtrl.$inject = ['someSvc']

    // constructor inject dependencies
    // name someSvc doesn't have to match (since we used $inject above)
    // but kept same for clarity
    function someCtrl(someSvc) {
        this.doSomething = function () {
            someSvc.publicMethod();
        }
    }
    // javascript functions are "hoisted", so it's available even if declared last
})();

Scopes

There are several registration methods on angular which essentially provide different scopes like a standard DI container. .service news up the object only once (singleton). .factory expects a function which returns the object and only calls said function once (singleton). .controller is per object lifetime scope and generally used for page template controllers.

JS Minification

You must also keep in mind that variable names can and will be changed by minification process, so your method of injection must still work when variable names change. In angular, this is accomplished by specifying the string identifier of the dependency (via $inject or array syntax on the module registration).

Injection

The above syntax registers dependencies with the injector. The dependencies are injected by the injector like so:

// create an injector
var $injector = angular.injector(['ng']);

// use the injector to kick off your application
// use the type inference to auto inject arguments, or use implicit injection
$injector.invoke(function($rootScope, $compile, $document) {
  $compile($document)($rootScope);
  $rootScope.$digest();
});

Example pulled from this link. The injector reads the parameter names (or the $inject property) of the invoked function and tries to find matching dependency names in its registry. If it cannot, then it crashes. Obviously, it is your responsibility to make sure the appropriate modules are registered before calling the injector. (Angular automatically calls the injector during it's startup process as it scans and finds registered components specified in the HTML DOM.)

More information on angular DI can be found here.


答:
Yeah, agility has some advantages.

It allows business folks to change their minds mid-flight.

It sort of protects the business against the engineer's perpetually bad estimates.

It delivers value early and often, before the final vision is achieved.

It spares you some of the up-front planning cost, which can often produce bad plan anyway.

It's super cool. Right?

But, you still need to give reasonably accurate up-front estimates.

If you don't, you're effectively asking the business to invest in your product without any evidence that your product is even worth the initial investment -- and in some cases, anything at all.

And I can hear it now.

I've heard it before. I'm pretty sure I've said it before:

Oh - But Haow!? HAOW does a mere mortal man such as myself gaze mine eyes into the destiny of such things! Things which only the gods themselves can divine and direct. Things which mortal men can only dream in deepest slumbers and forget by wake of day! Oh tyrannical managerial types, HAOW can such demands be met!?

Use your past performance as a guide and be honest.

Have enough of a conversation with the stakeholder and/or end-user to determine how complex the product and/or it's major components are relative to other major components you've worked on. Make an initial, relative point estimate.

Inflate that number by the historical amount of scope change and bug fallout you've historically seen.

Apply your historical velocity to the point estimate to arrive at a rough timeline. And, apply a reasonable cone of uncertainty.

Re-review your estimate and understanding of the project. Be confident that you would be willing to make a decision about tackling a project based on your assessment.

Finally, present your cone of uncertainty to the stakeholders, state your assumptions and concerns, and leave it at that.

As an aside, I'd also suggest coming up with an objective point-estimation heuristic to sanity-check you and/or your team's normal estimates.

You can use this estimate as an Nth vote during planning poker, or in validating your private estimate if you're going solo. For example, my team tends to estimate about 1 point per minute of loosely technical discover discussion about a story. This is especially helpful if your gut tells you a story is 5 points, but it took you a 20 minutes to understand what needs to be done -- it's usually a good indicator that there are still complexities and misunderstandings lurking around.