问:
What to keep in mind when releasing an app which uses libraries licensed under the Apache 2.0 License?
I'm creating an Android app which is soon ready for release.

I'm just going to implement a tab system using this library. I read that it is licensed under the Apache 2.0 License. I've never used any licensed libraries for apps/programs/games that I've distributed (because I haven't distributed any), so I don't have any experience with licenses and licensed libraries, so I wonder if there are anything to keep in mind when distributing an app which uses a library licensed under the Apache 2.0 License.

Keep in mind

I asked this question at StackOverflow, but I was recommended to move it to Programmers instead, but to check the help center if this site accepted this kind of question before I posted. I did, and as far I could see and understand of what I read, this kind of question is allowed.

I have read several of the Similar Questions, and found answers for some of my questions, but there are still some things I wonder, and that I want to be clear so I don't make any mistakes.

These are the remaining questions

I read that "the users of my application must receive a copy of the Apache 2.0 License. To avoid confusion, you should also state which parts of the distribution the license applies to." Is it enough to just put a link to the Apache 2.0 License on the "About app" page in the app, and tell the name of the licensed library together with the link?

Continuing on the above question: How do I need to "state which parts of the distribution the license applies to." Does that just mean that I shall tell which part of my app which is licensed (in other words, that the library is the licensed part)?

Am I allowed to modify the source of the library, then include the modified version in my app and sell it?

(this has nothing to do with licensed libraries) Do I need to apply a license for my app? If yes, which one is recommended? Will my app be protected by copyright automatically when I upload it to Google Play Store? What is recommended to protect it from "copycats"?

Is there any recommendations or guidelines? I would like to know so that I don't make any mistakes and have to pay fines or get in trouble or something like that. Thanks!

UPDATE: I've read amon's answer and found some more questions:

As I understand from what amon said, my app is protected by copyright automatically. He also said that I can register the copyright and that that might give me some advantages in some jurisdictions. Where do I register the copyright?

What parts of the license do I have to print out on the "about"-page? Is it enough to put this (from the Apache 2.0 Library website) below the information text of the library and put a link to a separate page (in the app) with the whole Apache 2.0 License?:

Copyright [yyyy] [name of copyright owner]

Licensed under the Apache License, Version 2.0 (the "License"); you
  may not use this file except in compliance with the License. You may
  obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  implied. See the License for the specific language governing
  permissions and limitations under the License.

More questions might come.

答:
There are well-established patterns for attributing the libraries you use. In general, you put this attribution in the same place where you'd put your copyright notice.

In a desktop application: Often there is a menu item “Help > About”, which displays a small info window with the application name, version number, copyright, and developer contact. This would be a good place to display licenses of used libraries.

In a mobile app: In your settings menu you might have an info item “About” which contains the same info as the above case, or an “Open Source” item that lists used open-source libraries and their licenses.

You should also list these licenses along with your terms of service or your end user license agreement, especially when these open-source licenses confer special priveleges to the user.

I would expect the “about”-page to look somewhat like this:

My Application v1.2.3

© 2015 my company

Found a bug? Please [help us fix it](opens bug report form).

By using this application, you agree to our [terms and services](opens dialog).

This app uses the following open-source libraries:

Library Foo [website]

Library Foo copyright and license

Library Bar [website]

Library Bar copyright and license

You should spell out the whole license and not rely on external websites – all the legal information should be accessible without internet connectivity. Of course you can design the page so that the user won't have to scroll endlessly, though many writers of legal text seem to be fond of endless repetitive blathering IN ALL CAPS FOR WORSE LEGIBILITY.

Before accepting a license, make sure to read and understand it. Some licenses also have an official FAQ page that addresses many common questions. However, the Apache 2.0 license is fairly short and simple. Here is a relevant excerpt:

4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without
  modifications, and in Source or Object form, provided that You meet
  the following conditions:

You must give any other recipients of the Work or Derivative Works a copy of this License; and

You must cause any modified files to carry prominent notices stating that You changed the files; and

[…]

If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must
  include a readable copy of the attribution notices contained within
  such NOTICE file, […]

You may add Your own copyright statement to Your modifications and may provide additional or different license terms […], provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.

If the license allows you to modify the library and distribute the modified library, you may sell it. The Apache 2.0 license does allow this within certain restrictions. E.g. you would have to clearly list your changes to the original library, and attribute the original library even when your modified library uses a different license.

Regarding your “do I need a license”/“how do I get copyright” question:

You automatically own copyright for all your creative works, but you should clearly state your copyright by listing the years of publication and the name of the copyright holder. E.g. if I published a program in 2012 and issued updates in 2014 and 2015, I would write “© 2012, 2014–2015 amon”. In addition to this, formally registering your copyright can have some advantages in some jurisdictions.

The default license for everything copyrighted is “all rights reserved”. However, by distributing an app you probably imply a license to your users allowing them to use your app. Also, by using a market place such as the Google Play Store you accept their terms of service, which may subject you to certain requirements and give the users certain permissions – but I haven't read the relevant terms. It will probably make sense to provide your own terms of service in addition to any implicit licenses. However, you do not have to pick an existing open-source license.

Your legal requirements when publishing an app don't end here. Especially when you collect, store, or transmit data, you are probably subject to various data protection laws around the world. Note that this might happen even if you are not collection this data as part of the normal workings of this app, but “only” for advertising, analytics, or crash reporting.

If there is any way your app could make you money, your business plan should include talking to a specialized lawyer about terms of service, licenses, and privacy policies.

ContentLicense: CC BY-SA 4.0


问:
Can you implement "object-oriented" programming without the class keyword?
Say we want to provide an abstraction of an "account" in a bank. Here's one approach, using a function object in Python:

def account():
    """Return a dispatch dictionary representing a bank account.

    >>> a = account()
    >>> a['deposit'](100)
    100
    >>> a['withdraw'](90)
    10
    >>> a['withdraw'](90)
    'Insufficient funds'
    >>> a['balance']
    10
    """
    def withdraw(amount):
        if amount > dispatch['balance']:
            return 'Insufficient funds'
        dispatch['balance'] -= amount
        return dispatch['balance']
    def deposit(amount):
        dispatch['balance'] += amount
        return dispatch['balance']
    dispatch = {'balance': 0,
                'withdraw': withdraw,
                'deposit': deposit}
    return dispatch
```

<p>Here's another approach using type abstraction (i.e., <code>class</code> keyword in Python):</p>

<pre class="lang-py prettyprint-override"><code>class Account(object):
    """A bank account has a balance and an account holder.

    >>> a = Account('John')
    >>> a.deposit(100)
    100
    >>> a.withdraw(90)
    10
    >>> a.withdraw(90)
    'Insufficient funds'
    >>> a.balance
    10
    """

    def __init__(self, account_holder):
        self.balance = 0
        self.holder = account_holder

    def deposit(self, amount):
        """Add amount to balance."""
        self.balance = self.balance + amount
        return self.balance

    def withdraw(self, amount):
        """Subtract amount from balance if funds are available."""
        if amount > self.balance:
            return 'Insufficient funds'
        self.balance = self.balance - amount
        return self.balance
</code>```

My teacher started the topic "Object oriented programming" by introducing the class keyword, and showing us these bullet points:

Object-oriented programming

A method for organizing modular programs:

Abstraction barriers

Message passing

Bundling together information and related behavior

Do you think the first approach would suffice to satisfy the above definition? If yes, why do we need the class keyword to do object-oriented programming?

答:
Of course you can!

The Self programming language is a dynamic prototype-based object oriented language in which everything is an object and there is no sense of classes or whatsoever. It's focused in the idea of prototypical objects and the idea of cloning them instead of having classes as templates of how to create objects.

You should check http://www.selflanguage.org/ for more information. I think it is very interesting and if you like OOP it's a good idea to check something that is not that common.

ContentLicense: CC BY-SA 3.0


问:
Are the Repository Pattern and Active Record pattern compatible?
Currently I am developing a webapp where I have defined models implementing the Active Record pattern. Each model also is defined by an interface that specifies the Entity properties and makes it easy to inject it into other classes, specially useful for unit testing.
I am looking forward to implement each model with a Repository pattern to abstract the database implementation.

e.g. Article:

```<code>ArticleInterface
- title
- content

ArticleRepositoryInterface
- getArticle(title)
- saveArticle(ArticleInterface)

ArticleRepository implements ArticleRepositoryInterface
- constructor(ArticleInterface)
- ArticleInterface getArticle(title)
- saveArticle(ArticleInterface)

Article implements ArticleInterface extends ActiveRecordModel
</code>```

Both patterns are very popular in today web development frameworks, but It is not clear to me how to integrate them.
The Active Record pattern by definition wraps a row in a database table, encapsulates the database access, mapping each object property to a database table, so

how should you integrate each model repository with the model that implements the AR ?

Are there any alternatives to using a model that implements the AR, inheriting all the database methods, and injecting it into a Repository wrapping all the AR database methods?

What are the best practices in this scenario?

If it adds any context to this question, I'm using Laravel and Eloquent.

答:
The repository pattern:

Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects.

The Data Mapping layer that you've chosen is Active Record.  Ergo, the Repository is that software pattern that provides an additional layer of abstraction between your Active Record pattern and your business domain.

How should you integrate each model repository with the model that implements the AR?

By providing methods that return a collection-like interface to your business domain, using Active Record to retrieve the necessary results from the database.

Are there any alternatives to using a model that implements the AR, inheriting all the database methods, and injecting it into a Repository wrapping all the AR database methods?

You can use some other method for accessing the database, like Table Data Gateway, Row Data Gateway or Data Mapper, in place of Active Record.

What are the best practices in this scenario?

Those practices that best meet your software's functional and non-functional requirements in terms of performance and maintainability.


答:
Not always: it depends on the language. You've demonstrated the ability to do this in Python but (if your question is meant to be language agnostic despite the Python tag) not all languages can do this. Java, for example, mostly can't. Ignoring the class that contains main, there is no way to define arbitrary methods/fields on an object defined within main without the class keyword. Although anonymous classes do exist they require an interface and they can't have any public members except those defined in the interface. While it is possible to define custom interfaces then make anonymous classes for them, this is effectively the same (but less convenient) than simply using a class.

Doc Brown has a great answer but the point I'm trying to make is that I'm sure there's at least one language that won't allow your solution at all.

Title: Can you implement "object-oriented" programming without the class keyword?

Body:
Say we want to provide an abstraction of an "account" in a bank. Here's one approach, using a function object in Python:

def account():
    """Return a dispatch dictionary representing a bank account.

    >>> a = account()
    >>> a['deposit'](100)
    100
    >>> a['withdraw'](90)
    10
    >>> a['withdraw'](90)
    'Insufficient funds'
    >>> a['balance']
    10
    """
    def withdraw(amount):
        if amount > dispatch['balance']:
            return 'Insufficient funds'
        dispatch['balance'] -= amount
        return dispatch['balance']
    def deposit(amount):
        dispatch['balance'] += amount
        return dispatch['balance']
    dispatch = {'balance': 0,
                'withdraw': withdraw,
                'deposit': deposit}
    return dispatch
```

<p>Here's another approach using type abstraction (i.e., <code>class</code> keyword in Python):</p>

<pre class="lang-py prettyprint-override"><code>class Account(object):
    """A bank account has a balance and an account holder.

    >>> a = Account('John')
    >>> a.deposit(100)
    100
    >>> a.withdraw(90)
    10
    >>> a.withdraw(90)
    'Insufficient funds'
    >>> a.balance
    10
    """

    def __init__(self, account_holder):
        self.balance = 0
        self.holder = account_holder

    def deposit(self, amount):
        """Add amount to balance."""
        self.balance = self.balance + amount
        return self.balance

    def withdraw(self, amount):
        """Subtract amount from balance if funds are available."""
        if amount > self.balance:
            return 'Insufficient funds'
        self.balance = self.balance - amount
        return self.balance
</code>```

My teacher started the topic "Object oriented programming" by introducing the class keyword, and showing us these bullet points:

Object-oriented programming

A method for organizing modular programs:

Abstraction barriers

Message passing

Bundling together information and related behavior

Do you think the first approach would suffice to satisfy the above definition? If yes, why do we need the class keyword to do object-oriented programming?


问:
Difference between Single Source Of Truth and Single Responsibility Principle?
So I just found out about the term single source of truth while watching video series about programming code interviews.

From what I understood it meant that the single source of truth is an encapsulation of any type of operation/logic that might be used multiple times.

It reminded me very strongly of the SRP which is pretty much the same thing in a sense that it encapsulates certain operations and/or logic that might be used for multiple times.

Is there something very subtle that I am missing here?

Thank you all for your time.

答:
They're two different principles.  Pretty much the only thing they have in common is the word "single."

Single Source of Truth is the end result of the process of normalizing a database.  Every piece of entity information is stored once, and only once.

Single Source of Truth explains why we put Customers in one table, and Products in another.  By associating customers with products, using a CustomerProducts table, we avoid storing either customers or products in two different places, and instead put pointers in the CustomerProducts table that point to each customer and product.  This also allows us to associate multiple customers with a product, and multiple products with a customer, without duplicating information such as the product name or its price.

Having a Single Source of Truth (each datum is stored in only one place) means that, when you change that datum, the entire system sees the same change at the same instant.  Contrast that with multiple sources of truth, where you have to change the datum in all places where it is stored.  Different parts of the system might see two different values for the same datum, at least temporarily.

Single Responsibility Principle (SRP) means that a class should only have one responsibility or one reason to change.  The example that Fowler gives is that of a Modem class:

```<code>interface Modem
{
    public void dial(String phoneNumber);
    public void hangup();
    public void send(char c);
    public char recv();
}
</code>```

This class violates SRP, because it has two major responsibilities: establishing a connection, and sending data.  To correct the problem, you would split the interface into two different interfaces: a connection interface, and a communication interface.  The first interface would contain the dial and hangup methods, and the second interface would contain the send and receive methods.

SRP is not a law, but merely a principle.  Sometimes SRP is violated for convenience or other reasons. The same is true of database normalization; sometimes data is kept in a denormalized form (includes some duplication) for performance or other reasons.

Persistence Ignorance is another form of SRP: a class should have no knowledge of how to save itself to a data store.  That's not its responsibility; it's the responsibility of some other class.  Were this not the case, you would have to change every class that uses the data store if you wanted to change the data store to some other type of data store.

Body:
They're two different principles.  Pretty much the only thing they have in common is the word "single."

Single Source of Truth is the end result of the process of normalizing a database.  Every piece of entity information is stored once, and only once.

Single Source of Truth explains why we put Customers in one table, and Products in another.  By associating customers with products, using a CustomerProducts table, we avoid storing either customers or products in two different places, and instead put pointers in the CustomerProducts table that point to each customer and product.  This also allows us to associate multiple customers with a product, and multiple products with a customer, without duplicating information such as the product name or its price.

Having a Single Source of Truth (each datum is stored in only one place) means that, when you change that datum, the entire system sees the same change at the same instant.  Contrast that with multiple sources of truth, where you have to change the datum in all places where it is stored.  Different parts of the system might see two different values for the same datum, at least temporarily.

Single Responsibility Principle (SRP) means that a class should only have one responsibility or one reason to change.  The example that Fowler gives is that of a Modem class:

interface Modem
{
    public void dial(String phoneNumber);
    public void hangup();
    public void send(char c);
    public char recv();
}

This class violates SRP, because it has two major responsibilities: establishing a connection, and sending data.  To correct the problem, you would split the interface into two different interfaces: a connection interface, and a communication interface.  The first interface would contain the dial and hangup methods, and the second interface would contain the send and receive methods.

SRP is not a law, but merely a principle.  Sometimes SRP is violated for convenience or other reasons. The same is true of database normalization; sometimes data is kept in a denormalized form (includes some duplication) for performance or other reasons.

Persistence Ignorance is another form of SRP: a class should have no knowledge of how to save itself to a data store.  That's not its responsibility; it's the responsibility of some other class.  Were this not the case, you would have to change every class that uses the data store if you wanted to change the data store to some other type of data store.


答:
Umm, no? You seem to be missing fairly significant distinctions!

The single responsibility principle doesn't encapsulate anything. It does not de-duplicate any behaviors/code/logic. All it says is that a class should do one thing. You can still have two classes that do the same thing. The principle is totally fine with that.

The single source of truth doesn't encapsulate anything. It is a guideline that helps you clarify your design. Very often, you have two or more versions of the same data. One in a database, one in a cache, one in memory, one in the clientside, one in sqllite sitting on a PC somewhere... Single source of truth is something you designate. You say that one is the one that wins when your sources disagree. That version is truth.

In short, these are decidedly unrelated.

Title: Difference between Single Source Of Truth and Single Responsibility Principle?

Body:
So I just found out about the term single source of truth while watching video series about programming code interviews.

From what I understood it meant that the single source of truth is an encapsulation of any type of operation/logic that might be used multiple times.

It reminded me very strongly of the SRP which is pretty much the same thing in a sense that it encapsulates certain operations and/or logic that might be used for multiple times.

Is there something very subtle that I am missing here?

Thank you all for your time.


问:
What is the better way of getting different outputs for two very simmilar related workflows
I have a very concrete scenario but I think it would be quite frequent.

I'm trying to come up with a solution that it's "better" by better meaning more scalable, reusable and not smelly.

I'm working with very old crufty legacy code and Trying to improve it one thing at a time.
Right now I have a process in which users can "vote" "things".

The process to determine if a user can vote is a complex logic and it may be subject to change.

Right now I have two functions, one (call it can_vote() ) takes the user and the thing and returns true or false. It's used to know what to display to the user.

The other one is vote() It takes user and thing and and checks again all the logic that can_vote checks but instead of returning false on error throws an error that gets displayed to the user.

The system tries to never get to a state in which the user would be able to use "vote" if the result would be an exception but it still happens.

I know there may be a thousand flaws to the whole system but right now the only thing I'm trying to do is unite the logic of the two functions in one single place in the better way (as defined above).

Ideally I would like to be able to call can_vote in my controllers just getting a true or false and acting acordingly.
can_vote, being a binary question should return true|false.
I could be able to use the logic inside can_vote in places where I want to display information about "false" responses.

I've got multiple ideas about how to solve that but all of them seem... weird:

Possible solutions

a) use can_vote(user,thing,verbose)

verbose beeing true false
if true returns string with the error
if false returns true|false

```<code>public can_vote ( user, thing, verbose ) {
    if( user is not logged ) {
        if( verbose ) {
            throw user is not logged
        }
        return false
    }

    //all other checks
    return true
}
</code>```

cons

returns different types depending on parameters

you get an if else that you carry arround the function

b) use a private function to determine if can vote. Use two helper functions

that would be something like that:

```<code>private can_really_vote ( user, thing ) {
    if( user is not logged ) {
        throw user is not logged
    }

    //all other checks
    return true

}

public can_vote ( user, thing ) {
    try {
        can_vote = this->can_really_vote( user, thing )
    }
    catch {
        //can_really_vote threw an exception
        return false
    }

    return false
}

public vote ( user, thing ) {
    if ( this->can_vote( user, thing ) ) {
        //do the vote thingy
    }
    else {
        // you shouldn't even get here. The user should have gotten an exception from can_really_vote
    }
}
</code>```

c) what php usually does

That would be something like

```<code>public vote () {
    if ( can_vote() ) {
        //carry on with the voting
    }
    else {

        display can_vote_last_error()
    }
}
</code>```

Things like that are usually seen in database access classes and the like.
Really? Keeping an internal trace of all those silly errors like "you are not logged", "the contest is over" and all that stuff just to be able to recall them?
It seems quite complicated.

Of course It can be done better, for example with dedicated exceptions... doesn't seem right dough.

I'm sure I can get more solutions... the problem boils down to wanting to get a true/false result in one case and some text on another for the same logic.

I guess the problem is quite common so there should be some software pattern for this.
Or maybe I'm being unable to abstract from it so I see the obvious elegant solution.

What would you do?

Thanks!

PS I'm almost sure it doesn't matter but I'm working in vanilla PHP 5.3

答:
I would recommend (d) have your voting function return a result saying whether it was successful or not.  Whatever mechanism you use for voting can fail, the user should be informed if that happens.</p>

```<code>public bool vote() {
   if (!can_vote()) { return false;}

   // take whatever action you need to, prefer functions that signal failure
   return true;
}
</code>```

Body:
I would recommend (d) have your voting function return a result saying whether it was successful or not.  Whatever mechanism you use for voting can fail, the user should be informed if that happens.

public bool vote() {
   if (!can_vote()) { return false;}

   // take whatever action you need to, prefer functions that signal failure
   return true;
}


问:
How do I determine if customers have already received a newsletter?
The problem: When we were sending newsletters to customers, there was no way to confirm if the customer already received the mail. We have come up with two different approaches:

(Boss's Idea) Each time mail was being sent, do an INSERT in a db with the title of the newsletter being sent and the email address which is receving the email address. To ensure that any email address does not receive the same email twice, do a SELECT in the table and find the title of the newsletter being sent:

```<code>if (title of newsletter is found)
{
  check to see of the email we are sending mail to is already present. if it does, do not send mail
}
else
{
  send mail
}
</code>```

(My idea) create a column called unique and mark it as UNIQUE. Each time mail was being sent, concatenate email + newsletter id and record it in the UNIQUE row. The next time we do a "mysql_affected_rows" check to see if our INSERT was successful, we send the mail, else, there is already a duplicate and no need to send it.

Is either approach objectively superior? If yes, which one and why?

答: Hopefully this doesn't sound too harsh, but neither solution is very scalable or performant.  Unlike a lot of other answers I actually prefer your solution over his for what its worth!  This is going to be totally dependent on your specific needs, but if you only care if the user has received the LATEST newsletter, you could give a unique auto incrementing id to each newsletter and keep a number per email address specifying the last email they received.  You'd then be able to do an integer comparison instead of a string search of a potentially huge string.  If you don't only care about the latest newsletter, you might have a look at bloom filters. A bloom filter is a probabilistic set which means you can ask it if something is in a set (has this user received this newsletter?).  The interesting part here though is that since it is probabilistic it will tell you "no" or "maybe".  No is never a lie, but maybe is uncertain.  You could use one of these to ensure that no users got the same news letter twice, at the cost of maybe not all users getting the newsletter in the first place.  The bloom filter could also just be used as a "fast query" where if it replies maybe, then you do the slower string check.  Hope this gives you some alternate thoughts on solving the problem!</p>


问:
What is language-agnosticism and why is it called that?
When is something language agnostic? Why is it called that?</p>

答: I haven't heard the term before, however, I would assume it means learning aspects of programming that are independent of any specific programming language.</p>

ContentLicense: CC BY-SA 2.5


问:
Designing Message class in Java
I'm writing a class for Message. Message comes with Header and Payload.

Header has following fields:

Version

Type

For Type "XYZ", the following Payloads are allowed.

Configuration

Metafile

where configuration can only be an HashMap of Key, value pairs.
And Metafile can only be a String (file contents)

Will Builder pattern suit here to build a message "Version:123, Type:XYZ, Configuration, HashMap" ? Or what is the best way to model this problem in Java?

答:
No, a builder is not unheard of for building messages. Spring Integration does something similar with a Builder. Spring Integration messages have a general structure like yours: a payload and a header.

There's the Message interface

```<code>public interface Message<T> {
    T getPayLoad();
    MessageHeaders getHeaders();
}
</code>```

The MessageHeaders class (your Header) is just a Serializable POJO that implements Map<String, Object>

```<code>public final class MessageHeaders implements Map<String, Object>, Serializable { ... }
</code>```

The payload is just a POJO. You've already gotten XYZ

Putting it all together, you can have

```<code>public abstract class XYZMessage implements Message<XYZ>{

   private XYZ payload;
   private Headers headers;

   public abstract XYZ getPayload();
   public abstract getHeaders();

}
</code>```

Your builder will not look unlike what we have for Spring Integration. Granted, the Spring Framework's implementation is more meaty than you'll ever need, but you could still borrow a leaf from it. If you do, your usage would be as clean as the following

```<code>Message<Account> m = MessageBuilder.withPayload(a)
                                   .setHeader("VERSION", "123")
                                   .build();
</code>```

Title: Designing Message class in Java

Body:
No, a builder is not unheard of for building messages. Spring Integration does something similar with a Builder. Spring Integration messages have a general structure like yours: a payload and a header.

There's the Message interface

public interface Message<T> {
    T getPayLoad();
    MessageHeaders getHeaders();
}

The MessageHeaders class (your Header) is just a Serializable POJO that implements Map<String, Object>

public final class MessageHeaders implements Map<String, Object>, Serializable { ... }

The payload is just a POJO. You've already gotten XYZ

Putting it all together, you can have

public abstract class XYZMessage implements Message<XYZ>{

   private XYZ payload;
   private Headers headers;

   public abstract XYZ getPayload();
   public abstract getHeaders();

}

Your builder will not look unlike what we have for Spring Integration. Granted, the Spring Framework's implementation is more meaty than you'll ever need, but you could still borrow a leaf from it. If you do, your usage would be as clean as the following

Message<Account> m = MessageBuilder.withPayload(a)
                                   .setHeader("VERSION", "123")
                                   .build();


问:
Use GPL code in commercial android app by spawning a separate process
As I understand, GPL allows use of a GPL program along with a proprietary program as long as they are separate programs and communicate at arms length.

In order to do this, if I spawn a process from my commercial android app which would only contain the gpl code and communicate with the main process via sockets,

would this violate the GPL? If so, is there any other way to use a gpl program (or code) in a commercial android app?

Relevant portions of gpl-faq:

http://www.gnu.org/licenses/gpl-faq.html#GPLInProprietarySystem

http://www.gnu.org/licenses/gpl-faq.html#MereAggregation

thank you,

答:
You probably understand wrongly (you should not wrap a GPL program with some protocol to communicate with a proprietary software without great cautions), and you should contact your lawyer, or the FSF.

I am not a lawyer, but my understanding is that if you design a specific protocol to communicate (from some GPL program) with only a proprietary process it is legally a linking or a derived work (license-wise, linking is not restricted to use ld). Things could be different if you have a public and documented protocol communicating with several programs, one of them being GPL.

In some legal systems, the court will evaluate if your intent was to hijack the spirit of GPL. You really need a lawyer and or the advice of FSF.

Did you consider publishing your application as free software under a GPL compatible license (You can commercialize GPL software, provided you give access to the source code under GPL license)?

And please, read more about free software. The goal of free software is not to assist proprietary developers (but to give freedom to users). Please visit the https://www.fsf.org/ site

You are probably considering making a huge mistake; are you sure to want to violate (or even to risk violating) the GPL license or its spirit?  your career, your reputation, your employer & clients could suffer (e.g. financial loss, or even go to jail in some countries); at your place I would not risk doing what you want to do (unless covered by a lawyer, who will defend you in court)!

BTW, the whole point is understanding what "communicate at arms length" means, and you probably need a lawyer for that.


问:
angularjs best practice by example
I am trying to get my head around how to better structure my angularjs applications by not overloading my controllers with too much logic. I feel like I have read just about every article on the subject but was hoping someone might be able to provide advice based on a specific example. I have put the requirements below for a job listing (as in jobs for a service company) screen and the functionality required.

Requirements:

Jobs are listed in a table and contain the following columns: id, customer, value ($), due date

Data is coming from a backend api (laravel/php) which provides a json array of objects with nested related objects and array of objects. Data is raw e.g. value ($) is 123.23 and due date is 2015-03-09.

The screen contains several filters for selecting a customer from a drop down list/autocomplete or selecting a date range for due date. Filtering is done server side, and server expects query params with a filter object e.g. filters={due_date_from='2015-03-07', due_date_to='2015-03-09',customer_id=123}

Filters are only applied when the user clicks on a filter button

Each column is sortable and sorting is done server side, so server expects query params with a sort object e.g. sort=[{by:'due_date', dir:'asc'}, {by:'customer_id',dir:'desc'}]

25 jobs per page, paging is done server side e.g. page=2

Where jobs are overdue, the row should be red

The state of filters, paging, sorts should be stored in the URL and read upon initialisation.

A reset button should clear all filters

I am using the Restangular 3rd party module for pulling data from the server side and have used the extendModel methods to added helper functions such as isOverdue() which returns true/false.

Currently I have created the following properties and methods in my JobsListController.

```<code>$scope.jobs = [];
$scope.filters = [];
$scope.sorts = [];
$scope.loadData = function(){}; //build data packet to send to server
$scope.sort = function(); // checks if column is currently sort in order to reverse direction
$scope.reset = function(){}; //clears filters, sorts and paging to send to server
</code>```

In my html I have the following things:

```<code><input type="date" ng-model="filters.due_from" />

<td>on-click="sortBy('customer_id')"></td>
</code>```

Ultimately I think my question is, should I be creating a service/factory called JobsListModel rather than having all this functionality in the controller?

答:
Here are my 2 cents from an AngularJS project I've been handling these past 6 months. While I'm in no way an expert in Angular, I did found out issues and uncovered some bad practices I've tended to do (and somewhat fixed along the way).

Controllers are a problem because they tend to get rally fat, rally fast. If your controller is passing the 500 lines mark (or you're feeling it's gonna pass really soon) you should stop everything and refactor your code. a couple of things I did were

separate service (remote data fetching) and controller (displaying data on view) logic, this is the first thing you should do when writing your app, if you have error handling in you http calls, send them to the service. that should shave off a couple of lines in your controllers. you should decouple your code either by logic or by job types.

you can assign more than one controller per view. In my project I had to write a dashboard that fetches data to several charts in a view, and to populate ~5 log tables, all in the same view. I've separated the dashboard view to 2 controllers, one to handle the charts and the other for the log tables. I may separate the charts controller even more in the future.

filters, no matter how small they should be in their own files, every new module you assign to your project should have it's own file, it keeps things organized

I often found myself doing doing complex validation in my controllers (an example being to validate an input field as a valid i.p. address), you can instead, write a directive and migrate that logic over there.

style guides are your best friends! here are a couple of good ones, this one and that one

Title: angularjs best practice by example

Body:
I am trying to get my head around how to better structure my angularjs applications by not overloading my controllers with too much logic. I feel like I have read just about every article on the subject but was hoping someone might be able to provide advice based on a specific example. I have put the requirements below for a job listing (as in jobs for a service company) screen and the functionality required.

Requirements:

Jobs are listed in a table and contain the following columns: id, customer, value ($), due date

Data is coming from a backend api (laravel/php) which provides a json array of objects with nested related objects and array of objects. Data is raw e.g. value ($) is 123.23 and due date is 2015-03-09.

The screen contains several filters for selecting a customer from a drop down list/autocomplete or selecting a date range for due date. Filtering is done server side, and server expects query params with a filter object e.g. filters={due_date_from='2015-03-07', due_date_to='2015-03-09',customer_id=123}

Filters are only applied when the user clicks on a filter button

Each column is sortable and sorting is done server side, so server expects query params with a sort object e.g. sort=[{by:'due_date', dir:'asc'}, {by:'customer_id',dir:'desc'}]

25 jobs per page, paging is done server side e.g. page=2

Where jobs are overdue, the row should be red

The state of filters, paging, sorts should be stored in the URL and read upon initialisation.

A reset button should clear all filters

I am using the Restangular 3rd party module for pulling data from the server side and have used the extendModel methods to added helper functions such as isOverdue() which returns true/false.

Currently I have created the following properties and methods in my JobsListController.

```<code>$scope.jobs = [];
$scope.filters = [];
$scope.sorts = [];
$scope.loadData = function(){}; //build data packet to send to server
$scope.sort = function(); // checks if column is currently sort in order to reverse direction
$scope.reset = function(){}; //clears filters, sorts and paging to send to server
</code>```

In my html I have the following things:

```<code><input type="date" ng-model="filters.due_from" />

<td><a on-click="sortBy('customer_id')"></td>
</code>```

Ultimately I think my question is, should I be creating a service/factory called JobsListModel rather than having all this functionality in the controller?


答: Paradigms or features that aren't applied to only one language.</p>

Title: What is language-agnosticism and why is it called that?

Body: When is something language agnostic? Why is it called that?</p>


问:
Microservices - should there be multiple instances of the same service?
I've been doing some research on microservices, and one question I've had that is not well addressed is whether there should be multiple instances of a microservice, and if so, how to deal with this?

Suppose for example I have a system of two microservices, A and B where A depends on B. Looking at B, is B supposed to be a single instance always, and handle everything A throws at it, or is it possible to create a pool of service Bs, so they can handle the load?

If the latter, how does one manage a pool of microservice B instances, with respect to load balancing and their data ownership?

答: Why not. If the microservices are stateless or have a shared database backed state then you should be able to have multiple instances of the services behind a network load balancer (F5 big-ip or Microsoft NLB as an example). I am assuming the microservices have a http api (REST). The answer is slightly more complicated if the microservices are integrated over a servicebus but even then you can have multiple instances.</p>


答: Services in general should be stateless, if possible. This allows you to harness one of their most powerful advantages: horizontal scalability. If you're on AWS, for example, you can set up auto-scale groups that simply create more servers when necessary and destroy them afterwards, with no loss of information or requests.</p>

Title: Microservices - should there be multiple instances of the same service?

Body:
I've been doing some research on microservices, and one question I've had that is not well addressed is whether there should be multiple instances of a microservice, and if so, how to deal with this?

Suppose for example I have a system of two microservices, A and B where A depends on B. Looking at B, is B supposed to be a single instance always, and handle everything A throws at it, or is it possible to create a pool of service Bs, so they can handle the load?

If the latter, how does one manage a pool of microservice B instances, with respect to load balancing and their data ownership?


问:
What non-programming books should a programmer read to help develop programming/thinking skills?
There are a lot of questions about what programming books should be on the programmer's bookshelf. How about non-programming related books that can help you become a better programmer or developer? It would also be interesting to know why they would help.

My first choice would be Sun Tzu's "Art of War" (however cliché), because it made it obvious that the success of any project depends on the strength of its weakest link (and warfare is a big project).

答:
A Pattern Language: Towns, Buildings, Construction

It will teach you how to see that wildly disparate things can have underlying patterns in common that can be applied in an entirely different context. The aspect of a CEO's office that makes it a great office can be present in an undergrad's residence room, or missing from your million dollar mansion. Once you get this concept, you can apply it to software, as the Gang of Four did, and you will understand Design Patterns so much more completely. You will also have nicer living and working spaces for the rest of your life.


问:
Handling my antiquated coworker
I'm a fairly young programmer, and I work at a medium sized company's IT department. I have a coworker, and he is a really good Visual Basic 6 programmer. And I mean really good. Honestly. He can deliver working applications, containing very few bugs, in the time I need to get my first cup of coffee, and boot my machine. He is just that good.

Thing is, we are working with a team, and his working style is completely antiquated. He doesn't believe in versioning software (if you just make sure your code is correct, you don't need all that nonsense). Doesn't believe in deployment (I can deliver a working executable. How that is deployed is for the sysadmins to figure out). Doesn't believe in abstraction. ('if you want to create a subroutine, go ahead, but don't call any subroutines from that subroutine. It gets messy that way, and the code is hard to follow. This way every one can follow every step on the way.' or 'yeah, sure you can use that library to do that for you, but that way you don't really understand what's going on') and certainly doesn't believe in OOP. (we work in VB.net)

He is so good in what he does, he can deliver applications way faster than I can. But it just doesn't work in a team. Our other team member is quiet, and doesn't like to speak out, though he tends to agree. Our manager thinks I make valid points, but is not a programmer.

I have a really hard time maintaining programs he has written, and it doesn't make for a good team atmosphere. What do you think is the best thing for me to do?

答:
Look at this from the business side.

You take more time to produce buggier code. You produce less revenue therefore you suck.

If, over time, you can reverse this then you can reverse this.

But maybe, just maybe, this antiquated programmer can actually teach you a couple of things about producing code quickly that is so bug free? Maybe his techniques are not so old school as you think?

I find it suspect that somebody can produce such great code without some very good practices. You might be able to learn those practices and apply them to the "best practices" and trendy things that you understand.

Title: Handling my antiquated coworker


答:
Answer mostly depends on your scalability/uptime/failover requirements. If it's necessary to have highly resilient architecture, then yes, you need to have multiple instances (sometimes even distributed across multiple data centers).

This is actually one of the benefits of microservices - you can scale different services independently - some of them are more performance critical than others so you create more instances of these. Contrast this with monolithic applications where you can scale just the whole monolith (ignoring the fact different requirements for different parts of the monolith).

If you're lucky, then you microservice is stateless - all instances are completely isolated. This is great because you can scale them almost infinitely. But often you have some state which needs to be distributed among the individual nodes. If you have relational database, you can have all nodes connect to the same DB instance, but this usually doesn't scale well. You can then setup read replicas (slaves), or even multi-master replication (read and writes possible from several DB instances which then sync), but you can still hit some limits (depending on the application and scalability requirements). Recently there's hype for distributed key-value stores - e.g. Hazelcast which can have a lot of nodes (even one per application instance) which then synchronize. This usually scales better than relation DBs, but data is usually not persistent and lost after system crash.

When you have multiple application instances, it's a good idea to hide this fact from the client - you should have only one endpoint which is served by a load balancer (e.g. HAProxy) which then directs the traffic to the actual application instances. These instances can be added/removed based on the load dynamically, the endpoint never changes.


问:
Reusing a merged branch, good practice?
Currently, I used to create a new branch each time I have to add a new feature to my application.

When my feature is finished and functional, I merge it with the master branch.

But later, when I need to update this feature (like an improvement) is it better to create a new branch or do I need to rebase the previous with the master, do the update then merge again?

For example, I have branch called modeling-member in a Ruby on Rails application. Later, I need to add some attributes to the member model (which was created in this branch). What should I do? Rebase this branch with the master, update the model and merge it again or simply create a new branch?

答:
Create a new branch, because:

A brand new branch is less likely to have merge conflicts when you're done and want to merge it into master. Few things are more error-prone than fixing merge conflicts.

The feature may have gone through several changes and updates since its original implementation, making the original branch totally obsolete. The only way to bring it up to date is to merge master into the feature branch...and at that point you're just branching off master in a needlessly complicated way.

If only for simplicity's sake, it's usually a good idea to have the same workflow for updates, bug fixes and new features. That applies to branching, code reviews, bug tracker usage, and pretty much everything else. The difference between updating an existing feature, adding a new feature and fixing a bug is often subjective anyway.

Title: Reusing a merged branch, good practice?


问:
What is the value of encoders with decoders currently present
Can you tell me the value of using PHP encoder (ioncube, phpshield) with currently present service like decry.pt (http://www.decry.pt/) that can easily decode source codes.

I have tried decry.pt's free demo. Just drag & drop an encoded source and it will return the decoded one. It is so easy.

It seems the value of encoder can be easily be canceled.

答:
Can you tell me the value of using PHP encoder (ioncube, phpshield) with currently present service like decry.pt (http://www.decry.pt/) that can easily decode source codes.

The value is that the source code is no longer readable by humans.

I have tried decry.pt's free demo. Just drag & drop an encoded source and it will return the decoded one. It is so easy.

Yes, that is correct. The source code is only obfuscated.

It seems the value of encoder can be easily be canceled.

There is no security or copy-protection provided by obfuscation.

What you are looking for is encryption and not obfuscation. There are a few encryption engines out there, but they all require the following to work.

a license for the end-user to decrypt the source code.

encryption algorithm that uses a public/private key pair

software installed on the web server to decrypt the source code.

There is no way for anyone to decrypt the source code unless they have the private key. Zend Guard uses a licensing engine, source code encryption and an internal memory cache.


答:
Big difference between Active Record and Repository patterns is in my opinion the owner of the link between entity instance and underlying storage:

in Active Record, entity instance knows how and where to persist itself (this is what "active" means in my mind). That's why you can just call user.save() and it persists itself.

in Repository pattern, entity is more or less dumb POJO, it's the repository which manages its lifecycle. If you create a new instance of the entity, it's not magically persisted, you need to tell the repository to persist it.

Active Record is simpler but less flexible because it is attached to one backing storage.

In regards to who manages the entity's lifecycle, you need to choose one or the other.

But other than that you can create sort of a hybrid - e.g. your entities manage themselves (i.e. Active Record -> methods like .save() and .delete()), but then you have a repository which provides querying and mapping functionality without keeping track of "managed" entities (and without methods like .saveArticle()).

Title: Are the Repository Pattern and Active Record pattern compatible?

Body:
Currently I am developing a webapp where I have defined models implementing the Active Record pattern. Each model also is defined by an interface that specifies the Entity properties and makes it easy to inject it into other classes, specially useful for unit testing.
I am looking forward to implement each model with a Repository pattern to abstract the database implementation.

e.g. Article:

```<code>ArticleInterface
- title
- content

ArticleRepositoryInterface
- getArticle(title)
- saveArticle(ArticleInterface)

ArticleRepository implements ArticleRepositoryInterface
- constructor(ArticleInterface)
- ArticleInterface getArticle(title)
- saveArticle(ArticleInterface)

Article implements ArticleInterface extends ActiveRecordModel
</code>```

Both patterns are very popular in today web development frameworks, but It is not clear to me how to integrate them.
The Active Record pattern by definition wraps a row in a database table, encapsulates the database access, mapping each object property to a database table, so

how should you integrate each model repository with the model that implements the AR ?

Are there any alternatives to using a model that implements the AR, inheriting all the database methods, and injecting it into a Repository wrapping all the AR database methods?

What are the best practices in this scenario?

If it adds any context to this question, I'm using Laravel and Eloquent.


问:
Why sequences are recommended as conventional interfaces?
From the reference of berkeley's version of  sicp text, It is mentioned that:

Expressing programs as sequence operations helps us design programs that are modular. That is, our designs are constructed by combining relatively independent pieces, each of which transforms a sequence. In general, we can encourage modular design by providing a library of standard components together with a conventional interface for connecting the components in flexible ways.

For instance, In python, <class 'list'> and <class 'tuple'> are some of the types of mostly used sequential data models for storage.

For instance, In python <class 'dict'> is one popular type of non-sequential data model.

Text reference gives below solutions written in python to two different problems  and mentions as similar solution, which is not convincing, because these two problems could not be the representative sample to take this decision.

```<code>>>> def sum_even_fibs(n):
        """Sum the even members of the first n Fibonacci numbers."""
        return sum(filter(iseven, map(fib, range(1, n+1))))
>>> sum_even_fibs(20)
3382
</code>```

```<code>>>> def acronym(name):
        """Return a tuple of the letters that form the acronym for name."""
        return tuple(map(first, filter(iscap, name.split())))
>>> acronym('University of California Berkeley Undergraduate Graphics Group')
('U', 'C', 'B', 'U', 'G', 'G')
</code>```

I am still not clear on the decision to make "sequences as conventional interfaces" despite these given examples.

So,
Amidst designing a library or component, Why sequential type data models are recommended to be chosen as conventional interfaces?Is this something to do with closure property of these sequential data models(provided by python/scheme/lisp)?

Note: Same recommendation is given in SICP text from MIT press

答:
The purpose of a dictionary is to return a value given a specified key, not to serve as a sequential container.  Just because other data structures are sequential but dictionaries are not does not mean that the benefits of sequences are invalidated.

Sequences are one of the three fundamental logic structures in computing.  Every (solvable) computing problem can be solved with three tools: sequences, loops, and decisions.

Sequences preserve the relationship between elements; that is, the first element must occur before the second element, which must occur before the third element, and so forth.  That means we can retrieve the next element in a sequence, and be assured that we retrieved the element in the correct order, relative to the other elements.  This has obviously useful benefits: words always consist of the same sequence of letters each time they are read, and methods consist of the same sequence of instructions each time they are called.

You can make sequences lazy.  You can create a class that implements a state machine, and returns an element from the state machine each time a method is called.  You can cache sequences.

Sequences can be created from linked lists, trees, and other data structures.  Each data structure has its own specific qualities; a singly-linked list can be efficiently traversed in one direction, but not the other.  Some data structures, such as binary trees, will give you sequential access and also efficient random access.  Some data structures, such as doubly-linked lists, allow you to efficiently traverse the sequence backwards.

If you write your data structure to conform to a sequential interface, you can switch out your implementation of the sequence to whichever data structure is most appropriate for your given requirements.  You can then write your code against that interface, and be assured that the underlying implementations are modular.

I don't know much about sequences in python, but the fundamental data structure in Scheme (used in the original SICP) is a list, and the ways in which you can compose such lists (which are essentially sequences), and the flexibility and power that affords, should be obvious.  Every language containing sequences allows such compositions.


答:
Quick Short Answer

Yes, Programmers can apply the Object Oriented Programming without "Classes".

Long Boring Extensive Descriptive Answer

There are several variations of "Object Orientation", altought, the first concept that comes to the mind of many programmers is "Classes".

Yes, Programmers can apply the Object Oriented Programming without "Classes", but, is limited to the features and limitations from each programming language.

Your post is tagged as Python, therefore, your question title may be more like "How to implement Object Oriented Programming without Classes in Python".

I currently use the "Object and Class Oriented Programming" phrase, to identify from other variations like Javascript's "Prototyping", or Visual Basic "Based", or emulation in "Pure C" using "functors".


问:
Converting from List<Object> to Array with threads
I have a large (>500.000) list of Objects and I want to convert it to a multidimensional array. Until now I am doing this using a for loop, but after some measurements I identified that this is a bottleneck for my program.

I am considering to make the conversion in parallel using a thread pool executor. The logic is that if I have N threads I will separate the initial data to N chunks. Each thread will 'convert' the Object values and insert them to the 'shared' array. Since I know the exact position of each item, I can ensure that 2 threads will never try to write to the same array position.

Is this a good way to go? Are there any considerations?

Are there any Libraries implementing such functionality? (Note: I am not asking for the libraries their-self, since this would be of topic. I just want to know, if there is something similar, meaning that I am in the good track)

Note 1: I know that creating thread is 'time-consuming' also, but to find for what amount_of_data / number_of_thread, parallel conversion is more optimal than serial is another issue.

答:
For me it seems pretty straightforward - as you say, you can divide the work beforehand to N chunks, each thread will pick up and process their assigned elements and put to pre-determined place in the array - threads effectively won't read/write same data.

Two things though:

You should preallocate all the arrays accessed by multiple threads before hand to avoid race conditions.

There's a potential visibility problem - shared data is sometimes cached thread-locally in the CPU registers, their changes doesn't have to be immediatelly propagated to the main memory. The risk here is that once all the changes are done in "worker" threads, these changes may not be visible (present in the main memory) for the thread which uses the produced multidimensional array. There are several possible ways how to handle it for this case, but arguably the simplest is to use java.util.concurrent.atomic.AtomicReferenceArray instead of simple array - this will solve the visibility problems without having to reason hard about what's going on.


问:
How did programmers work back when a computer was very expensive, rare, as big as a room?
I assume they weren't able to sit in front of a computer for the whole day like we do today. So how did they write their program? On a piece of paper and type it later when the computer is available? How did they do their testing?</p>

答:
I learned programming in PL/1 in 1975 (on IBM 370/168), as a teenager (I was born in 1959). I had the privilege of having a father working at IBM France. His boss,
M. Dornbush, wrote a book (in French) about programming in PL/1.

At that time, a program (as done by someone learning programming) was a packet of a few hundred punched cards. Charles E.Grant's answer describes the process: you wrote your program on paper first, and you checked it quite carefully. Then you punched the cards (on an IBM29 keypunch machine), and finally you put the card deck into the punched card reader. Notice that at that time source programs where quite small (a program of several thousand statements - that is, punched cards - was a very large program).

As a teenager, I was impressed by the ability of the PL/1 checkout compiler, in particular to suggest corrections on typos.

In the next years, I played with an old CAB/500 computer and an IBM/1620 computer at the Palais de la Découverte science museum in Paris (both computers were old enough to sit in a museum). CAB/500 was produced in the 1960s, and my father wrote its PAF compiler (a sort of BASIC language) when I was an infant or a toddler (1958-1962).

Today, I am still doing stuff (MELT) related to compilers, and one of the few who can claim that he saw his own father writing compilers!

The funny thing with PAF on CAB/500 was its interactive editor (with a physical tty & punched tapes) capable of completion (on keywords). It was a bit like the original IBM PC, somehow a "personal computer".

The funny thing with IBM/1620 was that you had to bootstrap it by entering a few digits on the keyboard to load the monitor and the Fortran compiler.

Notice that in the 1950s some computers did not even had punched card readers (AFAIK it was optional on IBM650 & IBM7094), but I never saw them.

Notice also that access to computers in the mid 1970s was a huge privilege (because they where costly equipments). Perhaps the equivalent today might be to get access to silicon making machines, or to datacenter-scale computing power.


问:
When the result set doesn't matter should Left Join or Inner Join be used
When you have a query where you're joining from a non-null foreign key to the foreign table it doesn't matter if you use LEFT JOIN or INNER JOIN from a result standpoint (since there won't be any cases where it doesn't match something on the right). In a case like this  which should be preferred, INNER JOIN or LEFT JOIN. I'd like to consider performance as well as style/documentation.

To me the INNER JOIN is closer to what you want, since the special characteristic of the LEFT JOIN doesn't happen, but in a lot of places I see LEFT JOIN just being the default unless INNER JOIN is explicitly needed so I'm partially worried that it may cause people to double think something that doesn't need thinking.

e.g. which of the following should be preferred

```<code>FROM dbo.Post p
LEFT JOIN dbo.User u ON p.UserID = u.UserID
</code>```

or

```<code>FROM dbo.Post p
INNER JOIN dbo.User u ON p.UserID = u.UserID
</code>```

assuming that UserID is a foreign key to the user table and no post can be created without a user

答:
I've had this exact situation come up with a co-worker and when reviewing code from contractors -- the code should always convey your intent and expectations as clearly as possible given the constraints of performance and size.

Performance with SQL relies upon the query optimizer -- while it probably won't make any difference, if it does, more likely than not, using a left join will HURT performance not enhance; you are in effect lying to the optimizer.

I have yet to encounter a convincing argument for misleading code other than "it was necessary in order to make it work".

In short, never use a left join where you mean inner join.

Not part of your question but from the same experince -- never use top 1 "just in case more than 1 row is returned" for a sub-query.   At best you hide your expectations, at worst you return incorrect results semi-randomly.


答:
If you want to save only commits from a merge on the master and you are using github, you could use "Fork" to every new feature and do a pull request and accept pull request after you get every new feature done.

I don't recommend working on old branches, since you can get conflicts when you merge it to the head of master and of course it's not needed to do it...

Title: Reusing a merged branch, good practice?

Body:
Currently, I used to create a new branch each time I have to add a new feature to my application.

When my feature is finished and functional, I merge it with the master branch.

But later, when I need to update this feature (like an improvement) is it better to create a new branch or do I need to rebase the previous with the master, do the update then merge again?

For example, I have branch called modeling-member in a Ruby on Rails application. Later, I need to add some attributes to the member model (which was created in this branch). What should I do? Rebase this branch with the master, update the model and merge it again or simply create a new branch?


答:
Use a new branch.

For naming, you could consider using an internal format that this_work is an extension or change to that_work

For example you could name the second branch

```<code>modeling-member--attributes
</code>```

with the -- signalling that the name name on the left is the original branch

We tackle a somewhat similar problem as we use Jira ticket numbers for branch names.  Sometimes there is an additional bit of work for the same ticket.  Sometimes a database change could not be rolled back.  In those cases we use, for example, original branch SEND-123 and second branch to be SEND-123a

Title: Reusing a merged branch, good practice?

Body:
Use a new branch.

For naming, you could consider using an internal format that this_work is an extension or change to that_work

For example you could name the second branch

modeling-member--attributes

with the -- signalling that the name name on the left is the original branch

We tackle a somewhat similar problem as we use Jira ticket numbers for branch names.  Sometimes there is an additional bit of work for the same ticket.  Sometimes a database change could not be rolled back.  In those cases we use, for example, original branch SEND-123 and second branch to be SEND-123a


问:
Why can't there be any implicit conversions?
As I understand it, implicit conversions can cause errors.

But that doesn't make sense -- shouldn't normal conversions also cause errors, then?

Why not have

```<code>len(100)
</code>```

work by the language interpreting (or compiling) it as

```<code>len(str(100))
</code>```

especially since that's the only way (I know of) for it to work. The language knows what the error is, why not fix it?

For this example I used Python, though I feel that for something this small it's basically universal.

答:
As I understand it, implicit conversions can cause errors.

You're missing a word: implicit conversions can cause runtime errors.

For a simple case like you show, it's pretty clear what you meant. But languages can't work on cases. They need to work with rules. For many other situations, it's not clear if the programmer made an error (using the wrong type) or if the programmer meant to do what the code assumes they meant to do.

If the code assumes wrong, you get a runtime error. Since they're tedious to track down, many languages err towards the side of telling you that you messed up and letting you tell the computer what you really meant (fix the bug or explicitly do the conversion). Other languages make the guess, since their style lends itself to quick and easy code that is easier to debug.

One thing to note is that implicit conversions do make the compiler a little more complex. You need to be more careful about cycles (let's try this conversion from A to B; oops that didn't work, but there's a conversion from B to A! and then you need to worry about C and D sized cycles too), which is a small motivation to avoid implicit conversions.


问:
Does it always make sense to "program to an interface" in Java?
I've seen the discussion at this question regarding how a class that implements from an interface would be instantiated. In my case, I'm writing a very small program in Java that uses an instance of TreeMap, and according to everyone's opinion there, it should be instantiated like:

```<code>Map<X> map = new TreeMap<X>();
</code>```

In my program, I'm calling the function map.pollFirstEntry(), which is not declared in the Map interface (and a couple others who are present in the Map interface too). I've managed to do this by casting to a TreeMap<X> everywhere I call this method like:

```<code>someEntry = ((TreeMap<X>) map).pollFirstEntry();
</code>```

I understand the advantages of the initialization guidelines as described above for large programs, however for a very small program where this object would not be passed to other methods, I would think it is unnecessary. Still, I'm writing this sample code as part of a job application, and I don't want my code to look badly nor cluttered. What would be the most elegant solution?

EDIT: I would like to point out that I'm more interested in the broad good coding practices instead of the application of the specific function TreeMap. As some of the answers have already pointed out (and I've marked as answered the first one to do so), the higher abstraction level possible should be used, without losing functionality.

答:
It's about communicating your intent of how the object should be used. For example, if your method expects a Map object with a predictable iteration order:

```<code>private Map<String, String> processOrderedMap(LinkedHashMap<String, String> input) {
    // ...
}
</code>```

Then, if you absolutely need to tell callers of the above method that it too returns a Map object with a predictable iteration order, because there is such an expectation for some reason:

```<code>private LinkedHashMap<String,String> processOrderedMap(LinkedHashMap<String,String> input) {
    // ...
}
</code>```

Of course, callers may still treat the return object as a Map as such, but that's beyond the scope of your method:

```<code>private Map<String, String> output = processOrderedMap(input);
</code>```

Taking a step back

The general advice of coding to an interface is (generally) applicable, because usually it's the interface that provides the guarantee what the object should be able to perform, aka the contract. Many beginners start with HashMap<K, V> map = new HashMap<>() and they are advised to declare that as a Map, because a HashMap doesn't offer anything more than what a Map is supposed to do. From this, they will then be able to understand (hopefully) why their methods should take in a Map instead of a HashMap, and this lets them realize the inheritance feature in OOP.

To quote just one line from the Wikipedia entry of everyone's favorite principle related to this topic:

It is a semantic rather than merely syntactic relation because it intends to guarantee semantic interoperability of types in a hierarchy...

In other words, using a Map declaration isn't because it makes sense 'syntactically', but rather invocations on the object should only care that it is a type of Map.

Cleaner code

I find that this allows me to write cleaner code at times too, especially when it comes to unit testing. Creating a HashMap with a single read-only test entry takes more than a line (excluding the use of double-brace initialization), when I can easily replace that with Collections.singletonMap().

OwnerDisplayName: jimijazz

Body:
It's about communicating your intent of how the object should be used. For example, if your method expects a Map object with a predictable iteration order:

private Map<String, String> processOrderedMap(LinkedHashMap<String, String> input) {
    // ...
}

Then, if you absolutely need to tell callers of the above method that it too returns a Map object with a predictable iteration order, because there is such an expectation for some reason:

private LinkedHashMap<String,String> processOrderedMap(LinkedHashMap<String,String> input) {
    // ...
}

Of course, callers may still treat the return object as a Map as such, but that's beyond the scope of your method:

private Map<String, String> output = processOrderedMap(input);

Taking a step back

The general advice of coding to an interface is (generally) applicable, because usually it's the interface that provides the guarantee what the object should be able to perform, aka the contract. Many beginners start with HashMap<K, V> map = new HashMap<>() and they are advised to declare that as a Map, because a HashMap doesn't offer anything more than what a Map is supposed to do. From this, they will then be able to understand (hopefully) why their methods should take in a Map instead of a HashMap, and this lets them realize the inheritance feature in OOP.

To quote just one line from the Wikipedia entry of everyone's favorite principle related to this topic:

It is a semantic rather than merely syntactic relation because it intends to guarantee semantic interoperability of types in a hierarchy...

In other words, using a Map declaration isn't because it makes sense 'syntactically', but rather invocations on the object should only care that it is a type of Map.

Cleaner code

I find that this allows me to write cleaner code at times too, especially when it comes to unit testing. Creating a HashMap with a single read-only test entry takes more than a line (excluding the use of double-brace initialization), when I can easily replace that with Collections.singletonMap().


答:
Implicit conversions are quite possible to do.  The situation where you get in trouble is when you don't know which way something should work.

An example of this can be seen in Javascript where the + operator works in different ways at different times.

```<code>>>> 4 + 3
7
>>> "4" + 3
43
>>> 4 + "3"
43
</code>```

If one of the arguments is a string, then the + operator is a string concatenation, otherwise it is addition.

If you are given an argument and don't know if it is a string or an integer, and want to do addition with it, it can be a bit of a mess.

Another way to deal with this is from the Basic heritage (that perl follows from - see Programming is Hard, Let's Go Scripting...)

In Basic, the len function only makes sense being invoked on a String (docs for visual basic: "Any valid String expression or variable name. If Expression is of type Object, the Len function returns the size as it will be written to the file by the FilePut function.").

Perl follows this concept of context. The confusion that exists in JavaScript with implicit conversion of types for the + operator being sometimes addition and sometimes concatenation doesn't happen in perl because + is always addition and . is always concatenation.

If something is used in a scalar context, its a scalar (e.g. using an list as a scalar, the list behaves as if it was a number corresponding to its length).  If you use a string operator (eq for equality test, cmp for string comparison) the scalar is used as if it was a string.  Likewise, if something was used in a math context (== for equality test and <=> for numerical comparison), the scalar is used as if it was a number.

The fundamental rule for all programming is "do the thing that surprises the person the least".  This doesn't mean there aren't surprises in there, but the effort is to surprise the person the least.

Going to a close cousin of perl - php, there are situations where an operator can act on something in either string or numeric contexts and the behavior can be surprising to people.  The ++ operator is one such example. On numbers, it behaves exactly as expected. When acting on a string, such as "aa", it increments the string ($foo = "aa"; $foo++; echo $foo; prints ab).  It will also roll over so that az when incremented becomes ba.  This isn't particularly surprising yet.

$foo = "3d8";
echo "$foo\n";
$foo++;
echo "$foo\n";
$foo++;
echo "$foo\n";
$foo++;
echo "$foo\n";
```

<p><sup>(ideone)</sup></p>

<p>This prints out:</p>

```3d8
3d9
3e0
4
```

Welcome to the dangers of implicit conversions and operators acting different on the same string. (Perl handles that code block a bit differently - it decides that "3d8" when the ++ operator is applied is a numeric value from the start and goes to 4 right away (ideone) - this behavior is well described in perlop: Auto-increment and Auto-decrement)

Now, why one language does something one way and another does it another way gets to the design thoughts of the designers.  Perl's philosophy is There's more than one way to do it - and I can think of a number of ways of doing some of these operations.  On the other hand, Python has a philosophy described in PEP 20 -- The Zen of Python which states (among other things): "There should be one-- and preferably only one --obvious way to do it."

These design differences have lead to different languages. There is one way to get the length of a number in Python.  Implicit conversion goes against this philosophy.

Related reading: Why doesn't Ruby have implicit conversion of Fixnum into String?

Title: Why can't there be any implicit conversions?

Body:
As I understand it, implicit conversions can cause errors.

But that doesn't make sense -- shouldn't normal conversions also cause errors, then?

Why not have

```<code>len(100)
</code>```

work by the language interpreting (or compiling) it as

```<code>len(str(100))
</code>```

especially since that's the only way (I know of) for it to work. The language knows what the error is, why not fix it?

For this example I used Python, though I feel that for something this small it's basically universal.

Body:
Implicit conversions are quite possible to do.  The situation where you get in trouble is when you don't know which way something should work.

An example of this can be seen in Javascript where the + operator works in different ways at different times.

>>> 4 + 3
7
>>> "4" + 3
43
>>> 4 + "3"
43

If one of the arguments is a string, then the + operator is a string concatenation, otherwise it is addition.

If you are given an argument and don't know if it is a string or an integer, and want to do addition with it, it can be a bit of a mess.

Another way to deal with this is from the Basic heritage (that perl follows from - see Programming is Hard, Let's Go Scripting...)

In Basic, the len function only makes sense being invoked on a String (docs for visual basic: "Any valid String expression or variable name. If Expression is of type Object, the Len function returns the size as it will be written to the file by the FilePut function.").

Perl follows this concept of context. The confusion that exists in JavaScript with implicit conversion of types for the + operator being sometimes addition and sometimes concatenation doesn't happen in perl because + is always addition and . is always concatenation.

If something is used in a scalar context, its a scalar (e.g. using an list as a scalar, the list behaves as if it was a number corresponding to its length).  If you use a string operator (eq for equality test, cmp for string comparison) the scalar is used as if it was a string.  Likewise, if something was used in a math context (== for equality test and <=> for numerical comparison), the scalar is used as if it was a number.

The fundamental rule for all programming is "do the thing that surprises the person the least".  This doesn't mean there aren't surprises in there, but the effort is to surprise the person the least.

Going to a close cousin of perl - php, there are situations where an operator can act on something in either string or numeric contexts and the behavior can be surprising to people.  The ++ operator is one such example. On numbers, it behaves exactly as expected. When acting on a string, such as "aa", it increments the string ($foo = "aa"; $foo++; echo $foo; prints ab).  It will also roll over so that az when incremented becomes ba.  This isn't particularly surprising yet.

$foo = "3d8";
echo "$foo\n";
$foo++;
echo "$foo\n";
$foo++;
echo "$foo\n";
$foo++;
echo "$foo\n";

(ideone)

This prints out:

3d8
3d9
3e0
4

Welcome to the dangers of implicit conversions and operators acting different on the same string. (Perl handles that code block a bit differently - it decides that "3d8" when the ++ operator is applied is a numeric value from the start and goes to 4 right away (ideone) - this behavior is well described in perlop: Auto-increment and Auto-decrement)

Now, why one language does something one way and another does it another way gets to the design thoughts of the designers.  Perl's philosophy is There's more than one way to do it - and I can think of a number of ways of doing some of these operations.  On the other hand, Python has a philosophy described in PEP 20 -- The Zen of Python which states (among other things): "There should be one-- and preferably only one --obvious way to do it."

These design differences have lead to different languages. There is one way to get the length of a number in Python.  Implicit conversion goes against this philosophy.

Related reading: Why doesn't Ruby have implicit conversion of Fixnum into String?


问:
Save flags in an int32
Unity3d PlayerPrefs only allow saving certain types - string, float, and int32. Since int is composed of 32 bits, it should be able to store 32 flags or a bool[] of length 32.

So far, I've thought about setting the int based on a binary number of 32 digits, where each digit represents a flag. I'm having trouble doing this with consideration of negative numbers.

Is there a way to access each individual bit of the int without recursive math to store and use them as flags?

答: Yes, there is a Flags attribute that lets you use enums as flags for an int, and the type has methods to help identify if a flag is set and the such.</p>

Title: Save flags in an int32


答:
Expanding on @Telastyn's answer, you can declare your flags as an enum with the Flags attribute instead of using an array of booleans:

```<code>[Flags]
public enum Options : uint {
    Empty = 0,
    FancyClouds = 1,
    EnhancedGrassTextures = 2,
    HiDefNoses = 4,
    NoPantsMode = 8,
    // etc. values are increasing powers of 2 up to 2^31
}
</code>```

You can fiddle with the flags using bitwise operators:

```<code>Options flags = Options.HiDefNoses | Options.FancyClouds;
flags &= ~Options.HiDefNoses;               // remove an option
if ((flags & Options.HiDefNoses) != 0) {    // test an option
if (flags.HasFlag(Options.HiDefNoses)) {    // same thing, nicer(?) syntax
</code>```

And the enum value can be (explicitly) cast to and from Int32:

```<code>int i = (int)flags;
Options o = (Options)i;     // round-tripped to int and back
</code>```

Title: Save flags in an int32

Body:
Unity3d PlayerPrefs only allow saving certain types - string, float, and int32. Since int is composed of 32 bits, it should be able to store 32 flags or a bool[] of length 32.

So far, I've thought about setting the int based on a binary number of 32 digits, where each digit represents a flag. I'm having trouble doing this with consideration of negative numbers.

Is there a way to access each individual bit of the int without recursive math to store and use them as flags?

Body:
Expanding on @Telastyn's answer, you can declare your flags as an enum with the Flags attribute instead of using an array of booleans:

[Flags]
public enum Options : uint {
    Empty = 0,
    FancyClouds = 1,
    EnhancedGrassTextures = 2,
    HiDefNoses = 4,
    NoPantsMode = 8,
    // etc. values are increasing powers of 2 up to 2^31
}

You can fiddle with the flags using bitwise operators:

Options flags = Options.HiDefNoses | Options.FancyClouds;
flags &= ~Options.HiDefNoses;               // remove an option
if ((flags & Options.HiDefNoses) != 0) {    // test an option
if (flags.HasFlag(Options.HiDefNoses)) {    // same thing, nicer(?) syntax

And the enum value can be (explicitly) cast to and from Int32:

int i = (int)flags;
Options o = (Options)i;     // round-tripped to int and back


答:
You're saying that implicit conversions could be a good idea for operations that are unambiguous, like int a = 100; len(a), where you obviously mean to convert the int to a string before calling.

But you're forgetting that these calls may be syntactically unambiguous, but they may represent a typo made by the programmer who meant to pass a1, which is a string. This is a contrived example, but with IDEs providing autocomplete for variable names, these mistakes happen.

The type system aims to help us avoid errors, and for languages who choose stricter type checking, implicit conversions undermine that.

Check out Javascript's woes with all the implicit conversions performed by ==, so much so that many now recommend sticking with the no-implicit-conversion === operator.


答:
Consider for a moment the context of your statement.  You say this is the "only way" it could work, but are you really sure it will work like that?  What about this:

```<code>def approx_log_10(s):
    return len(s)
print approx_log_10(3.5)  # "3" is probably not what I'm expecting here...
</code>```

As others have mentioned, in your very specific example, it seems simple for the compiler to intuit what you meant.  But in a larger context of more complicated programs, it is often not at all obvious whether you meant to input a string, or typo'd one variable name for another, or called the wrong function, or any of dozens of other potential logic errors.

In the case where the interpreter/compiler guesses what you meant, sometimes it's magically works, and then other times you spend hours debugging something that mysteriously doesn't work for no apparent reason.  It is much safer, in the average case, to be told that the statement doesn't make sense, and spend a few seconds correcting it to what you actually meant.

Body:
Consider for a moment the context of your statement.  You say this is the "only way" it could work, but are you really sure it will work like that?  What about this:

def approx_log_10(s):
    return len(s)
print approx_log_10(3.5)  # "3" is probably not what I'm expecting here...

As others have mentioned, in your very specific example, it seems simple for the compiler to intuit what you meant.  But in a larger context of more complicated programs, it is often not at all obvious whether you meant to input a string, or typo'd one variable name for another, or called the wrong function, or any of dozens of other potential logic errors.

In the case where the interpreter/compiler guesses what you meant, sometimes it's magically works, and then other times you spend hours debugging something that mysteriously doesn't work for no apparent reason.  It is much safer, in the average case, to be told that the statement doesn't make sense, and spend a few seconds correcting it to what you actually meant.


问:
The need for Explicit Type Conversion in C#
Consider the following code:

```<code>DerivedClass drbObj = (DerivedClass)obj;
</code>```

Here obj is of type Object and this is reasonable since Object is the base type of every Class in C#.

Here, since the type of derObj is defined at compile time, what is the need to explicitly use type conversion here. Can't the compiler predict on it's own that it will be of DerivedClass. I understand that, the Conversion type doesn't have to match the Derived type, but for practical purpose, it will only be as useful as the Derived type.

Could someone explain with a small, hypothetical example, as to why the Explicit Type Conversion is necessary when a reference of type Object is being assigned to a derived class.

From what I know, in C, there is no  need to do perform Explicit type conversion from void* to any pointer and the compiler can handle it, based on the type of the pointer to which the converted value is being assigned.

答:
When asking "why," it is important to ask two sub-questions.  What does this gain us, and what does this lose us?

What does this gain us?

Nothing, actually.  I would guess you want to cut down on copy paste.  That's an admirable goal, but the idiomatic C# way to write this is actually:

```<code>var drbObj = (DerivedClass)obj;
</code>```

What does this lose us?

Compile-time checks on runtime safety.  The compiler usually doesn't know for sure that obj will always hold a reference to an instance of the derived class.  It also doesn't know whether you are willing to risk an uncaught type-casting exception here.  It doesn't know how to handle this situation at compile time.

When you put in the explicit cast, you are resolving that problem.  You are explicitly telling the compiler, "I know that there is a DerivedClass instance in here, and I am willing to suffer an exception if I'm wrong."  The compiler then does what you told it.  It would be quite risky (runtime crashes without warning?  no thanks!) to let the compiler decide to do that on its own.

Body:
When asking "why," it is important to ask two sub-questions.  What does this gain us, and what does this lose us?

What does this gain us?

Nothing, actually.  I would guess you want to cut down on copy paste.  That's an admirable goal, but the idiomatic C# way to write this is actually:

var drbObj = (DerivedClass)obj;

What does this lose us?

Compile-time checks on runtime safety.  The compiler usually doesn't know for sure that obj will always hold a reference to an instance of the derived class.  It also doesn't know whether you are willing to risk an uncaught type-casting exception here.  It doesn't know how to handle this situation at compile time.

When you put in the explicit cast, you are resolving that problem.  You are explicitly telling the compiler, "I know that there is a DerivedClass instance in here, and I am willing to suffer an exception if I'm wrong."  The compiler then does what you told it.  It would be quite risky (runtime crashes without warning?  no thanks!) to let the compiler decide to do that on its own.