答:
In order to define what a service's responsibilities are, you first need to define what a service is.

Service is not a canonical or generic software term. In fact, the suffix Service on a class name is a lot like the much-maligned Manager: It tells you almost nothing about what the object actually does.

In reality, what a service ought to do is highly architecture-specific:

In a traditional layered architecture, service is literally synonymous with business logic layer. It's the layer between UI and Data. Therefore, all business rules go into services. The data layer should only understand basic CRUD operations, and the UI layer should deal only with the mapping of presentation DTOs to and from the business objects.

In an RPC-style distributed architecture (SOAP, UDDI, BPEL, etc.), the service is the logical version of a physical endpoint. It is essentially a collection of operations that the maintainer wishes to provide as a public API. Various best practices guides explain that a service operation should in fact be a business-level operation and not CRUD, and I tend to agree.

However, because routing everything through an actual remote service can seriously hurt performance, it's normally best not to have these services actually implement the business logic themselves; instead, they should wrap an "internal" set of business objects. A single service might involve one or several business objects.

In an MVP/MVC/MVVM/MV* architecture, services don't exist at all. Or if they do, the term is used to refer to any generic object that can be injected into a controller or view model. The business logic is in your model. If you want to create "service objects" to orchestrate complicated operations, that's seen as an implementation detail. A lot of people, sadly, implement MVC like this, but it's considered an anti-pattern (Anemic Domain Model) because the model itself does nothing, it's just a bunch of properties for the UI.

Some people mistakenly think that taking a 100-line controller method and shoving it all into a service somehow makes for a better architecture. It really doesn't; all it does is add another, probably unnecessary layer of indirection. Practically speaking, the controller is still doing the work, it's just doing so through a poorly named "helper" object. I highly recommend Jimmy Bogard's Wicked Domain Models presentation for a clear example of how to turn an anemic domain model into a useful one. It involves careful examination of the models you're exposing and which operations are actually valid in a business context.

For example, if your database contains Orders, and you have a column for Total Amount, your application probably shouldn't be allowed to actually change that field to an arbitrary value, because (a) it's history and (b) it's supposed to be determined by what's in the order as well as perhaps some other time-sensitive data/rules. Creating a service to manage Orders does not necessarily solve this problem, because user code can still grab the actual Order object and change the amount on it. Instead, the order itself should be responsible for ensuring that it can only be altered in safe and consistent ways.

In DDD, services are meant specifically for the situation when you have an operation that doesn't properly belong to any aggregate root. You have to be careful here, because often the need for a service can imply that you didn't use the correct roots. But assuming you did, a service is used to coordinate operations across multiple roots, or sometimes to handle concerns that don't involve the domain model at all (such as, perhaps, writing information to a BI/OLAP database).

One notable aspect of the DDD service is that it is allowed to use transaction scripts. When working on large applications, you're very likely to eventually run into instances where it's just way easier to accomplish something with a T-SQL or PL/SQL procedure than it is to fuss with the domain model. This is OK, and it belongs in a Service.

This is a radical departure from the layered-architecture definition of services. A service layer encapsulates domain objects; a DDD service encapsulates whatever isn't in the domain objects and doesn't make sense to be.

In a Service-Oriented Architecture, a service is considered to be the technical authority for a business capability. That means that it is the exclusive owner of a certain subset of the business data and nothing else is allowed to touch that data - not even to just read it.

By necessity, services are actually an end-to-end proposition in an SOA. Meaning, a service isn't so much a specific component as an entire stack, and your entire application (or your entire business) is a set of these services running side-by-side with no intersection except at the messaging and UI layers. Each service has its own data, its own business rules, and its own UI. They don't need to orchestrate with each other because they are supposed to be business-aligned - and, like the business itself, each service has its own set of responsibilities and operates more or less independently of the others.

So, by the SOA definition, every piece of business logic anywhere is contained within the service, but then again, so is the entire system. Services in an SOA can have components, and they can have endpoints, but it's fairly dangerous to call any piece of code a service because it conflicts with what the original "S" is supposed to mean.

Since SOA is generally pretty keen on messaging, the operations that you might have packaged in a service before are generally encapsulated in handlers, but the multiplicity is different. Each handler handles one message type, one operation. It's a strict interpretation of the Single Responsibility Principle, but makes for great maintainability because every possible operation is in its own class. So you don't really need centralized business logic, because commands represents business operations rather than technical ones.

Ultimately, in any architecture you choose, there is going to be some component or layer that has most of the business logic. After all, if business logic is scattered all over the place then you just have spaghetti code. But whether or not you call that component a service, and how it's designed in terms of things like number or size of operations, depends on your architectural goals.

There's no right or wrong answer, only what applies to your situation.

Title: How accurate is "Business logic should be in a service, not in a model"?

Body:
Situation

Earlier this evening I gave an answer to a question on StackOverflow.

The question:

Editing of an existing object should be done in repository layer or in service?

For example if I have a User that has debt. I want to change his debt. Should I do it in UserRepository or in service for example BuyingService by getting an object, editing it and saving it ?

My answer:

You should leave the responsibility of mutating an object to that same object and use the repository to retrieve this object.

Example situation:

class User {
    private int debt; // debt in cents
    private string name;

    // getters

    public void makePayment(int cents){
        debt -= cents;
    }
}

class UserRepository {
    public User GetUserByName(string name){
        // Get appropriate user from database
    }
}
```

<p><em>A comment I received:</em></p>

<blockquote>
  <p>Business logic should really be in a service. Not in a model.</p>
</blockquote>

<p><strong>What does the internet say?</strong></p>

<p>So, this got me searching since I've never really (consciously) used a service layer.
I started reading up on the Service Layer pattern and the Unit Of Work pattern but so far I can't say I'm convinced a service layer has to be used.</p>

<p>Take for example this article by Martin Fowler on the anti-pattern of an Anemic Domain Model:</p>

<blockquote>
  <p>There are objects, many named after the nouns in the domain space, and these objects are connected with the rich relationships and structure that true domain models have. The catch comes when you look at the behavior, and you realize that there is hardly any behavior on these objects, making them little more than bags of getters and setters. Indeed often these models come with design rules that say that you are not to put any domain logic in the the domain objects. Instead there are a set of service objects which capture all the domain logic. These services live on top of the domain model and use the domain model for data.</p>

  <p>(...)  The logic that should be in a domain object is domain logic - validations, calculations, business rules - whatever you like to call it.</p>
</blockquote>

<p>To me, this seemed exactly what the situation was about: I advocated the manipulation of an object's data by introducing methods inside that class that do just that. However I realize that this should be a given either way, and it probably has more to do with how these methods are invoked (using a repository).</p>

<p>I also had the feeling that in that article (see below), a Service Layer is more considered as a façade that delegates work to the underlying model, than an actual work-intensive layer.</p>

<blockquote>
  <p>Application Layer [his name for Service Layer]: Defines the jobs the software is supposed to do and directs the expressive domain objects to work out problems. The tasks this layer is responsible for are meaningful to the business or necessary for interaction with the application layers of other systems. This layer is kept thin. It does not contain business rules or knowledge, but only coordinates tasks and delegates work to collaborations of domain objects in the next layer down. It does not have state reflecting the business situation, but it can have state that reflects the progress of a task for the user or the program.</p>
</blockquote>

<p>Which is reinforced here:</p>

<blockquote>
  <p>Service interfaces. Services expose a service interface to which all inbound messages are sent. You can think of a service interface as a façade that exposes the business logic implemented in the application (typically, logic in the business layer) to potential consumers.</p>
</blockquote>

<p>And here:</p>

<blockquote>
  <p>The service layer should be devoid of any application or business logic and should focus primarily on a few concerns. It should wrap Business Layer calls, translate your Domain in a common language that your clients can understand, and handle the communication medium between server and requesting client.</p>
</blockquote>

<p>This is a serious contrast to other resources that talk about the Service Layer:</p>

<blockquote>
  <p>The service layer should consist of classes with methods that are units of work with actions that belong in the same transaction.</p>
</blockquote>

<p>Or the second answer to a question I've already linked:</p>

<blockquote>
  <p>At some point, your application will want some business logic. Also, you might want to validate the input to make sure that there isn't something evil or nonperforming being requested. This logic belongs in your service layer.</p>
</blockquote>

<p><strong>"Solution"?</strong></p>

<p>Following the guidelines in this answer, I came up with the following approach that uses a Service Layer:</p>

<pre class="lang-cs prettyprint-override"><code>class UserController : Controller {
    private UserService _userService;

    public UserController(UserService userService){
        _userService = userService;
    }

    public ActionResult MakeHimPay(string username, int amount) {
        _userService.MakeHimPay(username, amount);
        return RedirectToAction("ShowUserOverview");
    }

    public ActionResult ShowUserOverview() {
        return View();
    }
}

class UserService {
    private IUserRepository _userRepository;

    public UserService(IUserRepository userRepository) {
        _userRepository = userRepository;
    }

    public void MakeHimPay(username, amount) {
        _userRepository.GetUserByName(username).makePayment(amount);
    }
}

class UserRepository {
    public User GetUserByName(string name){
        // Get appropriate user from database
    }
}

class User {
    private int debt; // debt in cents
    private string name;

    // getters

    public void makePayment(int cents){
        debt -= cents;
    }
}
</code>```

Conclusion

All together not much has changed here: code from the controller has moved to the service layer (which is a good thing, so there is an upside to this approach). However this doesn't look like it had anything to do with my original answer.

I realize design patterns are guidelines, not rules set in stone to be implemented whenever possible. Yet I have not found a definitive explanation of the service layer and how it should be regarded.

Is it a means to simply extract logic from the controller and put it inside a service instead?

Is it supposed to form a contract between the controller and the domain?

Should there be a layer between the domain and the service layer?

And, last but not least: following the original comment

Business logic should really be in a service. Not in a model.

Is this correct?

How would I introduce my business logic in a service instead of the model?


问:
What is the difference between all-static-methods and applying a singleton pattern?
I am making a database to store information about the users of my website (I am using stuts2 and hence Java EE technology). For the database I'll be making a DBManager. Should I apply singleton pattern here or rather make all its methods static?

I will be using this DBManager for basic things like adding, deleting and updating User profiles. Also, I'll use it for all other querying purposes, for instance to find out whether a username already exists and to get all users for administrative purposes and stuff like that.

My questions:

What is the benefit of singleton pattern?

Which thing is most apt here? All static methods or a singleton pattern?

Please compare both of them.

P.S. The database is bigger than this. Here I am talking only about the tables which I'll be using for storing User Information.

答:
Neither is ideal, but especially not a bunch of statics.  Here's a real world example from my experience.  We talked to a database.  Everybody said "there will only be one", so somebody used a standard singleton configured by Spring.  Then there was a new requirement added: to be able to copy our data to another (remote) database.  Oops.  Since we had an actual Object representing the DB, and this was a "rarely used" feature, I was able to hack it by making a temp copy and changing fields and values, but had this been implemented with global statics it would have been a real disaster.

In my experience, when "they" say that there will be only one DB, one user, one application, one main window, etc., "they" are wrong.  With a Singlton you at least have a chance to refactor and fix it.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
When are Getters and Setters Justified?
Getters and setters are often criticized as being not proper OO. On the other hand, most OO code I've seen has extensive getters and setters.

When are getters and setters justified? Do you try to avoid using them? Are they overused in general?

If your favorite language has properties (mine does) then such things are also considered getters and setters for this question. They are the same thing from an OO methodology perspective. They just have nicer syntax.

Sources for Getter/Setter Criticism (some taken from comments to give them better visibility):

http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html

http://typicalprogrammer.com/?p=23

http://c2.com/cgi/wiki?AccessorsAreEvil

http://www.darronschall.com/weblog/2005/03/no-brain-getter-and-setters.cfm

http://www.adam-bien.com/roller/abien/entry/encapsulation_violation_with_getters_and

http://www.yegor256.com/2014/09/16/getters-and-setters-are-evil.html

To state the criticism simply: Getters and Setters allow you to manipulate the internal state of objects from outside of the object. This violates encapsulation. Only the object itself should care about its internal state.

And an example

Procedural version of code:

```<code>struct Fridge
{
    int cheese;
}

void go_shopping(Fridge fridge)
{
     fridge.cheese += 5;
}
</code>```

Mutator version of code:

```<code>class Fridge
{
     int cheese;

     void set_cheese(int _cheese) { cheese = _cheese; }
     int get_cheese() { return cheese; }
 }

void go_shopping(Fridge fridge)
{
     fridge.set_cheese(fridge.get_cheese() + 5);
}
</code>```

The getters and setters made the code much more complicated without affording proper encapsulation. Because the internal state is accessible to other objects we don't gain a whole lot by adding these getters and setters.

The question has been previously discussed on Stack Overflow:

https://stackoverflow.com/questions/565095/java-are-getters-and-setters-evil

https://stackoverflow.com/questions/996179

答:
From http://www.adam-bien.com/roller/abien/entry/encapsulation_violation_with_getters_and

JavaBean style:

```<code>connection.setUser("dukie");
connection.setPwd("duke");
connection.initialize();
</code>```

OO-style:

```<code>connection.connect("dukie","duke");
</code>```

Well, clearly I prefer the latter approach; it doesn't bleed implementation details, it's simpler and more concise, and all of the needed information is included with the method call, so it's easier to get it right.  I also prefer setting private members using parameters in the constructor, whenever possible.

Your question is, when is a getter/setter justified?  Perhaps when a mode change is needed, or you need to interrogate an object for some information.

```<code>myObject.GetStatus();
myObject.SomeCapabilitySwitch = true;
</code>```

In thinking about it, when I first started coding in C#, I wrote a lot of code in the Javabeans style illustrated above.  But as I gained experience in the language, I began doing more setting of members in the constructor, and using methods that looked more like the above OO style.

Title: When are Getters and Setters Justified?

Body:
From http://www.adam-bien.com/roller/abien/entry/encapsulation_violation_with_getters_and

JavaBean style:

connection.setUser("dukie");
connection.setPwd("duke");
connection.initialize();

OO-style:

connection.connect("dukie","duke");

Well, clearly I prefer the latter approach; it doesn't bleed implementation details, it's simpler and more concise, and all of the needed information is included with the method call, so it's easier to get it right.  I also prefer setting private members using parameters in the constructor, whenever possible.

Your question is, when is a getter/setter justified?  Perhaps when a mode change is needed, or you need to interrogate an object for some information.

myObject.GetStatus();
myObject.SomeCapabilitySwitch = true;

In thinking about it, when I first started coding in C#, I wrote a lot of code in the Javabeans style illustrated above.  But as I gained experience in the language, I began doing more setting of members in the constructor, and using methods that looked more like the above OO style.

ContentLicense: CC BY-SA 2.5


问:
How do I create an environment where fixing tests is seen as a priority?
I am a software engineer at a medium sized company.  We have a fairly robust testing platform running on TeamCity.  It does unit tests on every checkin, and a daily unit test/BVT run.

The problem is - we have a great deal of broken unit tests.

Quite often, I bring up the pointlessness of unit tests if they are constantly breaking and unmaintained.  Being unable to see if a change has caused a regression removes most of the value of a unit testing platform.

I would like to get a seed planted that will create a culture of good habits - fixing tests when they're broken, seeing them as valuable, prioritizing the fixing of tests along with other work.

I've tried bribery (baked goods!), just plain asking, and speaking to team leads.  Everyone says that it's a good idea, but I see to be the only one doing anything about it.

What is the best way to get started on encouraging others to fix their tests, and prioritize test fixing within their sprints?

If there is a less subjective way to ask this, I would be happy to accept any tips.

答:
Units tests that fail are not the problem. They are a symptom.

The real problem is in the culture. You need to tread gently: here be dragons. You cannot change the culture by yourself, and being the squeaky wheel will, in the end, make you an outcast. Literally.

I suggest that if you try to find a senior person to champion the cause and lead the way. If that fails, try raising it in a general developers meeting, without pointing fingers or calling names. Another alternative is to take responsibility yourself for doing a proper job: just fix some more tests every time you do a check-in. Keep a chart on the wall showing how many tests fail over time. Others will see it: maybe they'll opt in.

There is no easy answer.


问:
Requirement gathering and use cases examples
I've heard a lot about requirement gathering and use cases in theory, but in practice often happens that we ask ourselves "should we include this? should this be a use case? in which language should we write this particular requirement" and so on. These questions are mainly because of lack of practice, and since we cannot go picking projects to "learn in practice" it's a little bit hard to get used to the kind of thinking we need in the process of gathering requirements for a new app.

In that case, is there some place where can I find real life examples of requirements gathering and application of use cases? I've found some books, but they are mainly focused on teams and I work alone, so it becomes a little confusing.

答:
You get use-cases from your users or clients.

Essentially, they drive the acceptance criteria.

Without talking to users or clients we can think of many possible use (patterns) for our software, but it's the users or clients who should be telling us which ones are the keys.

On the other hand, users will often come up with ways of using our software that we had never considered, and in the process find bugs. This is how successful software evolves and generates new requirements.

Think of use cases as user cases.


答:
A simple example. You assist a user who tests your e-commerce product. At some point, the user wants to get every product matching given tags within a price range. Currently, this is impossible, because the product allows to filter products by tags or to filter products by price, but not both at the same time.

The users' need would be:

I want to filter products by tags and prices. How do I do it?

Transformed into a user story, it would become:

As a user, I should be able to filter the list of products using both tags and prices criteria.

From that point, you may study the implications of the new change and start to write tests and implement the new feature.

Title: Requirement gathering and use cases examples

Body:
I've heard a lot about requirement gathering and use cases in theory, but in practice often happens that we ask ourselves "should we include this? should this be a use case? in which language should we write this particular requirement" and so on. These questions are mainly because of lack of practice, and since we cannot go picking projects to "learn in practice" it's a little bit hard to get used to the kind of thinking we need in the process of gathering requirements for a new app.

In that case, is there some place where can I find real life examples of requirements gathering and application of use cases? I've found some books, but they are mainly focused on teams and I work alone, so it becomes a little confusing.


问:
Do you believe it's a good idea for Software Engineers to have to work as Quality Assurance Engineers for some period of time?
I believe it is.  Why?

I've encountered many Software Engineers who believe they are somehow superior to QA engineers.  I think it may help quench this belief if they do the job of a QA engineer for some time, and realize that it is a unique and valuable skill-set of its own.

The better a Software Engineer is at testing their own programs, the less cost in time their code incurs when making its way through the rest of the software development life-cycle.

The more time a Software Engineer spends thinking about how a program can break, the more often they are to consider these cases as they are developing them, thus reducing bugs in the end product.

A Software Engineer's definition of "complete" is always interesting...if they have spent time as a QA engineer maybe this definition will more closely match the designer of the software's.

Note I make above suggestion with a small time-frame in mind as I am aware having someone work in a position that is not the position they are hired for is definitely a recipe for losing that developer.

What do you all think?

答:
1. I've encountered many Software Engineers who believe they are somehow superior to QA engineers. I think it may help quench this belief if they do the job of a QA engineer for some time, and realize that it is a unique and valuable skill-set of its own.

A good software engineering has a background in quality, including testing, metrics, and statistics. Anyone doing any kind of software development should be aware (if not familiar with) maintaining at quality source code and producing/maintaining effective test cases. Over time, I would suspect that any software developer would gain an understanding of the different facets of quality - code quality, portability, maintainability, testability, usability, reliability, efficiency, and security.

Software engineers might focus on a particular aspect of the lifecycle - requirements engineering, architecture and design, construction, testing, and maintenance. However, regardless of your focus (either as a job or at the current phase of the project), it's important to remember quality.

2. The better a Software Engineer is at testing their own programs, the less cost in time their code incurs when making its way through the rest of the software development life-cycle.

That might be true. But some issues are best seen later in development. For example, performance and efficiency issues might not be seen until integration. Having good, solid code and effective unit tests are just the beginning. Quality needs to begin with requirements, and follow all the way through maintenance activities.

3. The more time a Software Engineer spends thinking about how a program can break, the more often they are to consider these cases as they are developing them, thus reducing bugs in the end product.

That's a totally true statement. But then again, it's also up to the requirements engineers to verify that there are no conflicts in requirements, architects to ensure that the design actually addresses the requirements, and so on. Everyone should be trying to poke holes in their work and then working with the appropriate people to seal them up nice and tight.

4. A Software Engineer's definition of "complete" is always interesting...if they have spent time as a QA engineer maybe this definition will more closely match the designer of the software's.

"Complete" can only be measured against requirements. Either the requirements are satisfied and the project is complete, or there are incomplete requirements and the project is not complete. Any other measure of complete is useless.


问:
Generating a Nakagami Random Variable
Assuming the only tool for generating random numbers I have available is generating a uniformly distributed variable u on U(0,1). I want to generate a Nakagami Random Variable from it.

I know I could just plug u into the inverse CDF of the Nakagami distribution, but unfortunately, the inverse CDF isn't trivial to compute.

答:
Which difficulties do you have computing the CDF?  Special functions gamma and \Gamma are availble in scientific computing libraries.

If the CDF-based method will not do, you can generate Nagakami distributed numbers based on Gamma distributed numbers or Chi distributed numbers.  The methods are described in Wikipedia:

http://en.wikipedia.org/wiki/Nakagami_distribution

Title: Generating a Nakagami Random Variable


问:
Can relational algebra/calculus proofs be used to test/verify SQL?
Is it feasible or even possible to use relational algebra and/or relational calculus in the form of proofs to test/verify the correctness of SQL statements, functions, and stored procedures?

It seems to me like it should be at least possible, but I don't know if there's a detail I'm missing that makes a 1:1 mapping between the proof and the code incorrect.

Have any of you tried a method like this? Did it work? What were your experiences like?

答:
There are some known mapping rules between relational algebra operators and SQL statements. For example, the Sigma operator maps to a SELECT statement, there's a one-to-one mapping for the join operators, Delta maps to selecting a subset of columns, etc.

Is it possible to use relational algebra to verify the correctness of SQL statements?

Yes, it is possible. Of course you'll need to have a clear schema of the database with all the relationships, foreign keys, etc. In some cases it's even easier to manipulate relational algebra statements than SQL statements (there are proven transformation rules for modifying and simplifying statements).

But on the other hand, I don't think that verifying statements using relational algebra is much easier than testing SQL statements, especially when you have a database ready where you can execute the queries and see the results.


答:
In practice Requirement gathering should occur first and then followed by use cases (and you could have a feedback loop to verify the requirements). The case that you describe of "should we include this" , "should this be a use case" comes up mostly in product development environments. Making this choice is tricky based on your appetite for risk and your team.

If however you are trying to develop a solution for a client the question really is "Does the client need this" and nothing more. You may encounter situations where the client really does not know what he needs, in that case I would recommend you to go even deeper and understand the business problem that needs to be solved. Once that is clear the technical solution can follow. In such scenarios I would usually recommend short iterations and an incremental solution with active client participation.

In which language should we write this particular requirement

Are you implying a programming language ? In that case that is definitely the wrong question to ask during requirement gathering. The technical implementation is usually decided much after the requirement gathering phase.

First there should be a technical solution like say a web-app, mobile-app, middleware, integration , db solution etc.

You could have hints thereabout ofcourse if say your client has a .net shop or java shop or deals with a particular vendor or even worse is vendor locked-in. Even then the first thing should be the technical solution and based on time/budget/resources/misc conditions the technical implementation will evolve.

Unfortunately books can only hint at various scenarios, and the best learning is in practise.


问:
Why not expose a primary key
In my education I have been told that it is a flawed idea to expose actual primary keys (not only DB keys, but all primary accessors) to the user.

I always thought it to be a security problem (because an attacker could attempt to read stuff not their own).

Now I have to check if the user is allowed to access anyway, so is there a different reason behind it?

Also, as my users have to access the data anyway I will need to have a public key for the outside world somewhere in between. Now that public key has the same problems as the primary key, doesn't it?

There has been the request of an example on why do that anyway, so here is one.
Keep in mind that the question is meant to be about the principle itself not only if it applies in this example. Answers addressing other situations are explicitly welcome.

Application (Web, Mobile) that handles activity, has multiple UIs and at least one automated API for intersystem communication (e.G. the accounting department wants to know how much to charge the customer based on what has been done).
The Application has multiple customers so separation of their data (logically, the data is stored in the same DB) is a must have of the system. Each request will be checked for validity no matter what.

Activity is very fine granular so it is together in some container object, lets call it "Task".

Three usecases:

User A wants to send User B to some Task so he sends him a link (HTTP) to get some Activity done there.

User B has to go outside the building so he opens the Task on his mobile device.

Accounting wants to charge the customer for the Task, but uses a third party accounting system that automatically loads the Task / Activity by some code that refers to the REST - API of the Application

Each of the usecases requires (or gets easier if) the agent to have some addressable identifier for the Task and the Activity.

答:
This is a combination answer of the other ones (aka. what I have learned). If you feel like upvoting this one, you should at least upvote one of the other ones as well as they did the actual work. If you are more interested, read the other answers instead.

You should not expose the databases primary key but instead use a surrogate key

If you want your users to be able to remember (at least a bit) or recognize the identifier of an entry. (Graystone28s Answer)

If you want to plan ahead and consider that you might change systems (Database or otherwise) that will likely change your PK. (Telastyns Answer)

If you want to ensure your users have a consistent way of accessing data that wont change even if your company shifts ownership and the data is thous migrated into a different system altogether. (Michael Durrants Answer)

If your PK is predictable (like a sequence) your system can suffer resource harvest problems. (CodeCasters Answer) This only applies if your system has information that is worth harvesting and that is accessible by anybody or at least somebody who has a harvesting interest.

Note: Your created key should be (kinda) human comprehensible (Sqlvogels Answer).

If your system has no need for 1. to 4. then there is no reason not to use the databases PK as your public identifier (several of the answers). Also security is not an issue here (several of the answers).

Title: Why not expose a primary key


问:
Which specific practices could be called "software craftsmanship" rather than "software engineering"?
Although not a new idea there seems to have been a big increase in the interest in software craftsmanship over the last couple of years (notably the often recommended book Clean Code's full title is Clean Code: A Handbook of Agile Software Craftsmanship).

Personally I see software craftsmanship as good software engineering with an added interest in ensuring that the end result is a joy to work with (both as an end user and as someone maintaining that software) - and also that its focus is more at the coding level of things than the higher level process things.

To draw an analogy - there were lots of buildings constructed in the 50s and 60s in a very modern style which took very little account of the people who would be living in them or how those buildings would age over time. Many of those buildings rapidly developed into slums or have been demolished long before their expected lifespans. I'm sure most developers with a few years under their belts will have experienced similar codebases.

What are the specific things that a software craftsman might do that a software engineer (possibly a bad one) might not?

答:
Going by http://manifesto.softwarecraftsmanship.org/ I would derive the following.

A craftsman is different from traditional perceptions of an "engineer" because

They focus on value, not just meeting requirements.

They focus on quality even in the style of their code, not just meeting requirements.

They participate in the broader software development community, not just their workplace.

They don't just understand that today's state of the art is tomorrow's junk, they are active in bringing it about at one level or another.

It's not just a job, it's who they are.


问:
Is this an example of 'over engineered' or a good practice?
The code I've inherited has a design that I'm not familiar with (I'm still new to the world of programming).

It is a .net project and there are 3 classes in question here.

```<code>public Class1
{
    public void DoSomething()
    {
        Class2 class2 = new Class2();
        string myValue = class2.GetSomeValuePlease();

       //why would I not do class2.MyClass3.GetActualValue();
    }
}

public Class2
{
    public Class3 MyClass3 = new Class3();
    public string GetSomeValuePlease()
    {
        return this.MyClass3.TheActualValue();
    }
}

public Class3
{
    public string TheActualValue()
    {
        return "This is the value";
    }
}
</code>```

As you can see, all 3 classes are public. I don't understand why, using the example above, I would use Class2 at all? I could understand if within the GetSomeValuePlease() method there was some logic which affected Class2, but there isn't.

Normally, I'd just go ahead and remove the Class2 method (GetSomeValuePlease) and call Class3 method (GetActualValue) direct from Class1, but, the developer I took over (who is not contactable) is wiser and more experienced than I. I have a feeling this is just over engineering and this is just extra code / extra maintenance.

Does any one have experience in designing this way that could explain the thought process or implications of having this "middle class" vs going direct?

答:
Looks like the purpose of Class2 is to abstract away the implementation of Class3.

This allows Class3 to be changed in the future. Maybe the value will be grabbed from a database, maybe it will be read from a local file, maybe it will be read from the web.
Maybe it won't even be read from Class3 at all, maybe it will be read from Class4.

The abstraction makes it possible to change the implementation of getting a correct value without Class1 having to change any code.

This is a valid design pattern (see <s>Facade Pattern</s> Bridge Pattern). To say whether or not it is necessary, you'd need to provide the actual classes.


问:
Many JS files included, one breaks all, smart approach to fix?
I'm doing a project that uses svg-edit(JS drawing tool) and the page grows big. By now there are about 20 JS file in a page - plug-ins and so on.

One of the editor's files breaks in some kind of 'Uncaught TypeError' but it's compressed and can not understand anything.

I used several jquery plug-ins that are important for the usability of the page and it's not possible to remove any of them. There are severe conflicts obviously but I can't rewrite any of the plug-ins.

Any smart approach to fix this ? Where I can start ?

答:
The usual approach is to run with uncompressed files in development environment, and with compressed files in production environment.

This way, the development environment lets you find out where the error is, in a clear code. While the production environment benefits from compressing the files.

Of course, it means being able to run a development environment. You can, right?


答:
It's completely normal for entities have a unique identifier that is exposed to the outside world. For some objects it might be possible to find an identifier that actually has a meaning (for example invoice number) but for other no such identifier exists and therefore it has to be generated.

For the sake of consistency and readability I find it a good practice for all the entities in a system to use the exact same type and name for their identifier. Normally this identifier would be exposed (<type> getId()) in some abstract base class.

For the same reason each service in the system (for example invoice service) should provide identical methods for accessing entities by their identifier. Normally this method (findById(<type> id)) would be inherited from a generic service interface or base class.

This identifier doesn't have to be the primary key of the entity but it can be one. Only thing one has to ensure is that the key generation strategy produces reasonably unique identifiers (not necessary universally unique but at least within the system).

If the system is later migrated (big if in my experience) to another database then it's not a problem to use a different strategy (not based on primary keys) for creating the identifiers as long as the strategy is compatible with the original one.

Title: Why not expose a primary key

Body:
In my education I have been told that it is a flawed idea to expose actual primary keys (not only DB keys, but all primary accessors) to the user.

I always thought it to be a security problem (because an attacker could attempt to read stuff not their own).

Now I have to check if the user is allowed to access anyway, so is there a different reason behind it?

Also, as my users have to access the data anyway I will need to have a public key for the outside world somewhere in between. Now that public key has the same problems as the primary key, doesn't it?

There has been the request of an example on why do that anyway, so here is one.
Keep in mind that the question is meant to be about the principle itself not only if it applies in this example. Answers addressing other situations are explicitly welcome.

Application (Web, Mobile) that handles activity, has multiple UIs and at least one automated API for intersystem communication (e.G. the accounting department wants to know how much to charge the customer based on what has been done).
The Application has multiple customers so separation of their data (logically, the data is stored in the same DB) is a must have of the system. Each request will be checked for validity no matter what.

Activity is very fine granular so it is together in some container object, lets call it "Task".

Three usecases:

User A wants to send User B to some Task so he sends him a link (HTTP) to get some Activity done there.

User B has to go outside the building so he opens the Task on his mobile device.

Accounting wants to charge the customer for the Task, but uses a third party accounting system that automatically loads the Task / Activity by some code that refers to the REST - API of the Application

Each of the usecases requires (or gets easier if) the agent to have some addressable identifier for the Task and the Activity.


问:
Which is preferred coding style to validate and return from a method
Which of the below is a preferred coding style (in c# .net)

```<code>public void DoWork(Employee employee)
{
  if(employee == null)
   return;

  if(!string.IsNullOrEmpty(employee.Name))
   return;

  // Do Work

}
</code>```

or

```<code>public void DoWork(Employee employee)
{
  if(employee != null && !string.IsNullOrEmpty(employee.Name))
  {
    // Do Work
  }
}
</code>```

答:
When the first method fails it's easy to see which part has the issue.

In the second approach you don't know if it was the string being null or being empty that caused the return to happen.


问:
Opensource, noncommercial License?
i want to publish my software under a opensource license with the following conditions:

you are allowed to:

Share — to copy, distribute and transmit the work

use a modified version of the code in your application

you are not allowed to:

publish modified versions of the code

use the code in anything commercial

Is there a software license out there that fits my needs ?

(crosspost: https://stackoverflow.com/questions/4558546/opensource-noncommercial-license)

答:
The CC-NC-ND (Creative Commons - non-commercial - no derivates) license would fit your model.

But keep in mind that a "non-commercial" clause in a license is often much more restrictive than intended. "Not anything commercial" can also mean, for example:

It can not be added as a freebie on something which is sold (like a DVD of freeware which comes with a magazine)

It can not be bundled with something which might be used commercially (like a Linux distribution)

It can not be offered for download on a website which has paid advertising

It can not be used to practice a skill and then apply that skill commercially

It can not be used by non-profit organizations which perform commercial activity to cover their costs (this could even include collecting donations).

Commercial media is not allowed to review it, because testing it to write an article about it would also be commercial activity.

When someone uses the software for creative purposes, they effectively lose their copyright (when they have no way to monetize their work, they have no reason to demand  reimbursement when people use it unauthorized)

You didn't say anything about what your software actually does and what's your motivation for creating and distributing it. So I can't say which of these points apply or don't apply to you.

OwnerDisplayName: nick-russler

Title: Opensource, noncommercial License?


问:
What's the benefit of avoiding the use of a debugger?
Over the course of my career, I've noticed that some developers don't use debugging tools, but do spot checking on erroneous code to figure out what the problem is.

While many times being able to quickly find errors in code without a debugger is a good skill to have, it seems it's less productive to spend a lot of time looking for issues when a debugger would easily find little mistakes like typos.

Is it possible to manage a complex without a debugger? Is it advisable? What benefits are there to be had by using "psychic debugging?"

答:
What a bunch of nonsense: "Real Programmers don't need Debuggers."  Might as well say that a real programmer doesn't need any IDE, just give me a note pad and a dull pencil.  The debugger is a tool like any other that aids productivity.

Also, consider that not everyone tasked with debugging code is familiar with that code in question.  Many time contractors come into an environment where they only have a general ideal what is happening. They may even be given a detailed description of an environment – or a 20 year old schema map and guide to arcane naming conventions (try understanding the difference between table X1234 and table X4312 with fields F1, F2, and F3 [yes, garbage like this exists] when you are new), but many times that description is wrong; otherwise, why is there a "mystery" error.

As someone new to an environment, you can spend hours or days mapping and getting to "know" a large database for a problem area that you may fix and then never have need to look at again. This is a huge waste of time and money. If you have access to the debugger, you look see what is happening, correct it, and are gone in a matter of minutes.  All of this "you don't need debuggers" hooey is just elitist puffery.


问:
What is the difference between requirements and acceptance criteria?
I am trying to understand the difference a little better as it seem like they are the same thing.

I have work in projects with no use of the requirements and everything is an acceptance criteria, and on projects that have both.

答:
The acceptance criteria defines when the application is finished. Or to put it another way, when you can ship it. It includes list of requirements that it has to fulfill. This means that some requirements  (usually "nice to have" requirements) may fall off, and be implemented in next version.

To expand it even further (taken from here) :

Microsoft Press defines Acceptance Criteria as “Conditions that a software product must satisfy to be accepted by a user, customer or other stakeholder.” Google defines them as “Pre-established standards or requirements a product or project must meet.”

and

Acceptance Criteria are a set of statements, each with a clear pass/fail result, that specify both functional (e.g., minimal marketable functionality) and non-functional (e.g., minimal quality) requirements applicable at the current stage of project integration. These requirements represent “conditions of satisfaction.” There is no partial acceptance: either a criterion is met or it is not.

A requirement describes a certain functionality of the application.

Or, as wiki nicely stated :

a requirement is a singular documented physical and functional need
  that a particular design, product or process must be able to perform.

What is the difference between the acceptance criteria and the application requirements?

With above definitions, the difference is quite clear.

OwnerDisplayName: BЈовић


答:
Requirements are what the client / customer have asked for.

Acceptance Criteria, often expressed as tests, are used to illustrate Requirements and to indicate, when the tests pass, that the Requirements have been met.

Title: What is the difference between requirements and acceptance criteria?

Body:
I am trying to understand the difference a little better as it seem like they are the same thing.

I have work in projects with no use of the requirements and everything is an acceptance criteria, and on projects that have both.

OwnerDisplayName: Derek Davidson


问:
Where did Java go wrong on the client?
Not talking about the recent Java/Oracle debacle here, but something I've been wondering recently.

When I first started programming, Java was the big thing client-side, however these days you hardly ever see a Java applet whereas Flash and Javascript are ubiquitous.

Where did Java go wrong? Did Sun decide to concentrate on the server-side and let client-side stagnate? How did Flash become dominant over Java? Flashy (no pun intended) graphics? Marketing?

Never having been a Java developer, I've not followed this closely so I'm interested to hear your thoughts.

答:
Applets and Flash are different technology. When first introduced, Applets had a lot of security holes in them, you could effectively run your program on the Client side which is not what any customer wants. Later this technology was improved substantially. On the other side Flash is more lightweight than Applets were. People more readily accepted Flash and didn't consider it as a security threat. Apart from minor vulnerabilities that do occur in Flash plugins, Flash was much safe. The initial security setback hurt Applets dearly. Also you are right probably Sun didn't pursue Applets that aggressively.

Something similar to Applets and probably more useful, is the native client that Google is trying to build for Chrome. Let's see how it goes.

Title: Where did Java go wrong on the client?


问:
What are the reasons for great performance differences running the same program?
I wrote a Python program that has to perform some expensive spatial searches while holding lots of data in memory. I tried to improve the performance, that is tried different approaches (see my question here for example).

First, and maybe not so surprisingly, I found great performance differences when running the same code on two different machines (up to 6 x faster on one machine).

Then however and very much to my own surprise, running the exactly same code on the same machine on two different days showed great performance differences.

To give you a rough idea what I mean by great.

Machine 1, day 1: 11 minutes

Machine 1, day 2: 2 minutes

There was no reboot in the meantime by the way.

What could be possible reasons for this difference? How can I can I make sure my system is ready for high performance when I start running my program?

答:
Using two different machines to compare a program is out of question. There are so many factors that affect the results (different hardware, different software, caches, other processes running, etc.) that what you get has no value.

When using the same machine, you can do some things to make the results more reliable. A few examples: (1) Always reboot before starting a new benchmark. It's the only way of ensuring that all caches are cold. (2) Run the same benchmark multiple times (eg. at least five) and average the results instead of relying on a single execution. (3) Consider switching into single user mode or stopping all the rest running programs/services (unless they're absolutely necessary), since they might affect the execution time of your program.

If you want to know more about how hard proper benchmarking is I recommend A Nine Year Study of File System and Storage Benchmarking


答:
It's often a matter of timing

Requirement are ahead of time.  Acceptance criteria are at the software delivery point.

This is as others have answered...

There is a deeper issue though and perhaps you are seeing it:

In an 'ideal' world these would just match.  However in the real world a lot happens between these two events, often including some of the following:

as the software is developed the requirements change.

the software is built with Agile processes

the budget changes

the timetable changes

the availability of technical talent is not 100% and changes over time

the determination that not all functionality is needed for go-live.

the business is affected by external factors that change what is needed.

It is frequently a matter of 'level of detail', with the requirements at a high level, e.g. "a refund processing module" and the acceptance criteria at a more low level and more detailed such as "a refund requested should be completed within 3 days and a notice emailed to the customer"


答:
Requirements are what you're supposed to do.

Acceptance Criteria are the agreed upon measures to prove you've done them.


问:
Do algorithms published in academic journals need to be licensed?
I'm looking at creating an implementation of Daugman's iris recognition algorithm, which is covered in his seminal paper on the topic.

What I don't know is, if I implement his algorithm, do I need a license?

答: It may depend on the country you live in. In France algorithms are regarded as ideas and are not subject to copyright, patents, etc. (While the article describing the algorithm or a specific implementation are subject to these.)  So, the short answer to your question is “probably not!”.</p>


答:
Requirements fall under verification which answers the question:

Was the product built correctly? (bottom-up as per the requirements)

Acceptance Criteria fall under validation which answers the question:

Was the correct product built? (top-down as evidenced by passing acceptance tests)


答:
Requirements are often driven by the client. In a waterfall development pattern these are the list of expected results from the completion of a project. In it's most basic description requirements are nothing more than a to-do for a project.

Acceptance criteria are often driven by the relationship between two parties. They can be independant from the requirements, and/or related to the requirements. That doesn't make them the same thing, but just related. Unlike requirements acceptance criteria is not a to-do list. It's a list of conditions that must be met for the agreement to be considered finished.

Some answers have stated unit tests, budgeting, and project management as examples but those are just examples of conditions placed upon the agreement as an acceptance criteria.

It is possible for a developer to complete none of the requirements, and still meet the acceptance criteria to finish the project.

For example;

Requirement to update point of sales system with new tax law changes. Acceptance criteria between the developer and client states developer agrees to complete 40 hours work to perform the update. If the work is not completed in that time no updates for the system will be published as this is the clients budget limit.

The developer enters into the agreement, and after 40 hours of work he reports that the change is significant resulting in more than 40 hours to finish. The client accepts this result, pays the developer their wages and their agreement is finished.


问:
Is there any "real" reason multiple inheritance is hated?
I've always liked the idea of having multiple inheritance supported in a language.  Most often though it's intentionally forgone, and the supposed "replacement" is interfaces.  Interfaces simply do not cover all the same ground multiple inheritance does, and this restriction can occasionally lead to more boilerplate code.

The only basic reason I have ever heard for this is the diamond problem with base classes.  I just can't accept that.  To me, it comes off an awful lot like, "Well, it's possible to screw it up, so it's automatically a bad idea."  You can screw up anything in a programming language though, and I mean anything.  I just cannot take this seriously, at least not without a more thorough explanation.

Just being aware of this problem is 90% of the battle.  Furthermore I think I heard something years ago about a general-purpose work-around involving an "envelope" algorithm or something like that (does this ring a bell, anyone?).

Concerning the diamond problem, the only potentially genuine problem I can think of is if you're trying to use a third-party library and can't see that two seemingly unrelated classes in that library have a common base class, but in addition to documentation, a simple language feature could, let's say, require that you specifically declare your intent to create a diamond before it'll actually compile one for you.  With such a feature, any creation of a diamond is either intentional, reckless, or because one is unaware of this pitfall.

So that all being said...Is there any real reason most people hate multiple inheritance, or is it all just a bunch of hysteria that causes more harm than good?  Is there something that I am not seeing here?  Thank you.

Example

Car extends WheeledVehicle, KIASpectra extends Car and Electronic, KIASpectra contains Radio.  Why doesn't KIASpectra contain Electronic?

Because it is an Electronic.  Inheritance vs. composition should always be an is-a relationship vs. a has-a relationship.

Because it is an Electronic.  There are wires, circuit boards, switches, etc. all up and down that thing.

Because it is an Electronic.  If your battery goes dead in the winter, you're in just as much trouble as if all your wheels suddenly went missing.

Why not use interfaces?  Take #3, for instance.  I don't want to write this over and over again, and I really don't want to create some bizarre proxy helper class to do this either:

private void runOrDont()
{
    if (this.battery)
    {
        if (this.battery.working && this.switchedOn)
        {
            this.run();
            return;
        }
    }
    this.dontRun();
}
```

(We're not getting into whether that implementation is good or bad.)  You can imagine how there may be several of these functions associated with Electronic that are not related to anything in WheeledVehicle, and vice-versa.

I wasn't sure whether to settle down on that example or not, since there is room for interpretation there.  You could also think in terms of Plane extending Vehicle and FlyingObject and Bird extending Animal and FlyingObject, or in terms of a much purer example.

答:
Is there something that I am not seeing here?

Allowing multiple inheritence makes the rules about function overloads and virtual dispatch decidedly more tricky, as well as the language implementation around object layouts. These impact language designers/implementors quite a bit, and raise the already high bar to get a language done, stable and adopted.

Another common argument I've seen (and made at times) is that by having two+ base classes, your object almost invariably violates the Single Responsibility Principle. Either the two+ base classes are nice self-contained classes with their own responsibility (causing the violation) or they're partial/abstract types that work with each other to make a single cohesive responsibility.

In this other case, you have 3 scenarios:

A knows nothing about B - Great, you could combine the classes because you were lucky.

A knows about B - Why didn't A just inherit from B?

A and B know about each other - Why didn't you just make one class? What benefit comes from making these things so coupled but partially replacable?

Personally, I think multiple inheritance has a bad rap, and that a well done system of trait style composition would be really powerful/useful... but there are a lot of ways that it can be implemented badly, and a lot of reasons it's not a good idea in a language like C++.

[edit] regarding your example, that's absurd. A Kia has electronics. It has an engine. Likewise, it's electronics have a power source, which just happens to be a car battery. Inheritance, let alone multiple inheritance has no place there.


答:
In many cases, people use inheritance to provide a trait to a class. For example think of a Pegasus. With multiple inheritance you might be tempted to say the Pegasus extends Horse and Bird because you've classified the Bird as an animal with wings.

However, Birds have other traits that Pegasi don't. For example, birds lay eggs, Pegasi have live birth. If inheritance is your only means of passing sharing traits then there's no way to exclude the egg laying trait from the Pegasus.

Some languages have opted to make traits an explicit construct within the language. Other's gently guide you in that direction by removing MI from the language. Either way, I can't think of a single case where I thought "Man I really need MI to do this properly".

Also let's discuss what inheritance REALLY is. When you inherit from a class, you take a dependency on that class, but also you have to support the contracts that class supports, both implicit and explicit.

Take the classic example of a square inheriting from a rectangle. The rectangle exposes a length and width property and also a getPerimeter and getArea method. The square would override length and width so that when one is set the other is set to match getPerimeter and getArea would work the same (2*length+2*width for perimeter and length*width for area).

There is a single test case that breaks if you substitute this implementation of a square for a rectangle.

var rectangle = new Square();
rectangle.length= 5;
rectangle.width= 6;
Assert.AreEqual(30, rectangle.GetArea());
//Square returns 36 because setting the width clobbers the length
```

It's tough enough to get things right with a single inheritance chain. It gets even worse when you add another to the mix.

The pitfalls I mentioned with the Pegasus in MI and the Rectangle/Square relationships are both the results of a inexperienced design for classes. Basically avoiding multiple inheritance is a way to help beginning developers avoid shooting themselves in the foot. Like all design principles, having discipline and training based on them allows you to in time discover when it's okay to break from them. See the Dreyfus Model of Skill Acquisition, at the Expert level, your intrinsic knowledge transcends reliance on maxims/principles. You can "feel" when a rule doesn't apply.

And I do agree that I somewhat cheated with a "real world" example of why MI is frowned upon.

Let's look at a UI framework. Specifically let's look at a few widgets that might at first brush look like they are simply a combination of two others. Like a ComboBox. A ComboBox is a TextBox that has a supporting DropDownList. I.e. I can type in a value, or I can select from a pre-ordained list of values. A naive approach would be to inherit the ComboBox from TextBox and DropDownList.

But your Textbox derives its value from what the user has typed. While the DDL gets its value from what the user selects. Who takes precedent? The DDL might have been designed to verify and reject any input that wasn't in its original list of values. Do we override that logic? That means we have to expose the internal logic for inheritors to override. Or worse, add logic to the base class that is only there in order to support a subclass (violating the Dependency Inversion Principle).

Avoiding MI helps you sidestep this pitfall altogether. And might lead to you extracting common, reusable traits of your UI widgets so that they can be applied as needed. An excellent example of this is the WPF Attached Property which allows a framework element in WPF to provide a property that another framework element can use without inheriting from the parent framework element.

For example a Grid is a layout panel in WPF and it has Column and Row attached properties that specify where a child element should be placed in the grid's arrangement. Without attached properties, if I want to arrange a Button within a Grid, the Button would have to derive from Grid so it could have access to the Column and Row properties.

Developers took this concept further and used attached properties as a way of componentizing behavior (for example here is my post on making a sortable GridView using attached properties written before WPF included a DataGrid). The approach has been recognized as a XAML Design Pattern called Attached Behaviors.

Hopefully this provided a little more insight on why Multiple Inheritance is typically frowned upon.

Title: Is there any "real" reason multiple inheritance is hated?

Body:
I've always liked the idea of having multiple inheritance supported in a language.  Most often though it's intentionally forgone, and the supposed "replacement" is interfaces.  Interfaces simply do not cover all the same ground multiple inheritance does, and this restriction can occasionally lead to more boilerplate code.

The only basic reason I have ever heard for this is the diamond problem with base classes.  I just can't accept that.  To me, it comes off an awful lot like, "Well, it's possible to screw it up, so it's automatically a bad idea."  You can screw up anything in a programming language though, and I mean anything.  I just cannot take this seriously, at least not without a more thorough explanation.

Just being aware of this problem is 90% of the battle.  Furthermore I think I heard something years ago about a general-purpose work-around involving an "envelope" algorithm or something like that (does this ring a bell, anyone?).

Concerning the diamond problem, the only potentially genuine problem I can think of is if you're trying to use a third-party library and can't see that two seemingly unrelated classes in that library have a common base class, but in addition to documentation, a simple language feature could, let's say, require that you specifically declare your intent to create a diamond before it'll actually compile one for you.  With such a feature, any creation of a diamond is either intentional, reckless, or because one is unaware of this pitfall.

So that all being said...Is there any real reason most people hate multiple inheritance, or is it all just a bunch of hysteria that causes more harm than good?  Is there something that I am not seeing here?  Thank you.

Example

Car extends WheeledVehicle, KIASpectra extends Car and Electronic, KIASpectra contains Radio.  Why doesn't KIASpectra contain Electronic?

Because it is an Electronic.  Inheritance vs. composition should always be an is-a relationship vs. a has-a relationship.

Because it is an Electronic.  There are wires, circuit boards, switches, etc. all up and down that thing.

Because it is an Electronic.  If your battery goes dead in the winter, you're in just as much trouble as if all your wheels suddenly went missing.

Why not use interfaces?  Take #3, for instance.  I don't want to write this over and over again, and I really don't want to create some bizarre proxy helper class to do this either:

private void runOrDont()
{
    if (this.battery)
    {
        if (this.battery.working && this.switchedOn)
        {
            this.run();
            return;
        }
    }
    this.dontRun();
}
```

(We're not getting into whether that implementation is good or bad.)  You can imagine how there may be several of these functions associated with Electronic that are not related to anything in WheeledVehicle, and vice-versa.

I wasn't sure whether to settle down on that example or not, since there is room for interpretation there.  You could also think in terms of Plane extending Vehicle and FlyingObject and Bird extending Animal and FlyingObject, or in terms of a much purer example.

Body:
In many cases, people use inheritance to provide a trait to a class. For example think of a Pegasus. With multiple inheritance you might be tempted to say the Pegasus extends Horse and Bird because you've classified the Bird as an animal with wings.

However, Birds have other traits that Pegasi don't. For example, birds lay eggs, Pegasi have live birth. If inheritance is your only means of passing sharing traits then there's no way to exclude the egg laying trait from the Pegasus.

Some languages have opted to make traits an explicit construct within the language. Other's gently guide you in that direction by removing MI from the language. Either way, I can't think of a single case where I thought "Man I really need MI to do this properly".

Also let's discuss what inheritance REALLY is. When you inherit from a class, you take a dependency on that class, but also you have to support the contracts that class supports, both implicit and explicit.

Take the classic example of a square inheriting from a rectangle. The rectangle exposes a length and width property and also a getPerimeter and getArea method. The square would override length and width so that when one is set the other is set to match getPerimeter and getArea would work the same (2*length+2*width for perimeter and length*width for area).

There is a single test case that breaks if you substitute this implementation of a square for a rectangle.

var rectangle = new Square();
rectangle.length= 5;
rectangle.width= 6;
Assert.AreEqual(30, rectangle.GetArea());
//Square returns 36 because setting the width clobbers the length

It's tough enough to get things right with a single inheritance chain. It gets even worse when you add another to the mix.

The pitfalls I mentioned with the Pegasus in MI and the Rectangle/Square relationships are both the results of a inexperienced design for classes. Basically avoiding multiple inheritance is a way to help beginning developers avoid shooting themselves in the foot. Like all design principles, having discipline and training based on them allows you to in time discover when it's okay to break from them. See the Dreyfus Model of Skill Acquisition, at the Expert level, your intrinsic knowledge transcends reliance on maxims/principles. You can "feel" when a rule doesn't apply.

And I do agree that I somewhat cheated with a "real world" example of why MI is frowned upon.

Let's look at a UI framework. Specifically let's look at a few widgets that might at first brush look like they are simply a combination of two others. Like a ComboBox. A ComboBox is a TextBox that has a supporting DropDownList. I.e. I can type in a value, or I can select from a pre-ordained list of values. A naive approach would be to inherit the ComboBox from TextBox and DropDownList.

But your Textbox derives its value from what the user has typed. While the DDL gets its value from what the user selects. Who takes precedent? The DDL might have been designed to verify and reject any input that wasn't in its original list of values. Do we override that logic? That means we have to expose the internal logic for inheritors to override. Or worse, add logic to the base class that is only there in order to support a subclass (violating the Dependency Inversion Principle).

Avoiding MI helps you sidestep this pitfall altogether. And might lead to you extracting common, reusable traits of your UI widgets so that they can be applied as needed. An excellent example of this is the WPF Attached Property which allows a framework element in WPF to provide a property that another framework element can use without inheriting from the parent framework element.

For example a Grid is a layout panel in WPF and it has Column and Row attached properties that specify where a child element should be placed in the grid's arrangement. Without attached properties, if I want to arrange a Button within a Grid, the Button would have to derive from Grid so it could have access to the Column and Row properties.

Developers took this concept further and used attached properties as a way of componentizing behavior (for example here is my post on making a sortable GridView using attached properties written before WPF included a DataGrid). The approach has been recognized as a XAML Design Pattern called Attached Behaviors.

Hopefully this provided a little more insight on why Multiple Inheritance is typically frowned upon.


答:
As far as I can tell, part of the problem (besides making your design a little bit harder to understand (nevertheless easier to code)) is that the compiler is going to save enough space for your class data, allowing this a huge amount of memory waste in the following case:

(My example might not be the best, but try to get the gist about multiple memory space for the same purpose, it was the first thing that came to my mind :P )

Concider a DDD wher the class dog extend from caninus and pet, a caninus has a variable which indicates the amount of food it should eat (an integer) under the name dietKg, but a pet also has another variable for that purpose usually under the same name (unless you set another variable name, then you'll have codify extra code, which was de initial problem that you wanted avoid, to handle and keep the integrity of bouth variables), then you'll have two memory spaces for the exact same purpose, to avoid this you will have to modify your compiler to recognize that name under the same namespace and just assign a single memory space to that data, which unfortunately is umposible to determine in compilation time.

You could, of course, design a languaje to specify that such variable might have already an space defined somewhere else, but at the end the programer should specify where is that memory space which this variable is referencing to (and again extra code).

Trust me the people implementing this thought really hard about all this, but I'm glad you asked, your kind prespective is the one which changes paradigms ;), and concider this, I'm not saying it is impossible (but many asumptions and a multiphased compiler must be implemented, and a really complex one), I'm just saying it does not exists yet, if you start a project for your own compiler capable of doing "this" (multiple inheritance) please let me know, I'll be glad to join to your team.


问:
Versioning and deploying dependent systems
I need some best practices or experiences of developer teams who had to treat the same issues I have at the moment =)

Our company is developing a client software for years. The one and only dependency was to have an appropriate database. With each release (update) we also update (incremental) the database if necessary. The versioning schema is well-established and matches our ideology.

Now we have started developing mobile applications (act as external client). Some preliminary remarks to our architecture:

The interface between the mobile client and the database (same database as for the desktop client) is a RESTful webservice. The versioning of both clients are independent. One application is maintained by the desktop development team and the mobile part is maintained by another team.

But I don't know how to handle the webservice. Should it be independent as well (own versioning) despite the fact that it's using a lot of shared libraries which are maintained by the desktop development team?

How it works:

The mobile client synchronizes it's reference data with the webservice which interacts live with the database (read-only access to database).
User data which are produced on the mobile application become also synchronized with the webservice but it's written to some persistent temporary tables. And an asynchronous job will be started to try the import to the database (could fail in case of locking issues, permissions, ....). If the import fails the same import procedure can also be started on the desktop client (they use the same library for importing from temporary tables to the specific ones)

In general each of these three parts could change (e.g. bugfix, features, performance improvements) without affecting the other two. Therefore I need a strategy to deploy each by itself. Nevertheless most probably it will affect two of three.

Where / when should i check if all three systems are compatible? How should I check this? Having a table in the database with every single possible combination of version which work together?

If you don't understand my question because it's entirely ambiguous, please let me know. It's not that easy to describe =)

答:
Should it be independent as well (own versioning) despite the fact that it's using a lot of shared libraries which are maintained by the desktop development team?

IMHO there are 2 possible models here:

The Web Service is seen as part of the desktop application and gets the same version number.

The Web Service is seen as a separate application, gets it's own version numbering (and you have to keep track which WS version numbers match the application & database version number)

Model 1 is fine when your REST API is very stable and does not change very often, and you want to provide a new WS version every time you create a new version of your desktop application & database. That will typically include a new deployment of the WS whenever you deploy a new version of the main application. This may also imply a new release (and deployment) of the desktop application whenever you have to provide a bugfix for the WS. The latter can be avoided if you use a versioning scheme like "major.minor.patchlevel", where only "major.minor" is equal for WS and desktop app/database, whilst the patchlevel is allowed to be different as long as arbitrary patch levels of your desktop app/database and your WS can work together. Such a versioning scheme is a "light version" of model 2..

Model 2 is better if the WS has a completely different "release cycle" as your application & database. For example, when you change your REST API much more often than the rest of the application (sounds unlikely), or when most application & database changes don't affect the webservice, and you just don't need to supply (and don't want to deploy) a new WS version. This can also depend on who is developing the WS: if you have a separated team on this, it will be likely that they demand to have their own release cycle to get things done (see Conway`s law).

When your web service shares a lot of libraries with the desktop application, I guess it's more likely that you want to deliver a new WS version whenever you provide a new desktop application's version (model 1), otherwise you get a bunch a different versions of the same libs in production, which increases maintenance complexity.

Where / when should i check if all three systems are compatible?

Let the WS check if the database has a version number he is compatible with whenever it connects the db. In model 1 that should be simple, in model 2 you need a list of version numbers of the database he can deal with (this list must be integral part of the WS installation, so it can't be messed up by a wrong deployment).

The mobile applications should also check if the REST API provides everything they are expecting. They could either contain an explicit version check (and stop working, or demanding an update, when the WS version is too old or too new), or individual checks for different REST api features, with different behaviour when some features are missing. What's best depends a lot on how the REST API looks like, what your users expect, how you deploy new versions to the mobile devices etc.

It may be a good idea to keep new versions of the REST API downwards compatible to older versions (if possible without too much headaches), and use the WS as a point where the mobile applications' version become decoupled from the versioning of the other system's part.


问:
Visual Studio's Developer License duals as a personal license?
I can be completely wrong but I vaguely remember hearing from a podcast that according to Visual Studio's license, a developer who works with Visual Studio professionally at their work place automatically has the license to use it in their personal life. That means a developer may not have to pay for Visual Studio to legally use/own it.

Again, I can be completely wrong but if I'm right, can someone confirm with a source?

答:
According to this whitepaper, a user with an MSDN license can use the software on any number of computers. Both MSDN and Visual Studio licences operate on a per-user basis.

The whitepaper provides the following example:

A developer with an MSDN subscription uses MSDN software at work during the day, but occasionally needs to develop at home as well, using a different computer. Under the MSDN license, there is no difference between a PC at work and a home PC; the home PC is just another device on which the developer is entitled use the MSDN software.

However, as user1100269 pointed out in the comments, your employer or your contract may state that anything you create with company property automatically becomes property of the company, so you may want to be careful.


答:
Firewalls would sometimes block java applets, so developers couldn't be sure if they were going to work or not.

They required a browser plug-in, which led many developers to favour javascript over java applets, so that they didn't require the user to download and install a plug-in.  The Macromedia Flash plug-in had a simpler, more seamless, and less noisy means for downloading, installing and updating.

The API wasn't so standardized then, so applets could fail to work if the user didn't have the right version of java installed.

They had a slow loading time and used too much memory.  They would often crash the browser.

Java applets died before Swing came out, so GUIs were difficult and ugly.

IE wasn't so good at supporting applets fully, so compatibility was difficult to sort out.

Flash and javascript are much easier to use for non-programmers.

Title: Where did Java go wrong on the client?

Body:
Not talking about the recent Java/Oracle debacle here, but something I've been wondering recently.

When I first started programming, Java was the big thing client-side, however these days you hardly ever see a Java applet whereas Flash and Javascript are ubiquitous.

Where did Java go wrong? Did Sun decide to concentrate on the server-side and let client-side stagnate? How did Flash become dominant over Java? Flashy (no pun intended) graphics? Marketing?

Never having been a Java developer, I've not followed this closely so I'm interested to hear your thoughts.