问:
avoiding multiple calls to SQL while being modular
I have a BusinessLayer.dll which calls DataAccessLayer.dll which ultimately makes the tcp connection to the SQL server. Each business layer method has a corresponding method in the data access layer which then calls its respective view in the database.

Now the question is what if I have a requirement where I need to get data from three views at one go for one business layer method? These views will be required individually in other areas of the application as well but in one or two areas the data will need to be fetched from all three views at once.

Option 1: Should I call those individual methods in the business layer in a fourth method by making three different hits to the database via their respective business and data access layers and then group the data together in my business layer or

Option 2: Should I just have a stored procedure that calls these three views and return the data to back to the DataAccessLayer and then back to the business layer?

In the above image Option 1 is denoted by the green boxes and the fourth business layer method is denoted by the black box that initiates the three hits to the SQL box to get the data.

Option 2 is denoted by the orange boxes. The benefit of the approach using option 2 is that you dont incur multiple IO hits over the network, but then the code in the Data layer is probably duplicating the code written in the green boxes.

The client can be a web or a windows based application. In a windows based application, the business layer will be wrapped by a service which the windows client will call. How does one acheive a balance of modularity and performance here?

答:
In order:

Is there something which allows you to assert that the application is slow? Is there a non-functional requirement related to performance that the application doesn't fulfill any longer? Does it feel slow (in which case your first concern should be to write down a non-functional requirement which will explicitly tell what are you expecting)?

If the application is fast enough, you're doing premature optimization. Please, don't do that.

What are the results when you profile the application? Have you profiled it and identified that the fact that you're doing three queries instead of one is the bottleneck which affects the performance in a very noticeable way?

If not, do this first. Run profiling, identify the bottlenecks. Very probably, you'll find that the number of queries (3 vs. 1) is your least concern in terms of performance.

Note that connection pooling (if you're using Microsoft SQL Server) reduces considerably the cost of closing and reopening a connection several times. Make sure you close your connections properly, i.e. you dispose the resources. You should have using () { } around all SqlConnections, SqlTransactions, SqlCommands, etc. The static checking tool called Code Analysis helps you finding the stuff not properly disposed.

Remember to profile your views as well. Execution plans are particularly useful in this case. Watch for the indexes (not necessarily the lack of them, but also which ones are there and why). Look at the data you load and the data you actually need (sometimes, developers load too much data from a database, and only then filter it at application level; this is unfortunate, since databases do the filtering job very well themselves).

If you're using an ORM, watch the queries it builds (you may use SQL Server Profiler for that; most ORMs also allow to log the queries they send to the database). Sometimes, ORMs need help for figuring out the best way to build an optimized query.

Do you use caching?

If not, you may want to focus on that first, before dealing with multiple queries vs. one query. Since you're talking about views, I imagine that you're not modifying data, but only reading it (although, you can modify data through views in Microsoft SQL Server). This means that this data can very probably be cached on the server, which means that instead of 3 or 1 queries, you'll have 0.

Only then, i.e. only if you know that the application doesn't respond to a non-functional requirement of performance, that it is slow because it does three queries instead of one and that caching won't help should you be concerned by optimization consisting of replacing three queries by one.

Remember that you're not necessarily forced to do it through a stored procedure. In your particular case, since all you do is to access three views, creating a fourth view can be the solution.

In all cases, I'm surprised that you have found that (or that you believe that) performance is affected on I/O level by three queries instead of one:

What could have been the issue is to close and reopen connections two times. As I previously said, connection pooling solves that.

In general, the time spent sending a query to an SQL server is nearly zero compared to the time spent reading the data back, unless you're querying a scalar value.

In general, the time spent sending a query to an SQL server is not as important as the time spent by the SQL server loading the data (given that most SQL servers do a great job of caching data in memory, which makes most queries outstandingly fast).


问:
How do you solve issue of consistency in concurrent and distributed application (built around Bankers Dilemma)?
This is a classic problem which I'm sure has been solved many times by many different people. I don't have any formal training (I've not studied computer science or any other such academic subject) and so I'm not sure of the best way to solve the problem I'm about to describe.

If we imagine the below diagram is an example of a bankers dilemma (two users Foo and Bar have access to a single bank account: Baz). What is the expected behaviour when following one of the paths shown?

Note: I'm assuming we're using a mutex (or some other form of synchronisation) on the Baz variable.

Example 1: Baz initially holds the value 10. If Foo writes a new value (which is the result of removing 5 from the current value) before Bar; then Bar will end up taking 10 from the new value 5, leaving a minus balance (i.e. the final value will be -5). Meaning more money has been taken than available.

Example 2: Baz initially holds the value 10. If Bar writes a new value (which is the result of removing 10 from the current value) before Foo; then Foo will end up taking 5 from the new value 0, leaving a minus balance (i.e. the final value will be -5). Meaning more money has been taken than available.

Both actions (Foo (-5) and Bar (-10)) are triggered at the same time. So how do we ensure that either Foo or Bar is alerted to the fact that their transaction cannot be completed (as there are not enough funds for it to succeed)?

It seems a potential solution is to ensure the caller executes a method that uses a mutex internally to lock the value first; then once the value is locked we can read the value; and then check if the action is valid. If the condition passes then we update the value and release the lock on the value. Meaning the next caller will be able to lock the value down and run through the same steps.

But how would this approach work with a distributed system? You could suggest using a global data store, but it would have to be one that guarantees consistency (e.g. a service such as AWS' Dynamo DB offers "eventual consistency" and so wouldn't work for a banking institution); but guaranteed consistency is generally considered to be very slow (depending on the number of distributed nodes I assume).

So how do we attempt to solve this design problem?

答:
For a distributed system, you would either:

a) Use "subtract amount or return error if you can't", where the code responsible for baz returns an error if the result would've been negative (or returns "success" if there wasn't an error)

b) Use the equivalent of locking; where the code responsible for baz has an "acquire baz" and "release baz" that need to be used before and after.

Note that this is typically just the tip of the iceberg. More likely is that you've got 2 or more bank accounts, and want to transfer funds from one to the others such that either all accounts are updated or none are updated. In this case you might (e.g.) end up with a combination.

For example, if there are two accounts "Fred" and "Jane" and you want to transfer $5 from Fred to Jane; then you might end up with a sequence like:

From you to Fred's account: "If Fred's account is 5 or greater lock Fred's account and tell me I can proceed, else tell me I can't proceed"

From Fred's account to you: "You may proceed"

From you to Jane's account: "If Jane's account can be increased by 5 lock Jane's account and tell me I can proceed, else tell me I can't proceed"

From Jane's account to you: "You may proceed"

From you to Fred's account: "Subtract 5 from Fred's account and release the lock you gave me previously"

From you to Jane's account: "Add 5 to Jane's account and release the lock you gave me previously"

Note that for this example; you, Fred's account and Jane's account may all be running on completely different computers communicating with messages/packets (with no shared memory at all).

ContentLicense: CC BY-SA 3.0


问:
Custom mobile app and custom server app
I have this little bit simple and general question. Let's say I build an android app which requires an online server to communicate with. The thing is that I want to make the communication on my own ( because now I know only with http post/get). Are there any libraries or how do you do this at all? </p>

答:
If you want to start experimenting with client/server communication with Android and a web service you don't need to develop a fully blown RESTful API to do it (though there are very good reasons why you might want to use a RESTful API eventually when you've had enough experience to think about how to design it well).

The first recommendation is to use HTTPS and not HTTP if you are communicating over a public network (like the Internet for example). Otherwise all data between client and server will be visible to anyone and everyone who can see the data.

For the simplest solution, the client on the Android device could, for example, POST an HTTPS form with some simple fields like 'username' and 'password' (so you can authenticate the client device rather than accept input from anyone poking around at your server's API), and a third field called something like 'content' where you send the info from the client to the server. The sending of the username and password in the form is another reason to use HTTPS - otherwise authentication is pointless.

The form field 'content' could contain any kind of data, including request for data from the server, or data you want to store on the server.

The server then only has to accept HTTPS form posts, and read the username and password and check them, and then process the content and reply with an appropriate response. The response could just be plain text, or JSON or XML, or whatever. The library on Android that performs the HTTPS POST will read this response and pass it to the client system to process.

What you put in the content message, how you process it, and how your client responds to the response is up to you.

RESTful APIs do exactly the same kind of thing, but use the HTTP protocol verbs (PUT, GET, POST, DELETE etc.) to tell the server what you want to do with the data you send to it. You can simulate this in the server's response to the HTTPS form POST even though this is, by many, considered to be bad practice. RESTful APIs make you think about what you are doing with data, and how to think about resources in a more structured way, but they are not mandatory for client/server communications over HTTP.

So I think experimenting with simple form POSTs for all communications until you are satisfied how your system might work, and then rewriting the API part to be RESTful may be a good way to go. It could be that you never go RESTful because the form POSTs are good enough for a simple application.

Title: Custom mobile app and custom server app


问:
Should I bother to develop for JavaScript disabled?
Should I bother to develop for JavaScript disabled?

I feel that my time is better spent developing for the majority.

答:
Only on mission critical functionality

Generally its a good idea to "degrade gracefully". However I would I would only concentrate on mission critical parts of your web application, to cater for situations when JavaScript may not be available.

If its just "bells & Whistles" effects, then no don't bother. People who deliberately surf with out JavaScript will just have to make do a plain experience (hey that's their choice for not using Js)

ContentLicense: CC BY-SA 2.5


问:
Efficient Code Design for Pattern Search Using a Singleton Pattern
I am having difficulty figuring out an efficient (thread-safe) code design for the following problem. I have been at it for some time now and would really appreciate some advice and input on how best to approach this.

I am basically searching for various patterns inside a data set. I would like to have one "master" class. I call this class Patterns. I am thinking of making this class a singleton pattern or a static class. I wish to have only one instance of this master class. I am coding this class as a singleton pattern
(pattern by Jon Skeet) at this time.

```<code> public sealed class Patterns
 {
      private Patterns()
      {}

      public static Patterns Instance { get { return Nested.instance; } }

      private class Nested
      {
           // Explicit static constructor to tell C# compiler
           // not to mark type as beforefieldinit
           static Nested()
           {
                // ...  create a list to hold data for internal use
                List<Point> Data = new List<Point>();
           }

           internal static readonly Patterns instance = new Patterns();
      }
 }
</code>```

I have chosen a singleton pattern because:

I want the singleton to hold nested classes; one class for each pattern.

I want these nested classes to be instance classes (i.e. not static)

I would like the singleton to instantiate the nested classes, perhaps using a factory pattern, as needed.

I am not sure whether my reasoning here is correct so any advice would be greatly appreciated.

Now I plan to add the various pattern classes as nested classes because patterns do not make sense outside the master Pattern class. Also, IPattern is an interface for the patterns.

```<code> public sealed class Patterns
 {
      private Patterns()
      {}

      public static Patterns Instance { get { return Nested.instance; } }

      private class Nested
      {
           // Explicit static constructor to tell C# compiler
           // not to mark type as beforefieldinit
           static Nested()
           {
                // ...  create a list to hold data for internal use
                static List<Point> Data = new List<Point>();

                // ... indices to track occurences of each pattern
                static int AIndex = 0;
                static int BIndex = 0;
                static int CIndex = 0;
           }

           internal static readonly Patterns instance = new Patterns();
      }

      // ... Methods

      public bool SearchForPattern(Point dataPoint)
      {
           // ... add data to list
           Data.Add(dataPoint);
      }

      // ... nested pattern classes

      class PatternA : IPattern
      {
           static int = some integer
           static double[] arr = new double[];

           // ... do some work
      }

      class PatternB : IPattern
      {
           // ... do some work
      }

      class PatternC : IPattern
      {
           // ... do some work
      }
 }
</code>```

The List Data is static because I want the data to be retained throughout the lifetime of the application. Same for the static fields in the nested classes.

This is where I now begin to really get lost. In the method SearchForPattern(Point dataPoint) I would like to do the following:

```<code>      public bool SearchForPattern(Point dataPoint)
      {
           // ... add data to list
           Data.Add(dataPoint);

           bool haveA = PatternA.SearchForA();
           if (haveA)
           {
                PatternA a1 = new PatternA();     // the number after a will change as other A patterns are found; as per AIndex value
                AIndex++;
           }

                ... and so on for other patterns
      }
</code>```

So here are my questions. Please note that I am fairly new to C# and I am trying to learn.

Is this the best (i.e. most computationally efficient) approach to take with this problem? If not, can you please suggest an alternative approach?

I do not know how to incorporate the factory pattern for the instantiation of the nested pattern classes. Should this be done? If so, can you suggest how?

Am I missing anything here that I need to consider but have not considered so far?

答:
I have chosen a singleton pattern because:

I want the singleton to hold nested classes; one class for each pattern.

This doesn't require a singleton, or a static class. You could have

```<code>public class Patterns // non-static
{
    public class PatternA : IPattern { }
    public class PatternB : IPattern { }
}
</code>```

and you'd be able to use it as a bag for your pattern definitions, and to instantiate instances of PatternA and PatternB just the same.

I want these nested classes to be instance classes (i.e. not static)

This again has nothing to do with using a singleton (see above).

I would like the singleton to instantiate the nested classes, perhaps using a factory pattern, as needed.

Once again, no singleton necessary. You could have a non-static pattern factory:

```<code>public class PatternsFactory
{
    public IEnumerable<IPattern> CreatePatterns()
    {
        return new List<IPattern>
        {
            new Patterns.PatternA(),
            new Patterns.PatternB()
        };
    }
}
</code>```

Now I plan to add the various pattern classes as nested classes
  because patterns do not make sense outside the master Pattern class.

And why not? That's what namespaces are for. Using an umbrella class as a bag for class definitions looks like reinventing the wheel to me. Namespaces serve this very purpose: grouping related classes together. Why bounce them out of their only job?

If patterns may make no sense outside the Patterns namespace, mark them as internal, that is invisible from outside the namespace. You might want to keep IPattern itself public for testing purposes, though (about this in a while).

Am I missing anything here that I need to consider but have not considered so far?

One of the reasons that the use of statics is frowned upon is testability. How would you write a suite of unit tests for your pattern matching functionality? You can't create a mock pattern, because you cannot inject another pattern into your Pattern class. Heck, you can't even subclass it, since you made it sealed.

You're forcing all patterns to save their matches in a static Data object, which means that testing would require wiping it clean after every test. And again, there is no way to override it, other than rewriting the thing.

More reading on the subject:

Singletons are pathological liars

Static methods are death to testability

Another concern is extensibility. What happens every time you want to add another pattern? You need to edit your Patterns class and put another implementation in there. You need to edit code of SearchForPattern to add all these nice

```<code>if (haveN) PatternN n = new PatternN();
</code>```

That's inflexible and hard to maintain. The open/closed principle states that code should be open for extension, and your approach rules this out.

If not, can you please suggest an alternative approach?

I would ditch singletons, because I see no purpose of using them. I'd create a PatternFactory, capable of returning a set of all supported IPattern objects, and instantiate the factory wherever I would need it (it's stateless anyway).

As for the data - pattern matches - that you want to retain throughout the lifetime of the application (List Data is static because I want the data to be retained throughout the lifetime of the application), well, you can make it static, although that's not the only possible way of tying its lifecycle to the one of the application.

But why be hellbent on placing it in the same class object where all the patterns are defined?? Knowing all supported patterns, and persisting all pattern matches that we detected somewhere are not the same responsibility at all (see Single Responsibility Principle). This design choice smells of the God object antipattern.

Is this the best (i.e. most computationally efficient) approach to take with this problem?

What is computationally expensive here is the pattern matching itself, for non-trivial amounts of data at least. Therefore the cost of creating instances as opposed to using a static class is negligible, so as far as OOP design goes, I wouldn't expect performance to be affected.

Body:
I have chosen a singleton pattern because:

I want the singleton to hold nested classes; one class for each pattern.

This doesn't require a singleton, or a static class. You could have

public class Patterns // non-static
{
    public class PatternA : IPattern { }
    public class PatternB : IPattern { }
}

and you'd be able to use it as a bag for your pattern definitions, and to instantiate instances of PatternA and PatternB just the same.

I want these nested classes to be instance classes (i.e. not static)

This again has nothing to do with using a singleton (see above).

I would like the singleton to instantiate the nested classes, perhaps using a factory pattern, as needed.

Once again, no singleton necessary. You could have a non-static pattern factory:

public class PatternsFactory
{
    public IEnumerable<IPattern> CreatePatterns()
    {
        return new List<IPattern>
        {
            new Patterns.PatternA(),
            new Patterns.PatternB()
        };
    }
}

Now I plan to add the various pattern classes as nested classes
  because patterns do not make sense outside the master Pattern class.

And why not? That's what namespaces are for. Using an umbrella class as a bag for class definitions looks like reinventing the wheel to me. Namespaces serve this very purpose: grouping related classes together. Why bounce them out of their only job?

If patterns may make no sense outside the Patterns namespace, mark them as internal, that is invisible from outside the namespace. You might want to keep IPattern itself public for testing purposes, though (about this in a while).

Am I missing anything here that I need to consider but have not considered so far?

One of the reasons that the use of statics is frowned upon is testability. How would you write a suite of unit tests for your pattern matching functionality? You can't create a mock pattern, because you cannot inject another pattern into your Pattern class. Heck, you can't even subclass it, since you made it sealed.

You're forcing all patterns to save their matches in a static Data object, which means that testing would require wiping it clean after every test. And again, there is no way to override it, other than rewriting the thing.

More reading on the subject:

Singletons are pathological liars

Static methods are death to testability

Another concern is extensibility. What happens every time you want to add another pattern? You need to edit your Patterns class and put another implementation in there. You need to edit code of SearchForPattern to add all these nice

if (haveN) PatternN n = new PatternN();

That's inflexible and hard to maintain. The open/closed principle states that code should be open for extension, and your approach rules this out.

If not, can you please suggest an alternative approach?

I would ditch singletons, because I see no purpose of using them. I'd create a PatternFactory, capable of returning a set of all supported IPattern objects, and instantiate the factory wherever I would need it (it's stateless anyway).

As for the data - pattern matches - that you want to retain throughout the lifetime of the application (List Data is static because I want the data to be retained throughout the lifetime of the application), well, you can make it static, although that's not the only possible way of tying its lifecycle to the one of the application.

But why be hellbent on placing it in the same class object where all the patterns are defined?? Knowing all supported patterns, and persisting all pattern matches that we detected somewhere are not the same responsibility at all (see Single Responsibility Principle). This design choice smells of the God object antipattern.

Is this the best (i.e. most computationally efficient) approach to take with this problem?

What is computationally expensive here is the pattern matching itself, for non-trivial amounts of data at least. Therefore the cost of creating instances as opposed to using a static class is negligible, so as far as OOP design goes, I wouldn't expect performance to be affected.


问:
Begin and Finish or Pre and Post in async call pair?
In an async call pair you would rather have a BeginDoSomething & FinishDoSomething or PreDoingSomething & PostDoingSomething pair?

Cheers

答:
If the method causes the async functionality to begin, then I would call it Begin....

If the method causes the async functionality to end, then I would call it End...

If the method should be run before the async functionality starts, then I might call it Pre...

If the method should be run after the async functionality ends, then I might call it Post...

The begin and end options seem to indicate that they cause things to happen with respect to the async function, like turning the key in the ignition, or turning it off again.

The pre and post options seem to indicate that they are detached from the actual async function they surround, like closing the car door before you put your foot on the accelerator, or putting on the handbrake before exiting the car.


问:
Why was Fortran never used to develop an Operating System?
I'm not a Fortran developer myself, but I'm about to use it a little and found myself wondering why, if it is much older than C but equally as performant as C, was it never used to develop any operating system before C and UNIX came along?

A substitute answer, if the above is invalid, might be which operating systems were developed in Fortran. But still, it didn't seem to catch on at all.

答:
Who says FORTRAN was never used to develop an operating system?

Prime Computer's PRIMOS was written in FORTRAN.  I first encountered it in 1982, but it had been around for a while already.  There was some assembler, but no more than there was in Unix, which is largely described as "written in C".


问:
UML 2.0 Use case diagrams extend
I have a question regrading usecase diagram which im rather confused when to use extended and include. Ive gone through a tone of documents and tutorial and examples. But im rather confused.

I have a scenario where it says "you can make a booking for either fitness classes or personal trainer session".

So the model I have so far has a usecase called "make booking" and usecase "make booking" extends to 2 other uses cases called "Book fitness class" and "Book PT session".

Is that valid with contrast to having two independent usecase called "book classes" and "book PT session".

Im for sure latter method is right. However im not quite sure if my fomer method is right tho. Could anyone help me understand?

Thanks

答:
I think your former method might not work, here's my reasoning:

In extend situation, the base use case should be complete by itself, and doesn't need to depend or know about extend use case. Complete here means it should contains a complete sequence of user interaction that achieve the use case purpose.

So you can ask yourself: does "make booking" base use case work without "book fitness class" and "book PT session" extend use cases? To me, "make booking" by itself doesn't do anything, and it's dependent on the other 2 use cases.

I usually think of extend use case as alternate use case, only triggered when some condition is met in base use case

Hope it helps

Title: UML 2.0 Use case diagrams extend


问:
Naming conventions DAL, BAL, and UI Layer
I am developing a typical Web Application with the following layers

UI Layer (MVC)

Business Logic Layer (BAL)

Data Access Layer (DAL)

Each layer has its own DTO object including the BAL and DAL. My questions regarding this are as follows

The DTO returned by the DAL is simply converted to the corresponding DTO in the BAL and sent to the UI Layer. Both attributes and the structure of the DTO objects are the same in some cases. In such scenarios is it better to simply return the DTO in the DAL to the UI layer without including an intermediate object.

What is the best way to name these DTO objects and other objects in each layer. Should I use some prefix such as DTOName, ServiceName? The reason why I am asking to use a prefix is because if not the classes in my Solution clashes with other classes in the Framework and with a prefix it is easier for me to understand where each class belongs?

答:
I usually build application as

```<code>ProjectName.Core            // "framework"/common stuff
|- Extenders
|- Gravatar.cs

ProjectName.DataProvider    // database provider layer
|- Migrations
|- ApplicationDbContext.cs  // entity framework

ProjectName.Domain          // database objects
|- Post.cs
|- Tag.cs

ProjectName.Services        // validations, database stuff
|- PostService.cs
</code>```

It is somewhat similar to Sharp-Lite.

About prefixes, I hate them. Microsoft's Internal Coding Guidelines hate them as well. Also there is a tool called StyleCop that complains about prefixes as well.

Body:
I usually build application as

ProjectName.Core            // "framework"/common stuff
|- Extenders
|- Gravatar.cs

ProjectName.DataProvider    // database provider layer
|- Migrations
|- ApplicationDbContext.cs  // entity framework

ProjectName.Domain          // database objects
|- Post.cs
|- Tag.cs

ProjectName.Services        // validations, database stuff
|- PostService.cs

It is somewhat similar to Sharp-Lite.

About prefixes, I hate them. Microsoft's Internal Coding Guidelines hate them as well. Also there is a tool called StyleCop that complains about prefixes as well.

ContentLicense: CC BY-SA 4.0


答:
Preface

Hopefully this is obvious, but... in the suggested namespaces below, you would replace MyCompany and MyProject with the actual names of your company and project.

DTOs

I would recommend using the same DTO classes across all layers. Fewer points of maintenance that way. I usually put them under a MyCompany.MyProject.Models namespace, in their own VS project of the same name. And I usually name them simply after the real-world entity that they represent. (Ideally, the database tables use the same names too, but sometimes it makes sense to set up the schema a bit differently there.)

Examples: Person, Address, Product

Dependencies: None (other than standard .NET or helper libraries)

DAL

My personal preference here is to use a one-for-one set of DAL classes matching the DTO classes, but in a MyCompany.MyProject.DataAccess namespace/project. Class names here end with an Engine suffix in order to avoid conflicts. (If you don't like that term, then a DataAccess suffix would work fine too. Just be consistent with whatever you choose.) Each class provides simple CRUD options hitting the database, using the DTO classes for most input parameters and return types (inside a generic List when there are more than one, e.g., the return from a Find() method).

Examples: PersonEngine, AddressEngine, ProductEngine

Dependencies: MyCompany.MyProject.Models

BAL/BLL

Also a one-for-one mapping here, but in a MyCompany.MyProject.Logic namespace/project, and with classes getting a Logic suffix. This should be the only layer that calls the DAL! Classes here are quite often just a simple pass-through to the DAL, but if & when business rules need to be implemented, this is the place for it.

Examples: PersonLogic, AddressLogic, ProductLogic

Dependencies: MyCompany.MyProject.Models, MyCompany.MyProject.DataAccess

API

If there's a web services API layer, I use the same one-for-one approach, but in a MyCompany.MyProject.WebApi namespace/project, with Services as the class suffix. (Unless you're using ASP.NET Web API, in which case you would of course use the Controller suffix instead).

Examples: PersonServices, AddressServices, ProductServices

Dependencies: MyCompany.MyProject.Models, MyCompany.MyProject.Logic (never bypass this by calling the DAL directly!)

An Observation on Business Logic

It seems to be increasingly more common for people to leave out the BAL/BLL, and instead implement business logic in one or more of the other layers, wherever it makes the most sense. If you do this, just be absolutely certain that (1) all application code goes through the layer(s) with the business logic, and (2) it's obvious and/or well-documented where each particular business rule has been implemented. If in doubt, don't try this at home.

A Final Note on Enterprise-Level Architecture

If you're in a large company, or other situation where the same database tables get shared across multiple applications, then I would recommend leaving the MyProject portion out of the above namespaces/projects. That way those layers can be shared by multiple front-end applications (and also behind-the-scenes utilities like Windows Services). But only do this if you have strong cross-team communication and thorough automated regressing testing in place!!! Otherwise, one team's changes to a shared core component are likely to break another team's application.

Title: Naming conventions DAL, BAL, and UI Layer

Body:
I am developing a typical Web Application with the following layers

UI Layer (MVC)

Business Logic Layer (BAL)

Data Access Layer (DAL)

Each layer has its own DTO object including the BAL and DAL. My questions regarding this are as follows

The DTO returned by the DAL is simply converted to the corresponding DTO in the BAL and sent to the UI Layer. Both attributes and the structure of the DTO objects are the same in some cases. In such scenarios is it better to simply return the DTO in the DAL to the UI layer without including an intermediate object.

What is the best way to name these DTO objects and other objects in each layer. Should I use some prefix such as DTOName, ServiceName? The reason why I am asking to use a prefix is because if not the classes in my Solution clashes with other classes in the Framework and with a prefix it is easier for me to understand where each class belongs?


问:
Can one determine the creation date of an email account?
Is it possible to determine the creation date of the mail account for the address supplied within the authentication process flow; Or at least determine that the mail account was/was not created the same day as signup (or specifically after confirmation)?

A use case is to flag such accounts for closer scrutiny as part of a risk management system.

What general considerations do you think come into play in approaching this problem?

I imagine that solutions might be specific to different email providers but if I could determine this information for the major ones it's a good place to be.

Would love specific answers in any language or pseudocode assuming this is solvable within ethical principles.

Disclaimer: I have asked this question on Stack Overflow. Some nice person said that email providers would not allow it for privacy reasons. Completely acceptable, but IMHO I think that the age of an email account has little to do with personal privacy. Also there are too many smart people using the stack* forums for me to just lie down and die.

答:
There is NO reliable way at all to do what you want.

Why not? Because ultimately you would be relying on information provided to you by 3rd parties.
So if a user provides an email adress, you are going to contact the mailhost of said email adress. How can you know that the user is not the server admin of the email server and provides you false information?

You can't.


答:
I understand finance industry uses a system of "after-the-fact" checking and fixups to resolve errors.

ie, you make each transaction on the individual systems independently (such that you know that each system is correct) and you write to a log the details of each transaction. These logs are then compared later, and if an error occurred in one, the other is instructed to rollback its transaction.

So, Bank A successfully withdraws money, but bank B fails to credit it. Later on, the transaction lists from both are compared and Bank A gets a credit to make things right.

You cannot implement a distributed "lock" in such systems as they make not respond in the way you expect - and you do not want to lock someone's account while you make a withdrawal if you cannot tell how long it will be before the other system involved in the transaction will take to complete, you might end up with a lock that remains open blocking other transactions on that account.

Title: How do you solve issue of consistency in concurrent and distributed application (built around Bankers Dilemma)?

Body:
This is a classic problem which I'm sure has been solved many times by many different people. I don't have any formal training (I've not studied computer science or any other such academic subject) and so I'm not sure of the best way to solve the problem I'm about to describe.

If we imagine the below diagram is an example of a bankers dilemma (two users Foo and Bar have access to a single bank account: Baz). What is the expected behaviour when following one of the paths shown?

Note: I'm assuming we're using a mutex (or some other form of synchronisation) on the Baz variable.

Example 1: Baz initially holds the value 10. If Foo writes a new value (which is the result of removing 5 from the current value) before Bar; then Bar will end up taking 10 from the new value 5, leaving a minus balance (i.e. the final value will be -5). Meaning more money has been taken than available.

Example 2: Baz initially holds the value 10. If Bar writes a new value (which is the result of removing 10 from the current value) before Foo; then Foo will end up taking 5 from the new value 0, leaving a minus balance (i.e. the final value will be -5). Meaning more money has been taken than available.

Both actions (Foo (-5) and Bar (-10)) are triggered at the same time. So how do we ensure that either Foo or Bar is alerted to the fact that their transaction cannot be completed (as there are not enough funds for it to succeed)?

It seems a potential solution is to ensure the caller executes a method that uses a mutex internally to lock the value first; then once the value is locked we can read the value; and then check if the action is valid. If the condition passes then we update the value and release the lock on the value. Meaning the next caller will be able to lock the value down and run through the same steps.

But how would this approach work with a distributed system? You could suggest using a global data store, but it would have to be one that guarantees consistency (e.g. a service such as AWS' Dynamo DB offers "eventual consistency" and so wouldn't work for a banking institution); but guaranteed consistency is generally considered to be very slow (depending on the number of distributed nodes I assume).

So how do we attempt to solve this design problem?


问:
Create fake HTTP server to simulate an API for testing
I'm looking to mock responses from an external API service that returns JSON during live events.

The first response would contain (fake) events that have happened up to time X, the second response would contain (fake) events up to time X + N where N is the interval between requests.

I'm not sure how to do this. Up until this point I have only mocked single responses, which was easy by just intercepting the response. However now I need to test against multiple requests.

答:
In unit testing, you'd mock the client part of this system so the calls never get made and the replace client library simply returns the results you expect the real system to return.

If you're doing a wider unit test and need the server, then you'll need to implement a real http server (there are many embedded servers that I'd use here as they're easier to setup and run - they could be part of your build for local testing) and have it return the required responses.


问:
Do objects with validation logic in their domain really represent their real world counterparts?
I asked a question about whether validation behavior should be treated the same as other types of behavior in regard to the concept of OOP being "data + behavior". I got some good answers back that addressed the question from the philosophical point of view and confirmed that the answer to that question seems to be yes.

Now I'd like to address this question from a different angle: Shouldn't objects represent their real world counterparts?

Suppose I give a paper form to someone to fill out. They can pencil in the fields on the form in any order they'd like to and they can even fill in all sorts of incorrect values. When they turn the paper in to me I, representing a broker, may hand it back to them and tell them I can't file it until they fix any invalid entries though.

There's also a comparison to be made between the format of the questions on the paper and a user interface that validates input. Maybe you put checkboxes on the paper and instruct the person to only select one. Of course software can get a lot fancier with this type of validation than a physical sheet of paper, but let's be clear that this type of validation is all in the user interface... validation in the 'domain' simply doesn't exist in the physical realm for this type of object.

Is the paper going to crumple itself up or catch on fire if you write something invalid on it?

So my question is this: if a physical piece of paper has no inherit ability to validate itself, then why would this behavior belong in the domain?

答:
Now I'd like to address this question from a different angle: Shouldn't objects represent their real world counterparts?

Yes. In most businesses there already exists a working system that should be translated to the software. Or to put it another way, decades of business practice has already probably figured out a good way to manage most business processes. And, often more importantly, those in the business already understand these 'real world' processes, so when it comes to checking if your software does what it is supposed to you can explain your software in terms of the real world process that the staff are already familiar with. Doing it differently in the software to how it is done in the real world will lead to confusion and inefficiency.

So my question is this: if a physical piece of paper has no inherit ability to validate itself, then why would this behavior belong in the domain?

Look at what happens in the real world. The validation is handled by a behaviour of the broker, who looks at the piece of paper and accepts or rejects it based on some business rules that she is familiar with.

You have a "person who validates the form" object in the real world in the shape of the role that person is playing at that moment. In some businesses that might be the broker herself, in other larger organisations you would have someone who's only job is to do that.

Either way it is a unique unit of behaviour, and as such should be its own object that encapsulates this behaviour, independent to the form object (the paper)


问:
How should I break this user story into tasks
I am trying to understand how to create user stories and tasks. I have read articles stating that you should create small user stories and they should be a "vertical slice" of functionality instead of a "horizontal slice".

I have a user story:

As a buyer I want to add items to the shopping cart so that I later can buy the items.

From my understanding tasks should be the things you have to do in order to complete this user story. Am I right if the tasks should also be created as "vertical slices" instead of "horizontal". Instead of creating a task for "create shopping cart model" I would have a task "Update shopping cart service to be able to add products".

But with that task I only have one task, is it to big, should it be broken down in another way? Is it bad that a user story only have one task?

答:
Yes, user story says what you want to achieve, the tasks say how you go about making that happen.

In this case, for example. The tasks could be 'add item to cart UI button', 'check stock levels', 'get user account', 'update temporary cart', 'update user account last-bought list' etc.

Its possible some of those shoudl be part of a different user story, but I wouldn't worry too much about crossing every t and dotting every little i, the important thing to focus on with agile is getting it done, not working the bureaucracy.


答:
In my opinion it depends on the weight of the user story. If the user story is about only adding the item to cart, first task should be getting the design for this approach.

After that you have to break up the tasks according to the design (loggedin scenario, if not loggedin, so on).

Title: How should I break this user story into tasks

Body:
I am trying to understand how to create user stories and tasks. I have read articles stating that you should create small user stories and they should be a "vertical slice" of functionality instead of a "horizontal slice".

I have a user story:

As a buyer I want to add items to the shopping cart so that I later can buy the items.

From my understanding tasks should be the things you have to do in order to complete this user story. Am I right if the tasks should also be created as "vertical slices" instead of "horizontal". Instead of creating a task for "create shopping cart model" I would have a task "Update shopping cart service to be able to add products".

But with that task I only have one task, is it to big, should it be broken down in another way? Is it bad that a user story only have one task?


问:
What metadata do files contain?
I know when a file is created date information such as date created, last modified, last opened, is automatically updated as meta data on that file. Is there other meta data though? Specifically, is there a way to tell what computer-name/user/whatever created a given file?

What is the extent meta data can be modified?

答:
Normally a file should not contain metadata. As the prefix meta
indicates, metadata is beyond data. It belongs to a different realm
where you are concerned with characteristics of the file to know what
it is useful for, and that (usually) cannot be inferred with certainty
or easily enough from the content. Putting that information in the
file would interfere with the actual use of the file, as applications
would have to know about it. Furthermore, you may want to allow
different access regimes (use, modification) for the data and the
metadata.

Such considerations show that metadata concerning the file is to be
stored outside the file, though be associated with the file. Hence
metadata is often managed in a different memory location, though associated
with the file at OS level, either by the OS itself or by some
applications.

From an implementation point of view, metadata could be stored in the
file, if it is managed by the OS so that application receive a
stripped file (without metadata) when they are not supposed to be
metadata aware. This is also important when moving files to another
OS.

This said, metadata can be any information about the data, that helps
to better understand its relevance and usability for some purposes. It
can be very general, such as date or location of creation, ownership,
history, mutability, encoding standard, or very specific of some
applications such as artistic school or style, library classification,
keywords, etc.

In practice the kind of metadata available depends much on the
operating system, or on the file system (especially on removable
media). Some, such as access rights and date, may be found in the
directory structure. Some can be inferred from the file name suffix,
though this does not formally enforce its correctness. Some can be
managed by the storage location, for example some directories may
correspond to a specific role of files found in them. That is very
variable. There are also special tools to retrieve metadata, when it
is lost such as the file command in Unix.

Some files corresponding to a specific encoding scheme, such as JPEG,
may contain in the file metadata that is meaningful for that encoding
scheme. That is not a problem, since the existence of this metadata
will be known to all applications accessing meaningfully the content
of the file.

As you see, metadata can be any information about the file,
whether technical or semantical. An it can be stored and associated
with the file in a wide variety of ways. Also. what is metadata for
one application may also be simply part of the file for other less
knowledgeable applications.

What can be done with or to metadata is also very variable.

The origin of the file, such as computer-name or user-name is not
standard on operating systems. But it does have owner, dates and access rights information, which may vary depending on operating systems and file systems.

The whole point of this is: to get a precise answer to your question,
you have to make it much more specific, and make more precise whether
you mean OS level, application level (which), encoding standard level,
etc.

Title: What metadata do files contain?


问:
When should something be a class? And are my chosen classes good OO design?
My background:

I am new to programming. Python is my only programming knowledge. I program as a hobby, and I'm teaching myself by reading copious amounts of books.

I understand enough about OOP to write OO software. However, I keep feeling uneasy about the things I write... The design seems messy, etc. And I'm unsure as to what should be a class, method, or function.

I have read OOP books such as, 'Object Oriented Thought'. Such books are useful, however, they always deal with easy topics such as making a 'blackjack' game. The applications that I want to write, however, are not based on easy-to-imagine, real world objects.

The application:

I am currently working on a project. The aim of the software is to download images and video from my favourite blogs. (eg, Google Blogger blogs, or WordPress hosted blogs.)

(Yes, it is easy to make, and I've already made it, but the problem is I want to learn  how to make elegant and properly designed OO software.)

Classes:

I have decided on the following classes:

API Client: This will make it easier to deal with sending and receiving various API requests.

BloggerClient, WordPressClient: I will inherit from a generic API Client class, so that I can specialize with specific APIs, eg. Google's, Tumblr's, and Wordpress' APIs.

Parser: A generic media parser. This will get the media from the blogs.

BloggerParser, WordPressParser: I will inherit from the generic Parser, so I can grab posts and media specific to each website.

Use Case:

I will present an example of getting images from a WordPress.com blog.

WordPressParser asks WordPressClient to get blog-posts from photography.wordpress.com

WordPressClient sends an API request to WordPress.

WordPress Client receives a response and sends the posts to WordPressParser.

WordPressParser parses the media links/urls from each blog-post.

The media links are downloaded to disk.

The problems:

I actually don't know if I have made good choices here.

For example, I need the media (photo and video) downloaded to disk. In this case should I make 'download_media()' methods in the Parser class, or is it better design to create a Downloader class?

'Parse' could easily be a method, instead I have used 'Parser', so it could easily be a class. I really don't know when something should be a class or a method.

Should there be a class for BlogPosts? It seems to me that blog-posts are objects (the equivalent to pages of a book, perhaps).

I seem to be taking verbs, 'download', 'parse', and then converting them to nouns in order to make them appear as valid classes.

I feel very lost and confused. Again, the purpose for me is to learn how to properly make and design OO software. I'm not looking just to get the program to work.

Here is the sourcecode for each of my classes so far:

API Client: http://pastebin.com/QRdPqM5F

Base Parser: http://pastebin.com/kV8gBEe6

Parser: http://pastebin.com/cC0yPYdK

In terms of extensibility, I will be adding more websites in the future, so I need something maintainable.

I hope someone could advise me as to what I'm doing wrong. You can view my source code in the links above to really see what I'm talking about.

Thank you!

答:
I seem to be taking verbs, 'download', 'parse', and then converting them to nouns in order to make them appear as valid classes.

I feel very lost and confused. Again, the purpose for me is to learn how to properly make and design OO software. I'm not looking just to get the program to work.

The biggest challenge when starting out with object orientated design is the mental shift required to think about a problem in terms of different objects interacting to achieve a goal, rather than thinking of the procedural steps required to make the computer do something.

One thing that can help is an exercise in anthropomorphiation

Either grab a few of your friends/co-workers or grab a few toy figures or army men, go into a room and set about organizing the people to solve the problem when each person can do one thing and/or tell another object to do one thing.

You might start off with only a few people doing a lot of the work. Keep splitting up persons so that each person does just one thing while instructing other people to do other tasks for them.

Telling someone to do something is passing them a message, and message passing between objects is the core of OOD. You can also pass objects themselves to other objects, so imagine a person passing over a person to a third person if that third person needs this.

Try to design your system using this method. If a single person is doing too much, break them up into two more people. You will end up with a room over people saying out loud "I do this, then I tell Bob to do this"

You will notice that there is no code in this exercise. That is on purpose. The design of the system is far more important than the computer language used to implement it. Learning how to think in terms of objects as units of behaviour which achieve a goal through message passing among themselves is far more important than learning an OO programming language.

This excercise can help for both real world problems and also very abstract problems like the one you detail above because ultimately the details of how each person does what they do (opening a drawer to get a form or downloading the form form a HTTP web server) are not as relevant as what they say they can do.


问:
What's the advantage of auto-property initializers without primary constructors?
In this chart about the features that are in or out of the next version of Roslyn (specifically, for C#), primary constructors are out, but auto-property initializers are in.

The best use case I've seen for the auto-property initializers is using them in conjunction with the primary constructors, i.e.:

```<code>public class Customer(string first, string last)
{
    public string First { get; } = first;
    public string Last { get; } = last;
}
</code>```

However, without the primary constructor, I don't see a good use case for using auto-property initialization that can't just be performed with a normal backing field, like so:

```<code>public class Customer
{
    private string _first = "Foo";
    public string First { get { return _first; } };
}
</code>```

What is the point of using an auto-property initializer without the primary constructor functionality?

答:
You don't technically need initializers at all. You can always have a backing property, and you can always do your initialization in (all of) your constructors.

They are a convenience to reduce the ceremony that programmers need to go through to do the "right thing" (use properties for public members, have sane, consistent defaults, make code readable). Because if doing the right thing is easier, people are more likely to actually do it.


答:
What is the point of using an auto-property initializer without the primary constructor functionality?

Brevity mostly - if you don't require initialization (beyond the default .NET initialization of fields), auto properties are a good succinct syntax:

```<code>public string { get; set; }
</code>```

Now, in your examples you just have a getter, so without a backing field that can be initialized, yes, these are fairly useless.

You could argue that you could simply expose the field directly, instead of using the property, but then, if you do want to change the field or its access semantics, that's a breaking change.

Title: What's the advantage of auto-property initializers without primary constructors?

Body:
In this chart about the features that are in or out of the next version of Roslyn (specifically, for C#), primary constructors are out, but auto-property initializers are in.

The best use case I've seen for the auto-property initializers is using them in conjunction with the primary constructors, i.e.:

```<code>public class Customer(string first, string last)
{
    public string First { get; } = first;
    public string Last { get; } = last;
}
</code>```

However, without the primary constructor, I don't see a good use case for using auto-property initialization that can't just be performed with a normal backing field, like so:

```<code>public class Customer
{
    private string _first = "Foo";
    public string First { get { return _first; } };
}
</code>```

What is the point of using an auto-property initializer without the primary constructor functionality?

Body:
What is the point of using an auto-property initializer without the primary constructor functionality?

Brevity mostly - if you don't require initialization (beyond the default .NET initialization of fields), auto properties are a good succinct syntax:

public string { get; set; }

Now, in your examples you just have a getter, so without a backing field that can be initialized, yes, these are fairly useless.

You could argue that you could simply expose the field directly, instead of using the property, but then, if you do want to change the field or its access semantics, that's a breaking change.


问:
Are there any language agnostic unit testing frameworks?
I have always been skeptical of rewriting working code - porting code is no exception to this.  However, with the advent of TDD and automated testing it is much more reasonable to rewrite and refactor code.

Does anyone know if there is a TDD tool that can be used for porting old code? Ideally you could do the following:

Write up language agnostic unit tests for the old code that pass (or fail if you find bugs!).

Run unit tests on your other code base that fail.

Write code in your new language that passes the tests without looking at the old code.

The alternative would be to split step 1 into "Write up unit tests in language 1" and "Port unit tests to language 2", which significantly increases effort required and is difficult to justify if the old code base is going to stop being maintained after the port (that is, you don't get the benefit of continuous integration on this code base).

EDIT: It's worth noting this question on StackOverflow.

答:
Language agnostic test framework are generic test framework suited for acceptance test (point  of view) and testcases in that framework is managed by QA
e.g Robotframework</p>


问:
Is this what "Cloud-Scaling" is?
When talking about things like "building your systems/applications around the cloud" or "using cloud technology for scalability", is "cloud-scaling" (from a provider eg. Amazon) this:

When placing your (eg.) web application into an AWS data-centre located within your office-region, the folks working at AWS have some type of monitoring technology that monitors resource-usage of your application and automatically scales up (or down) the resources when they reach a bottleneck (for example, RAM is hitting 92%, so their monitoring tech automatically provisions an extra 2GB and dynamically adds it to your current instance to prevent application-failure)

Using the example above, but this time, "cloud-scaling" is referring to the ability of your own (or some sys-admin provider) to manually (and much more easily) scale up/down your resources as needed (without any auto-adjusting monitoring technology doing that job)

Which one of the 2 options is it?

答:
Neither.

As long as your system runs on a single machine, you're not doing cloud scaling. In the context of cloud computing, scalability means horizontal scaling.

Thus, "cloud scalability" means that you can add more machines to your system to increase its capacity, and doing this should be relatively easy. Ideally, it would even happen automatically, but personally I wouldn't say that's strictly necessary.

Title: Is this what "Cloud-Scaling" is?


问:
Clean Code and Hybrid Objects and Feature Envy
So I recently made some major refactorings to my code. One of the main things I tried to do was split out my classes into data objects and worker objects. This was inspired, among other things, by this section of Clean Code:

Hybrids

This confusion sometimes leads to unfortunate hybrid data structures that are half object and half data structure. They have functions that do significant things, and they also have either public variables or public accessors and mutators that, for all intents and purposes, make the private variables public, tempting other external functions to use those variables the way a procedural program would use a data structure.

Such hybrids make it hard to add new functions but also make it hard to add new data structures. They are the worst of both worlds. Avoid creating them. They are indicative of a muddled design whose authors are unsure of - or worse, ignorant of - whether they need protection from functions or types.

Recently I was looking at the code to one of my worker objects (that happens to implement the Visitor Pattern) and saw this:

```<code>@Override
public void visit(MarketTrade trade) {
    this.data.handleTrade(trade);
    updateRun(trade);
}

private void updateRun(MarketTrade newTrade) {
    if(this.data.getLastAggressor() != newTrade.getAggressor()) {
        this.data.setRunLength(0);
        this.data.setLastAggressor(newTrade.getAggressor());
    }
    this.data.setRunLength(this.data.getRunLength() + newTrade.getLots());
}
</code>```

I immediately said to myself "feature envy! this logic should be in the Data class - specifically in the handleTrade method. handleTrade and updateRun should always happen together". But then I thought "the data class is just a public data structure, if I start doing that, then it will be come a Hybrid Object!"

What's better and why? How do you decide which to do?

答:
From my point of view a class should contain
"values for state (member variables) and implementations of behavior (member functions, methods)".

The "unfortunate hybrid data structures" emerges if you make class state member-variables (or their getters/setters) public that should not be public.

So I see not need to have seperate classes for data data objects and worker objects.

You should be able to keep state-member-variables non-public (your database-layer should be able to handle non-public member-variables)

A Feature envy is  a class that uses methods of another class excessively. See Code_smell. Having a class with methods and state would eliminate this.


答:
The fact that handleTrade() and updateRun() always happen together (and the second method is actually on the visitor and calls several other methods on the data object) smells of temporal coupling. This means that you must call methods in a specific order, and I would guess that calling methods out of order will break something at worst, or fail to provide a meaningful result at best. Not good.

Typically the correct way to refactor that dependency out is for each method to return a result which can either be fed into the next method or acted upon directly.

Old code:

```<code>MyObject x = ...;
x.actionOne();
x.actionTwo();
String result = x.actionThree();
</code>```

New code:

```<code>MyObject x = ...;
OneResult r1 = x.actionOne();
TwoResult r2 = r1.actionTwo();
String result = r2.actionThree();
</code>```

This has several advantages:

It moves separate concerns into separate objects (SRP).

It removes temporal coupling: it is impossible to call methods out of order, and the method signatures provide implicit documentation about how to call them. Have you ever looked at documentation, seen the object you want, and worked backwards? I want object Z. But I need a Y to get a Z. To get a Y, I need an X. Aha! I have a W, which is required to get an X. Chain it all together, and your W can now be used to get a Z.

Splitting objects like this is more likely to make them immutable, which has numerous advantages beyond the scope of this question. The quick takeaway is that immutable objects tend to lead to code that is more safe.

Title: Clean Code and Hybrid Objects and Feature Envy

Body:
So I recently made some major refactorings to my code. One of the main things I tried to do was split out my classes into data objects and worker objects. This was inspired, among other things, by this section of Clean Code:

Hybrids

This confusion sometimes leads to unfortunate hybrid data structures that are half object and half data structure. They have functions that do significant things, and they also have either public variables or public accessors and mutators that, for all intents and purposes, make the private variables public, tempting other external functions to use those variables the way a procedural program would use a data structure.

Such hybrids make it hard to add new functions but also make it hard to add new data structures. They are the worst of both worlds. Avoid creating them. They are indicative of a muddled design whose authors are unsure of - or worse, ignorant of - whether they need protection from functions or types.

Recently I was looking at the code to one of my worker objects (that happens to implement the Visitor Pattern) and saw this:

```<code>@Override
public void visit(MarketTrade trade) {
    this.data.handleTrade(trade);
    updateRun(trade);
}

private void updateRun(MarketTrade newTrade) {
    if(this.data.getLastAggressor() != newTrade.getAggressor()) {
        this.data.setRunLength(0);
        this.data.setLastAggressor(newTrade.getAggressor());
    }
    this.data.setRunLength(this.data.getRunLength() + newTrade.getLots());
}
</code>```

I immediately said to myself "feature envy! this logic should be in the Data class - specifically in the handleTrade method. handleTrade and updateRun should always happen together". But then I thought "the data class is just a public data structure, if I start doing that, then it will be come a Hybrid Object!"

What's better and why? How do you decide which to do?

Body:
The fact that handleTrade() and updateRun() always happen together (and the second method is actually on the visitor and calls several other methods on the data object) smells of temporal coupling. This means that you must call methods in a specific order, and I would guess that calling methods out of order will break something at worst, or fail to provide a meaningful result at best. Not good.

Typically the correct way to refactor that dependency out is for each method to return a result which can either be fed into the next method or acted upon directly.

Old code:

MyObject x = ...;
x.actionOne();
x.actionTwo();
String result = x.actionThree();

New code:

MyObject x = ...;
OneResult r1 = x.actionOne();
TwoResult r2 = r1.actionTwo();
String result = r2.actionThree();

This has several advantages:

It moves separate concerns into separate objects (SRP).

It removes temporal coupling: it is impossible to call methods out of order, and the method signatures provide implicit documentation about how to call them. Have you ever looked at documentation, seen the object you want, and worked backwards? I want object Z. But I need a Y to get a Z. To get a Y, I need an X. Aha! I have a W, which is required to get an X. Chain it all together, and your W can now be used to get a Z.

Splitting objects like this is more likely to make them immutable, which has numerous advantages beyond the scope of this question. The quick takeaway is that immutable objects tend to lead to code that is more safe.


问:
Finding common subsets in a list of sets
Let say I have a list of sets, defined like this (3 sets in this example) :

```<code>A = [1, 2, 3, 4, 5]
B = [4, 5, 6, 7, 8]
C = [1, 2, 3, 4, 5, 6, 7, 8]
</code>```

Total number of elements defined in sets : 18

I'd like to find which subsets are common in sets, in order to simplify the sets definition.

In this example, [4, 5] is common to all sets. I can easily find this by applying an intersection between all sets.
Then I can rewrite sets definition like this :

```<code>A, B, C = [4, 5]
A = [1, 2, 3]
B = [6, 7, 8]
C = [1, 2, 3, 6, 7, 8]
</code>```

Total number of elements : 14

However, this can be improved further more :

```<code>A, C = [1, 2, 3]
B, C = [6, 7, 8]
A, B, C = [4, 5]
</code>```

Total number of elements : 8

My question is : is there any algorithm (pseudocode) in order to simplify sets definition like in this example ?

答: I answered a similar question at https://stackoverflow.com/questions/26028124/the-intersection-of-all-combinations-of-n-sets/26028865#26028865 and the only difference in what you need is that the second map should map an element to the set of sets it is in, rather than every subset of that set.</p>


答:
The following may sound a bit artificial, but you should get the point (think of it as a Web-App):

The scenario you give is:

Selecting a gym-class

In order to achieve that, you need to display the different classes. Or to put it into UML-Speak: selecting a gym-course includes displaying the different classes.

You use include as something like an import of another use-case: to do x it is necessary to do y, which is in itself an independend usecase (e.g. displaying could also be used only for information without the possibility to select anything).

If you want to book some extras like sauna after training, this is also some kind of import, but this time it is fully optional, which is in UML the extend relationship. In case of a web form, think of a simple checkbox: sauna ✓ after the checkbox for the class.

booking a gym-class includes displaying the classes and booking sauna extends booking a gym-class. Booking sauna is in itself an independend use-case and could be done without booking a gym-class. Furthermore - and that is where the difference lies - it is not necessary to book sauna in order to book a gymclass, its facultative.

Or in ordinary language:

In order to book a gymclass, you have to display the overview. Additionally you could also book sauna together with the class.

Title: UML 2.0 Use case diagrams extend

Body:
I have a question regrading usecase diagram which im rather confused when to use extended and include. Ive gone through a tone of documents and tutorial and examples. But im rather confused.

I have a scenario where it says "you can make a booking for either fitness classes or personal trainer session".

So the model I have so far has a usecase called "make booking" and usecase "make booking" extends to 2 other uses cases called "Book fitness class" and "Book PT session".

Is that valid with contrast to having two independent usecase called "book classes" and "book PT session".

Im for sure latter method is right. However im not quite sure if my fomer method is right tho. Could anyone help me understand?

Thanks


答:
The text you quoted has good advice, although I will replace “data structures” by “records”, assuming that something like structs is meant. Records are just dumb aggregations of data. While they might be mutable (and thus stateful in a functional-programming mindset), they don't have any internal state, no invariants that have to be protected. It is completely valid to add operations to a record that make its usage easier.

For example, we can argue that a 3D vector is a dumb record. However, that should not prevent us from adding a method like add, which makes adding vectors easier. Adding behaviour does not turn a (not so dumb) record into a hybrid.

This line is crossed when the public interface of an object allows us to break encapsulation: There are some internals which we can access directly, thus bringing the object into an invalid state. It seems to me that Data does have state, and that it can be brought into an invalid state:

After handling a trade, the last aggressor might not be updated.

The last aggressor can be updated even when no new trade occurred.

The run length might retain its old value even when the aggressor was updated.

etc.

If any state is valid for your data, then everything is fine with your code, and you can carry on. Otherwise: The Data class is responsible for its own data consistency. If handling a trade always involves updating the aggressor, this behaviour has to be part of the Data class. If changing the aggressor involves setting the run length to zero, this behaviour has to be part of the Data class. Data was never a dumb record. You already made it a hybrid by adding public setters.

There is one scenario in which you can consider relaxing these strict responsibilities: If Data is private to your project and is therefore not part of any public interface, you can still ensure proper usage of the class. However, this places the responsibility for maintaining Data consistency throughout the code, rather than collecting them at a central location.

I recently wrote an answer on encapsulation, which goes into more depth on what encapsulation is and how you can ensure it.


问:
Is there any hard data on the (dis-)advantages of working from home?
Is there any hard data (studies, comparisons, not-just-gut-feel analysis) on the advantages and disadvantages of working from home?

My devs asked about e.g. working from home one day per week, the boss doesn't like it for various reasons, some of which I agree with but I think they don't necessarily apply in this case.

We have real offices (2..3 people each), distractions are still common. IMO it would be beneficial for focus, and with 1 day / week, there wouldn't be much loss at interaction and communication. In addition it would be a great perk, and saving the commute.

Related: Pros and cons of working remotely / from home  (interesting points, but no hard facts)

To clarify: it's not my decision to make, I agree that there are pro's and con's depending on circumstances, and we are pushing for "just try it". I've asked this specific question because (a) facts are a good addition to thoughts in arguing with an engineer boss, and (b) we, as developers, should build upon facts like every respectable trade.

答:
There may be some scientific studies...and there may not. They may or may not be indicative of your results. Some people are more efficient when they telecommute, some are not.

The only way to know is to try it, for a month, and see if stuff still gets done. See how the people like it. Start with one day a week. If that's good, go to two days a week. And so on. Find ways to avoid in-person meetings unless absolutely necessary. Eventually, if all goes well, you'll get to telecommuting five days a week, and you can get rid of the office expense.

Anecdote: when the price of gas shot through the roof after Hurricane Katrina, many firms in California instituted telecommuting as a 'temporary' measure - and found that productivity increased, moral increased, etc. (how could you not be happier and more productive if you no longer had a two-hour California commute?) so they kept doing it after gas prices went back to normal.


问:
Server side or client side mvc: which approach imposes less load on the server?
Which is the best approach when developing a dynamic web app with multiple views and dynamic content. regarding server load and responce times:

use a server side mvc (such as Sailsjs or ASP.NET MVC) to render and then display views or

use an api to get data from the server and a client side MVC (such as angular) to render the views

Which approach imposes less load on the server?

答:
Disclaimer: There are so many other factors in play that your decision on which approach to use should probably not be made solely on this evaluation. Consider team skill sets, long-term maintainability, features needed versus features provided by various frameworks, which client platforms/devices you need to support, and so on. However, from a purely academic standpoint...

Server-side MVC: Server handles data access + building HTML

Client-side MVC: Server handles data access + serializing DTOs

So at first glance, it seems to be a simple matter of which is more resource-intensive, building HTML or serializing DTOs? If  building HTML is less taxing than serializing DTOs, then go with server-side MVC. If not, then go with client-side MVC.

But one other factor to keep in mind is the raw number of HTTP requests hitting your server. With server-side MVC, this is likely to be relatively low (typically 1 request per "page"). But with client-side MVC, depending on how you set up your web services API, you could have any number of HTTP requests hitting your server for each "page" in the app. An extremely chatty approach could cause far more server resource utilization from HTTP request processing overhead than from the actual work of either building HTML or serializing DTOs.


问:
Orthogonality of unit tests vs. concision of unit tests
I'm writing unit tests for a steering system for a video game. The system has several behaviours (avoid this area because of reason A, avoid this area because of reason B, each adding a bit of context to a map of the region. A separate function then parses the map and produces a desired movement.

I'm having trouble deciding how to write the unit tests for the behaviours. As TDD suggests, I'm interested only in how the behaviours affect the desired movement. For instance, avoid-because-of-reason-A should result in a movement away from the suggest bad position. I don't care actually how or why the behaviour adds context to the map, only that the desired movement is away from the position.

So my tests for each behaviour set up the behaviour, make it write to the map, then executes the map-parsing function to work out the desired movement. If that movement satisfies my specifications then I'm happy.

However now my tests depend on both the behaviours working correctly, and the map parsing function working correctly. If the parsing function fails, then I would get hundreds of failed tests rather than a couple. Many test-writing guides suggest this is a bad idea.

However if I test directly against the output of the behaviours by mocking out the map, then surely I'm coupling too tightly to the implementation? If I can get the same desired movement from the map by using a slightly different behaviour, then the tests should still pass.

So now I'm suffering cognitive dissonance. What's the best way to structure these tests?

答:
This kind of testing is why mocks were invented. The main idea: You write a mock for your object (map, behavior, character, ...), then write tests using that mock instead of the actual object. People sometimes call mocks stubs, and I believe there are other words for both.

In your case, you would write a mock for the map whenever you need to test the behaviors, and other mocks for behaviors whenever you want to test the map. Your mocks would ideally be much simpler than the actual behaviors you are mocking, only incorporating methods or variables you actually need for that test. You may have to write a different mock for each and every test, or you may be able to reuse some mocks. Regardless, they should be suited for the test, and shouldn't try to be as much like the actual behavior as possible.

If you included some examples of maps or behaviors, perhaps someone could provide examples of the mocks you could write. Not me, as I have never programmed a more advanced video game than Pong, and even then I was following a book, but perhaps someone well-versed in both unit testing and game development.


问:
Is it appropriate to ask for reasons after rejected after the interview?
I thought I did okay in the interviews but apparently the interviewers didn't think so. Is it appropriate to ask for a reason after I have received the rejection email? After all I don't want to annoy the HR person.

I am a student, so not so much job hunting experience so far. Bear with me if this question sounds stupid.

答:
I just want to add that if you don't get detailed feedback, please don't take it personally, and neither should you push harder to try to get it. I'm not a recruiter or an HR person; I'm a business owner who sometimes needs to hire someone to join our firm. Here's what that process looks like for me: first, there's all kinds of calculating and number crunching to establish whether or not we really can afford to do this, including trying to guess what the market is paying at the moment, writing the job description, spreading the word, etc. Then, there's a huge wave of resumes, many from people who can't even spell the technologies they claim to know. I have too much work anyway - that's why I'm hiring - but I have to find the time to extract a short list from the pile. Then I (or if I'm lucky, someone I delegate to) must get in touch with the short list and schedule the interviews, deal with having someone on my short list already hired elsewhere, etc. Then the actual interviews, which can be kind of a blur sometimes but I take a lot of notes. Then selecting a first choice, making an offer, which might get accepted but might not. Possibly making an offer to the second choice. Finally writing to the rest saying we hired someone else. Then busy training the new person and trying to catch up on whatever backlog accumulated while I had to hire.

And then candidate #3, or #7, emails and wants feedback on what was not great and what could be better and how to improve? Look, I'm a really helpful person, you can see that, I spend time here, I blog, I speak at conferences, you know? But there's a time and a place. And right after finishing an exhausting round of hiring is almost never the time. I sometimes tell people "you outperformed several other candidates, but were not the highest ranked." The chances of getting more details than that are slim. It's different in a big company where they might want to keep you on file for another position. It's certainly very very different for a recruiter who wants to place you and wants to improve your interview performance. But for me (and plenty of other interviewers), it's a favour you're asking, at a time when we may not be able to grant it.

That said, I wouldn't hold it against you to ask. I just might not answer usefully.


问:
Haskell's ':' operator
I am currently studying about pattern matching in Haskell from here. The author gives an example of the implementation of "head" function (which returns the first element of a list) as following:

```<code>head' (x:_) = x
</code>```

He kind of explains the use of the operator but it's not clear to me. I understand that we can use it to append elements at front of a list:

```<code>5:[6,7] will give [5,6,7]
</code>```

I can't see though how we can use the ':' operator as a part of the argument (x:_) or (x:xs) in general.

How does that binding mechanism that binds the first element to x work?

答:
It's a little confusing, because : does two different things depending on the context.  In a regular context, : does as you describe.  It prepends the element on the left with the list on the right.

In a pattern matching context, it does the exact opposite.  It's a completely different operation, even though it uses the same syntax.  Behind the scenes, the compiler generates completely different code.  In this context, it takes the first element of the list and assigns it to the variable before the :, and it takes the remainder of the list and assigns it to the variable after the :.  If a constant was there instead of a variable, it checks to make sure the argument matches that constant, instead of doing an assignment.

If the : appears on the left side of an = or ->, you use the pattern matching definition.  Otherwise, you use the prepending definition.  The syntax is the same so that constructing a list looks the same as deconstructing one.

That's a lot of overloading happening on that one operator, but when you get used to it, it makes for some very concise code.

Title: Haskell's ':' operator


问:
Algorithms: How do I sum O(n) and O(nlog(n)) together?
I have the follow algorithm which finds duplicates and removes them:

```<code>public static int numDuplicatesB(int[] arr) {
    Sort.mergesort(arr);
    int numDups = 0;
    for (int i = 1; i < arr.length; i++) {
        if (arr[i] == arr[i - 1]) {
            numDups++;
} }
    return numDups;
}
</code>```

I am trying to find the worst case time complexity of this. I know mergesort is nlog(n), and in my for loop I am iterating over the entire data set so that would count as n.
I am unsure what to do with these numbers though. Should I just sum them together? If I were to do that, how would I do it?

答:
The big O notation is defined as a set:

So  contains all functions that are - starting from some arbitrary large point  - always smaller than g.

Now, when you have a function that is in  and then execute another one that increases slower than g it is certainly increasing slower than 2g. So executing anything slower than g will not change the complexity class.

More formally:

You can easily prove that.

TL;DR

It is still


问:
Is there any reason to override Equals for an Entity?
An entity has identity, which implies there should only be one object (e.g. a particular customer) in memory.

As such, reference equality (which is what the base version of object.equals checks for) should be the only equality we care about.

A value object on the other hand would need to overrride Equals as there may be many in memory.

Are there any issues with the above reasoning?

I just can't imagine why I would have two customer objects representing the same customer, and in any case where I did (e.g. took a clone to do something with it), I can't think of any circumstances where I would need to check if it was equal to the orginal object.

Even in a distributed environment, any client process should only contain one object for a certain customer.

答:
I just can't imagine why I would have two customer objects
  representing the same customer

Not all objects represent "customers". Other objects represent other kind of entities. In those cases a value equality could be more or less useful according to bussines rules, allowing to be able to check whether or not a given object passed as a parameter is already (business-based) in a given collection.

Even in a distributed environment, any client process should only contain one object for a certain customer.

Distributed systems are not centralized. They are the opposite of centralized. They interoperate sending objects back and forth. A value equality helps in such interoperability since, being distributed, memory location addresses wouldn't match. Also how would you prevent independent, distributed processes from instantiating objects that are the same according to a business rule ?

Again, not all objects are customers and your question is about "entities". Maybe you should rename your question to "Is there any reason to override equeals for a customer class?"

Another issue.

According to your reasoning two separate customer objects, with identical state ( values ) would be different customers since they will have different memory addresses (variable references).


问:
Should I bother to develop for JavaScript disabled?
Should I bother to develop for JavaScript disabled?

I feel that my time is better spent developing for the majority.

答:
For one, I disagree with the people out there who insist that everything should function without Javascript. It is nice to code to the lowest common denominator in a lot of cases (for example, I would be really pissed if my bank's site required Flash or some such nonsense.) But realistically almost everyone has Javascript enabled these days and if used properly the resulting sites can be quite spectacular and useful! (I mean, let's see how nice Google Maps is when Javascript is turned off...)

However, this should not absolve you from at the very least ensuring that your page fails gracefully if Javascript is not present. Never EVER leave your users staring at a half loaded, broken page with no indication as to what went wrong. Just ask yourself: Would I rather spend 2 minutes coding up a "This page requires Javascript" message or receive 10 emails daily from users telling me that my page is broken because they have noscript enabled?


问:
Illegal in PHP: Is there an OOP design reason?
The below interface inheritance is illegal in PHP, but I think it would be fairly useful in real life. Is there an actual antipattern or documented problem with the below design, that PHP is protecting me from?</p>

```<code><?php

/**
 * Marker interface
 */
interface IConfig {}

/**
 * An api sdk tool
 */
interface IApi
{
    public __construct(IConfig $cfg);
}

/**
 * Api configuration specific to http
 */
interface IHttpConfig extends IConfig
{
    public getSomeNiceHttpSpecificFeature();
}

/**
 * Illegal, but would be really nice to have.
 * Is this not allowed by design?
 */
interface IHttpApi extends IApi
{
    /**
     * This constructor must have -exactly- the same
     * signature as IApi, even though its first argument
     * is a subtype of the parent interface's required
     * constructor parameter.
     */
    public __construct(IHttpConfig $cfg);

}
</code>```

答:
Yes, this follows directly from the Liskov Substitution Principle (LSP). When you override a method, the return type can become more specific, while types of arguments must stay the same or can become more general.

This is more obvious with methods other than __construct. Consider:

```<code>class Vehicle {}
class Car extends Vehicle {}
class Motorcycle extends Vehicle {}

class Driver {
    public drive(Vehicle $v) { ... }
}
class CarDriver extends Driver {
    public drive(Car $c) { ... }
}
</code>```

A CarDriver is a Driver, so a CarDriver instance must be able to do anything that a Driver can. Including driving Motorcycles, because it's just a Vehicle. But the argument type for drive says that a CarDriver can only drive Cars – a contradiction: CarDriver can't be a proper subclass of Driver.

The reverse makes more sense:

```<code>class CarDriver {
    public drive(Car $c) { ... }
}
class MultiTalentedDriver extends CarDriver {
    public drive(Vehicle $v) { ... }
}
</code>```

A CarDriver can only drive Cars. A MultiTalentedDriver can also drive Cars, because a Car is just a Vehicle. Therefore, MultiTalentedDriver is a proper subclass of CarDriver.

In your example, any IApi can be constructed with an IConfig. If IHttpApi is a subtype of IApi, we must be able to construct an IHttpApi using any IConfig instance – but it only accepts IHttpConfig. This is a contradiction.

Body:
Yes, this follows directly from the Liskov Substitution Principle (LSP). When you override a method, the return type can become more specific, while types of arguments must stay the same or can become more general.

This is more obvious with methods other than __construct. Consider:

class Vehicle {}
class Car extends Vehicle {}
class Motorcycle extends Vehicle {}

class Driver {
    public drive(Vehicle $v) { ... }
}
class CarDriver extends Driver {
    public drive(Car $c) { ... }
}

A CarDriver is a Driver, so a CarDriver instance must be able to do anything that a Driver can. Including driving Motorcycles, because it's just a Vehicle. But the argument type for drive says that a CarDriver can only drive Cars – a contradiction: CarDriver can't be a proper subclass of Driver.

The reverse makes more sense:

class CarDriver {
    public drive(Car $c) { ... }
}
class MultiTalentedDriver extends CarDriver {
    public drive(Vehicle $v) { ... }
}

A CarDriver can only drive Cars. A MultiTalentedDriver can also drive Cars, because a Car is just a Vehicle. Therefore, MultiTalentedDriver is a proper subclass of CarDriver.

In your example, any IApi can be constructed with an IConfig. If IHttpApi is a subtype of IApi, we must be able to construct an IHttpApi using any IConfig instance – but it only accepts IHttpConfig. This is a contradiction.


答:
Let's ignore for a second that the method in question is __construct and call it frobnicate. Now suppose you have an object api implementing IHttpApi, and an object config implementing IHttpConfig. Clearly, this code fits the interface:

```<code>$api->frobnicate($config)
</code>```

But let's suppose we upcast api to IApi, for example passing it to function frobnicateTwice(IApi $api). Now in that function, frobnicate is called, and since it only deals with IApi, it may perform a call such as $api->frobnicate(new SpecificConfig(...)) where SpecificConfig implements IConfig but not IHttpConfig. At no point anyone did anything unsavory with types, yet IHttpApi::frobnicate got a SpecificConfig where it expected a IHttpConfig.

This is no good. We don't want to prohibit upcasting, we want subtyping, and we clearly want multiple classes implementing an interface. So the only sensible option is to prohibit a subtype method requiring more specific types for parameters. (A similar problem occurs when you want to return a more general type.)

Formally, you've walked into a classic trap surrounding polymorphism, variance. Not all occurrences of a type T can be replaced by a subtype U. Conversely, not all occurrences of a type T can be replaces by a supertype S. Careful consideration (or better yet, strict application of type theory) is necessary.

Coming back to __construct: Since AFAIK you can't exactly instantiate an interface, only a concrete implementer, this may seem like a pointless restriction (it's never going to get called through an interface). But in that case, why include __construct in the interface to begin with? Regardless, it would be of little use to special-case __construct here.

Title: Illegal in PHP: Is there an OOP design reason?

Body:
The below interface inheritance is illegal in PHP, but I think it would be fairly useful in real life. Is there an actual antipattern or documented problem with the below design, that PHP is protecting me from?</p>

```<code><?php

/**
 * Marker interface
 */
interface IConfig {}

/**
 * An api sdk tool
 */
interface IApi
{
    public __construct(IConfig $cfg);
}

/**
 * Api configuration specific to http
 */
interface IHttpConfig extends IConfig
{
    public getSomeNiceHttpSpecificFeature();
}

/**
 * Illegal, but would be really nice to have.
 * Is this not allowed by design?
 */
interface IHttpApi extends IApi
{
    /**
     * This constructor must have -exactly- the same
     * signature as IApi, even though its first argument
     * is a subtype of the parent interface's required
     * constructor parameter.
     */
    public __construct(IHttpConfig $cfg);

}
</code>```

Body:
Let's ignore for a second that the method in question is __construct and call it frobnicate. Now suppose you have an object api implementing IHttpApi, and an object config implementing IHttpConfig. Clearly, this code fits the interface:

$api->frobnicate($config)

But let's suppose we upcast api to IApi, for example passing it to function frobnicateTwice(IApi $api). Now in that function, frobnicate is called, and since it only deals with IApi, it may perform a call such as $api->frobnicate(new SpecificConfig(...)) where SpecificConfig implements IConfig but not IHttpConfig. At no point anyone did anything unsavory with types, yet IHttpApi::frobnicate got a SpecificConfig where it expected a IHttpConfig.

This is no good. We don't want to prohibit upcasting, we want subtyping, and we clearly want multiple classes implementing an interface. So the only sensible option is to prohibit a subtype method requiring more specific types for parameters. (A similar problem occurs when you want to return a more general type.)

Formally, you've walked into a classic trap surrounding polymorphism, variance. Not all occurrences of a type T can be replaced by a subtype U. Conversely, not all occurrences of a type T can be replaces by a supertype S. Careful consideration (or better yet, strict application of type theory) is necessary.

Coming back to __construct: Since AFAIK you can't exactly instantiate an interface, only a concrete implementer, this may seem like a pointless restriction (it's never going to get called through an interface). But in that case, why include __construct in the interface to begin with? Regardless, it would be of little use to special-case __construct here.


答:
Never assume your inability to imagine why someone would WANT to do something has any correlation as to what someone else WILL do.

Remember Murphy's Law, and ask "is there ANY situation where not being able to recognize distinct objects as equal will cause problems".  If the answer is yes, the few lines of code needed to compare equality by value will be worthwhile.

Title: Is there any reason to override Equals for an Entity?

Body:
An entity has identity, which implies there should only be one object (e.g. a particular customer) in memory.

As such, reference equality (which is what the base version of object.equals checks for) should be the only equality we care about.

A value object on the other hand would need to overrride Equals as there may be many in memory.

Are there any issues with the above reasoning?

I just can't imagine why I would have two customer objects representing the same customer, and in any case where I did (e.g. took a clone to do something with it), I can't think of any circumstances where I would need to check if it was equal to the orginal object.

Even in a distributed environment, any client process should only contain one object for a certain customer.