答:
The criticisms of Google's C++ style guide (and I agree some are justified) are not about Google's naming conventions or indentation style but rather about some of their other rules and policies. Indentation / formatting and naming conventions are both something of a matter of taste and are fertile ground for endless programmer religious wars but in C++ where unlike say C# there is no universal standard the only really important guideline is consistency. For a new project, pick a naming convention and indentation style you like and use it consistently. For an existing project, stick with the convention already in use. Rule 0 in C++ Coding Standards is "Don't sweat the small stuff." where they argue that naming conventions and indentation style are just not that important as long as you're consistent.

A big productivity booster for me has been automating indentation / formatting using clang-format. Once you've settled on some indentation and formatting rules, I highly recommend setting up a customized .clang-format configuration file and then never having to worry about it again :-)

Clang-format is a standalone tool and doesn't require you to be using clang as a compiler. There's even an official plugin available for Visual Studio.

Title: Style guide for C++

Body:
Right now I am using Google C++ Style Guide in my C++ code and I was pretty happy with it.

Recently I was told that this guide is very bad: it is used internally by Google (I knew that), is outdated, and promotes some very bad practices. So I want to use another coding style.

What good and fairly used C++ style guides are there? I write code for both gcc and Visual Studio, and I use a lot of the C++11 features.

What I liked very much about Google C++ Style Guide was the indentation, the whitespace and the naming conventions (specially naming all classes, types - including typedefs, type aliases and template aliases - with capital first letter).

I know any answer is subjective (I hope this is ok on this site) and I would appreciate any opinion, but I am interested which guides are used these days.


问:
Writing Selenium Tests - Modifying Markup Under Test
We'd like to know what you view as best practices and what has worked for your projects

My organization is in the beginning phases of creating a Selenium test suite, and have had some early discussions about how to ensure that our tests are robust.

In one of the first tests, we modified the markup under test to facilitate testing:

The original markup was something along the lines of:

Some Text

And the author of the test added an ID to the anchor tag:

Some Text

A few points of view emerged:

Adding anything to the markup solely for the purpose of facilitating testing is a bad thing.

a.) It clutters the markup, which hurts front-end developers (i.e. where is this id even being used?).

b.) It increases the payload being sent to the clients.

Adding an id to an element to facilitate testing is okay.

a.) It allows for more robust selectors (traversing the DOM / using a XPath can be much more brittle and difficult to read).

b.) Assuming that you use unique id's, there's no material downside to adding identifiers to elements on a page.

Adding another attribute (i.e. data-testing-id) is preferable to adding an id.

a.) While it clutters the markup and is also sent in the response to clients,   the purpose of the attribute is very clear.

b.) Similar to point 2, you can write more robust selectors.

答:
I've worked with small and medium-large Selenium-based test suites. We've had discussions like this with all the same points of view. In my opinion, the best approach is this:

add id attributes where possible

if it's not possible use other attributes like class for use with automation

only add tags as needed/requested for testing. Start bottom up instead of top down.

Adding id attributes can make front-ends easier to test, easier to automate, and more organized. These are generally Good Things.

I'm a bit troubled by this statement though:

Adding anything to the markup solely for the purpose of facilitating testing is a bad thing.

Here's the problem with this statement: you're focusing on the wrong problem. Instead of asking "how can this cause problems with our app", ask "how can we make our app more testable?"

It's a good practice for elements in the DOM to be designed so that they are uniquely identifiable. That's part of the point of the id attribute. Some elements naturally lend themselves to having an id like an OK, Save or Cancel buttons. Sometimes elements in a list or grid can't realistically be given an id which brings in using other attributes or some other approach.

Also, the idea that using id can hurt the payload requires evidence. Usually that's just premature optimization-style thinking. In our app, adding ids slowed down page loads by less than 100 milliseconds on average, a negligible amount in our context.  Perhaps adding hundreds of id attributes might hurt performance on some platforms, on some browsers but again, investigate. We're not living in 1996 on the web anymore.

ContentLicense: CC BY-SA 3.0


问:
Do nested conditionals have a significant performance impact?
This is a question that lives in my mind from a long time.

Does the use of multiple nested conditional statements impact the performance of a taken code? So far I know that programmers have created a precise term to describe this situation, the in-famous "Pyramid of doom" [Wikipedia page], but a side from that how much can this degrade performances?

Let's take this situation as an example: I have a JSON coming from a server response containing a few objects that represent the user purchases in an application, before taking the needed data from it I need to check various conditions:

Is the response we are looking for?

Does response has resultCode: OK?

Are the any contents to process?

At this point if everything is true a "processing process" will begin, parsing and editing the server response, in this case for changing the date format from US to the standard european format. The process consist in two nested for-loops and an if statement.

This is the example code in Objective-C, since I'm an iOS Developer:

```<code>if ([remoteManager.operationId isEqualToString:NEEDED_OPERATION_ID]) {
    if ([response[RESULT_CODE_KEY] isEqualToString:@"OK"]) {
        if ([response[RESULT_OBJ_KEY][@"CONTENT_LIST"] count] > 0) {
            NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];

            for (NSMutableDictionary *productsAvailable in response[RESULT_OBJ_KEY][@"CONTENT_LIST"]) {
                for (NSString *key in productsAvailable) {
                    if ([key isEqualToString:@"NEEDED_KEY"]) {
                        /* We change the date format here */
                    }
                }
            }
        }
    }
}
</code>```

In my opining this code can't really have an impact on the performance of an application because those checks are not so complicated for the system to do. But does this can be a problem if we need to have the maximum speed and performances? In other words: should nested conditionals be avoided or not? And also does putting multiple conditions at the same time reduces the performance problems (if any)?

答:
The problem with nested conditions is not speed, its human comprehension.

Human beings have trouble coping with many possibilities at once.
They reach their limit (which is fairly small) then start to make mistakes without realising it.

Conditional statements increase complexity fairly quickly: 2, 4, 8, 16, 32, 64, 128... and for almost all programmers, the limit is in single digits.

Computers have no problems optimising code with very many nested conditions, but humans will find it almost impossible to maintain the source code - which means it won't work.

Most programming techniques are about coping with human weakness, rather than speed. Source code is for humans.


问:
What was the first programming language with Enumerations?
I'm reading about Swift enum's in the Swift Programming Language guide and the text was comparing the differences between Swift's enum and C's enum. This made me curious as to where enumerations came from originally. I did search online before asking and even asked a few people and they assumed C. (I suppose I'm trying to confirm if enumerations came from C originally.)

What was the first programming language to include enumerations?

答:
Probably Lisp (1958).

In Lisp dialects, symbols can be used in the same way as C's enumerations. Indeed, the Wikipedia page for Symbol (Programming) says:

In the most trivial implementation, [symbols] are essentially named integers (e.g. the enumerated type in C).

Scheme and Common Lisp have a member function, which can be used like:

```<code>(member 'b '(a b c))
;=> (b c)
</code>```

Fortran also has an enumeration type, but it looks like it was added in Fortran2003 for compatibility with C's enum, which itself was only added in ANSI C (1989).

Body:
Probably Lisp (1958).

In Lisp dialects, symbols can be used in the same way as C's enumerations. Indeed, the Wikipedia page for Symbol (Programming) says:

In the most trivial implementation, [symbols] are essentially named integers (e.g. the enumerated type in C).

Scheme and Common Lisp have a member function, which can be used like:

(member 'b '(a b c))
;=> (b c)

Fortran also has an enumeration type, but it looks like it was added in Fortran2003 for compatibility with C's enum, which itself was only added in ANSI C (1989).


问:
Can I use a timestamp parameter for cache invalidation?
I am considering a scheme for passing a timestamp value in a cached response, and then sending it back to the service to perform cache invalidation. I'm wondering if that's a valid approach. Is that a common approach?

For example, if I have a service that returns a "Foo" record, which is a combination of DB lookups and calculations. Let's say Foo is identified with a key. To speed things up, I want to keep a local cache of results.

The problem is, across a bank of servers, the local caches will get out of sync, because the calculated results will change over time.

So my thought is:

for a request, calculate a Foo

store the Foo in local cache with an "as of" timestamp

return the Foo along with the "as of" timestamp

when the client wants to fetch a Foo, it passes the key as well as the "as of" timestamp.

if the server finds the key in the local cache, and the "as of" timestamp in cache is newer than the "as of" parameter, return the cached Foo with the Foo, key and "as of" timestamp

otherwise recalculate the Foo, cache it, and return the (new) Foo, key and (new) "as of" timestamp

The client would need to keep track of both the key and the "as of" timestamp, but then it would essentially control when service instances refresh their local cache, without the service instances talking to each other or some back-end storage for coordination.

If the client wanted to force a cache refresh, it could pass "as of" of max value, which would force a refresh on any service instance it hits.

Certainly I could put a caching layer in front of my service, and I could also save results in a distributed cache. Those solutions have their own data replication and expiration issues too. But for the purpose of this question, I really want to consider local caching & consider the architectural questions separately.

Q: Does that work? Is it valid or good to use a timestamp parameter as a mechanism for cache invalidation?

答:
Local caching is simpler to implement.  The issues to watch out for are:

Multiple cache misses during the cache population event.

Cache population fails.

Depending on which server the request hits will return a different answer.

With .NET I handled the cache miss problem by having the cache store the Task<> asynchronous wrapper, and using locking to ensure that only one Task<> to obtain the cached value was created.  This worked well.

When the process to obtain the cache value fails, what does your application do?  Does it cache the failure returning the error until the cache expires?  Or do you create a new attempt to obtain the value?

When you have a multiple servers with independent caches and the underlying values changing regularly the answer will depend entirely on which server handles that request.  This may not be an issue in your application, but think long and hard about what this means for your user and their confidence in your competence.  If you keep getting conflicting data it can undermine trust.

Implementing a distributed cache with riak and key expiration solves many of these issues when you have multiple application servers.  However it does not solve the cache population issue, when multiple threads on multiple servers all decide that the cache needs re-populating.


问:
Throwing exceptions in application configuration providers
Simple question: What is the best/common practice regarding to throwing errors for application configuration providers?

Given is a simple key/value-based configuration source:

```<code>class Configuration
    string GetValue(key);
    void SetValue(key, value);
</code>```

Or more extended, with the ability to add/remove key/value elements

```<code>class Configuration
    string GetValue(key);
    void SetValue(key, value);
    void AddKeyValuePair(string key, string value);
    void RemoveKeyValuePair(string key);
</code>```

Not throwing exceptions on methods like GetValue() has the benefit of not interrupting the application flow and making code easier to read because of a lack of exception handling etc. It also allows to use null-conditional operators (maybe monads) or null-coalescing operators for e.g. setting defaults:

```<code>var value = configuration.GetValue("myKey") ?? "Hello World";
</code>```

Return null simply tells the user: 'Whoops, got nothing to return since nothing is set/there'.

However..

If I'd avoid throwing exceptions, what would happen if I try to add a key/value pair which is already available? Or set the value with a key that isn't there in the underlying storage? Or removing a key/value pair that isn't available? Would it be obvious for the user that simply nothing happens when we tries to remove a none-existing key pair?

What is the prefered approach for application configuration?

答:
It sounds like you are on the verge of Railway Oriented Programming.

As with most things there is no Right Way To Do It, only trade-offs. Exceptions are costly when thrown, but they are fairly standard practice in C#. Conversely, returning a pass/fail means you have to check the return value (if you care about it failing).

Using Exceptions, they will have to wrap calls to your code in try/catch blocks (which I never find fun). If you were going to avoid using exceptions for expected failures (key not found), I would change the API to make the return value explicit as to whether or not the configuration was changed. And make the methods clear as to expected preconditions (key present or not). That way, the caller can pick a method which allows them to ignore the return value. Or else they can explicitly handle the case where their requested change could not be performed.

Here is an example class with more explicit methods and return values.

```<code>class Configuration
    string GetValue(string key); // presence expected, null means not there
    bool ChangeExistingValue(string key, string value); // only change if present
    bool AddNewKeyValuePair(string key, string value); // add only if not present
    void AddOrUpdateValue(string key, string value); // obvious use
    bool RemoveKeyValuePair(string key); // obviously presence is expected
</code>```

When called, I can choose the method I need (C#):

```<code>// don't want to add the value if it's not already there
// return value of false is ignored
config.ChangeExistingValue("asdf", "fdsa");

// -- vs --

// there is a problem if this value is not there
if (!config.ChangeExistingValue("asdf", "fdsa"))
    throw new SomeException(...);

// -- vs --

// I don't care about before, just put it in there now
config.AddOrUpdateValue("asdf", "fdsa");
</code>```

Body:
It sounds like you are on the verge of Railway Oriented Programming.

As with most things there is no Right Way To Do It, only trade-offs. Exceptions are costly when thrown, but they are fairly standard practice in C#. Conversely, returning a pass/fail means you have to check the return value (if you care about it failing).

Using Exceptions, they will have to wrap calls to your code in try/catch blocks (which I never find fun). If you were going to avoid using exceptions for expected failures (key not found), I would change the API to make the return value explicit as to whether or not the configuration was changed. And make the methods clear as to expected preconditions (key present or not). That way, the caller can pick a method which allows them to ignore the return value. Or else they can explicitly handle the case where their requested change could not be performed.

Here is an example class with more explicit methods and return values.

class Configuration
    string GetValue(string key); // presence expected, null means not there
    bool ChangeExistingValue(string key, string value); // only change if present
    bool AddNewKeyValuePair(string key, string value); // add only if not present
    void AddOrUpdateValue(string key, string value); // obvious use
    bool RemoveKeyValuePair(string key); // obviously presence is expected

When called, I can choose the method I need (C#):

// don't want to add the value if it's not already there
// return value of false is ignored
config.ChangeExistingValue("asdf", "fdsa");

// -- vs --

// there is a problem if this value is not there
if (!config.ChangeExistingValue("asdf", "fdsa"))
    throw new SomeException(...);

// -- vs --

// I don't care about before, just put it in there now
config.AddOrUpdateValue("asdf", "fdsa");


问:
Modifying a GNU LGPL v 2.1 code and license
I have found a piece of code online (https://github.com/kenkendk/sharpaescrypt/blob/master/Source/SharpAESCrypt.cs) licensed under GNU LGPL v 2.1

If I would like to make some changes to this file and re-distribute it under the same license (GNU LGPL v 2.1) do I update the copyright date or owner name (in order to reflect the changes), or retain the original one?

答:
As I commented,  for a github thing, you might make a pull request. Don't change the owner name but add your own name as contributor (and update the copyright years). YMMV. And don't change the license (e.g. to GPLv3+) without permission from the original author (unless you are sure that your license is upward compatible with his one, and even then you'll better discuss that with him). But I am not a lawyer!

The original author has then the ability to incorporate your changes, and the github platform offers an easy way to do that for him (or her) if he / she wants to, if your changes are organized as a pull request.

In general, you'll rather try to cooperate & interact with the original free software project authors and community. Forking a project is often frowned upon.


问:
SQL Table With A Call To Action?
This is all done in Microsoft Access 2007 and SQL Server. We are creating a way for our users to quickly make notes on a customer. These quick-notes will contain tags that will prompt the user for data based on that tag. The tags are to be limited to a few select options for the user to pick from. The tags will be coded as [TAG] in the database.

A couple examples:

Order refund

```<code>[[OrderNumber]] - Was refunded
</code>```

When the user selects the above example, he/she would be prompted with a list of the currently selected customer's orders and a field to allow the user to input a specific order. When the user chooses the order, the quick note would look like:

```<code>[123456] - Was refunded
</code>```

General Note

```<code>Emailed receipt for order [[OrderNumber]] to email address: [emailAddress]
</code>```

Would look like:

```<code>Emailed receipt for order [123456] to email address: Seymour@butts.com
</code>```

The Problem

The main issue is that each tag invokes a different action.

An order number tag calls up a function that will extract the order number from a few columns in an order table.

An email address tag will show all the current customer's email addresses or allow the user to put a different email into a field.

Our Purposed Solution

We though about putting the data into a table with the following format:

```<code>╔════════╦══════════════╦══════════════════════╦════════════════╗
║ NoteID ║   NoteTag    ║   columnReference    ║ tableReference ║
╠════════╬══════════════╬══════════════════════╬════════════════╣
║      1 ║ emailaddress ║     email address    ║ emailAddTable  ║
╚════════╩══════════════╩══════════════════════╩════════════════╝
</code>```

Now this table may be a quick way to grab the data, but it will be awkward for function calling, and a lot will still be handled programmatically.

The Questions

What is a clean and simple way to invoke particular calls to action in a program based on the tags in a quick note? A big loop checking for tags in a string and then calling the specific functions?

答:
Use a Factory Method.

```<code>Public Function GetObjectByClassName(ByRef className As String) As Object
    Select Case className
        Case "Cat: Set Factory = New Cat
        Case "Dog": Set Factory = New Dog
        Case Else: Err.Raise Description:="Factory does not recognise this className."
    End Select
End Function
</code>```

Now all you need is a class for each action, and an "execute" method in each class.

```<code>Dim executor as object
executor = GetObjectByClassName("Dog")
executor.Execute() 'woof
</code>```

Title: SQL Table With A Call To Action?

Body:
Use a Factory Method.

Public Function GetObjectByClassName(ByRef className As String) As Object
    Select Case className
        Case "Cat: Set Factory = New Cat
        Case "Dog": Set Factory = New Dog
        Case Else: Err.Raise Description:="Factory does not recognise this className."
    End Select
End Function

Now all you need is a class for each action, and an "execute" method in each class.

Dim executor as object
executor = GetObjectByClassName("Dog")
executor.Execute() 'woof


问:
UML modeling angular controllers / factories and services
I have to create UML documentation for my upcoming project. Now I have previously worked with Java which as an object orientated language is relativly easy to design UML class diagrams for. For my next project I will have to design an AngularJs Application.

As some of you might know an Angular application consists of many things including Controllers Factories Services and many more.

My question is when designing these using UML should Controllers / Factories / Services be seen as classes in a class diagram even though they are never defined as classes nor have any constructor but merely consists of variables and functions?

答:
** Short Quick Technical Answer **

You can model Controllers, Factories, and Services as a class, with a stereotype.

```<code>..........................
..+--------------------+..
..|   <<Controller>>   |..
..|   SomeController   |..
..+--------------------+..
..........................
..+--------------------+..
..|     <<Factory>>    |..
..|     SomeFactory    |..
..+--------------------+..
..........................
..+--------------------+..
..|     <<Service>>    |..
..|     SomeService    |..
..+--------------------+..
..........................
</code>```

** Long Boring Conceptual Answer **

U.M.L. is a modeling tool, altought, was originally designed with Object Orientation, is not "glued" to it.

You can still use U.M.L. for concepts that are not strictly objects. In a matter of fact, many Software Application Developers may design an object in U.M.L., that does not traslates exactly, as an object in an specific Programming Language.

For example, the people that interact in a System, a.k.a. "Actors", they are not specifically objects, yet some U.M.L. diagrams allow to use a class or object diagram for an Actor, instead of the Standard icon.

Body:
** Short Quick Technical Answer **

You can model Controllers, Factories, and Services as a class, with a stereotype.

..........................
..+--------------------+..
..|   <<Controller>>   |..
..|   SomeController   |..
..+--------------------+..
..........................
..+--------------------+..
..|     <<Factory>>    |..
..|     SomeFactory    |..
..+--------------------+..
..........................
..+--------------------+..
..|     <<Service>>    |..
..|     SomeService    |..
..+--------------------+..
..........................

** Long Boring Conceptual Answer **

U.M.L. is a modeling tool, altought, was originally designed with Object Orientation, is not "glued" to it.

You can still use U.M.L. for concepts that are not strictly objects. In a matter of fact, many Software Application Developers may design an object in U.M.L., that does not traslates exactly, as an object in an specific Programming Language.

For example, the people that interact in a System, a.k.a. "Actors", they are not specifically objects, yet some U.M.L. diagrams allow to use a class or object diagram for an Actor, instead of the Standard icon.


问:
Role of an architect in SAP ABAP or SAP BI projects
Given that SAP modules are architected and managed by SAP itself.

However, small changes are possible at the customer's end.

How can an ABAPer on the client's side take the role of an architect at SAP that designs SAP modules? So what does an architect at the client's side have left to do?

答:
Given that SAP modules are architected and managed by SAP itself.

This is only partially true. The large system design is done by SAP. However many organizations have custom implementations of some sort.

There are often required changes, whether small or large, that fit business applications into SAP. Or custom requirements for the business applications which are caused by SAP.

In an ideal world, you could easily just fit your applications that the business is developing (whether SAP transactions or a system feeding SAP). That process takes a fair bit of architecting.

However, small changes are possible at the customer's end.

You are (likely) kidding yourself if every customer implementation is identical. Unless someone is starting a business from nothing, where they can design their business around SAP's system.

Someone needs to make sure that the SAP design is correct. Understanding how pieces fit together.

How can an ABAPer on the client's side take the role of an architect at SAP that designs SAP modules? So what does an architect at the client's side have left to do?

So, the key piece is understanding how everything fits together. An ABAPer might understand this - but might have a very limited scope of experience. A good architect will have enough experience to see how pieces fit together, so when decisions are required, they can properly evaluate and identify the right decisions - and make them.

It is likely that an ABAPer on the client will not have this experience/broad system understanding. If they do, then that's great, but likely they will not.

An architect should be doing design types of work - not implementation work. An ABAPer is responsible more for implementation.


问:
Does C# 6.0's new null-conditional operator go against the Law of Demeter?
The Law of Demeter states the following:

Each unit should have only limited knowledge about other units: only units "closely" related to the current unit.

Each unit should only talk to its friends; don't talk to strangers.

Only talk to your immediate friends.

C# 6.0 introduced a new operator called the null-conditional operator. IMHO, it makes coding easier and improves readability.
But it also makes it easier to write more coupled code, as it is easier to navigate through class fields, already checking for nullity (something like var x = A?.B?.C?.D?.E?.F?).

Is it correct to state that this new operator goes against the Law of Demeter?

答:
Is it correct to state that this new operator goes against the Law of Demeter?

No*

* The null conditional operator is a tool within the language and the .NET framework.  Any tool has the ability to be abused and used in ways that could harm the maintainability of a given application.

But the fact that a tool can be abused doesn't necessarily mean that it has to be abused, nor that the tool violates any particular principle(s) that may be held.

The Law of Demeter and others are guidelines about how you should write your code.  It's targeted to humans, not the tools.  So the fact that the C# 6.0 language has a new tool within it doesn't necessarily affect how you should be writing and structuring your code.

With any new tool, you need to evaluate it as ... if the guy who ends up maintaining your code will be a violent psychopath ....  Note again, that this is guidance to the person writing the code and not about the tools being used.


问:
Deleting a domain object and ensuring any remaining references are subsequently unusable
If I have a domain class with an instance method Delete().  What is the best way to ensure that any leftover references to an instance that has "deleted itself" are subsequently unusable?

This question is very similar to mine, but I think the OP is more broadly concerned with how the API as a whole should be notified of deletions that occur elsewhere and react to such deletions.  Any mention of how the deleted instances should behave is merely peripheral.

For instance, one bullet point says:

If my wrapper object finds out that its unerlying [sic] storage has been
  deleted (e.g. because of access to an uncached property returned an
  error), should it now mark itself as Deleted (so that all access to
  properties and methods return some sort of ObjectDeletedException) or
  should it just clear all caches and allow future calls to fail
  naturally.

I'm more concerned with how to implement the failure that should occur when properties or methods of the deleted instance are used.  I can put a gateway check inside each property and method that throws an exception (as stated in the quote above), but that would create extremely brittle code since then every future developer -- including me -- would have to remember to add that check when creating new properties or methods.

Furthermore, I don't feel that such checks would be enough, as the mere presence of an object reference could be meaningful, regardless of its underlying properties or methods.  For example, a client of my API may hold references to these instances they believe exist, and if one has deleted itself, that instance should no longer be valid and should cause all sorts of hell.  Maybe it could just raise a "NotifyDeleted" event and leave it up to the client to respond, but I'm not sure if that's sufficient.

答:
Your aggregate should be taking care of cleaning up any references between the entities underneath it. So that really just leaves problems with aggregates referencing other aggregates.

Removing the aggregate references from other aggregates can be taken care of with a Process Manager... a component that listens for specific events and in turn issues commands. Among other things, it's a way to make things happen across aggregates without having a transaction involving multiple aggregates (which limits scalability and/or performance).

Technically, you could remove aggregate-to-aggregate references from the client just after you successfully delete the aggregate. But this requires a level of trust (both in intention and handling it correctly) in the client that you may not have or want to assume going forward.

In the past when I needed the deleted object to respond "I'm sorry Dave. I'm afraid I can't do that.", I have had the repository return an interface. (Many people do this anyway as a matter of course.)

```<code>public interface IMyDomainThing
{
    void Method1();
    void Method2();
    string Property1 { get; }
}

// repo method
public IMyDomainThing GetMyDomainThing(Guid id);
</code>```

Then the repository itself checked whether the item was deleted and returns a deleted version in that case:

```<code>public DeletedMyDomainThing: IMyDomainThing
{
    private void RaiseError()
    {
        throw new NotSupportedException("Not allowed on a deleted object");
    }

    public void Method1() { RaiseError(); }
    public void Method2() { RaiseError(); }
    // not entirely sure this is necessary
    public string Property1 { get { RaiseError(); } }
}
</code>```

Yes, the maintenance on this sucks, because changing the public members requires you to touch the interface, non-deleted class, and deleted class. However, I wouldn't call it brittle, because the interface gives you compile-time (and in VS, design-time) checking to make sure that your deleted version has everything filled in.

Body:
Your aggregate should be taking care of cleaning up any references between the entities underneath it. So that really just leaves problems with aggregates referencing other aggregates.

Removing the aggregate references from other aggregates can be taken care of with a Process Manager... a component that listens for specific events and in turn issues commands. Among other things, it's a way to make things happen across aggregates without having a transaction involving multiple aggregates (which limits scalability and/or performance).

Technically, you could remove aggregate-to-aggregate references from the client just after you successfully delete the aggregate. But this requires a level of trust (both in intention and handling it correctly) in the client that you may not have or want to assume going forward.

In the past when I needed the deleted object to respond "I'm sorry Dave. I'm afraid I can't do that.", I have had the repository return an interface. (Many people do this anyway as a matter of course.)

public interface IMyDomainThing
{
    void Method1();
    void Method2();
    string Property1 { get; }
}

// repo method
public IMyDomainThing GetMyDomainThing(Guid id);

Then the repository itself checked whether the item was deleted and returns a deleted version in that case:

public DeletedMyDomainThing: IMyDomainThing
{
    private void RaiseError()
    {
        throw new NotSupportedException("Not allowed on a deleted object");
    }

    public void Method1() { RaiseError(); }
    public void Method2() { RaiseError(); }
    // not entirely sure this is necessary
    public string Property1 { get { RaiseError(); } }
}

Yes, the maintenance on this sucks, because changing the public members requires you to touch the interface, non-deleted class, and deleted class. However, I wouldn't call it brittle, because the interface gives you compile-time (and in VS, design-time) checking to make sure that your deleted version has everything filled in.


答:
Sort of.

If you're only doing one access (a?.Foo) then it is equivalent to:

```<code>a == null ? null : a.Foo
</code>```

which most people would agree is not a violation of the Law of Demeter. At that point, it is just syntactic sugar to improve readability.

Anything more than that, and it probably would violate the Law of Demeter, and this feature does tend to promote that sort of usage. I would even say that the above "good" usage alone isn't enough to warrant this sort of change to the language, so I expect that it was made to support the less clearly good usage.

That said, it is worth remembering that the Law of Demeter isn't a law per se, but more of a guideline. Lots of code violates it and works well. Sometimes the simplicity of design or of code is worth more than the risk posed by violating the Law of Demeter.

Title: Does C# 6.0's new null-conditional operator go against the Law of Demeter?

Body:
The Law of Demeter states the following:

Each unit should have only limited knowledge about other units: only units "closely" related to the current unit.

Each unit should only talk to its friends; don't talk to strangers.

Only talk to your immediate friends.

C# 6.0 introduced a new operator called the null-conditional operator. IMHO, it makes coding easier and improves readability.
But it also makes it easier to write more coupled code, as it is easier to navigate through class fields, already checking for nullity (something like var x = A?.B?.C?.D?.E?.F?).

Is it correct to state that this new operator goes against the Law of Demeter?

Body:
Sort of.

If you're only doing one access (a?.Foo) then it is equivalent to:

a == null ? null : a.Foo

which most people would agree is not a violation of the Law of Demeter. At that point, it is just syntactic sugar to improve readability.

Anything more than that, and it probably would violate the Law of Demeter, and this feature does tend to promote that sort of usage. I would even say that the above "good" usage alone isn't enough to warrant this sort of change to the language, so I expect that it was made to support the less clearly good usage.

That said, it is worth remembering that the Law of Demeter isn't a law per se, but more of a guideline. Lots of code violates it and works well. Sometimes the simplicity of design or of code is worth more than the risk posed by violating the Law of Demeter.


答:
Are we talking about classes and instances (as per first para) or objects and references (as per title)?

In both cases, you either:

Keep the deleted item (though marked as deleted), then disallow accesses to the deleted item.  Occasionally, you'll have to determine when deleted items no longer have any references so you can release/free them, or else you'll have a memory leak.

-or-

You find all usages (instances or references) and delete them as well as part of the item deletion.  You'll have to do this recursively, and either atomically or deleting references first, then items.

-or-

Disallow the deletion because of outstanding uses, forcing the user or client to track them down and delete them first.

I would work this problem from the client-side experience to see what the domain users expect.

Which ever solution you use, there are techniques that make these things easier.  The problem/solution spaces here are similar to memory management, (alloc/free), garbage collection, and referential integrity management (databases).

Reference counts work will if all you need is to know if there is a reference, and, your domain precludes cycles.  However, backward references may be helpful so you can more quickly find the references; tracing your structures like GC's do is another option.

Still yet, you can use a SQL database and take advantage of cascading deletions.

In any case, I think the domain experience is the most important, and I'd start with design requirements from that perspective, then pick among the various solutions that meet your business/domain needs.

For example, do you want a trash-can-like effect where you can support un-delete, or undo?  Do you want to keep objects that have references (to deleted items), but clear or null out the reference?  Should the whole referring objects also be deleted with no further ado?  Do your clients/users expect to be able to ask "what are the items that refer to this item" (just first level, or, possibly recursively in one query)?  What are the implications on multi-user editing of the same space (that an object one user is aware of is delete by another user).

Title: Deleting a domain object and ensuring any remaining references are subsequently unusable

Body:
If I have a domain class with an instance method Delete().  What is the best way to ensure that any leftover references to an instance that has "deleted itself" are subsequently unusable?

This question is very similar to mine, but I think the OP is more broadly concerned with how the API as a whole should be notified of deletions that occur elsewhere and react to such deletions.  Any mention of how the deleted instances should behave is merely peripheral.

For instance, one bullet point says:

If my wrapper object finds out that its unerlying [sic] storage has been
  deleted (e.g. because of access to an uncached property returned an
  error), should it now mark itself as Deleted (so that all access to
  properties and methods return some sort of ObjectDeletedException) or
  should it just clear all caches and allow future calls to fail
  naturally.

I'm more concerned with how to implement the failure that should occur when properties or methods of the deleted instance are used.  I can put a gateway check inside each property and method that throws an exception (as stated in the quote above), but that would create extremely brittle code since then every future developer -- including me -- would have to remember to add that check when creating new properties or methods.

Furthermore, I don't feel that such checks would be enough, as the mere presence of an object reference could be meaningful, regardless of its underlying properties or methods.  For example, a client of my API may hold references to these instances they believe exist, and if one has deleted itself, that instance should no longer be valid and should cause all sorts of hell.  Maybe it could just raise a "NotifyDeleted" event and leave it up to the client to respond, but I'm not sure if that's sufficient.


答:
Short Quick Answer

There are several techniques to detect when there are several references to the same [domain] object, and the object is removed.

Long Boring Answer

There are several techniques to clear several references of the same object.

And those techniques can be combined.

[1] Always use a pointer or reference

Since you object is conceptually "shared" by other objects, use a "reference" or "pointer" in all of them.

You did not mention which Programming Language you were applying your question. In some P.L.'s "pointers" are used, "references" are used.

In some P.L.'s like C++ or Object Pascal, a object variable can be declared in two ways:

[1.1] Direct (variable "statically allocated")

[1.2] Or using a "pointer" ("dynamic variables")

And the syntax for each ways are different.

In "reference" P.L. both concepts are kind of mixed.

Many programmers use a standard variable, or non pointer variable,
the first time, and pointers, later, use always a pointer or reference.

[2] Use the "Observer" (a.k.a. "Publisher-Subscriber") Design Pattern

As @Christopher Francisco, mention you may want to use the "Observer" Software Design Pattern, a.k.a. "Publisher-Subscriber", a.k.a. "Client-Server".

Wikipedia Info:

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

https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern

Basically, when an object wants to do something with itself, has a preregistered set of references to other objects, that notifies changes.

In this case, the object to be removed, notifies the containers or owners of the references, not the references itselves, that its going to be removed.

[3] Use "BeforeEvent", "ExecuteEvent", "AfterEvent" pattern

This one is usually confused with the "Observer" Design Pattern, because it's mixed with it, many times.

You will se this a lot in G.U.I. controls.

Basically means, that an object may split some important actions in 3,
"before", "while", and "after". Sometimes the "before" includes doing a confirmation of the action, and if the action is cancelled, the other 2 methods are not executed.

So this:

```<code>...........................
..+---------------------+..
..|       SomeClass     |..
..+---------------------+..
..| [+] Delete()        |..
..+---------------------+..
...........................
</code>```

May become this:

```<code>...........................
..+---------------------+..
..|      SomeClass      |..
..+---------------------+..
..| [#] BeforeDelete()  |..
..| [#] ExecuteDelete() |..
..| [#] AfterDelete()   |..
..+---------------------+..
..| [+] Delete()        |..
..+---------------------+..
...........................
</code>```

And, of course, the public Delete method calls the other methods.

When mixed with the "Observer" Design Pattern, in each action, a notification is sent to each subscriber object.

Body:
Short Quick Answer

There are several techniques to detect when there are several references to the same [domain] object, and the object is removed.

Long Boring Answer

There are several techniques to clear several references of the same object.

And those techniques can be combined.

[1] Always use a pointer or reference

Since you object is conceptually "shared" by other objects, use a "reference" or "pointer" in all of them.

You did not mention which Programming Language you were applying your question. In some P.L.'s "pointers" are used, "references" are used.

In some P.L.'s like C++ or Object Pascal, a object variable can be declared in two ways:

[1.1] Direct (variable "statically allocated")

[1.2] Or using a "pointer" ("dynamic variables")

And the syntax for each ways are different.

In "reference" P.L. both concepts are kind of mixed.

Many programmers use a standard variable, or non pointer variable,
the first time, and pointers, later, use always a pointer or reference.

[2] Use the "Observer" (a.k.a. "Publisher-Subscriber") Design Pattern

As @Christopher Francisco, mention you may want to use the "Observer" Software Design Pattern, a.k.a. "Publisher-Subscriber", a.k.a. "Client-Server".

Wikipedia Info:

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

https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern

Basically, when an object wants to do something with itself, has a preregistered set of references to other objects, that notifies changes.

In this case, the object to be removed, notifies the containers or owners of the references, not the references itselves, that its going to be removed.

[3] Use "BeforeEvent", "ExecuteEvent", "AfterEvent" pattern

This one is usually confused with the "Observer" Design Pattern, because it's mixed with it, many times.

You will se this a lot in G.U.I. controls.

Basically means, that an object may split some important actions in 3,
"before", "while", and "after". Sometimes the "before" includes doing a confirmation of the action, and if the action is cancelled, the other 2 methods are not executed.

So this:

...........................
..+---------------------+..
..|       SomeClass     |..
..+---------------------+..
..| [+] Delete()        |..
..+---------------------+..
...........................

May become this:

...........................
..+---------------------+..
..|      SomeClass      |..
..+---------------------+..
..| [#] BeforeDelete()  |..
..| [#] ExecuteDelete() |..
..| [#] AfterDelete()   |..
..+---------------------+..
..| [+] Delete()        |..
..+---------------------+..
...........................

And, of course, the public Delete method calls the other methods.

When mixed with the "Observer" Design Pattern, in each action, a notification is sent to each subscriber object.


问:
Why HTML5 got rid of Rich Desktop applications?
I recently noticed that Rich desktop applications (I define it as an application running inside a virtual machine embded in a web browser, based on tools like Java Web Start, Adobe Flash or Unity web player) seems to become more and more rare. I only see some when I play some plain old flash video games online.
They are now replaced by HTML5/Javascript applications, which have the advantage of being compatible with all browsers without plugins. But despite the compatibility, it seems I missed some other reasons.

Technologically speaking, I see important advantages to RDA, especially the possibility to download the application once and being able to run it offline though an application manager. At first sight, it seems to be better than downloading javascript code embded in a web page. It looked promising.

So here are my questions :

What are the main reasons (which might be technology-related or not)
why this architecture failed?

Regarding compatibility, why didn't the main browsers ended up embding by default some of those plugins?

答:
I think you answered your own question partly. People are designing applications for browsers and mobile devices. In order to target both, and share code, using HTML5/JS is a very quick approach.

Technologically speaking, I see important advantages to RDA, especially the possibility to download the application once and being able to run it offline though an application manager.

Oddly enough some of the applications you might use right now are being written with HTML5/JS and you might not even notice it. Electron, nw.js, and probably other containers allow HTML5/JS applications to access the filesystem and OS. These containers essentially remove all the limitations of the web allowing application developers to create cross platform solutions on every device seamlessly. (That and it has all the advantages of HTML allowing simple theming and layouts).

Also just as a side-note you can create a webpage that functions offline in the browser. A few sites do function this way, but it's usually a low priority feature that's ignored. (Especially with cellphones being prevalent).

What are the main reasons (which might be technology-related or not) why this architecture failed?

Things like Flash were created merely to fill holes that the HTML (including WebApps) standards currently didn't have. There was a time when the web was very simple. Things like video and audio were not really considered, so plugins were required to fill in the gaps. Plugins can still exist as long as they fill in a perceived hole. The Unity Web Player probably still fills a niche performance-wise compared to some WebGL alternatives as an example. Using flash for video or audio though, not so much.

Generally plugins are proprietary. This plays into one alternate reason why plugins have failed which is security. A lot of people distrust Flash and Java because they've been exploited numerous times.

Regarding compatibility, why didn't the main browsers ended up embding by default some of those plugins?

Not part of the specs. Web browsers are extremely complicated with thousands of individual pieces spread across numerous specs. Supporting something like Flash, Java, or Unity that merely duplicate most of the functionality would be a waste of time. Most companies, especially Microsoft, have discovered it's far easier to work with the specs and suggest changes over time when features aren't there. A big part of this though is browsers are now controlled by large corporations who have the manpower to implement complex features and organize development. This has made the need for proprietary plugins unnecessary unless the specs can't be modified to include a feature. (A good example recently is Encrypted Media Extensions which used to require plugins).


问:
Deep SQL relationships to a C# object model
I have a database with deep table to table relationships

for example

Clients (one to many) -> ClientData (one to many) -> ClientJob (one to many) -> ClientProcess (one to many) -> ClientStep... so on.

And these aren't one branch trees either. So Clients also has a one to many relationship with another tree of tables. The database has a very large number of tables and a bunch of relationships between them.

The C# models I have are similar in design to this

```<code>public class Client {

   //base client data
   public string ClientId { get; set; }

   public string ClientName { get; set; }
   //etc...

   //Objects with the one to many relationship
   public List<ClientData> {get; set;}

   public List<ClientLocation> {get; set;}

   //etc..
}
</code>```

And the ClientData object has it's base data and lists of objects representative of it's relational database relationships and so on.

I have been directed to not use Entity Framework, and instead I must create hand written views or stored procedures for data access.

My question is, is there a design pattern I can employ here that makes this SQL/C# structure efficient and maintainable?

I would like the ability to also query substructures, so instead of always getting a complete Client and all of it's related objects, I can get a specific ClientData and all of it's nested objects but not the Client which owns it.

答:
Sounds like somebody wants you to write a lot of SQL.

I'm assuming here only reading data since that is all the question specifically mentions.

In the past, I have created an AutoMapper-like component which would map a DataRow to a class by examining the class's property names with reflection, then assign matching DataTable columns of same name and similar type to the class's properties.

Then building on that only a little, you can convert an entire DataTable to a list of objects. I believe AutoMapper will do this already.

The query to populate an entire object tree usually returned multiple DataTables in the DataSet.

```<code>-- data table 0
SELECT ... FROM Client WHERE ClientId = @clientId;
-- data table 1
SELECT ... FROM ClientData WHERE ClientId = @clientId;
-- data table 2
SELECT b.*
FROM ClientData a
JOIN ClientJob b ON b.ClientDataId = a.ClientDataId
WHERE a.ClientId = @clientId;
-- etc.
</code>```

Then building on that and with some up-front configuration, you can convert an entire DataSet into an object tree.

```<code>var sqlToObjectConfig = new []
{
    typeof(Client),
    typeof(ClientData),
    typeof(ClientJob)
};

// call your converter
ConvertToObject<Client>(sqlToObjectConfig, dataSet);
// it will use the config to know the type of each DataTable (by index)
</code>```

So your normal steps would be:

Develop a query to get the data you want

Define a configuration array for the query's conversion to objects

Define a method to execute the query and convert

You could relatively easily query a specific branch like ClientJobs on down.

Body:
Sounds like somebody wants you to write a lot of SQL.

I'm assuming here only reading data since that is all the question specifically mentions.

In the past, I have created an AutoMapper-like component which would map a DataRow to a class by examining the class's property names with reflection, then assign matching DataTable columns of same name and similar type to the class's properties.

Then building on that only a little, you can convert an entire DataTable to a list of objects. I believe AutoMapper will do this already.

The query to populate an entire object tree usually returned multiple DataTables in the DataSet.

-- data table 0
SELECT ... FROM Client WHERE ClientId = @clientId;
-- data table 1
SELECT ... FROM ClientData WHERE ClientId = @clientId;
-- data table 2
SELECT b.*
FROM ClientData a
JOIN ClientJob b ON b.ClientDataId = a.ClientDataId
WHERE a.ClientId = @clientId;
-- etc.

Then building on that and with some up-front configuration, you can convert an entire DataSet into an object tree.

var sqlToObjectConfig = new []
{
    typeof(Client),
    typeof(ClientData),
    typeof(ClientJob)
};

// call your converter
ConvertToObject<Client>(sqlToObjectConfig, dataSet);
// it will use the config to know the type of each DataTable (by index)

So your normal steps would be:

Develop a query to get the data you want

Define a configuration array for the query's conversion to objects

Define a method to execute the query and convert

You could relatively easily query a specific branch like ClientJobs on down.


答:
The sequence of steps that you described appears to be a sequence of steps that you must perform, in order for your application to achieve what it is supposed to achieve.  So, there is nothing that you could add or remove.

With the existing code, you have the following options:

Rearrange the order in which the conditionals are evaluated. You could, perhaps, achieve better performance by re-arranging the conditionals so that the most frequently failing ones are evaluated first, or so that the more computationally expensive ones are evaluated last, but it is hardly worth the effort, and in any case you need to spend some time measuring stuff before you attempt that, otherwise you are shotgunning the problem and running the danger of worsening things instead of improving things.

Replace nesting with multiple expressions ANDed together. I know nothing of Objective-C, but I would be willing to bet that it stays true to the tradition of C, and it uses short-circuit boolean expression evaluation, so the construct if(a) { if(b) { ... } } is equivalent to if((a) && (b)) { ... }, so nesting or no nesting makes absolutely no difference.

Replace nesting with early-exiting.  Early exiting is when you say if(!a) return; if(!b) return; bulk-of-code-goes-here. There are people who insist on early exiting, so as to reduce the nesting, and others who see no problem with nesting, and believe that early exiting is evil. But again, this makes no difference on how fast the code will run, so this issue is all about style, not performance: "to nest or not to nest" is an entirely subjective question which can only receive a subjective answer. (Which is of course "die, you nesting fool !")

So, there is pretty much nothing you can do to improve things, and nesting or no nesting has absolutely no impact on performance.  On top of that, no matter how you structure your conditionals, the compiler is generally free to emit the machine code in whatever way it sees fit, as long as it has the same result, so your nested conditionals will probably be implemented as early exits by the compiler, just as short-circuit evaluation would. This means that at the end of the day, the only criterion for how to arrange your conditionals ought to be how it is most natural for you to read them and understand them.

I would recommend that you heed the advice contained in gnat's excellent (and ironic) suggestion that your question is a duplicate of another question which is in fact about micro-optimizations: stop worrying about performance of code.  You should only start being worried about performance if your final product is found to actually suffer performance-wise, and even then, the solutions that you will find will most likely be algorithmic, big-picture optimizations, and it is highly unlikely that they will have anything to do with how you order individual instructions.

Title: Do nested conditionals have a significant performance impact?

Body:
This is a question that lives in my mind from a long time.

Does the use of multiple nested conditional statements impact the performance of a taken code? So far I know that programmers have created a precise term to describe this situation, the in-famous "Pyramid of doom" [Wikipedia page], but a side from that how much can this degrade performances?

Let's take this situation as an example: I have a JSON coming from a server response containing a few objects that represent the user purchases in an application, before taking the needed data from it I need to check various conditions:

Is the response we are looking for?

Does response has resultCode: OK?

Are the any contents to process?

At this point if everything is true a "processing process" will begin, parsing and editing the server response, in this case for changing the date format from US to the standard european format. The process consist in two nested for-loops and an if statement.

This is the example code in Objective-C, since I'm an iOS Developer:

```<code>if ([remoteManager.operationId isEqualToString:NEEDED_OPERATION_ID]) {
    if ([response[RESULT_CODE_KEY] isEqualToString:@"OK"]) {
        if ([response[RESULT_OBJ_KEY][@"CONTENT_LIST"] count] > 0) {
            NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];

            for (NSMutableDictionary *productsAvailable in response[RESULT_OBJ_KEY][@"CONTENT_LIST"]) {
                for (NSString *key in productsAvailable) {
                    if ([key isEqualToString:@"NEEDED_KEY"]) {
                        /* We change the date format here */
                    }
                }
            }
        }
    }
}
</code>```

In my opining this code can't really have an impact on the performance of an application because those checks are not so complicated for the system to do. But does this can be a problem if we need to have the maximum speed and performances? In other words: should nested conditionals be avoided or not? And also does putting multiple conditions at the same time reduces the performance problems (if any)?


问:
Algorithm to determine best combination of keeping students together in their camp rooms
I have a problem I'd like to solve and am not sure whether there is a known algorithm or how the best way to approach it would be.

Say for example there is a class of 30 students who are going on a school camp. They will each share a room with other students. Each student can provide a list of 3 friends that they ideally want to share a room with.

I'd like to know if there is a programmatic way to determine the best outcome for keeping students together with who they requested to go with?

There is also another complication here, being that there are x amount of rooms, each room allowing a varying amount of students per room (up to 7).

答:
As far as I can tell this problem is a special case of the quadratic assignment problem (QAP)

If the size of the problem is reasonable I would probably try modelling it as an integer problem and solve it with a MIP solver (see GLPK or CBC for open source solvers).

The mathematical problem would probably look something like that (assuming that all room have the same capacity, if you want to model heterogeneous rooms, the model would be a bit different):

Let us assume that Q is the capacity of the room.
Let S be the set of students.
Let $x_{i,j}$ be a binary variable saying that student i is in the same room as student j.
Let $a_{i,j}$ be 1 if i wants to be with j and 0 otherwise.

We try to maximise
$\sum_{i \in S, j \in S} x_{i,j}a_{i,j}$

Subject to:

$\sum_{j \in S} x_{i,j} = Q, \forall i \in S$
$x_{i,j} = x_{j,i}, \forall i \in S, j \in S$
$x_{i,k} \geq x_{i,j} + x_{j,k} - 1,  \forall i \in S, j \in S, k \in S$


问:
Should source control file directory match solution/project namespaces?
My team is trying to decide how to best organize/structure our TFS directory. One proposed solution is to create a directory structure that will dictate the namespaces for our c# projects. For instance, if the tfs directory structure for a specific project was TFS\MyApp\Common, then any C# objects in this directory would be under a namespace called TFS.MyApp.Common

Is coupling the TFS directory structure to our solution namespaces a good idea? Could that be hard to maintain after many changes are made inside of projects and solutions? Does anybody do this where you work today?

答:
I would not put TFS in your namespaces - it seems redundant and unnecessary.

Typically you'd use namespaces to organize class libraries by related function.  So if you have an API layer for project A, you'd have A.API.  You might also have A.UI.

Those are fine, and the suggestion you made looks good, just don't include the TFS part.


答:
This is where an Object Relational/Mapping library, like NHibernate or Entity Framework comes in handy. It juggles the SQL, lazy loading and mapping for you.

Having a deep structure of interconnected tables is not a bad idea. Proper data design and normalization can dictate the need for these relationships. OR/M's try to bridge that gap between a relational data model and an object oriented one to make it easier to do precisely what you are finding difficult.

I have been directed to not use Entity Framework, and instead I must create hand written views or stored procedures for data access.

You can still call stored procedures for data retrieval, inserts, updates, and deletes using NHibernate. Despite what you have been told, an OR/M will save you headaches. Your table structure and relationships are complex enough to benefit from this.

Title: Deep SQL relationships to a C# object model

Body:
I have a database with deep table to table relationships

for example

Clients (one to many) -> ClientData (one to many) -> ClientJob (one to many) -> ClientProcess (one to many) -> ClientStep... so on.

And these aren't one branch trees either. So Clients also has a one to many relationship with another tree of tables. The database has a very large number of tables and a bunch of relationships between them.

The C# models I have are similar in design to this

```<code>public class Client {

   //base client data
   public string ClientId { get; set; }

   public string ClientName { get; set; }
   //etc...

   //Objects with the one to many relationship
   public List<ClientData> {get; set;}

   public List<ClientLocation> {get; set;}

   //etc..
}
</code>```

And the ClientData object has it's base data and lists of objects representative of it's relational database relationships and so on.

I have been directed to not use Entity Framework, and instead I must create hand written views or stored procedures for data access.

My question is, is there a design pattern I can employ here that makes this SQL/C# structure efficient and maintainable?

I would like the ability to also query substructures, so instead of always getting a complete Client and all of it's related objects, I can get a specific ClientData and all of it's nested objects but not the Client which owns it.


答:
Object may be created for the purpose of encapsulating behaviors or holding data, and objects may be created for the purpose of being shared with outside code or held privately by their creator.

Objects which are created for the purpose of encapsulating behavior (whether shared or not), or for the being shared with outside code (whether they encapsulate behavior or data) should generally be accessed through their surface interface.  When data-holding objects are created for use exclusively by their creator, however, the normal Law-of-Demeter reasons for avoiding "deep" access don't apply.  If part of a class which stores or manipulate data in the object is changed in a way that would require adjusting other code, it will be possible to guarantee that all such code gets updated because--as noted above--the object was created for the exclusive use of one class.

While I think the ?. operator could perhaps have been better designed, there are enough situations where objects make use of nested data structures that the operator has many use cases which would not violate the principles expressed by the Law of Demeter.  The fact that it could be used to violate the LoD should not be taken as an argument against the operator, since it is no worse than the "." operator in that regard.


问:
Two tables with similar structure and referential integrity or one table
Overview

My question revolves around balancing database and code simplicity using 2 options to design around the following requirement.

Background Facts

The DB: Sql Server

The Code: ASP.NET MVC C# using EntityFramework

I have a table, AllocationNeed (see below).

```<code>/****** Object:  Table [dbo].[AllocationNeed]    Script Date: 10/7/2015 12:39:43 PM ******/
CREATE TABLE [dbo].[AllocationNeed](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [FacilityId] [int] NOT NULL,
    [WorkReleaseHeaderId] [int] NULL,
    [NeedSourceId] [int] NOT NULL,
    [NeedSourceType] [nvarchar](50) NOT NULL,
    [ItemId] [int] NOT NULL,
    [QtyNeeded] [decimal](18, 4) NOT NULL,
    [CreatedById] [int] NOT NULL,
    [CreatedOn] [datetime] NOT NULL,
    [ModifiedById] [int] NOT NULL,
    [ModifiedOn] [datetime] NOT NULL
</code>```

There are at least 2 sources of inventory needs and today am using a NeedSourceType and NeedSourceId to hold that information in this single table.

In this case a NeedSourceType is either a "Ship Order" and a "Work Order". These both are also represented in other tables as OrderHeader and WorkOrderHeader respectively. NeedSourceId is the respective foreign key values of OrderHeader.Id or WorkOrderHeader.Id.

There is also a related child table (many to 1 AllocationNeed) AllocatedContainers, which has a foreign key back to AllocationNeed.Id. In the near future, this table could also have the same issue in that we will need to add the concept of AllocatedLocations in addition to AllocatedContainers, so again, we could have this be 2 tables or one.

Approach Options Pros and Cons

Approach: One Table

Pros:

my code is a bit cleaner in that I normally need to run aggregates on the total combined inventory need, so no need to do a join if these were two tables

Code is simpler for writing and reading to this table instead of 2 or more tables

doesn't add additional tables to DB

Cons:

I often need to get attributes of the associated Ship and Work Orders, so I need to do joins in my code instead of just accessing AllocationNeed.OrderHeader.ShipDate

There is no referential integrity

Can't use cascading deletes so code is more complex to delete
records.

Approach: Two Tables

Basically the opposite Pros and Cons to the one table approach.

Looking for thoughts or input on this design dilemma.

答:
On your main tables on which you add/remove records, always do things in perfect relational tradition.  "Referential integrity is not enforceable" means "it is not relational", and "it is not relational" should always automatically mean "it is unacceptable".  If you do not do it this way, you will sooner or later regret it bitterly.

The type of either-or relationship you are trying to model is best (most relationally) described with multiple foreign keys, (in your case two,) of which exactly one will be non-null in any given row.  So, if I understand your scenario correctly, you would lose the NeedSourceType and NeedSourceId columns, and replace them with a ShipOrderId and a WorkOrderId.

If you need to have a simpler, read-only view of things, (such as for running aggregates on the total combined inventory,) create database views which are basically pseudo-tables defined as queries.

If you have more heavy data mining needs, then create additional sets of tables that contain the same information but in a denormalized form (not strictly relational) in order to facilitate easier querying.  But these tables should be used only for querying, never for updating and deleting.


问:
Anonymize Public Health Records Database
I am working on a project to anonymize PHI in our health records database when databases are copied to our testing environments. Currently, the database is copied and fields in the tables (first name, last name, address, DOB, etc.) are replaced pseudo-randomly (seed value generated by datetime) with values from a pre-generated list of values. For small databases this is fine, but when using very large databases with large tables values are repeated quite frequently and the scrubbing process takes a very long time. My thought was to use an algorithm that swaps values in the table, but is this a safe way to anonymize PHI? What types of algorithms would generate a sufficient variance in data while still maintaining a low processing time?</p>

答:
My thought was to use an algorithm that swaps values in the table, but is this a safe way to anonymize PHI?

No. You are still leaking information about your clients into the test environment.

It should be relatively trivial to generate an algorithm to randomly generate names (~100 first names + ~100 last names leads to a lot of combinations), addresses (number + tree + road/street/avenue/etc).

For small databases this is fine, but when using very large databases with large tables values are repeated quite frequently and the scrubbing process takes a very long time.

Outside of performance/load testing, you probably don't need large databases for your test environments. It may be as simple as capping the number of rows (and their relations).


答:
I worked at a company where we did almost exactly what you are doing. I don't know exactly what our algorithm was. I do know that we scrambled the data so no one could ever unscramble it, but we did not change the data itself. Replacing names, addresses, and so forth with your own values sanitizes the data and eliminates any chance of catching some interesting errors. Real data is not perfect, and we I can't tell you how many bizarre little errors we found because of it.

If you are going to replace everything, then you should just generate the database you want, rather than trying to conform an existing one.

Title: Anonymize Public Health Records Database

Body: I am working on a project to anonymize PHI in our health records database when databases are copied to our testing environments. Currently, the database is copied and fields in the tables (first name, last name, address, DOB, etc.) are replaced pseudo-randomly (seed value generated by datetime) with values from a pre-generated list of values. For small databases this is fine, but when using very large databases with large tables values are repeated quite frequently and the scrubbing process takes a very long time. My thought was to use an algorithm that swaps values in the table, but is this a safe way to anonymize PHI? What types of algorithms would generate a sufficient variance in data while still maintaining a low processing time?</p>


问:
How to write a simplistic functional test plan?
I was given an assignment and it is fairly simple, just a special type of search for a special type of objects.

However, I was told to implement a set of functional tests and also provide a 1 page test plan. However, I am not sure what this plan has to include.

I have searched for samples on-line but they are too large for the scope of this assignment since it is supposed to be 1 page only.

I implemented 16 tests using JUnit, they test the expected results that a search produces.

答:
You can include the following in form of a table:
Item number - this is pretty much of 1,2,3,4.... (Just Basic numbering). Or if your program consists of a menu with numbers, you can use that as your numbers.

Item tested - these is about what item you are testing. E.g. You have a menu in a program, so these are the menu options like if you are adding a member for a certain organisation, the item tested will be for "Add Member"

Test Method - What are the methods you used while testing the program... E.g. Enter the menu number and click 'OK'

Expected Result - What do you expect to happen when you run the program.. like in these case, you want to add a member so the expected result for this would be 'Program add Member or Member added successfully'

Actual result - You can use ticks and crossed for these.

Hope these helps.


问:
MIT License: Selling and distributing
I am confused when it comes to the MIT licenses.  If I create a project and put it under the MIT licenses and open source it. Can someone just take my project and turn it into something else and sell it?  I have read the licenses like 20 times and I'm still confused.  </p>

<p>Or if I find some code that is under the MIT licenses and I want to implement it in my project. Can I sell my project on the market? With that code in it? </p>

答:
MIT is a permissive license, apart from a few details about copyright and warranty representations.  It has three parts:

Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so

...which means that anyone can do anything that they want to with the software and cannot restrict others from doing the same, including incorporating your code into another project and selling it.

The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software

...which means that, if you use MIT-licensed code in another program, you have to say so.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO BLAH BLAH BLAH...

... which means that nobody is responsible in any way for how well the software works, or anything that happens as a result of using of the software.

Title: MIT License: Selling and distributing


问:
How to write loosely coupled tests
I work on a software that has a lot of tests. However, instead of helping us develop faster, these tests actually bog us down, because even tiny changes in the application break many tests. Clearly, the tests are too tightly coupled to the application.

A big problem is that our application is not designed with testability in mind. We have big classes with lots of dependencies to other classes, we use singletons and we have lots of mutable state, we don't use DI, we don't use PImpl. Our modules are also coupled fairly tightly to each other.

I wonder whether there are any general techniques we could use to reduce this coupling. Preferably without rewriting large parts of our application to make it easier to test.

答:
Tests are supposed to be tightly coupled to the application.

The fact that many tests fail when changes are made is a good thing. Far better than throwing it over the wall and have your customer/user find the errors.

However, code base aside, this rather assumes that you have good tests in place.

Some questions to ask when tests fail:

Is the test valid?

Does the logic under test still apply? If not, remove it.

Are the same tests failing?

If the same sorts of tests are failing, this highlights where your code is particularly brittle. A flippant remark you might think, but check through your source control and you may find the same tests have been repaired again and again and again.

Is the test in a reasonable area?

How close to the action is the failing test? If tests are failing in areas where you wouldn't expect, again, you have an issue you need to address.

Do you have to massage a test thru?

Do you have test that require a number of changes just to get them thru? If so, re-engineer the test so it is testing a smaller area of functionality.

Do the same fixes have to be applied to different tests?

If you're applying the same fix to multiple tests, this indicates a code smell. Either the test is too large or there is common code can be refactored out.

Do the tests following FIRST principles?

Ensure the tests are following the basic rules.

As for how you can improve the code without making wholesale changes, that is difficult to advise on without knowing the code base. As a starting point, I'd be inclined to target your changes on areas where tests are consistently failing.

Title: How to write loosely coupled tests


问:
UUID collisions
Has anybody done any real research on the probability of UUID collisions, especially with version 4 (random) UUIDs, given that the random number generators we use aren't truly random and that we might have dozens or hundreds of identical machines running the same code generating UUIDs?

My co-workers consider testing for UUID collision to be a complete waste of time, but I always put in code to catch a duplicate key exception from the database and try again with a new UUID.  But that's not going to solve the problem if the UUID comes from another process and refers to a real object.

答:
This is a very good question. I don't believe it's been adequately considered in the rush to use UUIDs everywhere. I haven't found any solid research.

A suggestion: tread very carefully here, and know your cryptography well. If you use a 128-bit UUID, the 'birthday effect' tells us that a collision is likely after you've generated about 2^64 keys, provided you have 128 bits of entropy in each key.

It is actually rather difficult to ensure that this is the case. True randomness can be generated from (a) radioactive decay (b) random background radio noise, often contaminated unless you're careful (c) suitably chosen electronic noise, e.g. taken from a reverse-biased Zener diode. (I've played with the last, and it works like a charm, BTW).

I wouldn't trust pronouncements like "I haven't seen this in a year of usage", unless the user has generated something approaching 2^64 (ie. about 10^19) keys, and checked them all against one another, a non-trivial exercise.

The problem is this. Let's say you have just 100 bits of entropy, when comparing your keys against all of the other keys everyone else is generating in a common keyspace. You'll start seeing collisions in about 2^50 ie. about 10^15 keys. Your chances of seeing a collision if you've populated your database with just 1000 billion keys are still negligible. And if you don't check, then you will later get unexpected errors that creep into your peta-row sized database. This could bite hard.

The very fact that there are multiple approaches to generating such UUIDs should cause a momentary spasm of concern. When you realise that few generators use 'truly random' processes with sufficient entropy for a type 4 UUID, you should be excessively concerned unless you've carefully examined the entropy content of the generator. (Most people will not do this, or even know how to; you might start with the DieHarder suite). Do NOT confuse pseudorandom number generation with true random number generation.

It's critical that you realise that the entropy you put in is the entropy that you have, and simply perturbing the key by applying a cryptographic function doesn't alter the entropy. It may not be intuitively obvious that if my entire space comprises the digits 0 and 1, the entropy content is the same as that of the following two strings, provided they are the only two options: "This is a really really complex string 293290729382832*!@@#&^%$$),.m}" and "And NOW FOR SOMETHING COMPLETELY DIFFERENT". There are still just two options.

Randomness is tricky to get right, and simply believing that "experts have looked at it, it's therefore OK" may not suffice. Expert cryptographers (and there are few of these who are really proficient) are the first to admit they often get it wrong. We trusted heartbleed, DigiNotar, etc.

I think Paul Tomblin is exercising appropriate caution. My 2c.

Title: UUID collisions


问:
How do I balance 100 clients checking the same database table in a loop?

What I have

This is a prototype. I have a pool of 100 clients connected to the server via websockets reporting things and awaiting for commands. The server polls the commands database table of type MEMORY in a loop using a query with WHERE client_id=?. I can insert a combination of client_id+command to that table, and once I do that, the corresponding loop will match and SELECT it and pass it back to the client.

What's the problem

The approach sounds like it would work, but as far as I understand I'm talking about n simultaneous database connections and queries in an endless loop (n being the number of clients), which doesn't sound effective. It'd be much better to do one query in one loop and then somehow check the client_id, if any, and distribute the results to the corresponding clients.

This reminds me of the approach where you're selecting articles first and then for () {} the resultset and do separate queries to get the details foe each of the items, which results in n+1 queries being made. The solution to that is doing a big query with JOINs and also preloading the other data that doesn't fit into the main JOINed query. There should be the similarly more effective way to do the database polling too.

UPDATE: I found this answer in the related section, and it says pretty much the same thing:

Hammering your database isn't really a good idea. While I'm pretty sure you've realized this, others might not have. I remember a friend of mine tried to use a php script and a Javascript AJAX function in a loop for a semi-real time game. He very quickly realized that performance degraded as more people joined, simply because he was executing a ton of queries per second which hammered the database.

So polling the database for each client sounds as unscalable and ineffective as building an AJAX chat application.

What I'm asking for

I guess that every possible programming approach must have been named and covered by now, so what is this one called? What is the common advice/approach here?

答:
You want a connection pool - 100 clients will be throttled to using a pool of a handful of DB connections so your DB will not get overloaded responding to many simultaneous requests.

You could try to optimise the calls but you will still need to allow the clients to access the DB through a mechanism identical to a connection pool, even if there is just 1 connection available in the pool, you can combine all the IDs from the pending clients together into a single where clause to pass to the DB and unpack the results to each client when it returns. You'll either have to track which client is in the request or ensure the results have a result for each requesting client as more clients will arrive while the DB query is in progress, when the results are distributed to the clients, you repeat with the new ones.

If you have a pool like this,and your circumstances allow it, you can also delay DB requests to a gentle rate, but hitting the DB repeatedly on a single connection doesn't impact performance anything like as much as 100 clients all jostling for attention simultaneously.


问:
OOD: Java inheritance and access to child methods via casting
I have several classes Parent and Child1 ... Child9 implemented in Java. Parent is an abstract class, containing all the common variables of the child classes (a lot, which is the main reason why I made Parent an abstract class and not an interface), some abstract and some implemented methods.

Some of the child classes have custom methods which are specific to them. So often I find myself calling a child method using downcasting:

```<code>Parent p = new Child1();
((Child1) p).child1SpecificMethod();
</code>```

Somehow I have the feeling that this is bad OOD practice, but I am not quite sure if that really is the case respectively how to improve the design.

- Edit -
What I probably should change anyway is the fact that I use the Parent class for organizing many (for now) common variables, making them (or a container object) members of the concrete classes.

答: Add an abstract method child1SpecificMethod() in Parent class(you need to mark class as abstract) and provide its implementation in respective child class.</p>


答:
Unless the queries the clients need to issue are complex, I wouldn't use an sql database here. There's quite a lot of overhead, even when usinga memory table: interprocess communication, interpreting the query, maintaining an index that probably supports query types you don't need (e.g. ranges), data marshalling, and so on.

Precisely how I would do it depends very much on the applications other requirements. If you don't foresee the need to scale to multiple servers, an in-process store (i.e. a javascript map in a shared variable) is by far the most efficient way of sharing data. Otherwise, I'd look at in-memory key value store databases, e.g. redis.

Above all else, I'd abstract data access so that changing between these options at a later date is easy.

Title: How do I balance 100 clients checking the same database table in a loop?

Body:
What I have

This is a prototype. I have a pool of 100 clients connected to the server via websockets reporting things and awaiting for commands. The server polls the commands database table of type MEMORY in a loop using a query with WHERE client_id=?. I can insert a combination of client_id+command to that table, and once I do that, the corresponding loop will match and SELECT it and pass it back to the client.

What's the problem

The approach sounds like it would work, but as far as I understand I'm talking about n simultaneous database connections and queries in an endless loop (n being the number of clients), which doesn't sound effective. It'd be much better to do one query in one loop and then somehow check the client_id, if any, and distribute the results to the corresponding clients.

This reminds me of the approach where you're selecting articles first and then for () {} the resultset and do separate queries to get the details foe each of the items, which results in n+1 queries being made. The solution to that is doing a big query with JOINs and also preloading the other data that doesn't fit into the main JOINed query. There should be the similarly more effective way to do the database polling too.

UPDATE: I found this answer in the related section, and it says pretty much the same thing:

Hammering your database isn't really a good idea. While I'm pretty sure you've realized this, others might not have. I remember a friend of mine tried to use a php script and a Javascript AJAX function in a loop for a semi-real time game. He very quickly realized that performance degraded as more people joined, simply because he was executing a ton of queries per second which hammered the database.

So polling the database for each client sounds as unscalable and ineffective as building an AJAX chat application.

What I'm asking for

I guess that every possible programming approach must have been named and covered by now, so what is this one called? What is the common advice/approach here?


答:
No. Let's consider both the operator on its own, and the heavily chained use you have for it.

On its own .?A depends upon the same amount of knowledge of the class the left-value is and of the type returned by the method as .A != null does, viz. It needs to know about that the A property exists and returns a value that can be compared with null.

We can only argue that this violates the law of Demeter if typed properties do. We aren't even forced to have A as a concrete type (its value could be of a derived type). The coupling here is minimal.

Now lets consider var x = A?.B?.C?.D?.E?.F.

Which means that A must be of a type that could be null, or could have a B property, which must be of a type that could be null or have a C property, and so on until the type of the E property being something that could be null or could have an F property.

In other words, we need to be doing this with either a statically-typed language or have applied a constraint on the types that can be returned if the typing is loose. C# in most cases uses static typing, so we've changed nothing.

If we had then the following code would also violate the law:

```<code>ExplicitType x;
var b = A.B;
if (b == null)
  x = null;
else
{
  var c = b.C;
  if (c == null)
    x = null;
  else
  {
    var d = c.D;
    if (d == null)
      x = null;
    else
    {
      var e = d.E;
      if (e == null)
        x = null;
      else
        x = e.F;
    }
  }
}
</code>```

Which is exactly the same. This code that is using the coupling of different elements needs to "know" about the full chain of coupling, but it is using code that doesn't violate the Law of Demeter to do so, with each unit having a well-defined coupling with the next.

Body:
No. Let's consider both the operator on its own, and the heavily chained use you have for it.

On its own .?A depends upon the same amount of knowledge of the class the left-value is and of the type returned by the method as .A != null does, viz. It needs to know about that the A property exists and returns a value that can be compared with null.

We can only argue that this violates the law of Demeter if typed properties do. We aren't even forced to have A as a concrete type (its value could be of a derived type). The coupling here is minimal.

Now lets consider var x = A?.B?.C?.D?.E?.F.

Which means that A must be of a type that could be null, or could have a B property, which must be of a type that could be null or have a C property, and so on until the type of the E property being something that could be null or could have an F property.

In other words, we need to be doing this with either a statically-typed language or have applied a constraint on the types that can be returned if the typing is loose. C# in most cases uses static typing, so we've changed nothing.

If we had then the following code would also violate the law:

ExplicitType x;
var b = A.B;
if (b == null)
  x = null;
else
{
  var c = b.C;
  if (c == null)
    x = null;
  else
  {
    var d = c.D;
    if (d == null)
      x = null;
    else
    {
      var e = d.E;
      if (e == null)
        x = null;
      else
        x = e.F;
    }
  }
}

Which is exactly the same. This code that is using the coupling of different elements needs to "know" about the full chain of coupling, but it is using code that doesn't violate the Law of Demeter to do so, with each unit having a well-defined coupling with the next.


问:
Iterator pattern - why is it important to not expose the internal representation?
I am reading C# Design Pattern Essentials. I'm currently reading about the iterator pattern.

I fully understand how to implement, but I don't understand the importance or see a use case. In the book an example is given where someone needs to get a list of objects. They could have done this by exposing a public property, such as IList<T> or an Array.

The book writes

The problem with this is that the internal representation in both of these classes has been exposed to outside projects.

What is the internal representation? The fact it's an array or IList<T>? I really don't understand why this is a bad thing for the consumer (the programmer calling this) to know...

The book then says this pattern works by exposing its GetEnumerator function, so we can call GetEnumerator() and expose the 'list' this way.

I assume this patterns has a place (like all) in certain situations, but I fail to see where and when.

答:
Software is a game of promises and privileges. It is never a good idea to promise more than you can deliver, or more than your collaborator needs.

This applies particularly to types. The point of writing an iterable collection is that its user can iterate over it - no more, no less. Exposing the concrete type Array usually creates many additional promises, e.g. that you can sort the collection by a function of your own choosing, not to mention the fact that a normal Array will probably allow the collaborator to change the data that's stored inside it.

Even if you think this is a good thing ("If the renderer notices that the new export option is missing, it can just patch it right in! Neat!"), overall this decreases the coherence of the code base, making it harder to reason about - and making code easy to reason about is the foremost goal of software engineering.

Now, if your collaborator needs access to a number of thingies so that they are guaranteed not to miss any of them, you implement an Iterable interface and expose only those methods that this interface declares. That way, next year when a massively better and more efficient data structure appears in your standard library, you'll be able to switch out the underlying code and benefit from it without fixing your client code everywhere. There are other benefits to not promising more than is needed, but this one alone is so big that in practice, no others are needed.


答:
Exposing the internal representation is virtually never a good idea. It does not only make the code harder to reason about, but also harder to maintain. Imagine you have chosen any internal represenation - lets say an IList<T> - and exposed this internal. Anybody using your code may access the List and code may rely on the internal representation being a List.

For whatever reason you are deciding to change the internal representation to IAmWhatever<T> at some later point in time. Instead on simply changing the internals of your class you will have to change every line of code and method relying on the internal representation being of type IList<T>. This is cumbersome and prone to errors at best, when you are the only one using the class, but it may break other peoples code using your class. If you just exposed a set of public methods without exposing any internals you could have changed the internal representation without any line of code outside your class taking notice, working as if nothing has changed.

This is why encapsulation is one of the most important aspects of any nontrivial software design.

Title: Iterator pattern - why is it important to not expose the internal representation?

Body:
I am reading C# Design Pattern Essentials. I'm currently reading about the iterator pattern.

I fully understand how to implement, but I don't understand the importance or see a use case. In the book an example is given where someone needs to get a list of objects. They could have done this by exposing a public property, such as IList<T> or an Array.

The book writes

The problem with this is that the internal representation in both of these classes has been exposed to outside projects.

What is the internal representation? The fact it's an array or IList<T>? I really don't understand why this is a bad thing for the consumer (the programmer calling this) to know...

The book then says this pattern works by exposing its GetEnumerator function, so we can call GetEnumerator() and expose the 'list' this way.

I assume this patterns has a place (like all) in certain situations, but I fail to see where and when.