问:
Does simplicity always improve Readability?
Recently, I was developing a set of coding standards for our company.  (We're a new team branching out into a new language for the company.)

On my first draft, I set the purpose of our coding standards as improving Readability, Maintainability, Reliability, and Performance.  (I ignored writability, portability, cost, compatibility with previous standards, etc.)

One of my goals while writing this document was to push through the idea of simplicity of code. The idea was that there should be only one function call or operation per line.  My hope was that this would increase readability.  It's an idea that I carried over from our previous language.

However, I've questioned the assumption behind this push:

Does simplicity always improve readability?

Is there a case where writing simpler code decreases readability?

It should be obvious, but by "simpler", I don't mean "easier to write", but less stuff going on per line.

答:
Does simplicity always improve readability?

I would say, maybe with a little bit of controversy, absolutely not.

You could hand me a class with 200 member functions in its public interface, and it may be the most humanly-readable public interface out there. It might be a joy just casually reading through such code and its documentation. However, I wouldn't call it "simple", because in spite of the readability, I would have to be concerned with how all these functions interact with each other, and potentially watch out for tricky edge cases resulting from misuse.

I would prefer a class with 20 member functions that weren't so easy to read to 200 that are, because "readability" is not the top priority to me in terms of preventing human error and improving the maintainability of code (the ease at which we can change it, i.e.).

However, this is all going to hinge on our personal definition of "simplicity". "Readability" typically doesn't vary that wildly among us, unless someone has acquired so much expertise and fluency that they consider regex to be very "readable", e.g., forgetting the rest of us mere mortals.

Simplicity

There was a time, long ago, where I thought "simplicty" meant "as easy to read as possible". So I would write C code with a lot of convenience functions, trying to improve the syntax and make things as easy to read and write as possible.

I designed very big, rich, high-level libraries as a result, trying to model a function for every natural human thought: helpers upon helpers upon helpers, all to shape the client code to a more readable syntax. The code I wrote back then may have been the most "readable", yet it was also the most "unmaintainable" and "complex".

Lisp

Yet I had a brief passion with LISP around the mid-90s (latecomer). It changed my whole idea of "simplicity".

LISP is not the most readable language. Hopefully no one thinks that extracting CDRs and CARs while invoking a recursive function with a boatload of nested parentheses is very "readable".

Nevertheless, after struggling to get my brain wrapped around the language's odd syntax and totally recursive ways of doing things, it permanently changed my idea of simplicity.

What I found with the code I wrote in LISP is that I was no longer making subtle errors anymore, even though the trickiness of thinking that way had me making more blatant mistakes (but those are easy to spot and correct). I wasn't misunderstanding what a function was doing and missing out on a subtle, unanticipated side effect. I was just having an easier time in general making changes and writing correct programs.

After LISP, simplicity to me became about minimalism, symmetry, flexibility, fewer side effects, fewer but more flexible functions that combine together in an infinite variety of ways.

I came to appreciate the mindset that the most reliable code of all is code that doesn't exist. While it's only a crude metric, I tend to see the potential for unreliability of code based on its quantity. Seeking the utmost syntactical convenience and readability tends to increase that quantity by a large factor.

Minimalism

With the LISP mindset embedded in me, I came to prefer minimalist APIs. I'd prefer a library with fewer but more reliable, flexible functions that are less convenient and potentiality harder to read than one which offers a boatload of "convenient" helpers and such which may make the code easy to "read" but potentially trip over more issues with unreliability and surprises that result from misunderstanding what one of these thousands of functions do.

Safety

Another thing about LISP was safety. It promoted minimal side effects and pure functions, and that was where I no longer saw myself making subtle mistakes, even though the difficulty of reading and writing in the language increased more blatant mistakes I could spot 10 seconds later.

Pure functions and immutable states became preferable to me whenever I could afford it, even if the syntax of:

```<code>sword = sharpen(sword)
</code>```

... is a little less straightforward and detached from human thinking than:

```<code>sharpen(sword)
</code>```

Readability VS. Simplicity

Yet again, LISP is not the most "readable" language. It can pack a lot of logic into a small section of code (possibly more than one human thought per line). I tend to ideally prefer one human thought per line for "readability", but it's not necessarily for "simplicity".

With this kind of definition of "simple", sometimes "simple" might actually somewhat compete with "readable". This is considering things more from an interface design point of view.

A simple interface means you need to learn far fewer things to use it, and potentially has greater reliability and fewer gotchas as result of its minimalism. A comprehensive documentation on the subject might fit a booklet rather than a massive volume of books. Nevertheless, it might require some more grunt-work and yield less readable code.

"Simple" to me improves our ability to understand the functionality in our system at a broad level. "Readable" to me improves our ability to connect each little line of code to natural language and thought and might speed up our understanding of what one line of code does, especially if we're not fluent in the language.

Regex is an example of what I consider "extremely simple". It's "too simple and too unreadable" for my personal taste. There's a balancing act for me between these extremes, yet regex does have that LISP-like quality of simplicity as I define it: minimalism, symmetry, incredible flexibility, reliability, etc. The problem for me with regex is that it's so simple that it has become so unreadable to the point where I don't think I'll ever become fluent at it (my brain just doesn't work that way and I envy people who can write regex code fluently).

So anyway, that's my definition of "simplicity", and it is completely independent of "readability" and may sometimes even interfere with the other, leading to a balancing act between a more "syntactically convenient" and readable but bigger library or a "syntactically inconvenient", less readable, yet smaller library. I've always found the true "convenience of understanding" and true "maintainability" priorities to align with the latter, with the strong preference towards minimalism even at some cost to readability and more natural human syntax (but not to the point of regex). YMMV.

Body:
Does simplicity always improve readability?

I would say, maybe with a little bit of controversy, absolutely not.

You could hand me a class with 200 member functions in its public interface, and it may be the most humanly-readable public interface out there. It might be a joy just casually reading through such code and its documentation. However, I wouldn't call it "simple", because in spite of the readability, I would have to be concerned with how all these functions interact with each other, and potentially watch out for tricky edge cases resulting from misuse.

I would prefer a class with 20 member functions that weren't so easy to read to 200 that are, because "readability" is not the top priority to me in terms of preventing human error and improving the maintainability of code (the ease at which we can change it, i.e.).

However, this is all going to hinge on our personal definition of "simplicity". "Readability" typically doesn't vary that wildly among us, unless someone has acquired so much expertise and fluency that they consider regex to be very "readable", e.g., forgetting the rest of us mere mortals.

Simplicity

There was a time, long ago, where I thought "simplicty" meant "as easy to read as possible". So I would write C code with a lot of convenience functions, trying to improve the syntax and make things as easy to read and write as possible.

I designed very big, rich, high-level libraries as a result, trying to model a function for every natural human thought: helpers upon helpers upon helpers, all to shape the client code to a more readable syntax. The code I wrote back then may have been the most "readable", yet it was also the most "unmaintainable" and "complex".

Lisp

Yet I had a brief passion with LISP around the mid-90s (latecomer). It changed my whole idea of "simplicity".

LISP is not the most readable language. Hopefully no one thinks that extracting CDRs and CARs while invoking a recursive function with a boatload of nested parentheses is very "readable".

Nevertheless, after struggling to get my brain wrapped around the language's odd syntax and totally recursive ways of doing things, it permanently changed my idea of simplicity.

What I found with the code I wrote in LISP is that I was no longer making subtle errors anymore, even though the trickiness of thinking that way had me making more blatant mistakes (but those are easy to spot and correct). I wasn't misunderstanding what a function was doing and missing out on a subtle, unanticipated side effect. I was just having an easier time in general making changes and writing correct programs.

After LISP, simplicity to me became about minimalism, symmetry, flexibility, fewer side effects, fewer but more flexible functions that combine together in an infinite variety of ways.

I came to appreciate the mindset that the most reliable code of all is code that doesn't exist. While it's only a crude metric, I tend to see the potential for unreliability of code based on its quantity. Seeking the utmost syntactical convenience and readability tends to increase that quantity by a large factor.

Minimalism

With the LISP mindset embedded in me, I came to prefer minimalist APIs. I'd prefer a library with fewer but more reliable, flexible functions that are less convenient and potentiality harder to read than one which offers a boatload of "convenient" helpers and such which may make the code easy to "read" but potentially trip over more issues with unreliability and surprises that result from misunderstanding what one of these thousands of functions do.

Safety

Another thing about LISP was safety. It promoted minimal side effects and pure functions, and that was where I no longer saw myself making subtle mistakes, even though the difficulty of reading and writing in the language increased more blatant mistakes I could spot 10 seconds later.

Pure functions and immutable states became preferable to me whenever I could afford it, even if the syntax of:

sword = sharpen(sword)

... is a little less straightforward and detached from human thinking than:

sharpen(sword)

Readability VS. Simplicity

Yet again, LISP is not the most "readable" language. It can pack a lot of logic into a small section of code (possibly more than one human thought per line). I tend to ideally prefer one human thought per line for "readability", but it's not necessarily for "simplicity".

With this kind of definition of "simple", sometimes "simple" might actually somewhat compete with "readable". This is considering things more from an interface design point of view.

A simple interface means you need to learn far fewer things to use it, and potentially has greater reliability and fewer gotchas as result of its minimalism. A comprehensive documentation on the subject might fit a booklet rather than a massive volume of books. Nevertheless, it might require some more grunt-work and yield less readable code.

"Simple" to me improves our ability to understand the functionality in our system at a broad level. "Readable" to me improves our ability to connect each little line of code to natural language and thought and might speed up our understanding of what one line of code does, especially if we're not fluent in the language.

Regex is an example of what I consider "extremely simple". It's "too simple and too unreadable" for my personal taste. There's a balancing act for me between these extremes, yet regex does have that LISP-like quality of simplicity as I define it: minimalism, symmetry, incredible flexibility, reliability, etc. The problem for me with regex is that it's so simple that it has become so unreadable to the point where I don't think I'll ever become fluent at it (my brain just doesn't work that way and I envy people who can write regex code fluently).

So anyway, that's my definition of "simplicity", and it is completely independent of "readability" and may sometimes even interfere with the other, leading to a balancing act between a more "syntactically convenient" and readable but bigger library or a "syntactically inconvenient", less readable, yet smaller library. I've always found the true "convenience of understanding" and true "maintainability" priorities to align with the latter, with the strong preference towards minimalism even at some cost to readability and more natural human syntax (but not to the point of regex). YMMV.


问:
Why would you store an enum in DB?
I've seen a number of questions, like this, asking for advice on how to store enums in DB. But I wonder why would you do that. So let's say that I have an entity Person with a gender field, and a Gender enum. Then, my person table has a column gender.

Besides the obvious reason of enforcing correctness, I don't see why I would create an extra table gender to map what I already have in my application. And I don't really like having that duplication.

答:
First you need to decide if the database will only ever be used by one application or if there is a potential for multiple applications to use it. In some cases a database is nothing more than a file format for an application (SQLite databases can often be used in this regard). In this case bit duplicating the enum definition as a table can often be fine and may make more sense.

However as soon as you want to consider the possibility of having multiple applications accessing the database, then a table for the enum makes a lot of sense (the other answers go into why in more detail). The other thing to consider will you or another developer want to look at the raw database data. If so, this can be considered another application use (just one where the lab gauge is raw SQL).

If you have the enum defined in code (for cleaner code and compile time checking) as well as a table in the database, I would recommend adding unit tests to verify that the two are in sync.

ContentLicense: CC BY-SA 3.0

Title: Why would you store an enum in DB?


问:
How to correctly implement key=value storage REST API
I'm new to REST API, so I decided to get familiar with it by designing a small web service API. I have its design written down and would like you to review it. I feel like I have made some mistakes in designing it and understanding REST concepts, which I try to address with questions on my design at the very end. I'm mostly unsure about my use of URLs for the API.

The web service I try to design provides a way for a user to store key=value pairs, i.e. retrieve value knowing its key, update the value of an existing key and delete an existing key. The whole CRUD set of actions!

Here is what I have came up with.

Versioning

Since my API might evolve, I want a notion of API versions, so I have

```<code>GET api.example.com/supported-versions
</code>```

Which returns a JSON list of integers denoting the API versions supported.

The API will be available at api.example.com/{VERSION}/ endpoint, e.g. api.example.com/1/ for the first version.

Key=value storage

```<code>GET api.exmaple.com/1/keys/{KEY}
</code>```

Allows a user to get a value associated with a key KEY. The server responds with a status code (200, 404, etc.) and a text value on success, both encoded in JSON.

```<code>POST and PUT api.exmaple.com/1/keys/{KEY}?value={VALUE}
</code>```

Allows a user to create/update the value associated with the key KEY. The server returns a status code (200, 404, etc.). VALUE is a text string.

```<code>DELETE api.exmaple.com/1/keys/{KEY}
</code>```

Allows a user to delete a key=value pair with key KEY. The server Which will delete the key=value pair and return a status code (200, 404, etc.).

Let's imagine that there is an OAuth2 authentication set up, which is used for the up above POST/PUT/DELETE methods (but not GET anyone can GET, you don't need authentication for that), so there is a way to uniquely identify a user and keep track which key=value pairs belong to which user.

Now, I want an authenticated user to be able to get a list of all keys they have, so that they don't have to store this information on client-side in order to send DELETE or PUT request later.

```<code>GET api.exmaple.com/1/keys?page={PAGE}
</code>```

This allows a user to get a list of all existing keys they have created. PAGE is an optional parameter. User can increase page count until the user gets an error status code. It returns a paged list of all existing keys a user have created and also a status code (200, 404, etc.).

Is there anything wrong with this API?

Should the first GET/POST/PUT/DELETE from Key=value storage section be on /keys/ or /values/?

Is it fine that the last "GET", the one which returns all keys a user has, is also /keys/?

答:
When the REST service returns a list of resources, such as the user's keys or the available versions, return (json) structures that contain URLs to these resources.  Google for "linked data" to see the benefits of this approach.

E.g. the request:

```<code>HTTP> GET /Data/Version=1/User=Kasper/My_keys
</code>```

Would result in the response:

```<code>200

{ keys:
   [
      { name: "SO_account",
        link: "http://api.example.com/Data/Version=1/keys/SO_Account
      },
      { name: "Facebook_account";
        link: "http://api.example.com/Data/Version=1/keys/Facebook_account"
      }
   ]
}
</code>```

Body:
When the REST service returns a list of resources, such as the user's keys or the available versions, return (json) structures that contain URLs to these resources.  Google for "linked data" to see the benefits of this approach.

E.g. the request:

HTTP> GET /Data/Version=1/User=Kasper/My_keys

Would result in the response:

200

{ keys:
   [
      { name: "SO_account",
        link: "http://api.example.com/Data/Version=1/keys/SO_Account
      },
      { name: "Facebook_account";
        link: "http://api.example.com/Data/Version=1/keys/Facebook_account"
      }
   ]
}


问:
in DDD, should repositories expose an entity or domain objects?
As I understand it, in DDD, it is appropriate to use a repository pattern with an aggregate root. My question is, should I return the data as an entity or domain objects/DTO?

Maybe some code will explain my question further:

Entity

```<code>public class Customer
{
  public Guid Id { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }
}
</code>```

Should I do something like this?

```<code>public Customer GetCustomerByName(string name) { /*some code*/ }
</code>```

Or something like this?

```<code>public class CustomerDTO
{
  public Guid Id { get; set; }
  public FullName { get; set; }
}

public CustomerDTO GetCustomerByName(string name) { /*some code*/ }
</code>```

Additional question:

In a repository, should I return IQueryable or IEnumerable?

In a service or repository, should I do something like.. GetCustomerByLastName, GetCustomerByFirstName, GetCustomerByEmail? or just make a method that is something like GetCustomerBy(Func<string, bool> predicate)?

答:
Based on my knowledge of DDD you should have this,

```<code>public CustomerDTO GetCustomerByName(string name) { /*some code*/ }
</code>```

In a repository, should I return IQueryable or IEnumerable?

It depends, you would find mix views from different peoples for this question. But I personally believe that if your repository will be used by a service like CustomerService then you may use IQueryable otherwise stick with IEnumerable.

Should Repositories return IQueryable?

In a service or repository, should I do something like..
  GetCustomerByLastName, GetCustomerByFirstName, GetCustomerByEmail? or
  just make a method that is something like GetCustomerBy(Func predicate)?

In your repository you should have a generic function like you said GetCustomer(Func predicate) but in your service layer add three different methods, this is because there is a chance your service being called from different clients and they need different DTOs.

You may also use Generic Repository Pattern for common CRUD, if you are not already aware.

Body:
Based on my knowledge of DDD you should have this,

public CustomerDTO GetCustomerByName(string name) { /*some code*/ }

In a repository, should I return IQueryable or IEnumerable?

It depends, you would find mix views from different peoples for this question. But I personally believe that if your repository will be used by a service like CustomerService then you may use IQueryable otherwise stick with IEnumerable.

Should Repositories return IQueryable?

In a service or repository, should I do something like..
  GetCustomerByLastName, GetCustomerByFirstName, GetCustomerByEmail? or
  just make a method that is something like GetCustomerBy(Func predicate)?

In your repository you should have a generic function like you said GetCustomer(Func predicate) but in your service layer add three different methods, this is because there is a chance your service being called from different clients and they need different DTOs.

You may also use Generic Repository Pattern for common CRUD, if you are not already aware.


答:
should I return the data as an entity or domain objects/DTO

Well that entirely depends on your use cases.  The only reason I can think of returning a DTO instead of a full entity is if your entity is huge and you only need to work on a subset of it.

If this is the case, then maybe you should reconsider your domain model and split your big entity into related smaller entities.

In a repository, should I return IQueryable or IEnumerable?

A good rule of thumb is to always return the simplest (highest in the inheritence hierarchy) type possible.  So, return IEnumerable unless you want to let the repository consumer work with an IQueryable.

Personally, I think returning an IQueryable is a leaky abstraction but I've met several developers who argue passionately that it isn't.  In my mind all querying logic should be contained and concealed by the Repository.  If you allow calling code to customise their query then what's the point of the repository?

In a service or repository, should I do something like.. GetCustomerByLastName, GetCustomerByFirstName, GetCustomerByEmail? or just make a method that is something like GetCustomerBy(Func predicate)?

For the same reason as I mentioned in point 1, definitely do not use GetCustomerBy(Func<string, bool> predicate).  It may seem tempting at first, but this is exactly why people have learned to hate generic repositories.  It's leaky.

Things like GetByPredicate(Func<T, bool> predicate) are only useful when they're hidden behind concrete classes.  So, if you had an abstract base class called RepositoryBase<T> which exposed protected T GetByPredicate(Func<T, bool> predicate) which was only used by concrete repositories (eg, public class CustomerRepository : RepositoryBase<Customer>) then that would be fine.

Title: in DDD, should repositories expose an entity or domain objects?

Body:
As I understand it, in DDD, it is appropriate to use a repository pattern with an aggregate root. My question is, should I return the data as an entity or domain objects/DTO?

Maybe some code will explain my question further:

Entity

```<code>public class Customer
{
  public Guid Id { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }
}
</code>```

Should I do something like this?

```<code>public Customer GetCustomerByName(string name) { /*some code*/ }
</code>```

Or something like this?

```<code>public class CustomerDTO
{
  public Guid Id { get; set; }
  public FullName { get; set; }
}

public CustomerDTO GetCustomerByName(string name) { /*some code*/ }
</code>```

Additional question:

In a repository, should I return IQueryable or IEnumerable?

In a service or repository, should I do something like.. GetCustomerByLastName, GetCustomerByFirstName, GetCustomerByEmail? or just make a method that is something like GetCustomerBy(Func<string, bool> predicate)?


答:
There's a sizable community of folks who use CQRS to implement their domains.  My feeling is that, if the interface of your repository is analogous to the best practices used by them, that you won't go too far astray.

Based on what I've seen...

1) Command handlers usually use the repository to load the aggregate via a repository.  Commands target a single specific instance of the aggregate; the repository loads the root by ID.  There isn't, that I can see, a case where the commands are run against a collection of aggregates (instead, you would first run a query to get the collection of aggregates, then enumerate the collection and issue a command to each.

Therefore, in contexts where you are going to be modifying the aggregate, I would expect the repository to return the entity (aka the aggregate root).

2) Query handlers don't touch the aggregates at all; instead, they work with projections of the aggregates -- value objects that describe the state of the aggregate/aggregates at some point in time.  So think ProjectionDTO, rather than AggregateDTO, and you have the right idea.

In contexts where you are going to be running queries against the aggregate, preparing it for display, and so on, I'd expect to see a DTO, or a DTO collection, returned, rather than an entity.

All of your getCustomerByProperty calls look like queries to me, so they would fall into the latter category.  I'd probably want to use a single entry point to generate the collection, so I would be looking to see if

```<code>getCustomersThatSatisfy(Specification spec)
</code>```

is a reasonable choice; the query handlers would then construct the appropriate specification from the parameters given, and pass that specification to the repository.  The downside is that signature really suggests that the repository is a collection in memory; it's not clear to me that the predicate buys you much if the repository is just an abstraction of running a SQL statement against a relational database.

There are some patterns that can help out, though.  For example, instead of building the specification by hand, pass to the repository a description of the constraints, and allow the implementation of the repository to decide what to do.

Warning: java like typing detected

```<code>interface CustomerRepository {
    interface ConstraintBuilder {
        void setLastName();
        void setFirstName();
    }

    interface ConstraintDescriptor {
        void copyTo(ConstraintBuilder builder);
    }

    List<CustomerProjection> getCustomersThatSatisfy(ConstraintDescriptor descriptor);
}

SQLBackedCustomerRepository implements CustomerRepository {
    List<CustomerProjection> getCustomersThatSatisfy(ConstraintDescriptor descriptor) {
        WhereClauseBuilder builder = new WhereClauseBuilder();
        descriptor.copyTo(builder);
        Query q = createQuery(builder.build());
        //...
     }
}

CollectionBackedCustomerRepository implements CustomerRepository {
    List<CustomerProjection> getCustomersThatSatisfy(ConstraintDescriptor descriptor) {
        PredicateBuilder builder = new PredicateBuilder();
        descriptor.copyTo(builder);
        Predicate p = builder.build();
        // ...
}

class MatchLastName implements CustomerRepository.ConstraintDescriptor {
    private final lastName;
    // ...

    void copyTo(CustomerRepository.ConstraintBuilder builder) {
        builder.setLastName(this.lastName);
    }
}
</code>```

In conclusion: the choice between providing an aggregate and providing a DTO depends on what you are expecting the consumer to do with it.  My guess would be one concrete implementation supporting an interface for each context.

Body:
There's a sizable community of folks who use CQRS to implement their domains.  My feeling is that, if the interface of your repository is analogous to the best practices used by them, that you won't go too far astray.

Based on what I've seen...

1) Command handlers usually use the repository to load the aggregate via a repository.  Commands target a single specific instance of the aggregate; the repository loads the root by ID.  There isn't, that I can see, a case where the commands are run against a collection of aggregates (instead, you would first run a query to get the collection of aggregates, then enumerate the collection and issue a command to each.

Therefore, in contexts where you are going to be modifying the aggregate, I would expect the repository to return the entity (aka the aggregate root).

2) Query handlers don't touch the aggregates at all; instead, they work with projections of the aggregates -- value objects that describe the state of the aggregate/aggregates at some point in time.  So think ProjectionDTO, rather than AggregateDTO, and you have the right idea.

In contexts where you are going to be running queries against the aggregate, preparing it for display, and so on, I'd expect to see a DTO, or a DTO collection, returned, rather than an entity.

All of your getCustomerByProperty calls look like queries to me, so they would fall into the latter category.  I'd probably want to use a single entry point to generate the collection, so I would be looking to see if

getCustomersThatSatisfy(Specification spec)

is a reasonable choice; the query handlers would then construct the appropriate specification from the parameters given, and pass that specification to the repository.  The downside is that signature really suggests that the repository is a collection in memory; it's not clear to me that the predicate buys you much if the repository is just an abstraction of running a SQL statement against a relational database.

There are some patterns that can help out, though.  For example, instead of building the specification by hand, pass to the repository a description of the constraints, and allow the implementation of the repository to decide what to do.

Warning: java like typing detected

interface CustomerRepository {
    interface ConstraintBuilder {
        void setLastName();
        void setFirstName();
    }

    interface ConstraintDescriptor {
        void copyTo(ConstraintBuilder builder);
    }

    List<CustomerProjection> getCustomersThatSatisfy(ConstraintDescriptor descriptor);
}

SQLBackedCustomerRepository implements CustomerRepository {
    List<CustomerProjection> getCustomersThatSatisfy(ConstraintDescriptor descriptor) {
        WhereClauseBuilder builder = new WhereClauseBuilder();
        descriptor.copyTo(builder);
        Query q = createQuery(builder.build());
        //...
     }
}

CollectionBackedCustomerRepository implements CustomerRepository {
    List<CustomerProjection> getCustomersThatSatisfy(ConstraintDescriptor descriptor) {
        PredicateBuilder builder = new PredicateBuilder();
        descriptor.copyTo(builder);
        Predicate p = builder.build();
        // ...
}

class MatchLastName implements CustomerRepository.ConstraintDescriptor {
    private final lastName;
    // ...

    void copyTo(CustomerRepository.ConstraintBuilder builder) {
        builder.setLastName(this.lastName);
    }
}

In conclusion: the choice between providing an aggregate and providing a DTO depends on what you are expecting the consumer to do with it.  My guess would be one concrete implementation supporting an interface for each context.


问:
Algorithm to find minimal set
I have a set of sets S and I want to find a minimal set of elements M such that each set in S shares at least one element with M.

```<code>S = set of sets
∀ f∈S ∃e · e∈f ∧ e∈M
</code>```

For example:

```<code>S = {{1}, {1, 2, 3}, {3, 4}, {5, 6}}
M = {1, 3, 5} or {1, 3, 6} or {1, 4, 5} or {1, 4, 6}
</code>```

Is there a name for this problem? What algorithms exist to find an approximation of M?

答:
This problem is known in the literature as "minimal hitting set", and there are lots of algorithms for both exact and approximate solutions. I recently benchmarked about twenty algorithms for exact solutions and found the MMCS and RS algorithms of Murakami and Uno 1 to be extremely fast and easy to implement. Those authors have made C implementations available, and I have provided a parallelized C++ implementation. I also have a survey paper in preparation which should be available on arXiv shortly if you're interested in the details.

1 K. Murakami and T. Uno, "Efficient algorithms for dualizing large-scale hypergraphs". Discrete Applied Mathematics 170, p. 83-94. doi:10.1016/j.dam.2014.01.012. arxiv:1102.3813

Title: Algorithm to find minimal set


问:
Algorithm for the shrinking of pixel art
This is something I've been wondering about for a while - are there any algorithms out there to scale pixel art down?

I'm sure we all know about the upscale versions on the Wikipedia page on Image Scaling.

I would have thought something like nearest neighbour resampling to get the colour pattern right, and then redrawing the outline, or high-contrast areas, over the top. Is there anything out there or am I going to have to learn how to do this myself?

Thanks!

答:
This is really towards the realm of non-photorealistic rendering (NPR). I think it's awesome -- it would have been so great if I had such a software many years ago.

But I used to do pixel art ages ago, and I don't think you can actually get this kind of pixel art look with any ordinary downsampling algorithm. It's often going to end up looking like that mipmap example from the same wiki page:

You might be able to get a sharper image, reduce the colors, get a slightly toonish look. But it's really hard to make it look like it was actually designed for that resolution through downsampling alone. That can apply even if you have a cartoony graphic with fat outlines.

It's funnily much, much easier to scale up than scale down with pixel art, since pixel-art tends to be carefully drawn for the low-res style (the artist isn't simply rendering smaller, he's changing the way he approaches the line art, e.g.).

Vector Graphics

If you're doing this to generate lower-res pixel content that looks hand-drawn rather than trying to do this in a realtime setting, what I recommend instead if you have a high-res image is look into algorithms that convert the higher-res artwork into vector graphics, detecting outline paths and broad regions of flat color and things of that sort.

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

I really think that gives you the ideal starting point, plus it's also potentially the most flexible since it gives you the ability to rasterize and play with different styles. Downsampling wants to focus on crunching pixels down no matter how elaborate, while capturing to vector graphics gives you something to work with which resembles like a "list of things to draw".

Then you can rasterize the vectorized shapes/paths at a lower resolution with a crisp line and curve style similar to how pixel artists draw.

We generally want deliberately aliased line rasterization in this case with crisp, 1-pixel stroke outlines.

For example, if we tried to scale this wrestler guy down to half the size, the lines actually won't get thinner. The artist would still use crisp, aliased, perfectly-coordinated 1-pixel outline strokes if he was to draw this guy at half the size. The actual style of the artwork would change and get more cartoony when drawn at half the scale, and primarily because the stroke thickness won't change. That's why I recommend the vector graphic approach, since down-sampling will want to use a sub-pixel outline if you tried to shrink this. The line art is the most critical part of all.

Always Crisp, Aliased, 1-Pixel Strokes Independent of Resolution

You might have noticed this phenomena playing old video games which were ported from a more capable graphics hardware to a less capable hardware (ex: arcade to nintendo), where the artists had to use lower resolution graphics. The way they drew the graphics for the less capable hardware would actually change in style to take on a more cartoonish look, and that's because the artists were sticking to that crisp, aliased 1-pixel stroke style which dominates pixel art (since the thickness of the line is absolute and unchanging even with the lower-res artwork, the lower-res artwork looks more cartoonish). The feeling of the overall piece changes based on the resolution it's drawn, which might make it seem hopeless to automate the process, but I actually think you can do a very nice job (better than any tools out there) if you can capture the strokes as paths through a vector graphic first.

Shading is actually the easiest part because there you can potentially just downsample and get a good result, since it's all just soft, fuzzy edges.

It's the crisp edges/outlines that are hard to preserve. It's not so much about sharpness as artistic intent and how the artist would communicate such an intent at this low-resolution scale. If you have a reasonable vector graphics source, I think you have the best chance since you're rasterizing the low-res result instead of trying to downsample the high-res result.

So this is kind of deviating from your original course, but I'd recommend looking at it this way. If you try this, maybe your first major goal is just trace the outline into an vector graphic and then try to rasterize the vector at a really low resolution with crisp, aliased lines/curves. If you can start doing that line work part reasonably, it's already ground-breaking and the next step can be to capture some flat color. Finally, shading will be quite easy in comparison, and there you might just downsample and composite/blend.

OwnerDisplayName: bonzairob


问:
Differences between `throw` and `throw new` and exactly how exceptions "bubble up"
Can someone please explain the differences in C# between:

throw

throw new

and exactly how exceptions "bubble up" as I've heard they do?

In my daily job, I've used just try/catch to mostly control the flow. I've divided the code into various "blocks" each one enclosed in a try/catch so I could log and debug exactly where a program crashed/had a problem, if there was any.

In researching, I've found there is a "bubble" logic behind the exception - which is used in more structured software development. For example, if I have a system in which I build modules/plugins/complex complementary classes, I might want the exceptions to point me to exactly where the code failed, OR, bubble up to a more generic part of the program to do a wider debug.

The way how we can do this sort of "bubble up" exception catching, I do not know, but is my understanding correct? Can someone perhaps give a clearer explanation of C#'s "bubble up" exception behaviour?

then about throw:

I see there is throw and throw new.

From what I've seen, throw is used when you check for a particular error/condition in your code and you want to warn the outside block that particular condition occurred.

Is this correct? I don't really understood why I have to use throw or throw new and the differences between them.

答:
When an exception is thrown, the framework will walk up the call stack until it finds an exception handler that handles the type of exception you threw.  If there is no such exception handler, the program ends.  So you can provide an exception handler anywhere in the call stack where it is convenient to put one.

In general, exceptions should be used for situations that your code cannot do anything about or recover from without user intervention. If your user provides a file name that does not exist, for example, your code cannot read the mind of the user to get the correct file name, so it throws an exception.

The difference between throw and throw new is that throw new throws a new exception, while  throw is used when you want to catch the original exception, do something with it (log it perhaps), and then rethrow it so that it continues to bubble up the call stack while preserving the original stack trace.

Generally speaking, you won't usually need custom exception classes unless you want to do something exotic like serialize your exceptions or capture specific data during the throw new (for diagnostic purposes).

An Interface has but one purpose: to decouple an implementation.  There are many reasons why you might want to do this, but they all amount to essentially the same thing: having the ability to provide multiple implementations that conform to the same interface specification.

ContentLicense: CC BY-SA 4.0


答:
So, first things first, programming language features and computing concepts in general are just tools. Your question indicates that you don't really seem to think this way. You think of needing to do something first, and find some pattern of code accomplishes that. I cannot stress how strongly how much this will limit your abilities as a programmer in general, and your career specifically.

I am going to explain exceptions from the tool side. Here is what they are. Here is how they work. Understanding the implications of that, and creating new, interesting, and wonderful stuff from them becomes your job.

now I need something in the style "Explain it like I'm 5" for exception throwing.

As your program executes, it progresses from one function to another. This eventually builds a path from the entrypoint to the current execution point in the program. The code itself is largely unaware of what function called it.

This leads to problem when things go wrong. When things go wrong in a function, it doesn't know who called it, so it doesn't really know what to do. Enter exceptions. Exceptions are there for the function to say "oh shit, something went wrong! I don't know what to do! I hope the stuff that called me knows what to do...".

What happens is that a function throws an exception, and then the computer goes back along the path of execution that the program built up until it finds some function that actually knows what to do. If no function is found, the OS generally just kills your program because something went horribly wrong.

That's exceptions in a nutshell.

In C#, the throw statement is how you tell the function to fire off that exception and go back along the execution path. The common usage of the statement takes an Exception object as an argument. Since you almost always have a new Exception, that's why you use new - just like any other object.

catch is how you tell the computer "I know how to deal with this sort of error if it happens here".

There are some other nuances around try/catch in C#, and other languages have some variation in how they work, but that general concept is fairly ubiquitous.

Title: Differences between `throw` and `throw new` and exactly how exceptions "bubble up"

Body:
Can someone please explain the differences in C# between:

throw

throw new

and exactly how exceptions "bubble up" as I've heard they do?

In my daily job, I've used just try/catch to mostly control the flow. I've divided the code into various "blocks" each one enclosed in a try/catch so I could log and debug exactly where a program crashed/had a problem, if there was any.

In researching, I've found there is a "bubble" logic behind the exception - which is used in more structured software development. For example, if I have a system in which I build modules/plugins/complex complementary classes, I might want the exceptions to point me to exactly where the code failed, OR, bubble up to a more generic part of the program to do a wider debug.

The way how we can do this sort of "bubble up" exception catching, I do not know, but is my understanding correct? Can someone perhaps give a clearer explanation of C#'s "bubble up" exception behaviour?

then about throw:

I see there is throw and throw new.

From what I've seen, throw is used when you check for a particular error/condition in your code and you want to warn the outside block that particular condition occurred.

Is this correct? I don't really understood why I have to use throw or throw new and the differences between them.


答:
Don't use exceptions to control program flow.  For GimmeTheNumber() return a

NumberResult

object or similar.

```<code>public class NumberResult
{
    public int Number;
    public bool ResultValid;
}

private NumberResult GimmeTheNumber()
{
    int x = CalculateStuff();
    if (x == 0 || x == 15)
    {
       return new NumberResult(x, false);
    }

    return new NumberResult(x, true);
}
</code>```

Then your code is:

```<code>var result = GimmeTheResult()

if(result.ResultValid)
{
   //Keep doing calculations unless the function result is 0 or 15

}
</code>```

Now the code is cleaner.  If you want, you could just put one exception handler at the function entry point to handle any unexpected errors while doing your calculations.

Body:
Don't use exceptions to control program flow.  For GimmeTheNumber() return a

NumberResult

object or similar.

public class NumberResult
{
    public int Number;
    public bool ResultValid;
}

private NumberResult GimmeTheNumber()
{
    int x = CalculateStuff();
    if (x == 0 || x == 15)
    {
       return new NumberResult(x, false);
    }

    return new NumberResult(x, true);
}

Then your code is:

var result = GimmeTheResult()

if(result.ResultValid)
{
   //Keep doing calculations unless the function result is 0 or 15

}

Now the code is cleaner.  If you want, you could just put one exception handler at the function entry point to handle any unexpected errors while doing your calculations.


问:
Tracking time users spend on my website
We are going to track user engagement (i.e. time spent on website, most viewed part/page of the system, etc).

I don't see Google Analytics / MixPanel being able to do this, since we have to analyze based on factors only present in OUR backend (such as users who go to specific school, users who are a specific type, etc) - not the general stuff like Country, Gender, etc.

I can think of a REALLY simple solution, but I am not sure if it is, serverwise, bad. You have a table that looks something like this:

```<code>CREATE TABLE `log` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `uri` int(11) DEFAULT NULL,
  `date` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `user` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
</code>```

And then whenever a page is loaded, a row is added to the "log" table, with current timestamp, the user id and the uri.

Now I got the data I want, which is great. I can figure out when the user was last online and how many minutes people spend in average.

BUT. Is this bad for the server? It is going to add a row each page load, which is a lot of rows, if you have 500 or 1000 active users. But will it matter? What are your thoughts?

答:
If you really think this will impose a heavy server load, consider logging everything to a NoSQL database like MongoDB (or possibly even a plain text/CSV file), then performing a bulk load operation during off-peak hours. If the load process is the only thing that writes to this table, then you can eliminate the auto-increment ID and pre-generate all your IDs before you insert.

This presumes you don't need real-time access to this data; if you do, then you could consider writing a data loader that would post the data in a controlled fashion (say only N rows/second, configurable). This would prevent the writer from swamping the database server.

Definitely load-test your per-page-load option first, though. That sounds like the most straightforward approach, don't go to a lot of work to address a performance issue that doesn't really exist.

Title: Tracking time users spend on my website


问:
Should I avoid using unsigned int in C#?
I recently thought about the use of unsigned integers in C# (and I guess similar argument can be said about other "high level languages")

When In need of an integer I am normally not faced with the dilemma of the size of an integer, an example would be an age property of a Person class (but the question is not limited to properties) . With that in mind there is, as far as I can see, only one advantage of using an unsigned integer ("uint") over a signed integer ("int") - readability. If I wish to express the idea that an age can only be positive I can achieve this by setting the age type to uint.

On the other hand, calculations on unsigned integers can lead to errors of all sorts and it makes it difficult to do operations such as subtracting two ages. (I read this is one of the reasons Java omitted unsigned integers)

In the case of C# I can also think that a guard clause on the setter would be a solution that gives the best of two worlds, but, this would not be applicable when I for example, an age would be passes to some method. A workaround would be to define a class called Age and have the property age be the only thing there, but this pattern would have Me create many classes and would be a source of confusion (other developers would not know when an object is just a wrapper and when it's something more sofisticaded).

What are some general best practices regarding this issue? How should I deal with this type of scenario?

答:
The designers of the .NET Framework chose a 32 bit signed integer as their "general-purpose number" for several reasons:

It can handle negative numbers, especially -1 (which the Framework uses to indicate an error condition; this is why a signed int is used everywhere indexing is required, even though negative numbers are not meaningful in an indexing context).

It's large enough to serve most purposes, while being small enough to be used economically almost anywhere.

The reason to use unsigned ints is not readability; it is having the capability to get the math that only an unsigned int provides.

Guard clauses, validation and contract preconditions are perfectly acceptable ways to insure valid numeric ranges.  Seldom does a real-world numeric range correspond exactly to a number between zero and 232-1 (or whatever the native numeric range is of the numeric type you chose), so using a uint to constrain your interface contract to positive numbers is kind of beside the point.


答:
You mainly need to be aware of two things: the data you're representing, and any intermediate steps in your calculations.

It certainly makes sense to have age be unsigned int, because we usually don't consider negative ages.  But then you mention subtracting one age from another.  If we just blindly subtract one integer from another, then it's definitely possible to end up with a negative number, even if we previously agreed that negative ages don't make sense.  So in this case you would want your calculation done with a signed integer.

In regards to whether unsigned values are bad or not, I would say that it is a huge generalization to say unsigned values are bad.  Java doesn't have unsigned values, as you mentioned, and it constantly annoys me.  A byte can have a value from 0-255 or 0x00-0xFF. But if you want to instantiate a byte larger than 127(0x7F), you either have to write it as a negative number or cast an integer to a byte.  You end up with code that looks like this:

```<code>byte a = 0x80; // Won't compile!
byte b = (byte) 0x80;
byte c = -128; // Equal to b
</code>```

The above annoys me to no end.  I'm not allowed to have a byte have a value of 197, even though that's a perfectly valid value for most sane people dealing with bytes. I can cast the integer or I can find the negative value (197 == -59 in this case). Also consider this:

```<code>byte a = 70;
byte b = 80;
byte c = a + b; // c == -106
</code>```

So as you can see, adding two bytes with valid values, and ending up with a byte with a valid value, ends up changing the sign. Not only that but it's not immediately obvious that 70 + 80 == -106.  Technically this is an overflow, but in my mind (as a human being) a byte shouldn't overflow for values under 0xFF.  When I do bit arithmetic on paper, I don't consider the 8th bit being a sign bit.

I work with a lot of integers on the bit level, and having everything be signed usually makes everything less intuitive and harder to deal with, because you have to remember that right-shifting a negative number gives you new 1s in your number.  Whereas right-shifting an unsigned integer never does that. For example:

```<code>signed byte b = 0b10000000;
b = b >> 1; // b == 0b1100 0000
b = b & 0x7F;// b == 0b0100 0000

unsigned byte b = 0b10000000;
b = b >> 1; // b == 0b0100 0000;
</code>```

It just adds extra steps that I feel shouldn't be necessary.

While I used byte above, the same applies to 32-bit and 64-bit integers.  Not having unsigned is crippling and it shocks me that there are high level languages like Java that don't allow them at all.  But for most people this is a non-issue, because many programmers don't deal with bit-level arithmetic.

In the end, it's useful to use unsigned integers if you're thinking of them as bits, and it's useful to use signed integers when you're thinking of them as numbers.

Title: Should I avoid using unsigned int in C#?

Body:
I recently thought about the use of unsigned integers in C# (and I guess similar argument can be said about other "high level languages")

When In need of an integer I am normally not faced with the dilemma of the size of an integer, an example would be an age property of a Person class (but the question is not limited to properties) . With that in mind there is, as far as I can see, only one advantage of using an unsigned integer ("uint") over a signed integer ("int") - readability. If I wish to express the idea that an age can only be positive I can achieve this by setting the age type to uint.

On the other hand, calculations on unsigned integers can lead to errors of all sorts and it makes it difficult to do operations such as subtracting two ages. (I read this is one of the reasons Java omitted unsigned integers)

In the case of C# I can also think that a guard clause on the setter would be a solution that gives the best of two worlds, but, this would not be applicable when I for example, an age would be passes to some method. A workaround would be to define a class called Age and have the property age be the only thing there, but this pattern would have Me create many classes and would be a source of confusion (other developers would not know when an object is just a wrapper and when it's something more sofisticaded).

What are some general best practices regarding this issue? How should I deal with this type of scenario?

Body:
You mainly need to be aware of two things: the data you're representing, and any intermediate steps in your calculations.

It certainly makes sense to have age be unsigned int, because we usually don't consider negative ages.  But then you mention subtracting one age from another.  If we just blindly subtract one integer from another, then it's definitely possible to end up with a negative number, even if we previously agreed that negative ages don't make sense.  So in this case you would want your calculation done with a signed integer.

In regards to whether unsigned values are bad or not, I would say that it is a huge generalization to say unsigned values are bad.  Java doesn't have unsigned values, as you mentioned, and it constantly annoys me.  A byte can have a value from 0-255 or 0x00-0xFF. But if you want to instantiate a byte larger than 127(0x7F), you either have to write it as a negative number or cast an integer to a byte.  You end up with code that looks like this:

byte a = 0x80; // Won't compile!
byte b = (byte) 0x80;
byte c = -128; // Equal to b

The above annoys me to no end.  I'm not allowed to have a byte have a value of 197, even though that's a perfectly valid value for most sane people dealing with bytes. I can cast the integer or I can find the negative value (197 == -59 in this case). Also consider this:

byte a = 70;
byte b = 80;
byte c = a + b; // c == -106

So as you can see, adding two bytes with valid values, and ending up with a byte with a valid value, ends up changing the sign. Not only that but it's not immediately obvious that 70 + 80 == -106.  Technically this is an overflow, but in my mind (as a human being) a byte shouldn't overflow for values under 0xFF.  When I do bit arithmetic on paper, I don't consider the 8th bit being a sign bit.

I work with a lot of integers on the bit level, and having everything be signed usually makes everything less intuitive and harder to deal with, because you have to remember that right-shifting a negative number gives you new 1s in your number.  Whereas right-shifting an unsigned integer never does that. For example:

signed byte b = 0b10000000;
b = b >> 1; // b == 0b1100 0000
b = b & 0x7F;// b == 0b0100 0000

unsigned byte b = 0b10000000;
b = b >> 1; // b == 0b0100 0000;

It just adds extra steps that I feel shouldn't be necessary.

While I used byte above, the same applies to 32-bit and 64-bit integers.  Not having unsigned is crippling and it shocks me that there are high level languages like Java that don't allow them at all.  But for most people this is a non-issue, because many programmers don't deal with bit-level arithmetic.

In the end, it's useful to use unsigned integers if you're thinking of them as bits, and it's useful to use signed integers when you're thinking of them as numbers.


问:
How to Manage Privileges in C# WPF applications
I'm writing my first "large" program in C# and WPF. It's a Database system (MySQL) that has three main items, Contracts, Companies and People. I have the main UI down for the Companies section of the Database and I'm now looking at managing user privileges before I go any further.

I've hit a roadblock really on what would be a way to manage user privileges. The privileges would include access like being able to add, edit or delete a Company, the ability to view a Person's private details (home address etc) and access to specific Contract details (value of the job, whose working on it).

There are going to be many different privileges throughout the Database system as many will be very specific to the section you are in (it's not going to be a simple add/edit/delete privilege system). Another layer of complication to this is that the user is going to see different parts of the Database based on which department they work in. For example, a salesman will see some details specific to a company whereas a builder will see something totally different, but on the same company.

My initial thought is to have a privileges table in MySQL, something that looks like this;

Every user has multiple entries into this table, based on which part of the program they are in. For example if they are in sales, then they will have about 7/8 entries purely based on what sales can do and so on and so forth. This would be managed in a system like this;

Where each CheckBox would correspond to a 0 or a 1 in that entry for that person in the Database. When the user then logs into my Database program I setup their privileges at the very beginning - it could reach something like 75 global variables for what the user can or cannot do in the program which I look at further down the line when necessary.

My question really is what would be a way to manage privileges in this system? I haven't had much experience in this area before so am open to suggestions!

答:
I worked on a system that had a list of privileges (IE: Create users, modify customer accounts, etc) that were then assigned to groups.  Users were then assigned to those groups and then had all the privileges of the group.

In our application when we wanted to check a permission we had a method DoesUserHavePermission(PermissionEnum.Option) that we could call (and later turned into an MVC controller action filter).  The method looked at the user to the group to the permission.  This allows us to quickly add a permission to a group of users.  IE: All the sales people now need the Add Customer permission, just add it to the sales group and every one gets it.

We had 5 main tables for our permissions: Users, Groups, Privileges, UserGroup, and GroupPrivilege.  The logic was that if there was a privilege that a group had there was an entry in the GroupPrivilege table (eliminated the need for bit fields) and if a user was part of a group there was an entry in the UserGroup table.  (GroupPrivilege and UserGroup are many to many union tables).

This has kept the configuration down to a minimum after initial setup and if we need a group of users with a different set of permissions we can create a new group with just the privileges needed and assign the users to that group.


答:
"Explain it like I'm 5" for exception throwing.

Exception-handling is probably best thought of as modeling a transaction mindset. Forget about the low-level control flow aspect. There is a control flow aspect to it, but it's like we don't want to use functions as an elaborate goto for branching. There's a higher-level concept and mental model associated with that which is better to focus on.

The idea is that things either succeed as a whole or fail as a whole.

```<code>try
{
   // Transaction site. Try things out.
}
catch (Exception e)
{
    // Recovery site. We might report a message to the user
    // and also reverse any side effects (things we tried that
    // didn't succeed as a whole, like deleting a file that we
    // only managed to write half the contents of).
    ...
}
finally
{
    // Post-transaction site. Do things here that you need to
    // do after the transaction whether or not it succeeded or
    // failed, like closing a file.
}
</code>```

External Error vs. Programmer Error vs. Non-Error

Now, unless you're working in Python which is totally bizarre to me with how they go about exceptions ("leap before you look"), normally the process of throwing exceptions is best utilized for external errors.

By external errors, I mean things you cannot help and are outside of your control. For example, trying to open a file might fail due to some environmental condition in the operating system (maybe the hard disk is full). Your program can't really help that so much. Maybe the user interrupted and aborted the middle of a loading process -- you can't anticipate that. Maybe allocating memory failed. All of these errors are the result of errors occurring externally, outside of your code.

This is the most natural place from which to throw an exception.

Programmer errors may or may not be tackled through exceptions. In C++, it's often discouraged in favor of an assertion mindset to catch programmer mistakes like accessing an array out of bounds, but I think C# might encourage throwing here. So a programmer mistake may or may not involve throwing exceptions depending on the language.

Outside of Python which has this "leap before you look" philosophy, generally you shouldn't throw for non-errors. By a non-error, I mean trying to find a key in a map and failing to find it. That's not an error so much as just a very valid post-condition for a find function (it didn't find it, very ordinary thing).

Throwing

When you throw an exception, you are reporting an error. The idea is completely decoupled from catching. Don't think about where an exception will be caught or how it will caught when you throw. That would tend to couple your function to the transaction and the call stack, and reduce generality. Potentially you might reuse this function in various transactions, but it can fail the same way. Throwing is kind of a shortcut to avoid manually having to return error; return error; return error; all the way down to the catch site, but try not to look at it that way so much.

Throwing is about reporting an error. It's broadcasting it to whomever is interested.

Throwing is Expensive

If this conceptual model of avoiding the throw for non-errors (like failing to find an item) is confusing, it's worth noting that throwing an exception can be very expensive (depending on language/compiler). Some implementations have to kind of suspend threads and stop the entire world.

You might equate it to the cost of a disk access. I don't know how expensive it is exactly and it seems to vary wildly from one language/compiler to another (in Python I imagine it has to be cheap), all you might need to know is that it is expensive. And that's why we don't want to necessarily use it to just report back non-errors to the caller that a key isn't found in a dictionary, e.g., in languages where this kind of thing isn't idiomatic. It's not a general branching mechanism, it's for genuinely exceptional paths.

Rethrow vs. Throw New

With transactions, you also have sub-transactions. For example, let's say that in the process of loading an HTML file (trying to do this in a transaction), and you come across an image tag specifying an image file.

Now you might start a sub-transaction to load an image, and perhaps we fail to load the image and encounter an exception. In that case, you might catch it inside your nested image transaction.

```<code>try
{
   // Load image file and add the image to the webpage.
}
catch (Exception ex)
{
   // We ran into an error loading the image.
}
finally
{
   // Close image file if it's open
}
</code>```

However, this is a sub-transaction. We've encountered an error loading the image but it's also an outer error in loading the HTML file. As a result, we don't want to simply catch the exception and return from the function. We need to throw again. Here you can do one of two things:

```<code>catch (Exception ex)
{
    // Translate the exception into a more meaningful one
    // for the user.
    throw new ImageException(...); // can embed a message containing
                                   // details about what happened.
}
</code>```

Swallowing up an exception and translating it this way might sometimes be useful if you want to try to report the error in a less "raw" kind of way to the caller of your image loading function.

... or you can do this:

```<code>catch (Exception ex)
{
    // Simply throw the same exception to the outer transaction.
    throw;
}
</code>```

... and simply pass the original exception back to the caller.

Which one you choose here is more of a design decision, whether you want to simply forward the exact same exception to the outer transaction that invoked the image loader or translate it into some kind of specific image loading exception.

It's up to you and will be based on how rich you want the error reporting to be. I personally prefer dealing with fewer exception types and catching more generally since most of the time I don't find much use for an exception type beyond just grabbing the message attached, but that may be my C++ side speaking where programmer errors aren't reported through exceptions (they don't point out mistakes, only those external input errors outside of our control that can occur even when our code is perfectly correct).

In cases where exceptions are used in a debugging context more than just a "report what happened to the user" kind of mindset, you might find it very helpful to know exactly what kind of exception was thrown, and catch more specifically when possible as well as throwing a wider range of exception types.

Body:
"Explain it like I'm 5" for exception throwing.

Exception-handling is probably best thought of as modeling a transaction mindset. Forget about the low-level control flow aspect. There is a control flow aspect to it, but it's like we don't want to use functions as an elaborate goto for branching. There's a higher-level concept and mental model associated with that which is better to focus on.

The idea is that things either succeed as a whole or fail as a whole.

try
{
   // Transaction site. Try things out.
}
catch (Exception e)
{
    // Recovery site. We might report a message to the user
    // and also reverse any side effects (things we tried that
    // didn't succeed as a whole, like deleting a file that we
    // only managed to write half the contents of).
    ...
}
finally
{
    // Post-transaction site. Do things here that you need to
    // do after the transaction whether or not it succeeded or
    // failed, like closing a file.
}

External Error vs. Programmer Error vs. Non-Error

Now, unless you're working in Python which is totally bizarre to me with how they go about exceptions ("leap before you look"), normally the process of throwing exceptions is best utilized for external errors.

By external errors, I mean things you cannot help and are outside of your control. For example, trying to open a file might fail due to some environmental condition in the operating system (maybe the hard disk is full). Your program can't really help that so much. Maybe the user interrupted and aborted the middle of a loading process -- you can't anticipate that. Maybe allocating memory failed. All of these errors are the result of errors occurring externally, outside of your code.

This is the most natural place from which to throw an exception.

Programmer errors may or may not be tackled through exceptions. In C++, it's often discouraged in favor of an assertion mindset to catch programmer mistakes like accessing an array out of bounds, but I think C# might encourage throwing here. So a programmer mistake may or may not involve throwing exceptions depending on the language.

Outside of Python which has this "leap before you look" philosophy, generally you shouldn't throw for non-errors. By a non-error, I mean trying to find a key in a map and failing to find it. That's not an error so much as just a very valid post-condition for a find function (it didn't find it, very ordinary thing).

Throwing

When you throw an exception, you are reporting an error. The idea is completely decoupled from catching. Don't think about where an exception will be caught or how it will caught when you throw. That would tend to couple your function to the transaction and the call stack, and reduce generality. Potentially you might reuse this function in various transactions, but it can fail the same way. Throwing is kind of a shortcut to avoid manually having to return error; return error; return error; all the way down to the catch site, but try not to look at it that way so much.

Throwing is about reporting an error. It's broadcasting it to whomever is interested.

Throwing is Expensive

If this conceptual model of avoiding the throw for non-errors (like failing to find an item) is confusing, it's worth noting that throwing an exception can be very expensive (depending on language/compiler). Some implementations have to kind of suspend threads and stop the entire world.

You might equate it to the cost of a disk access. I don't know how expensive it is exactly and it seems to vary wildly from one language/compiler to another (in Python I imagine it has to be cheap), all you might need to know is that it is expensive. And that's why we don't want to necessarily use it to just report back non-errors to the caller that a key isn't found in a dictionary, e.g., in languages where this kind of thing isn't idiomatic. It's not a general branching mechanism, it's for genuinely exceptional paths.

Rethrow vs. Throw New

With transactions, you also have sub-transactions. For example, let's say that in the process of loading an HTML file (trying to do this in a transaction), and you come across an image tag specifying an image file.

Now you might start a sub-transaction to load an image, and perhaps we fail to load the image and encounter an exception. In that case, you might catch it inside your nested image transaction.

try
{
   // Load image file and add the image to the webpage.
}
catch (Exception ex)
{
   // We ran into an error loading the image.
}
finally
{
   // Close image file if it's open
}

However, this is a sub-transaction. We've encountered an error loading the image but it's also an outer error in loading the HTML file. As a result, we don't want to simply catch the exception and return from the function. We need to throw again. Here you can do one of two things:

catch (Exception ex)
{
    // Translate the exception into a more meaningful one
    // for the user.
    throw new ImageException(...); // can embed a message containing
                                   // details about what happened.
}

Swallowing up an exception and translating it this way might sometimes be useful if you want to try to report the error in a less "raw" kind of way to the caller of your image loading function.

... or you can do this:

catch (Exception ex)
{
    // Simply throw the same exception to the outer transaction.
    throw;
}

... and simply pass the original exception back to the caller.

Which one you choose here is more of a design decision, whether you want to simply forward the exact same exception to the outer transaction that invoked the image loader or translate it into some kind of specific image loading exception.

It's up to you and will be based on how rich you want the error reporting to be. I personally prefer dealing with fewer exception types and catching more generally since most of the time I don't find much use for an exception type beyond just grabbing the message attached, but that may be my C++ side speaking where programmer errors aren't reported through exceptions (they don't point out mistakes, only those external input errors outside of our control that can occur even when our code is perfectly correct).

In cases where exceptions are used in a debugging context more than just a "report what happened to the user" kind of mindset, you might find it very helpful to know exactly what kind of exception was thrown, and catch more specifically when possible as well as throwing a wider range of exception types.


问:
Broken Old/Legacy Unit Tests
I work for a big company and I'm responsible for a large java application with thousands of junit tests.  Since I moved to this role, there have been 200-300 broken tests (likely broken for years).  The tests are old and fragile and they're a mess of spaghetti dependencies that typically end with live sandbox data.

My goal is 100% passing tests so we can break the build on unit test failures, but I can't do it until I address the broken tests. I have very little budget because the maintenance budget is primarily for support, but my team has identified and fixed the low-hanging fruit tests (mostly config/local resource issues) and we're down to 30-40 really ugly tests.

What are some opinions on best practice?  I don't think the tests are valuable, but I also don't know what they're testing or why they don't work without digging in, which takes time and money we probably don't have.

I'm thinking we should document the statuses of the broken tests with anything we know, then either delete or ignore the broken tests completely and enter a lower-priority bug/work item to investigate and fix them.  We'll then be at 100% and start to get real value out of the other tests and if we have a maintenance/refactoring windfall we'll be able to pick them up again.

What would be the best approach?

Edit: I think this is a different question than this question because I have a clear direction for the tests that we should be writing going forward, but I inherited legacy failing tests to address before the large current set of tests becomes meaningful.

答:
Any failing unit test should cause the build to be broken.  Good on you for realizing it and setting that goal.  The human mind can hardly ignore anything more completely than the source of a persistent false alarm.

Throw these tests away and don't look back.  If they have been failing for years and haven't been addressed by now then they are not a priority.

As for tribal knowledge, if the people with the tribal knowledge are still around they should have fixed the failing tests by now.  If not, then again, these are not a priority.

If there is no tribal knowledge, you and your team have to take ownership of the logic.  The failing tests may be more misleading than helpful - the world may have moved on.

Create new tests that are relevant and get on with writing great code.

Title: Broken Old/Legacy Unit Tests


问:
Multiple inheritance use cases
Java omits multiple inheritance on the grounds that it obviates the design goal of keeping the language simple.

I wonder if Java (with its eco-system) is really "simple". Python is not complex and has multiple inheritance. So without being too subjective, my question is...

What are the typical problem patterns that benefit from a code designed to make heavy use of multiple inheritance

答:
What are the typical problem patterns that benefit from a code
  designed to make heavy use of multiple inheritance?

This is just one example but one I find invaluable to improve safety and mitigate temptations to apply cascading changes throughout either callers or subclasses.

Where I've found multiple inheritance incredibly useful even for the most abstract, stateless interfaces is the non-virtual interface idiom (NVI) in C++.

They're not even really abstract base classes so much as interfaces that have just a little bit of implementation to them to enforce the universal aspects of their contracts, as they're not really narrowing the generality of the contract so much as better enforcing it.

Simple example (some might check that a file handle passed in is open or something like that):

// Non-virtual interface (public methods are nonvirtual/final).
// Since these are modeling the concept of "interface", not ABC,
// multiple will often be inherited ("implemented") by a subclass.
class SomeInterface
{
public:
    // Pre: x should always be greater than or equal to zero.
    void f(int x) /*final*/
    {
        // Make sure x is actually greater than or equal to zero
        // to meet the necessary pre-conditions of this function.
        assert(x >= 0);

        // Call the overridden function in the subtype.
        f_impl(x);
    }

protected:
    // Overridden by a boatload of subtypes which implement
    // this non-virtual interface.
    virtual void f_impl(int x) = 0;
};
```

In this case, maybe f is called by a thousand places in the codebase, while f_impl is overridden by a hundred subclasses.

It would be difficult to do this kind of safety check in all 1000 places that call f or all 100 places that override f_impl.

By just making this entry point to the functionality nonvirtual, it gives me one central place to perform this check. And this check is not reducing the abstraction in the slightest, as it is simply asserting a precondition required to call this function. In a sense, it's arguably strengthening the contract provided by the interface, and relieving the burden of checking the x input to make sure it conforms to valid preconditions in all 100 places that override it.

It's something I wish every language had, and also wished, even in C++, that it was a little more of a native concept (ex: not requiring us to define a separate function to override).

This is extremely useful if you didn't do this assert in advance, and realized you needed it later when some random places in the codebase were encountering negative values being passed to f.

Title: Multiple inheritance use cases

Body:
What are the typical problem patterns that benefit from a code
  designed to make heavy use of multiple inheritance?

This is just one example but one I find invaluable to improve safety and mitigate temptations to apply cascading changes throughout either callers or subclasses.

Where I've found multiple inheritance incredibly useful even for the most abstract, stateless interfaces is the non-virtual interface idiom (NVI) in C++.

They're not even really abstract base classes so much as interfaces that have just a little bit of implementation to them to enforce the universal aspects of their contracts, as they're not really narrowing the generality of the contract so much as better enforcing it.

Simple example (some might check that a file handle passed in is open or something like that):

// Non-virtual interface (public methods are nonvirtual/final).
// Since these are modeling the concept of "interface", not ABC,
// multiple will often be inherited ("implemented") by a subclass.
class SomeInterface
{
public:
    // Pre: x should always be greater than or equal to zero.
    void f(int x) /*final*/
    {
        // Make sure x is actually greater than or equal to zero
        // to meet the necessary pre-conditions of this function.
        assert(x >= 0);

        // Call the overridden function in the subtype.
        f_impl(x);
    }

protected:
    // Overridden by a boatload of subtypes which implement
    // this non-virtual interface.
    virtual void f_impl(int x) = 0;
};

In this case, maybe f is called by a thousand places in the codebase, while f_impl is overridden by a hundred subclasses.

It would be difficult to do this kind of safety check in all 1000 places that call f or all 100 places that override f_impl.

By just making this entry point to the functionality nonvirtual, it gives me one central place to perform this check. And this check is not reducing the abstraction in the slightest, as it is simply asserting a precondition required to call this function. In a sense, it's arguably strengthening the contract provided by the interface, and relieving the burden of checking the x input to make sure it conforms to valid preconditions in all 100 places that override it.

It's something I wish every language had, and also wished, even in C++, that it was a little more of a native concept (ex: not requiring us to define a separate function to override).

This is extremely useful if you didn't do this assert in advance, and realized you needed it later when some random places in the codebase were encountering negative values being passed to f.


答:
The purpose of an exception is: To halt execution because an error occurred and you cannot do the next operation.

The purpose of catching an exception is: To retry if possible or do whatever other corrective measures you may in the event of the given error scenario your application is in.

in C# an Exception is an object which:

Inherits from the System.Exception class

May be instantiated just like any exception by writing new WhateverException();

May be thrown with the syntax: throw instanceOfAnException;

May be caught with a catch statement that specifies the type of exception or any base-class that exception inherits from.

Since all exceptions inherit from System.Exception you can catch any exception with the clause catch(Exception e) { /* ... */ }

May be thrown again from inside a catch block with the statement throw; without needing to specify the instance being thrown (it automatically re-throws the exception instance that had been caught)

When an exception is thrown

The current statement block terminates immediately where it is, and checks if there's a catch block in it's parent blocks scope.

If no catch is found right away, it "bubbles up" scopes through statement blocks and functions terminating each one exactly where it is, and looking for a catch block which would match it's type or one it derives from.

If no catch is found all the way up to the main(), then the main() will terminate ending the entire application process.

If a matching catch is found, the application begins executing at the point of that catch block, and continues on from there.

A catch block

May specify a type of Exception it catches.

If it does, that type and any types that inherit from it will be caught in this block if they aren't caught in a lower-scope.

If it does not, any and all Exceptions that are thrown will be caught in this block.

May specify a variable name so that the Exception is addressable as a variable when caught as catch(Exception variableName) { /* do stuff with variableName here */ }

Does not have to specify a variable name and may simply catch(SomeExceptionType) { /* the exception is not available here */ }

May throw; without specifying which exception to throw and it will simply throw the exact Exception that was caught.


问:
Does it make sense to use the term "Space Leak" with regard to Java?
I stumbled across some posts on the main stackoverflow community about whether you can have a 'memory leak' in Java and it (maybe unsurprisingly) creates a lot of contentious debate.  At some point I had decided that Java applications don't have memory leaks (or have them all the time depending on how you look at it) but rather have 'space leaks'.

I can't recall where I got this term from did a quick search to make sure I hadn't dreamed it up or something and it seems to be used with regard to Haskell and lazy evaluation.  Here, I found a concise definition that appears to be authoritative.

A space leak occurs when a computer program uses more memory than
  necessary. In contrast to memory leaks, where the leaked memory is
  never released, the memory consumed by a space leak is released, but
  later than expected.

The concept of a 'memory leak' as I was taught back in the previous century was caused by losing track of memory without deallocating it.  It's something you can detect without understanding the program which is why it's the exact condition that a GC uses to know what is garbage.  What people refer to as 'memory leaks' in Java seem to me to be more closely aligned with the term 'space leak' because the application is still referencing the offending memory when it really doesn't need to.

I feel like this distinction would help bring some clarity to discussions about managed memory languages but I'm not sure if it's too much of a stretch?  Maybe it's too late but I think it would be best to keep the term 'memory leak' specific and not overload it to also apply to something that produces similar results but has different causes.

To clarify, I am not suggesting that leaks don't happen in a managed application.  I'm simply pondering about how we talk about them.  There are some highly upvoted discussions about memory leaks and Java that contain flame wars with 'fanboy' slurs and such that center around this exact question.  Actually given that even my question is misunderstood tells me that this is an issue of terminology.

答:
In C you can allocate memory for an object, discard all references to it, and then your program can never reliably recover that memory.  Programs that do this repeatedly end up consuming a lot of memory—typically more and more as time goes by.

In Java that cannot happen, because garbage collection will recover the memory of all unreachable objects.  What does happen often in Java is that an object will retain references to others that the program no longer needs, and these will accumulate with time until the program gets an OutOfMemoryError.

Both of these scenarios are popularly called "space leaks" by thousands and thousands of programmers, but it's important to note that this is not a dispute over facts.  There are countless thousands of knowledgeable people who understand the factual difference here and yet use the same term for both.

So your question is entirely terminological, and the best advice I can give is that whenever you see the term "space leak" you have to judge which of these two situations the author is talking about, based on the context.


问:
MIT License - Dual Authors
For an open source project created by 2 authors, is it proper for an MIT License to have two authors?</p>

```<code>The MIT License (MIT)

Copyright (c) 2016 FIRST NAME and SECOND NAME
</code>```

Title: MIT License - Dual Authors

Body: Yes.


问:
Java Heap Allocation Faster than C++
I already posted this question on SO and it did ok. It was unfortunately closed though(only needs one vote to reopen) but someone suggested I post it on here as it is a better fit so the following is literally a copy paste of the question

I was reading the comments on this answer and I saw this quote.

Object instantiation and object-oriented features are blazing fast to use (faster than C++ in many cases) because they're designed in from the beginning. and Collections are fast. Standard Java beats standard C/C++ in this area, even for most optimized C code.

One user (with really high rep I might add) boldly defended this claim, stating that

heap allocation in java is better than C++'s

and added this statement defending the collections in java

And Java collections are fast compared to C++ collections due largely to the different memory subsystem.

So my question is can any of this really be true, and if so why is java's heap allocation so much faster.

答:
Eden Space

So my question is can any of this really be true, and if so why is
  java's heap allocation so much faster.

I've been studying a bit about how the Java GC works since it's very interesting to me. I'm always trying to expand my collection of memory allocation strategies in C and C++ (interested in trying to implement something similar in C), and it is a very, very fast way to allocate a lot of objects in a burst fashion from a practical perspective but primarily due to multithreading.

The way the Java GC allocation works is to use an extremely cheap allocation strategy to initially allocate objects to "Eden" space. From what I can tell, it's using a sequential pool allocator.

That's a whole lot faster just in terms of algorithm and reducing compulsory page faults than general-purpose malloc in C or default, throwing operator new in C++.

But sequential allocators have a glaring weakness: they can allocate variable-sized chunks, but they can't free any individual chunks. They just allocate in a straight sequential fashion with padding for alignment, and can only purge all the memory they allocated at once. They're useful typically in C and C++ for constructing data structures which only need insertions and no removals of elements, like a search tree which only needs to be built once when a program starts and then is repeatedly searched or only has new keys added (no keys removed).

They can also be used even for data structures that allow elements to be removed, but those elements won't actually be freed from memory since we can't deallocate them individually. Such a structure using a sequential allocator would just consume more and more memory, unless it had some deferred pass where the data was copied to a fresh, compacted copy using a separate sequential allocator (and that's sometimes a very effective technique if a fixed allocator won't do for some reason -- just straight up sequentially allocate a new copy of the data structure and dump all the memory of the old one).

Collection

As in the data structure/sequential pool example above, it would be a huge problem if Java GC only allocated this way even though it's super fast for a burst allocation of many individual chunks. It wouldn't be able to free anything until the software is shut down, at which point it could free (purge) all the memory pools all at once.

So, instead, after a single GC cycle, a pass is made through existing objects in "Eden" space (sequentially allocated), and ones that are still referenced then get allocated using a more general-purpose allocator capable of freeing individual chunks. Ones that are no longer referenced will simply be deallocated in the process of purging. So basically it's "copy objects out of Eden space if they're still referenced, and then purge".

This would normally be quite expensive, so it's done in a separate background thread to avoid significantly stalling the thread that originally allocated all the memory.

Once memory is copied out of Eden space and allocated using this more expensive scheme that can free individual chunks after an initial GC cycle, the objects move to a more persistent memory region. Those individual chunks are then freed in subsequent GC cycles if they cease to become referenced.

Speed

So, put crudely, the reason the Java GC might very well outperform C or C++ at straight heap allocation is because it's using the cheapest, totally degeneralized allocation strategy in the thread requesting to allocate memory. Then it saves the more expensive work that we would normally need to do when using a more general allocator like straight-up malloc for another thread.

So conceptually the GC actually has to do overall more work, but it's distributing that across threads so that the full cost is not paid upfront by a single thread. It allows the thread allocating memory to do it super cheap, and then deferring the true expense required to do things properly so that individual objects can actually be freed to another thread. In C or C++ when we malloc or call operator new, we have to pay the full cost upfront within the same thread.

This is the main difference, and why Java might very well outperform C or C++ using just naive calls to malloc or operator new to allocate a bunch of teeny chunks individually. Of course there is typically going to be some atomic operations and some potential locking when the GC cycle kicks in, but it's probably optimized quite a bit.

Basically the simple explanation boils down to paying a heavier cost in a single thread (malloc) vs. paying a cheaper cost in a single thread and then paying the heavier cost in another that can run in parallel (GC). As a downside doing things this way implies that you require two indirections to get from object reference to object as required to allow the allocator to copy/move the memory around without invalidating existing object references, and also you can lose spatial locality once object memory is moved out of "Eden" space.

Last but not least, the comparison is a bit unfair because C++ code doesn't normally allocate a boatload of objects individually on the heap. Decent C++ code tends to allocate memory for many elements in contiguous blocks or on the stack. If it allocates a boatload of tiny objects one at a time on the free store, the code is shite.

Title: Java Heap Allocation Faster than C++


问:
SRP. Save to repository when edit. Internally or externally?
For example:

```<code>class Data {
    private String field1;
    private String field2;

    public void someEditMethod() {}
}

class DataRepository {
    public void save(Data data) {
        // save to DB
    }
}
</code>```

I need save Data when editing.

How better?

internally:

```<code>....
public void someEditMethod() {
    repo.save(this);
}
....
</code>```

or externally:

```<code>....
DataRepository repo = new DataRepository(dbConnection);
Data data = new Data(repo);
data.someEditMethod();
....
</code>```

Externally is uncomfortably, and I do not want to impose class customers knowledge about the repository.

答:
You are mixing repository and active record together. If you want to use repository in the true sense (such as M. Fowler suggests), the external approach is what you want to go for, but external in a different way than your proposed design.

With repository the process should look something like this:

```<code>DataRepository repo = new DataRepository(dbConnection);
Data data = repo.GetData();
data.someEditMethod();
repo.Save(data);
</code>```

If you want to use the internal approach, then the design is called active record - an entity which knows about its persistence (and although it is frown upon as an anti-pattern it can sometimes be better than use the repository approach).

The active record is not very popular in enterprise world, because the entities which usually know about their persistence also include business logic and thus mix two reponsibilities.

Body:
You are mixing repository and active record together. If you want to use repository in the true sense (such as M. Fowler suggests), the external approach is what you want to go for, but external in a different way than your proposed design.

With repository the process should look something like this:

DataRepository repo = new DataRepository(dbConnection);
Data data = repo.GetData();
data.someEditMethod();
repo.Save(data);

If you want to use the internal approach, then the design is called active record - an entity which knows about its persistence (and although it is frown upon as an anti-pattern it can sometimes be better than use the repository approach).

The active record is not very popular in enterprise world, because the entities which usually know about their persistence also include business logic and thus mix two reponsibilities.