答:
Ixrec's answer is good, but I will take a different approach because I believe that it is worth considering.  For the purpose of this discussion I will be talking about assertions, since that's the name by which your Preconditions.checkNotNull() has traditionally been known.

What I would like to suggest is that programmers often overestimate the degree by which they are certain that something will behave in a certain way, and underestimate the consequences of it not behaving that way. Also, programmers often do not realize the power of assertions as documentation. Subsequently, in my experience, programmers assert things far less often than they should.

My motto is:

The question you should always be asking yourself is not  "should I
  assert this?" but "is there anything I forgot to assert?"

Naturally, if you are absolutely sure that something behaves in a certain way, you will refrain from asserting that it did in fact behave that way, and that's for the most part reasonable. It is not really possible to write software if you cannot trust anything.

But there are exceptions even to this rule.  Curiously enough, to take Ixrec's example, there exists a type of situation where it is perfectly desirable to follow int i = 3; with an assertion that i is indeed within a certain range.  This is the situation where i is liable to be altered by someone who is trying various what-if scenarios, and the code which follows relies on i having a value within a certain range, and it is not immediately obvious by quickly looking at the following code what the acceptable range is.  So, int i = 3; assert i >= 0 && i < 5; might at first seem nonsensical, but if you think about it, it tells you that you may play with i, and it also tells you the range within which you must stay.  An assertion is the best type of documentation, because it is enforced by the machine, so it is a perfect guarantee, and it gets refactored together with the code, so it remains always pertinent.

Your getUser(int id) example is not a very distant conceptual relative of the assign-constant-and-assert-in-range example. You see, by definition, bugs happen when things exhibit behavior which is different from the behavior that we expected. True, we cannot assert everything, so sometimes there will be some debugging.  But it is a well established fact in the industry that the quicker we catch an error, the less it costs. The questions you should ask are not only how sure you are that getUser() will never return null, (and never return a user with a null name,) but also, what kinds of bad things will happen with the rest of the code if it does in fact one day return something unexpected, and how easy it is by quickly looking at the rest of the code to know precisely what was expected of getUser().

If the unexpected behavior would cause your database to become corrupt, then maybe you should assert even if you are 101% sure it won't happen.  If a null user name would cause some weird cryptic untraceable error thousands of lines further down and billions of clock cycles later, then perhaps it is best to fail as early as possible.

So, even though I do not disagree with Ixrec's answer, I would suggest that you seriously consider the fact that assertions cost nothing, so there is really nothing to be lost, only to be gained, by using them liberally.


问:
Why are the types in Java considered less 'strong' than haskell?
I asked this question a while ago - the answers were really helpful, and as I read them and the questions that were linked - I also saw this, and the first answer I think really addresses what I thought was the essence of the more powerful type system.

I was trying to really understand the pseudo-implementation of the functor that the author gives in his example - and I wondered if anyone can give me a slightly simpler explanation of this part of his answer.

Directly quoted from the answer - it's these bits that I don't quite get.

for this block of code.

interface Functor {
    Functor map(Function f);
}
```

The type system doesn't allow us to express the invariant that the
  map method always returns the same Functor subclass as the receiver.

Therefore, there's no statically type-safe manner to invoke a
      non-Functor method on the result of map.

Is a simple way of looking at this that in a concrete implementation of Functor, you can declare what you want to use as A,  but not what you want to use as B, or even the B is the same on both sides of the map function?

More generall, my slightly simplistic interpretation of this is that single-kinded types really mean that it limits how far you can "reach" or "specify" the contract you are trying to specify with your types. With higher kinded types, you get much more flexibility on how you specify your types, i.e you can constrain and bind your functions more specifically that you can with simple java generics.

... or I really it could be that I just don't understand what a Type Constructor is or why it's useful!

答:
It is helpful to look at Haskell code from the original answer:

```<code>class Functor f where
    fmap :: (a -> b) -> f a -> f b
</code>```

Here f denotes the same type in both f a (argument) and f b (result).

In Java version, Functor in result doesn't guarantee that it's the same Functor as in Functor. Let's start with correct example:

```<code>// This functor is totally OK: map returns the same type
class ContainerFunctor<A> implements Functor<A> {
    private final A element;

    public ContainerFunctor(A element) {
        this.element = element;
    }

    public ContainerFunctor<B> map(Function<A, B> f) {
        return new ContainerFunctor<B>(f.apply(element));
    }
}

// Usage:

ContainerFunctor<Integer> intF = new ContainerFunctor<Integer>(123);
ContainerFunctor<String> strF = intF.map(new Function<Integer, String> {
    public String apply(Integer i) {
        return i.toString();
    }
});
</code>```

Here intF and strF are the same kind of functors, ContainerFunctor, which is expected behavior of a functor.

Now let's see how it can be violated:

```<code>class BrokenFunctor implements Functor<A> {
    private final A element;

    public BrokenFunctor(A element) {
        this.element = element;
    }

    // it SHOULD return BrokenFunctor, but type system can't force it
    Functor<B> map(Function<A, B> f) {
        return new ContainerFunctor<B>(f.apply(element));
    }
}

// Usage:

BrokenFunctor<Integer> intF = new BrokenFunctor<Integer>(123);

// Broken!
BrokenFunctor<String> strF = (BrokenFunctor<String>) intF.map(new Function<Integer, String> {
    public String apply(Integer i) {
        return i.toString();
    }
});
</code>```

The Java's type system is weaker in this case: there is no way to force BrokenFunctor.map to return another BrokenFunctor as a result. This is bad because we cannot tell what kind of functor we will end up with after calling map. We still can make it right by discipline (telling everyone about the additional implicit contract of an interface), but there is no way to force it. So, if you ever create an interface like Functor, you can't force all possible implementations to be correct.

The type system doesn't allow us to express the invariant that the map method always returns the same Functor subclass as the receiver

True: in example above, BrokenFunctor.map doesn't return BrokenFunctor.

Therefore, there's no statically type-safe manner to invoke a non-Functor method on the result of map.

Also true: we have to cast the result of BrokenFunctor.map to ContainerFunctor to make it work:

```<code>// not type-safe!
ContainerFunctor<String> strF = (ContainerFunctor<String>) intF.map(new Function<Integer, String> {
    public String apply(Integer i) {
        return i.toString();
    }
});
</code>```

And again, in case of ContainerFunctor casting is not needed, but there is no way to force all implementations to behave this way.

ContentLicense: CC BY-SA 3.0

Body:
It is helpful to look at Haskell code from the original answer:

class Functor f where
    fmap :: (a -> b) -> f a -> f b

Here f denotes the same type in both f a (argument) and f b (result).

In Java version, Functor<B> in result doesn't guarantee that it's the same Functor as in Functor<A>. Let's start with correct example:

// This functor is totally OK: map returns the same type
class ContainerFunctor<A> implements Functor<A> {
    private final A element;

    public ContainerFunctor(A element) {
        this.element = element;
    }

    public ContainerFunctor<B> map(Function<A, B> f) {
        return new ContainerFunctor<B>(f.apply(element));
    }
}

// Usage:

ContainerFunctor<Integer> intF = new ContainerFunctor<Integer>(123);
ContainerFunctor<String> strF = intF.map(new Function<Integer, String> {
    public String apply(Integer i) {
        return i.toString();
    }
});

Here intF and strF are the same kind of functors, ContainerFunctor, which is expected behavior of a functor.

Now let's see how it can be violated:

class BrokenFunctor implements Functor<A> {
    private final A element;

    public BrokenFunctor(A element) {
        this.element = element;
    }

    // it SHOULD return BrokenFunctor, but type system can't force it
    Functor<B> map(Function<A, B> f) {
        return new ContainerFunctor<B>(f.apply(element));
    }
}

// Usage:

BrokenFunctor<Integer> intF = new BrokenFunctor<Integer>(123);

// Broken!
BrokenFunctor<String> strF = (BrokenFunctor<String>) intF.map(new Function<Integer, String> {
    public String apply(Integer i) {
        return i.toString();
    }
});

The Java's type system is weaker in this case: there is no way to force BrokenFunctor.map to return another BrokenFunctor as a result. This is bad because we cannot tell what kind of functor we will end up with after calling map. We still can make it right by discipline (telling everyone about the additional implicit contract of an interface), but there is no way to force it. So, if you ever create an interface like Functor, you can't force all possible implementations to be correct.

The type system doesn't allow us to express the invariant that the map method always returns the same Functor subclass as the receiver

True: in example above, BrokenFunctor.map doesn't return BrokenFunctor.

Therefore, there's no statically type-safe manner to invoke a non-Functor method on the result of map.

Also true: we have to cast the result of BrokenFunctor.map to ContainerFunctor to make it work:

// not type-safe!
ContainerFunctor<String> strF = (ContainerFunctor<String>) intF.map(new Function<Integer, String> {
    public String apply(Integer i) {
        return i.toString();
    }
});

And again, in case of ContainerFunctor casting is not needed, but there is no way to force all implementations to behave this way.


问:
Should I validate a method call's return value even if I know that the method can't return bad input?
I'm wondering if I should defend against a method call's return value by validating that they meet my expectations even if I know that the method I'm calling will meet such expectations.

GIVEN

```<code>User getUser(Int id)
{
    User temp = new User(id);
    temp.setName("John");

    return temp;
}
</code>```

SHOULD I DO

```<code>void myMethod()
{
    User user = getUser(1234);
    System.out.println(user.getName());
}
</code>```

OR

```<code>void myMethod()
{
    User user = getUser(1234);

    // Validating
    Preconditions.checkNotNull(user, "User can not be null.");
    Preconditions.checkNotNull(user.getName(), "User's name can not be null.");

    System.out.println(user.getName());
}
</code>```

I'm asking this at the conceptual level. If I know the inner workings of the method I'm calling. Either because I wrote it or I inspected it. And the logic of the possible values it returns meet my preconditions. Is it "better" or "more appropriate" to skip the validation, or should I still defend against wrong values before proceeding with the method I'm currently implementing even if it should always pass.

My conclusion from all answers (feel free to come to your own):

Assert when

The method has shown to misbehave in the past

The method is from an untrusted source

The method is used from other places, and does not explicitly state it's post-conditions

Do not assert when:

The method lives closely to yours (see chosen answer for details)

The method explicitly defines it's contract with something like proper doc, type safety, a unit test, or a post-condition check

Performance is critical (in which case, a debug mode assert could work as a hybrid approach)

答:
I would argue that the premise of your question is off: why use a null reference to begin with?

The null object pattern is a way to return objects that essentially do nothing: rather than return null for your user, return an object that represents "no user."

This user would be inactive, have a blank name, and other non-null values indicating "nothing here." The primary benefit is you do not need to litter your program will null checks, logging, etc. you just use your objects.

Why should an algorithm care about a null value? The steps should be the same. It is just as easy and far clearer to have a null object that returns zero, blank string, etc.

Here is an example of code checking for null:

```<code>User u = getUser();
String displayName = "";
if (u != null) {
  displayName = u.getName();
}
return displayName;
</code>```

Here is an example of code using a null object:

```<code>return getUser().getName();
</code>```

Which is clearer? I believe the second one is.

While the question is tagged java, it is worth noting that the null object pattern is really useful in C++ when using references. Java references are more like C++ pointers, and allow null. C++ references cannot hold nullptr. If one would like to have something analogous to a null reference in C++, the null object pattern is the only way I know of to accomplish that.

Body:
I would argue that the premise of your question is off: why use a null reference to begin with?

The null object pattern is a way to return objects that essentially do nothing: rather than return null for your user, return an object that represents "no user."

This user would be inactive, have a blank name, and other non-null values indicating "nothing here." The primary benefit is you do not need to litter your program will null checks, logging, etc. you just use your objects.

Why should an algorithm care about a null value? The steps should be the same. It is just as easy and far clearer to have a null object that returns zero, blank string, etc.

Here is an example of code checking for null:

User u = getUser();
String displayName = "";
if (u != null) {
  displayName = u.getName();
}
return displayName;

Here is an example of code using a null object:

return getUser().getName();

Which is clearer? I believe the second one is.

While the question is tagged java, it is worth noting that the null object pattern is really useful in C++ when using references. Java references are more like C++ pointers, and allow null. C++ references cannot hold nullptr. If one would like to have something analogous to a null reference in C++, the null object pattern is the only way I know of to accomplish that.


答:
If null is a valid return value of the getUser method, then your code should handle that with an If, not an Exception - it is not an exceptional case.

If null is not a valid return value of the getUser method, then there is a bug in getUser - the getUser method should throw an exception or otherwise be fixed.

If the getUser method is part of an external library or otherwise can't be changed and you want exceptions to be thrown in the case of a null return, wrap the class and method to perform the checks and throw the exception so that every instance of the call to getUser is consistent in your code.

Title: Should I validate a method call's return value even if I know that the method can't return bad input?

Body:
I'm wondering if I should defend against a method call's return value by validating that they meet my expectations even if I know that the method I'm calling will meet such expectations.

GIVEN

```<code>User getUser(Int id)
{
    User temp = new User(id);
    temp.setName("John");

    return temp;
}
</code>```

SHOULD I DO

```<code>void myMethod()
{
    User user = getUser(1234);
    System.out.println(user.getName());
}
</code>```

OR

```<code>void myMethod()
{
    User user = getUser(1234);

    // Validating
    Preconditions.checkNotNull(user, "User can not be null.");
    Preconditions.checkNotNull(user.getName(), "User's name can not be null.");

    System.out.println(user.getName());
}
</code>```

I'm asking this at the conceptual level. If I know the inner workings of the method I'm calling. Either because I wrote it or I inspected it. And the logic of the possible values it returns meet my preconditions. Is it "better" or "more appropriate" to skip the validation, or should I still defend against wrong values before proceeding with the method I'm currently implementing even if it should always pass.

My conclusion from all answers (feel free to come to your own):

Assert when

The method has shown to misbehave in the past

The method is from an untrusted source

The method is used from other places, and does not explicitly state it's post-conditions

Do not assert when:

The method lives closely to yours (see chosen answer for details)

The method explicitly defines it's contract with something like proper doc, type safety, a unit test, or a post-condition check

Performance is critical (in which case, a debug mode assert could work as a hybrid approach)


问:
How to decide what library to use?
I'm faced with the question of what library to use in an Android app.  For the sake of generality and objectivity, I'll avoid mentioning what the libraries actually do.  I've narrowed the field down to three options based on the criteria mentioned in the description of each.

My question is not which library is "best" for this or any other situation.  Rather, I'm interested in your insights into what other criteria I might apply to my decision, or anything else I might not have considered.

Whatever I choose, I'll be stuck with it.  The paradigms of the two libraries are different enough that I don't think it would be practical to wrap them in a common API and switch between them later.

Option #1: The old standby

The good: I've used this library in other apps and I'm quite comfortable with it.  The Javadoc is thorough.  The jar is only 95 KB.

The bad: Google recently deprecated the entire API that this library depends on.  This API is open source and still supported by the original developers, but Google's deprecation indicates that they plan to remove it from Android's standard library.  The developer of the library I'm using has announced plans to fork the third-party API and bundle it into his own library to guard against its eventual removal from Android.  Napkin math says this will bloat the library to at least 1 MB, and maybe twice that, since I don't know exactly which libraries it depends on.

Option #2: The shiny new solution

The good: This library has a lot more features than the one I've been using, and would replace an additional 163 KB of other libraries (258 KB total).

The bad: No Javadoc.  Normally I would consider that an instant deal-breaker, but my back is to the wall.  Without proper documentation, I expect it to cost at least a week or two to get comfortable with.  Weighs in at 573 KB, plus another 216 KB for an optional higher level abstraction.  So three times the size of what it's replacing, but potentially a third of the future size of what it's replacing.

Option #3: Roll my own

The good: It would be based on the API that Google is keeping, so it would be very small.  There would be Javadoc.  Other developers may be facing this same dilemma, so my API could become a product in its own right.

The bad: It would not be as feature-rich as option #1, let alone option #2.  It would cost me at least two weeks to write.

答:
Option #1: The old standby

Deprecated stuff should never be used if there is another option. Any libraries built using this deprecated library will technically be deprecated.  So your product would be deprecated before it was even finished.

It was deprecated for a reason. Typically that reason is that there is something better in every aspect, and you should use that.

Option #2: The shiny new solution

It sounds like this is the something better. I think you should bite the bullet, and climb that learning curve. This allows someone else to do the heavy lifting of creating it, updating it, and maintaining it. You don't want that on your plate.

Option #3: Roll my own

This is probably what I would do (despite my own advice). It does exactly what you want with zero overhead. You know exactly how it works. But...you have to make it. Making it will probably take longer than learning #2.  Don't reinvent the wheel.

Summary

I think #1 and anything deprecated should be avoided like the plague. #3 sounds the most appealing, but I would advise #2.

Title: How to decide what library to use?


答:
Only you know what your resources are: time, associated headaches, etc. However, this is the approach I advocate in the general case:

Avoid deprecated APIs unless there is no other alternative and they are not going away anytime soon. I could name several deprecated or otherwise unfavored APIs that have been sitting around 10+ years with no plans of being removed. Android is much more prone to those deprecated APIs going away, so in this case, avoid them like the plague.

Unless space really is at a premium (embedded), why bother unless a library is outrageously huge, like 100 mb? As an aside, I wish there were an easy way to prune libraries in Java/Dalvik the way C and C++ linkers do.

Prefer to use a built-in API when available: failing that, prefer to use a third-party (preferably free/open source) library if it is actively maintained. Abandonware helps no one. Finally, as a last resort, roll your own. I would open it up and maintain it, which helps others and gives back to the community.

Title: How to decide what library to use?

Body:
I'm faced with the question of what library to use in an Android app.  For the sake of generality and objectivity, I'll avoid mentioning what the libraries actually do.  I've narrowed the field down to three options based on the criteria mentioned in the description of each.

My question is not which library is "best" for this or any other situation.  Rather, I'm interested in your insights into what other criteria I might apply to my decision, or anything else I might not have considered.

Whatever I choose, I'll be stuck with it.  The paradigms of the two libraries are different enough that I don't think it would be practical to wrap them in a common API and switch between them later.

Option #1: The old standby

The good: I've used this library in other apps and I'm quite comfortable with it.  The Javadoc is thorough.  The jar is only 95 KB.

The bad: Google recently deprecated the entire API that this library depends on.  This API is open source and still supported by the original developers, but Google's deprecation indicates that they plan to remove it from Android's standard library.  The developer of the library I'm using has announced plans to fork the third-party API and bundle it into his own library to guard against its eventual removal from Android.  Napkin math says this will bloat the library to at least 1 MB, and maybe twice that, since I don't know exactly which libraries it depends on.

Option #2: The shiny new solution

The good: This library has a lot more features than the one I've been using, and would replace an additional 163 KB of other libraries (258 KB total).

The bad: No Javadoc.  Normally I would consider that an instant deal-breaker, but my back is to the wall.  Without proper documentation, I expect it to cost at least a week or two to get comfortable with.  Weighs in at 573 KB, plus another 216 KB for an optional higher level abstraction.  So three times the size of what it's replacing, but potentially a third of the future size of what it's replacing.

Option #3: Roll my own

The good: It would be based on the API that Google is keeping, so it would be very small.  There would be Javadoc.  Other developers may be facing this same dilemma, so my API could become a product in its own right.

The bad: It would not be as feature-rich as option #1, let alone option #2.  It would cost me at least two weeks to write.


问:
Using MonoDevelop for Commercial Software Developing
Can I sell the software which are developed with MonoDevelop without distribution of my source code and with commercial license?

Generally, Does the license of language and IDE affect the license of application developed using them? for example: Qt, MonoDevelop, ...

答:
The license of the IDE that was used to develop software generally does not have any impact on the licensing of the software that you wrote. The IDE is a tool, not a library. The IDE does not get distributed with your software in the end, unlike a library.

However, if you wanted to distribute a modified version of MonoDevelop, you would need to adhere to the license. In MonoDevelop's case, it is dual licensed with LGPL and MIT.

Libraries like Qt, however, do have an impact. Libraries are an integral part of your program and you need to adhere to its licensing.


答:
MonoDevlop is licensed by a mixture of LGPLv2 and X11/MIT code, therefore you can use it to develop any kind of software you want.

Your examples of MonoDevlop and Qt target two completely different realms:

Tools, such as MonoDevelop: While the license of a software tool such as an IDE doesn't usually affect the license of your work per se, if the license has restrictions on usage, it absolutely can have a broad influence on what software you can create with it, though it's a bit murky. If you have a 'non-commercial' version of an IDE, you could conceivably make closed-source freeware where you don't share the source, but you don't sell it either.
In the case of free software licenses such as the GPL or MIT, etc, which have no restrictions on use, then the licenses have no bearing whatsoever on what you use the tools to create*.

Libraries: Using libraries makes your software a derivative work of them, so they have absolute influence over what kind of license you pick, it must be compatible with the library or you may not use it. A good example is the GPL. To use a GPL library, your software must be GPL. (Which, doesn't necessarily restrict selling it commercially, but if sold, your customers can sell it themselves, too). To use Qt in a commercial program, you must dynamically link against it in order to abide by the LGPL, or fork over the cash for a commercial license of it.

*With some exceptions that you are pretty much guaranteed not to run into unless you are making a compiler.

Title: Using MonoDevelop for Commercial Software Developing

Body:
Can I sell the software which are developed with MonoDevelop without distribution of my source code and with commercial license?

Generally, Does the license of language and IDE affect the license of application developed using them? for example: Qt, MonoDevelop, ...


问:
Dealing with states in a immutable approach
I want to know how to deal when you have some states in a program, with functions that depends on them, but with a immutable approach. I read some examples and questions, but all focus in a small scenario, I want to understand this in a bigger program, close to real world.

My question isn't about some programming language or paradigm (it could be done with Java for eg. since we don't change variables values), so I'll illustrate a simple problem with this pseudo code:

```<code>--some states of my program
playerOne = {
  cards :: [Card]
  score :: Int
}
playerTwo = {
  cards :: [Card]
  score :: Int
}
tableCards :: [Card]

--a function that will perform a move in a game
--it needs to move a card from player to tableCards
--it needs to change the other player score with -1
doSomeMove()

--moves
doSomeMove(playerOne)
showScore() --p1: 10 p2: 9 tableCards: 1
doSomeMove(playerTwo)
showScore() --p1: 9 p2: 9 tableCards: 2
doSomeMove(playerOne)
showScore() --p1: 9 p2: 8 tableCards: 3
doSomeMove(playerTwo)
showScore() --p1: 8 p2: 8 tableCards: 4
</code>```

First: in "doSomeMove()" I need to read a player cards. Since I'll call this function in the middle of the game I can't read from "playerOne" variable, since it's immutable and won't change in the middle of the game! So how can I solve this? To read actual program current states? do I need to always receive the actual player cards states by parameter?

Second: I'll change cards (both player and table) and other player score in this function. As I can't really change the variables (since it's immutable) I'll clone them, and set the changed state in a local variable inside the function, right? But how can next function (doSomeMove() or others) will know about this change?

Basically, the only thing that I can think to solve is: getting whole program state by parameter, do some changes, and return everything as parameter as well to next function use and be aware of state changes. But I think this is very unpractical, since if I have 20 states, and 50 functions, do I need to all 50 functions passing and return all 20 states each one?

I don't want to solve this problem, just to understand how to solve programs like this or bigger with immutability. And I hope this question helps another people, since I asked to some people how to solve this and no one answered surely! Thanks!

答:
To reflect the changed state of an object (I will call this object now and reference with this to the OOP paradigm) you can return this object again which in itself is immutable again, e.g.

```<code>playerOne = doSomeMove(playerOne)
</code>```

Basically this is the idea behind the state pattern.

With this the single object is immutable but your changes are reflected by creating new objects (which is also the way an immutable list works).

If you have to change two objects at once then you have to look how to return them.

I think your basic misconception is to use global variables and treat them as immutable (differentiate between an immutable object state and an immutable variable.

Body:
To reflect the changed state of an object (I will call this object now and reference with this to the OOP paradigm) you can return this object again which in itself is immutable again, e.g.

playerOne = doSomeMove(playerOne)

Basically this is the idea behind the state pattern.

With this the single object is immutable but your changes are reflected by creating new objects (which is also the way an immutable list works).

If you have to change two objects at once then you have to look how to return them.

I think your basic misconception is to use global variables and treat them as immutable (differentiate between an immutable object state and an immutable variable.


问:
Licensing - Open Source with Paid Distribution
I have a project consisting of a core library with a number of platform-specific wrapper libraries. I want to release it all under an Open Source license (maybe MIT or LPGL).

I also want to sell the compiled binaries and support on platform-specific stores as an optional convenience to users. They will be able to build it themselves for free if they prefer, directly from the source.

Is this possible with standard licenses? Are there any considerations I should be aware of?

答:
It is possible, but you won't forbid someone to get the source code, perhaps adapt it, compile it, and distribute the resulting binary.

If you use the LGPL license, the entity redistributing binaries should (AFAIK) publish (as LGPL) the modified source code. If you use MIT license, that entity could redistribute binaries without even publishing its modifications.

I am not a lawyer, so ask your lawyer for details.

Read at least the LGPL license and its FAQ.


问:
How do you maintain productivity outside of work? (Programming Schedule)
I enjoy programming, but programming at work is just that, work. I would like to further develop my own personal interests in programming. Throughout the week I imagine myself completing a small project on the weekend or finishing up a programming related book. However, in reality I often fall short of my expectations. I often will get just one or two chapters of reading done and even less coding. In reality I will spend time surfing the net, watching television, or visiting friends and slacking off... because it is the weekend. But when Sunday evening rolls around I often reflect on my weekend and I am sorely disappointed with my use of time.

So my question is how do you maintain your productivity outside of work? I am sure some programmers could care less about programming on their free time. Although, I think the majority of programmers, especially on stackexchange, are passionate about programming.

Should I spend the weekend programming, or will I burn out and resent programming if I dedicate that much time to it?

How should I go about programming on my free time? Should I set a schedule? How much time should I dedicate to it? Most importantly how do I follow that schedule? Its only human nature to procrastinate.

I know there is a lot of questions here. Feel free to answer the ones that relate to how you remained focused outside of work. I am passionate about programming but after 40 hours of programming it can be difficult to maintain that enthusiasm.

答: Perhaps you need to adjust your expectations of yourself.  Weekends are supposed to be fun and relaxing, so spending time with friends and the other activities you mention sound more appropriate to me than spending your whole weekend coding or reading computer books.  You have to give your brain time to recharge.  Now if a project strikes your passion and you want to spend time writing it on the weekend, go for it.  Or if a new technology interests you and you want to read a book on the subject outside of work hours, great!  But it sounds like you are trying to find better ways to force yourself to do something you don't really want to do, which is spend your weekends programming.  Give yourself permission to enjoy your weekends and leave work at the office.

ContentLicense: CC BY-SA 2.5


答:
Open source licenses don't forbid anyone from selling the software for a fee or for providing additional services for a fee.

The main reason that open source software is usually provided for free is that if you ask a fee for the distribution, anyone is allowed to under-bid you and distribute the same software for less money (or even for free).

The difference between the two licenses you mention is that with the LGPL, any modified versions of your software must remain under the LGPL license (with the requirement that source code must be available), while the MIT license allows modified versions to be distributed under a different license (including a closed-source license).

Title: Licensing - Open Source with Paid Distribution

Body:
I have a project consisting of a core library with a number of platform-specific wrapper libraries. I want to release it all under an Open Source license (maybe MIT or LPGL).

I also want to sell the compiled binaries and support on platform-specific stores as an optional convenience to users. They will be able to build it themselves for free if they prefer, directly from the source.

Is this possible with standard licenses? Are there any considerations I should be aware of?


答:
Its tough, I had thought the same way but now I usually don't feel like programming outside of work, although I do read books from time to time.

I recommend trying to move your career in the direction of doing work on the things you like, such as if you are working on PHP (just as a random example) web apps but you really want to do Android mobile device development, maybe try to find freelance projects doing this or eventually find a job doing this (emphasize that you have plenty of programming experience and that it does translate over to this new field, when applying).

Other than that, something I have done a little and have been wanting to do more (and will do when I have more money) is to hire one or two part-time offshore freelancers to work on projects with me (such as through Odesk). This way I can get some things going on projects that I don't have the time to work on myself and step in to do coding when I want. It takes some work to find a good offshore person to work with but it can be done, you just have to maintain a close relationship with them and do code review, etc, at least at first.

Title: How do you maintain productivity outside of work? (Programming Schedule)

Body:
I enjoy programming, but programming at work is just that, work. I would like to further develop my own personal interests in programming. Throughout the week I imagine myself completing a small project on the weekend or finishing up a programming related book. However, in reality I often fall short of my expectations. I often will get just one or two chapters of reading done and even less coding. In reality I will spend time surfing the net, watching television, or visiting friends and slacking off... because it is the weekend. But when Sunday evening rolls around I often reflect on my weekend and I am sorely disappointed with my use of time.

So my question is how do you maintain your productivity outside of work? I am sure some programmers could care less about programming on their free time. Although, I think the majority of programmers, especially on stackexchange, are passionate about programming.

Should I spend the weekend programming, or will I burn out and resent programming if I dedicate that much time to it?

How should I go about programming on my free time? Should I set a schedule? How much time should I dedicate to it? Most importantly how do I follow that schedule? Its only human nature to procrastinate.

I know there is a lot of questions here. Feel free to answer the ones that relate to how you remained focused outside of work. I am passionate about programming but after 40 hours of programming it can be difficult to maintain that enthusiasm.


问:
Receive events in an event-loop, single-threaded
Let's say I have a program which consists of a main event loop. The event loop should check for tasks and if one exists, it is to be processed. The user interface consists of a GUI with buttons, for each of which can be defined a callback function when it is pressed.

Using multiple threads, I can simply execute the event loop in a separate thread. When a button is pressed, I feed a task into a queue which is shared by the UI and the event thread. The event thread then consumes and executes the task.

My question is how this behaviour is realized in a single threaded application or a language that does not support multithreading. My idea is to poll for user interaction, but how does this work in said GUI where a button press can only be registered by the invocation of a specified callback?

答:
The OS creates events and feeds it into the OS-supplied Event queue which the application polls in the event loop.

In Windows that is with GetMessage and friends.

Windowing frameworks (java's swing, Qt etc.) will implement this loop for you and allow you to insert your own custom events.


问:
How much trouble can the use of Singleton class as Model cause?
In my latest WPF applications I've been using a Singleton class, that I call Model, to contain all my application's logic, such as file reading, information handling, etc..

In the WPF Views or Windows I just call the methods that I need, when I need them: Model.Instance.GetProducts(string category);

Besides having always the same instance, I find this convenient because I can call any method that I want in any window, and I can define the Model in App.xaml to be a StaticResource and then do the bindings that I need. For example, set the Binding of a DataGrid to an ObservableCollection present in the Model.

What do you think of this approach? A few years ago at college, when working with Windows Forms we used to work with the MVC pattern, where the controller would contain some events that called methods from the Model, and those events would later be invoked by the Views.

答: God object is one of the worst "designs" you can create. Please, put some effort into separating different concerns. Your future self will thank you.</p>


答:
A definite no.

A caller should not ever check if the function it is calling respects its contract. The reason is simple: there are potentially very many callers and it is impractical and arguably even wrong from a conceptual point of view for each and every single caller to duplicate the logic for checking the results of other functions.

If any checks are to be done, each function should check its own post-conditions. The post-conditions give you confidence that you implemented the function correctly and the users will be able to rely on the contract of your function.

If a certain function isn't meant to ever return null, then this should be documented and become part of that function's contract. This is the point of these contracts: offer users some invariants that they can rely on so they face fewer hurdles when writing their own functions.


问:
ER Diagram Multiplicity (UML)
Schema:

```<code>#=PK
Employee (#NIN, fName, lName, address, DOB, sex, salary, taxCode, deptNo)
Department (#deptNo, deptName, managerNIN, businessAreaNo, regionNo)
Project (#projNo, projName, contractPrice, projectManagerNIN, deptNo)
WorksOn (#NIN, #projNo, hoursWorked)
Business (#businessAreaNo, businessAreaName)
Region (#regionNo, regionName)
</code>```

Where:

Department contains department details and deptNo is the key. managerNIN identifies the employee who is the manager of the department. There is only one manager for each department.

Project contains details of the projects in the company and the key is projNo. The project manager is identified by the projectManagerNIN, and the  department responsible for the project by deptNo.

WorksOn contains details of the hours worked by employees on each project and (NIN, projNo) forms the key.

Business contains names of the business areas and the key is businessAreaNo

Region contains names of the regions and the key is regionNo

This is the UML diagram that I've come up with:

I'm not sure how wrong/correct this is, but I'm particularly concerned with the multiplicities and the relationship that Employee has with WorksOn with Project.

For the record this is just a practice exercise.

答:
Several things in your diagram seem to be missing or wrong.

Do you really want to constrain employees to work on just one project?

Do you want to allow that employees work on a project of another department? If not, you have to add a constraint/invariant prohibiting this.

With your current multiplicities for the Employee-manages-Department association you require every employee to manage a department. That's probably not correct.

Title: ER Diagram Multiplicity (UML)


问:
Question about switch-case statement
What happens, and does code work properly if we write switch-case structure like this, why its not good to write code like this? I'm porting some firmware and have switch-case statement interrupted like this one, and when I remove code between that switch-case statements, it begins to operate normally.</p>

```<code>switch(state){
    case 0:
    break;
    case 1:
    break;
    case 2:
    break;
    case 3:
    break;
}

//here we interrupt switch-case and do a some other code

// after that code we continue with same switch

switch(state){
    case 4:
    break;
    case 5:
    break;
    case 6:
    break;
    case 7:
    break;
}
</code>```

答:
Sounds like the code in the middle is changing the value of the state variable, giving you different execution in the second switch statement.  Presumably, this matters; create a new variable, store the value of state into it and use this in the second switch statement:

```<code>int savedState = state ;
switch( savedState ) { ... } // 0, 1, 2, 3
// Other Code
switch( savedState ) { ... } // Everything else
</code>```

Title: Question about switch-case statement

Body:
Sounds like the code in the middle is changing the value of the state variable, giving you different execution in the second switch statement.  Presumably, this matters; create a new variable, store the value of state into it and use this in the second switch statement:

int savedState = state ;
switch( savedState ) { ... } // 0, 1, 2, 3
// Other Code
switch( savedState ) { ... } // Everything else


问:
MVC - Checking data in the model or the controller?
I'm currently creating a web application with Ruby on Rails and I'm facing an conceptual problem about the MVC pattern.

If I need to check, for example, if the name of a data that I want to add in the database exists in a given an array, where do I need to do this? In the controller or the model?

I read everywhere that the model only has to care about the database stuff so I guess it's the controller job.

But with Rails the model seems to do more stuff like the data validation (validate, :presence...) so I'm wondering if it's finally the model which does that?

If it's the model job, it means that I need to pass a controller attribute to the model (the array comes from an API), is it weird?

As asked I give you more details:

My application gets a list of items from an API. I include this list in a form (like in a select tag) and then when the form is submitted I get id of the selected item to finally add it in the database with other information from the form.

Before adding the data to the database I just want to be sure that the id of the item is valid (that's why I need to check if it is present or not in the array - in case of the user modify manually the HTML from his browser...).

答:
IMHO and in my understanding, You are validating the data from the given array, not from the database.

So I strongly believe you should do it in the controller.

the general rule of thumb is to only write database interactions inside model.


答:
You can mix several tasks in a single threaded loop, e.g. by using idle functions (as I explained here).

So with a GUI event loop, when some external event happens (e.g. the user presses a button), the callback could add an idle function into the loop.

Then it is important that the idle function gives back the control to the event loop quite quickly (typically, in a few milliseconds). It could add itself again to the loop to continue some processing.

Of course, the concept of continuations is relevant, and you can see an idle-function re-adding itself as some hand-written continuation-passing style

See also this answer for more references.

Title: Receive events in an event-loop, single-threaded

Body:
Let's say I have a program which consists of a main event loop. The event loop should check for tasks and if one exists, it is to be processed. The user interface consists of a GUI with buttons, for each of which can be defined a callback function when it is pressed.

Using multiple threads, I can simply execute the event loop in a separate thread. When a button is pressed, I feed a task into a queue which is shared by the UI and the event thread. The event thread then consumes and executes the task.

My question is how this behaviour is realized in a single threaded application or a language that does not support multithreading. My idea is to poll for user interaction, but how does this work in said GUI where a button press can only be registered by the invocation of a specified callback?


问:
What options does a disciplined developer have when joining a team of undisciplined developers as a regular member, not a lead?
What options does a disciplined developer have when joining a team of undisciplined developers?

Based on an environment of bad developers and a lack of software development infrastructure to guide quality software development, what are the odds that hiring a really good developer to join a team of bad developers will enhance the team's environment versus causing more problems based on a conflict of interest?

Suppose the new hire was not a rock-star, but rather an apprentice to software craftsmanship. Thus, suppose they were hired to be a team member and not a team lead.

Also, suppose "bad developers" are people that call themselves developers but have no desire to continuously improve their practice and instead treat their routine as a job and not as a profession.

答:
Without being in a position of team lead, the options are somewhat limited. There are different bases of power. The individual in your question won't have legitimate power, as they are not the lead or manager and they don't have the position to drive change. However, depending on their personality, they may be able to develop a position of referent power or expert power, but that will take time. Using coercive power likely won't be helpful in enacting changes.

If there is management support for implementing these good practices in the team, then having someone familiar with the practices, the team, and the technical components of the project would be extremely valuable. However, they would need to work closely with the manager to enact any changes. The individual would need to be in it for the long-haul, and understand their role in facilitating management's vision.

If neither management nor the senior members of the team want to change things, though, I think it's very unlikely that anything will change. Change needs to come from somewhere, either top-down from management or bottom-up from the team. If neither side is willing to support change, then change won't happen.

I would be concerned with the ability of the developer to leave. Working in the conditions that you describe - other developers who do not continually improve or mature their skills, lack of good software engineering practices, and not being in a position to drive changes to make the working conditions better - could lead the developer to leave the team or the organization to find a better fit. If the developer continues to work through it, they could see higher levels of stress, anxiety, and even burnout.

Alternatively, driving changes top-down could alienate members of the team. If you have people with very specific, business critical knowledge and you made changes that they see as difficult, they could become disgruntled and leave the organization as well. Management needs to be careful when rolling out changes to begin a transformative process, but not disrupt individuals or business activities.


问:
How to determine what should get its own respective controller?
I'm using the MVC pattern in my web application built with PHP.

I'm always struggling to determine whether I need a new dedicated controller for a set of actions or if I should place them inside an already existing controller.

Are there any good rules of thumb to follow when creating controllers?

For example I can have:

AuthenticationController with actions:

index() to display login form.

submit() to handle form submission.

logout(), self-explanatory.

OR

LoginController with actions:

index() to display login form.

submit() to handle form submission.

LogoutController with action:

index() to handle logging out.

OR

AccountController with actions:

loginGet() to display login form.

loginPost() to handle login form submission.

logoutGet() to handle logging out.

registerGet() to display registration form.

registerPost() to handle form submission.

And any other actions that are are involved with an account.

答:
In order to find the right grouping for controllers, think of the testing.

(Even if you don't actually do any testing, thinking of how you would go about testing your controllers will give you some very good insights on how to structure them.)

An AuthenticationController is not testable by itself, because it only contains functionality for logging in and logging out, but your testing code will need to somehow create fake accounts for testing purposes before it can test a successful login.  You could bypass the subsystem-under-test and go directly to your model for the creation of the testing accounts, but then you will have a fragile test in your hands: if the model changes, you will have to modify not only code which tests the model, but also also code which tests the controller, even though the interface and behavior of the controller has remained unchanged.  That's unreasonable.

A LoginController is unsuitable for the same reasons: you cannot test it without creating accounts first, and there are even more things that you cannot test, like for example preventing duplicate logins but then allowing a user to login after having logged out. (Since this controller has no logout functionality.)

An AccountController will give you everything you need in order to do your testing: you can create a test account and then try to login, you can delete the account and then make sure you cannot login anymore, you can change the password and make sure that the right password has to be used in order to login, etc.

To conclude: in order to write even the smallest test suite, you will need to make all of the functionality of the AccountController available to it.  Subdividing it down to smaller controllers appears to be yielding handicapped controllers with insufficient functionality for a proper test.  This is a very good indication that the functionality of AccountController is the smallest subdivision that makes sense.

And generally speaking, the "think of the testing" approach will work not only in this particular scenario, but in any similar scenario you come across in the future.


答:
Take maxims such as "thy model shall only care about the database stuff" with a grain of salt.  Dogma has no place in engineering.

In order to answer this question you need to first understand the nature of this validation array, and whether it fits conceptually with the model or with controlling the model.

The fact that these names are stored inside an array is inconsequential; you could be sending names out to a serial port and receiving back "yes" or "no" answers for all you care. This could still legitimately be part of your model. The question is: does the task of validation sound to you more like "controlling" the model, or like querying the model?

You have not provided enough details about this mysterious array, but I am tempted to believe that it is 100% part of the model.  The names that it contains could have easily been stored in the database, but for some reason someone decided not to.  If you narrowly think of "the model" as "the database", you might be mislead to think that they don't belong to the model, but if you realize that your model is your representation of all of your entities and the relationships between them, then perhaps it might begin to make sense that the contents of that array are simply describing a relationship which for some reason was not encoded in the database.

After the amendment to the question, I would say with even greater confidence that the list of items (and therefore the list of their ids) is part of the model, though I still cannot say it with complete confidence, since it is still not clear to me what is the nature of these entities and what is the domain that the database describes.

It seems to me, however, that what you are missing is an abstraction layer which combines the database and the API and whatever else you might have into a uniform model which looks homogeneous and spares the rest of your code from having to be concerned about different sources for different subsets of the information that it works with.  Conceptually, if these entities have ids, and these ids are stored in the database, then they are all part of the same model, regardless of where they come from.

Title: MVC - Checking data in the model or the controller?

Body:
I'm currently creating a web application with Ruby on Rails and I'm facing an conceptual problem about the MVC pattern.

If I need to check, for example, if the name of a data that I want to add in the database exists in a given an array, where do I need to do this? In the controller or the model?

I read everywhere that the model only has to care about the database stuff so I guess it's the controller job.

But with Rails the model seems to do more stuff like the data validation (validate, :presence...) so I'm wondering if it's finally the model which does that?

If it's the model job, it means that I need to pass a controller attribute to the model (the array comes from an API), is it weird?

As asked I give you more details:

My application gets a list of items from an API. I include this list in a form (like in a select tag) and then when the form is submitted I get id of the selected item to finally add it in the database with other information from the form.

Before adding the data to the database I just want to be sure that the id of the item is valid (that's why I need to check if it is present or not in the array - in case of the user modify manually the HTML from his browser...).


答:
A code example would help, but in rails, validations belong in the model. Check out validates_inclusion_of.

Also, you should be aware that models dont nescessarily have to be backed by persistence. There are lots of times when it's appropriate to use plain ruby objects. In general, its best to keep as much functionality out of the controller as possible, largely because controllers test are often slow to run, and awkward to write.


答:
If you only want to check that the name exists, yes it belongs to the model.

From wikipedia:

A controller can send commands to the model to update the model's
  state (e.g., editing a document). It can also send commands to its
  associated view to change the view's presentation of the model

You are not doing any of those. You are checking if the name already exists in the database. Think of it as an extra validation.


答:
Most developers are confronted with either creating crappy/less manageable/unscalable/not quite so perfect software in order to meet an arbitrary deadline or they get fired. One reason good programmers are considered good is because they're able to stand up to this because of their reputation, influence, persuasive skills, threatening to leave, etc.

Being a "rockstar" is relative and shouldn't be too hard for someone to shine in this group. Create just as much and better software in half the time. Then you get to leave in the middle of the day. They'll all want to know how you're able to do it. Or more likely, get things done and they'll assign you the tough tasks. Set an example.

Observe what everyone is doing. Ask questions. You may discover that it's not the developers who are not disciplined. Help them fix the things they see as being problems. You can't change everything at once. Few people want to be a bad programmer, but that doesn't mean they're willing to do what it takes to improve. The influence of a good programmer will be accepted by some. A good company can usually weed-out the non-hackers. Don't be surprised if this takes a few years.

Title: What options does a disciplined developer have when joining a team of undisciplined developers as a regular member, not a lead?

Body:
What options does a disciplined developer have when joining a team of undisciplined developers?

Based on an environment of bad developers and a lack of software development infrastructure to guide quality software development, what are the odds that hiring a really good developer to join a team of bad developers will enhance the team's environment versus causing more problems based on a conflict of interest?

Suppose the new hire was not a rock-star, but rather an apprentice to software craftsmanship. Thus, suppose they were hired to be a team member and not a team lead.

Also, suppose "bad developers" are people that call themselves developers but have no desire to continuously improve their practice and instead treat their routine as a job and not as a profession.


问:
Explanation of two of Lehman's Laws of Software Evolution
I have a hard time understanding #3 and #8 of Lehman's Laws of Software Evolution.

The laws are:

(1974) "Self Regulation" — E-type system evolution processes are self-regulating with the distribution of product and process measures close to normal

and

(1996) "Feedback System" (first stated 1974, formalised as law 1996) — E-type evolution processes constitute multi-level, multi-loop, multi-agent feedback systems and must be treated as such to achieve significant improvement over any reasonable base

The rest of the laws are clear to me.

Could someone explain these two laws?

答:
After talking to a professor at my university, and using the information provided by Ilyas and Boris (I will +rep as soon as I recieve 15 rep myself), this is what I have concluded:

Law 3 specifies that the growth of the system will follow the normal distribution curve. This means that the growth will be slower in the beginning and end of the life cycle compared to in the middle.

Law 8 states that software evolution is a complex process where feedback shall be collected from multiple sources (users, managers, runtime environment, application domain, etc.) to achieve significant improvement during the evolution process.

The following link is a pdf which contains alternate explanations for each of the eight laws: http://www.engr.uvic.ca/~seng371/lectures/L12-371-S13-bw.pdf

ContentLicense: CC BY-SA 4.0


问:
Injecting collections as constructor dependencies
We are using constructor dependency injection in our application. Following that approach we inject everything using an injection container so we are able to replace any dependency with a Mock.

Some colleagues complain about this procedure as they say that injecting collections of any type is going too far with injection and they prefer to call a new() inside the constructor.

What do you think about this? What procedure do you follow if you are using dependency injection?

One example of a real use case. We have a Dictionary with an special behavior, it allows to add the same key several times and it just increments an internal counter and it decreases the counter when removing elements from it only removing the element from memory when the counter is 0 (the class has been simplified a bit but I think you can get the idea):

```<code>public class ExtendedDictionary<TValue> : IExtendedDictionary<TValue>
{
    private readonly IDictionary<CustomKey, TValue> dictionary;

    public ExtendedDictionary(IDictionary<CustomKey, TValue> dictionary)
    {
        this.dictionary = dictionary;
    }

    public void Add(ParameterBase parameter, DriveInformation driveInformation, TValue data)
    {
        CustomKey key = new CustomKey (driveInformation, parameter.Index);

        if (this.dictionary.ContainsKey(key))
        {
            this.dictionary.Single(p => p.Key == key).Key.Count++;
        }
        else
        {
            this.dictionary.Add(key, data);
        }
    }

    public void Remove(ParameterBase parameter, DriveInformation driveInformation, TValue data)
    {
        CustomKey key = new CustomKey (driveInformation, parameter.Index);

        if (this.dictionary.ContainsKey(key))
        {
            this.dictionary.Single(p => p.Key == key).Key.Count--;
        }
        else
        {
            this.dictionary.Remove(key);
        }
    }
}
</code>```

答:
Dependency injection is very easy to take too far. You should use is whenever it decreases your overall effort, not because someone says it's a "good practice".

That said, I don't see any fundamental difference between collections and other data used in constructors. If they are liable to change often, or are hard to mock for testing otherwise, go ahead and inject them, and if you have so many of them that doing it by hand would lead to too much repeated code, go ahead and use a DI framework. Otherwise, don't. But deciding whether or not to do it based on the type of the injected thing is probably the wrong thing to do.


答:
This is an ancient debate really.  It goes all the way back to the first databases and the notion of "referential integrity", which in turn is a variation of the strong-typing / weak-typing debate.

Who's job is it to make sure that data is stored in a consistent and "known good" manner?  MVC purists will tell you it's the controller's job.  Database architects will tell you it's the model's job (or even the database's job).  Ux people might even tell you it's the view's job!  Big Data guys may say "It's the person using the data's job."

After being a software engineer / architect / developer for 20+ years, I've come to the conclusion that often the concern is important, but how you solve it is less important, so long as you decide on an approach and maintain it.  So, my advice would be something like:  rather than asking for people's opinions on dogma about it, think through solving the "who owns validation?" discussion using three different approaches: model, view, and controller.  Think about how your app will behave if you solve it those three different ways.  Will your end users be satisfied with all three approaches?  Chances are, depending on where you put this, your end users will experience something different.  Do they have an opinion?  Also, which route costs you the most in terms of time and money?  Which will be easier to maintain and explain to new people?  What about security? All of these things are important considerations when designing a system, and dogmatic answers don't factor these things in -- they substitute a common pattern for your precise context.  Sometimes that's a good idea, sometimes it's a shoe-horn disaster.  Only you can figure out which applies.


问:
Compile-time vs. run-time configuration
I'm starting new project and need to decide on how to handle configuration. I recently run into suckless project. While it has its own issues, I really liked its approach to configuration - just a header file with static variables.

What are pros and cons of using compile-time options vs run-time options (== config file)? Would it be acceptable for product aimed for more tech-savvy users to use compile-time config? Does it still have benefits on modern systems?

I'm focusing modern desktop/laptops, only supported architecture likely will be amd64. Project is GUI application focused on accesing various informations.

答: Your decision whether to have code-based configuration or file-based configuration will depend entirely on whether or not you need the flexibility of configuring at runtime vs. compile time.  Performance is almost certainly a non-issue, since you can cache the values once they are read from the configuration file.</p>

Title: Compile-time vs. run-time configuration


问:
Is doctrine 2 fast enough?
I need to build a social network that is expecting very high traffic, 10k - 50k + registrations in a day, not even including visitors, pageviews, image uploads, etc..., a lot of database activity. We have a solid quad core dedicated server right now with 8GB ddr3 and 2tb hdd sata. Will doctrine be to slow as far as queries and load time to handle such a high traffic website?</p>

答:
Answer is always Use normal queries instead of ORM to get better performance. If your are planning to change the database after some longer period ORM helps to done easily.You  need to sacrifice performance for convenience.

I suggest you to create the separate class where you can perform DML operations by getting the inputs as parameter and create the query and use it to execute it. Instead of writing insert statement each time or for many occurrences . but Make sure too create the query which is more optimized .

Title: Is doctrine 2 fast enough?


答:
This strikes me as a bit extreme, and overkill. I think it's a case of taking the common charge to never use new() in a class a bit too literally.

Injection is useful for having classes consume dependencies whose implementations can change or are (or need to be) replaceable. For unit testing, it's useful to get rid of your own classes that are already under test (and whose bugs should not impact testing of other code), or abstractions over items that make it difficult to isolate your code (such as the file system, databases, and things of that nature). A standard collection is (normally) neither of these. If a class needs to maintain a list of items, that is an implementation detail, and one that shouldn't cause you trouble. To whatever degree the  contents of that list impact the output should be the focus of your testing efforts.

```<code>public class Foo
{
    // limit, not eliminate, new()
    Frobber frobber = new Frobber(); // your enemy, makes isolation harder
    List<Bar> bars = new List<Bar>(); // usually a benign implementation detail
}
</code>```

Title: Injecting collections as constructor dependencies

Body:
We are using constructor dependency injection in our application. Following that approach we inject everything using an injection container so we are able to replace any dependency with a Mock.

Some colleagues complain about this procedure as they say that injecting collections of any type is going too far with injection and they prefer to call a new() inside the constructor.

What do you think about this? What procedure do you follow if you are using dependency injection?

One example of a real use case. We have a Dictionary with an special behavior, it allows to add the same key several times and it just increments an internal counter and it decreases the counter when removing elements from it only removing the element from memory when the counter is 0 (the class has been simplified a bit but I think you can get the idea):

```<code>public class ExtendedDictionary<TValue> : IExtendedDictionary<TValue>
{
    private readonly IDictionary<CustomKey, TValue> dictionary;

    public ExtendedDictionary(IDictionary<CustomKey, TValue> dictionary)
    {
        this.dictionary = dictionary;
    }

    public void Add(ParameterBase parameter, DriveInformation driveInformation, TValue data)
    {
        CustomKey key = new CustomKey (driveInformation, parameter.Index);

        if (this.dictionary.ContainsKey(key))
        {
            this.dictionary.Single(p => p.Key == key).Key.Count++;
        }
        else
        {
            this.dictionary.Add(key, data);
        }
    }

    public void Remove(ParameterBase parameter, DriveInformation driveInformation, TValue data)
    {
        CustomKey key = new CustomKey (driveInformation, parameter.Index);

        if (this.dictionary.ContainsKey(key))
        {
            this.dictionary.Single(p => p.Key == key).Key.Count--;
        }
        else
        {
            this.dictionary.Remove(key);
        }
    }
}
</code>```

Body:
This strikes me as a bit extreme, and overkill. I think it's a case of taking the common charge to never use new() in a class a bit too literally.

Injection is useful for having classes consume dependencies whose implementations can change or are (or need to be) replaceable. For unit testing, it's useful to get rid of your own classes that are already under test (and whose bugs should not impact testing of other code), or abstractions over items that make it difficult to isolate your code (such as the file system, databases, and things of that nature). A standard collection is (normally) neither of these. If a class needs to maintain a list of items, that is an implementation detail, and one that shouldn't cause you trouble. To whatever degree the  contents of that list impact the output should be the focus of your testing efforts.

public class Foo
{
    // limit, not eliminate, new()
    Frobber frobber = new Frobber(); // your enemy, makes isolation harder
    List<Bar> bars = new List<Bar>(); // usually a benign implementation detail
}


问:
Should curly braces appear on their own line?
Should curly braces be on their own line or not? What do you think about it?

```<code>if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}
</code>```

or should it be

```<code>if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}
</code>```

or even

```<code>if (you.hasAnswer())
    you.postAnswer();
else
    you.doSomething();
</code>```

Please be constructive! Explain why, share experiences, back it up with facts and references.

答:
I prefer the first method.  Braces are totally not worth separate line.

The thing is that braces are not important.  They're just syntactical trash, which is absolutely unnecessary to understanding of what code is for, of it's purpose and the way it's implemented.  They're just a tribute to old-style C-like languages where visual grouping of operators was impossible due to low screen space available.

There are languages (Python, Haskell, Ruby) which are OK without braces at all.  This only confirms that braces are trash, and should not deserve a line for them whenever possible:

```<code>if (you.hasAnswer()){
    you.postAnswer();
}else{
    you.doSomething();
}
</code>```

Body:
I prefer the first method.  Braces are totally not worth separate line.

The thing is that braces are not important.  They're just syntactical trash, which is absolutely unnecessary to understanding of what code is for, of it's purpose and the way it's implemented.  They're just a tribute to old-style C-like languages where visual grouping of operators was impossible due to low screen space available.

There are languages (Python, Haskell, Ruby) which are OK without braces at all.  This only confirms that braces are trash, and should not deserve a line for them whenever possible:

if (you.hasAnswer()){
    you.postAnswer();
}else{
    you.doSomething();
}


答:
The title hints that the topic is somewhat opinion-based.

However, let's ignore this issue and address the question.
I think the pros and cons are fairly obvious, since both methods are just trade offs.

For example, let's say you've implemented a runtime configuration-system.
Cons:

What do you do if some values are missing in the config / the config itself is missing? You need to define some "compile time values" anyway.

You'll have to load and parse the file. These days this isn't a problem any more, since we work with gigahertz processors and gigabytes of RAM. But imagine if you had a device that offers less.

Pros:

Flexibility. The user can adapt the values matching his needs. To be honest, in my opinion this outweighs any cons for this you can imagine.

Well, let's take a look at compile time configuration option:
Pros:

The program starts up faster and so on. But this isn't a problem these days since we have, as already mentioned, really strong computers compared to what we had a couple of years ago.

Cons:

Hard Coded values. The values are hard coded and you can hardly change them for debugging, for your personal joy or what so ever.

As mentioned at the beginning, this mostly opinion based, since the pros and cons do not have much weight. If you have already implemented a parser that you can feed with config files, then I would stick to it.

EDIT:
Something I forgot to say:
Do only expose those configuration values, which you want to be modified. There is no point in giving the user the ability to enable a feature which isn't support on his system.

Title: Compile-time vs. run-time configuration

Body:
I'm starting new project and need to decide on how to handle configuration. I recently run into suckless project. While it has its own issues, I really liked its approach to configuration - just a header file with static variables.

What are pros and cons of using compile-time options vs run-time options (== config file)? Would it be acceptable for product aimed for more tech-savvy users to use compile-time config? Does it still have benefits on modern systems?

I'm focusing modern desktop/laptops, only supported architecture likely will be amd64. Project is GUI application focused on accesing various informations.


答:
Resolve behavior, not data (with some exceptions, eg. constants).

If your business logic needs this data structure, then the business logic is responsible for initializing it, by using new or a factory. Then it can store this data structure in a cache or pass it around to other class through a method call. The container shouldn't have any responsibility in this case.


问:
Factory for creating a singleton instance
We have some legacy code that has a bunch of singletons all over the place (written in C#).

The singleton is a fairly "classic" implementation of the pattern:

```<code>public class SomeSingleton
{
    private static SomeSingleton instance;

    private SomeSingleton()
    {
    }

    public static SomeSingleton Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new SomeSingleton();
            }

            return instance;
        }
    }
}
</code>```

Note that thread safety is not a concern, so no locks are used.

In order to make the code more testable, and without making too many modifications, I'd like to modify this code to delegate the creation of the singleton instance in another class (a factory or similar pattern).

This can assist in creating a "test" instance for testing purposes, or the real version, as it is used now.

Is this a common practice? I could not find any reference to such pattern being used.

答:
In the comments you say you are using Unity and Mono for game development.  I am guessing that means Unity3D not Microsoft Unity.  As such I would recommend that you ditch the singleton pattern that you are following and instead use dependency injection.  I believe you can use Zenject with the unity3d framework.

The singleton class would be modified to be an instance of an interface like:

```<code>public class IImportantInterface
{
  DoSomethingImportant();
}

public class MySingletonImplementation: IImportantInterface
{
  public void DoSomethingImportant()
  {
    Console.WriteLine("This is Important!");
  }
}

public class DoImportantStuff
{
    private readonly IImportantInterface _ImportantInterface;

    public DoImportantStuff(IImportantInterface importantInterface )
    {
    _importantInterface = importantInterface;
    }

    public void DoSomething()
    {
    _importantInterface.DoSomethingImportant();
    }

}
</code>```

Then in you startup logic you can register a singleton instance with Zenject:

```<code>Container.Bind<IImportantInterface>().ToSingle<MySingletonImplementation>();
</code>```

A good blog post about this concept can be found here:
http://www.unityninjas.com/code-architecture/dependency-injection/

Body:
In the comments you say you are using Unity and Mono for game development.  I am guessing that means Unity3D not Microsoft Unity.  As such I would recommend that you ditch the singleton pattern that you are following and instead use dependency injection.  I believe you can use Zenject with the unity3d framework.

The singleton class would be modified to be an instance of an interface like:

public class IImportantInterface
{
  DoSomethingImportant();
}

public class MySingletonImplementation: IImportantInterface
{
  public void DoSomethingImportant()
  {
    Console.WriteLine("This is Important!");
  }
}

public class DoImportantStuff
{
    private readonly IImportantInterface _ImportantInterface;

    public DoImportantStuff(IImportantInterface importantInterface )
    {
    _importantInterface = importantInterface;
    }

    public void DoSomething()
    {
    _importantInterface.DoSomethingImportant();
    }

}

Then in you startup logic you can register a singleton instance with Zenject:

Container.Bind<IImportantInterface>().ToSingle<MySingletonImplementation>();

A good blog post about this concept can be found here:
http://www.unityninjas.com/code-architecture/dependency-injection/


答:
This answer is specific to C++ (as indicated by the tag on this question).

Most other compiled languages (outside C and C++) do not have such consideration, because in those languages there is no benefit in moving configurations to compile-time. Outside of C and C++, conditional compilation is greatly discouraged or simply unsupported. Also, C and C++ compilers apply aggressive dead-code elimination and other compile-time optimizations so that code that are provably excluded by compile-time configuration will not exist in the binary.

This question may also become a non-issue when just-in-time compilation (JIT) is considered. It is widely speculated that JIT will be available to C++ some day.

From a miles-high perspective, there are three main considerations for compile-time vs runtime (or program-launchtime) configuration.

Necessity.

Necessity refers to software, user or legal requirements which are rigid and cannot be worked around, and therefore impacts whether a configuration is required to be compile-time or runtime.

For example, if there is a requirement that a configuration can be changed without restarting an already running application, then obviously that configuration has to be run-time modifiable.

If the project has an optional dependency on a third-party component, and if that component has licensing terms that make it inapplicable to some subset of customers, then you will have to provide a build configuration for including or excluding the linking and use of that third-party component from your project. Obviously that configuration has to be compile-time.

Burden / Overhead.

This includes the time cost and inconvenience cost of everything - user's time recompiling, code execution overhead (conditional check, reading configurations, etc), and many other things.

As Dan Pichelman points out in the comment, the time spent on recompiling will typically greatly surpass the time spent on anything else.

The only exception to this observation is, if for some other reasons, the code is already being recompiled frequently, say, daily or even hourly. This can happen when a continuous-integration (automated builds and deployments) system is already in place. In such environments, putting configuration into compile-time can be effective because there is no additional cost and only a minor latency from change to effect.

Bloat.

Bloat refers to the increase in size, number of build artifacts, or other quantities when one needs to support multiple configurations (whether compile-time or runtime), when compared to the same quantity when only one such configuration is needed.

For example, if one has the choice of using Algorithm A versus Algorithm B for a certain task:

Option 1: compile both algorithms into the binary, thus allowing the choice to be made at runtime. The binary size is the sum of the binary size of both algorithms, minus the size of shared binary parts.

Option 2: only compile one of the two algorithms into the binary. The choice is fixed at compile-time; the application/user won't be able to choose at runtime.

Option 3: make one build (binary) containing only Algorithm A, and another build (binary) containing only Algorithm B. Provide both to the user. A change of choice will require restarting the application using the binary of choice.

Option 4: refactor both algorithms into a generalized algorithm model, and maximize the reuse of logic, in the hope of reducing binary size.

It is obvious that Option 3 will have to largest bloat, because a lot of binary logic that is common to both will have to be duplicated. The bloat resulting from Option 1 appears to be reasonable in comparison to Option 3.

Option 2 lacks the runtime choice, so it is subject to the first criteria - necessity - depending on the software's and user's requirements.

Option 4 takes extra programming effort, but will have the least impact to burden and bloat compared to all other options.

Title: Compile-time vs. run-time configuration


问:
Structuring Procedural vs OO code
I have spent the vast majority of my programming career using Java and very OO based C++. I am really interested in learning to think more procedurally, so I have been starting to do some practice using a more restricted subset of C++ (basically C) and trying to keep my code very procedural.

My question lies in the area of how to structure a program. In Java, I am constantly thinking of objects... so when I create a class I am thinking of:

What is this object representing?

What can this object do?

What do others need to be able to do to it?

What do I expose, what do I hide?

Etc

In the case of procedural code, how does this sort of thing work? Lets say wanted a struct to represent a Car. I would create a header to define it in... but where do functions go that should operate on a car type? Would you also define all Car related functions in the same file line you would a Java class? Am I totally thinking about this the wrong way, in that there should not be any Car related functions since the emphasis should not be on the Car object but on the functions themselves? IS the idea of a member function totally thrown out the window?

The bottom line is my brain has been wired to think about Objects, Encapsulation, Polymorphism, etc.. and I cant seem to wrap my head around anything else. How can I practice?

Any advice is appreciated!

答:
What is this object representing? What can this object do? What do others need to be able to do to it? What do I expose, what do I hide? Etc

When you create a struct, the only thing you need to answer is what its data structure should be. It can't do anything, it can't hide anything, all it is is a convenient method of accessing plain memory. It may be a good idea to try to answer some more questions about the struct, but there is no formal grammar for writing the answer to those questions. (That is also true for a lot of good questions about OO objects.)

but where do functions go that should operate on a car type?

Wherever you think it fits best, the struct does not make a decision for you, it doesn't even dictate that the relevant code should be a dedicated function. Decide on an implementation when you actually have to use it.

IS the idea of a member function totally thrown out the window?

It doesn't have to be, the function(object, parameters) structure is equivalent to the basic use of member functions. It should compile to pretty much the same thing.

Encapsulation

A bit simplified, all encapsulation ever does is throw an error message if you try to break it. Sure it can be nice to have some formal guarantees about what code can't do, but you mostly get the same benefits by defining non-compiler-checked boundaries. In any case, the only encapsulation method that you actually lose is private members and methods. In my experience, those are not nearly as important as variable scopes.

Polymorphism

The big case for OO. Solves a lot of weird problems, and doesn't have any simple replacement. But there are lots of structures that do similar things, here is a few:

Make a struct with space for all the data needed by any desired subtype, have a variable mark what subtype it is. You can use multiple such marks in order to make something that resembles multi inheritance. Rather than overloading methods, the code that deals with such structs must simply check the type and act accordingly. It may waste some memory, but in most cases that is probably not a big deal. If you have a lot of different subtypes it could however spread the code defining the differences between those subtypes all over your program.

Include function pointers as member variables, these can be set to the functions matching the subtype.

Include pointers to sub-structs, with memory for this specific subtype.

Make all the desired subtypes distinct struct, and copy-paste any code that apply to all. Doesn't sound good, but if the differences take up a lot more code than the similarities, it could be a reasonable choice. The don't-do-this-at-home version is where you construct the memory layout so that the same code will work on different structs.

For learning purposes I think it is a wonderful idea to shelf an advanced feature, especially if it is one you tend to overuse. In real-world code, you should of course use the OO features where it makes sense.

Title: Structuring Procedural vs OO code


答:
Start from data structures.

Write functions operating on those data structures.

If you want encapsulation, do it at the level of modules, not objects.

If you want polymorphism, use higher-order functions, not virtual dispatch.

That’s about it. OOP as practiced is not a significant departure from procedural programming. It’s primarily a set of reasonable defaults for constructing procedural programs.

Title: Structuring Procedural vs OO code

Body:
I have spent the vast majority of my programming career using Java and very OO based C++. I am really interested in learning to think more procedurally, so I have been starting to do some practice using a more restricted subset of C++ (basically C) and trying to keep my code very procedural.

My question lies in the area of how to structure a program. In Java, I am constantly thinking of objects... so when I create a class I am thinking of:

What is this object representing?

What can this object do?

What do others need to be able to do to it?

What do I expose, what do I hide?

Etc

In the case of procedural code, how does this sort of thing work? Lets say wanted a struct to represent a Car. I would create a header to define it in... but where do functions go that should operate on a car type? Would you also define all Car related functions in the same file line you would a Java class? Am I totally thinking about this the wrong way, in that there should not be any Car related functions since the emphasis should not be on the Car object but on the functions themselves? IS the idea of a member function totally thrown out the window?

The bottom line is my brain has been wired to think about Objects, Encapsulation, Polymorphism, etc.. and I cant seem to wrap my head around anything else. How can I practice?

Any advice is appreciated!


问:
Is it okay to have objects that cast themselves, even if it pollutes the API of their subclasses?
I have a base class, Base.  It has two subclasses, Sub1 and Sub2.  Each subclass has some additional methods.  For example, Sub1 has Sandwich makeASandwich(Ingredients... ingredients), and Sub2 has boolean contactAliens(Frequency onFrequency).

Since these methods take different parameters and do entirely different things, they're completely incompatible, and I can't just use polymorphism to solve this problem.

Base provides most of the functionality, and I have a large collection of Base objects.  However, all Base objects are either a Sub1 or a Sub2, and sometimes I need to know which they are.

It seems like a bad idea to do the following:

```<code>for (Base base : bases) {
    if (base instanceof Sub1) {
        ((Sub1) base).makeASandwich(getRandomIngredients());
        // ... etc.
    } else { // must be Sub2
        ((Sub2) base).contactAliens(getFrequency());
        // ... etc.
    }
}
</code>```

So I came up with a strategy to avoid this without casting.  Base now has these methods:

```<code>boolean isSub1();
Sub1 asSub1();
Sub2 asSub2();
</code>```

And of course, Sub1 implements these methods as

```<code>boolean isSub1() { return true; }
Sub1 asSub1();   { return this; }
Sub2 asSub2();   { throw new IllegalStateException(); }
</code>```

And Sub2 implements them in the opposite way.

Unfortunately, now Sub1 and Sub2 have these methods in their own API.  So I can do this, for example, on Sub1.

```<code>/** no need to use this if object is known to be Sub1 */
@Deprecated
boolean isSub1() { return true; }

/** no need to use this if object is known to be Sub1 */
@Deprecated
Sub1 asSub1();   { return this; }

/** no need to use this if object is known to be Sub1 */
@Deprecated
Sub2 asSub2();   { throw new IllegalStateException(); }
</code>```

This way, if the object is known to be only a Base, these methods are un-deprecated, and can be used to "cast" itself to a different type so I can invoke the subclass's methods on it.  This seems elegant to me in a way, but on the other hand, I'm kind of abusing Deprecated annotations as a way to "remove" methods from a class.

Since a Sub1 instance really is a Base, it does make sense to use inheritance rather than encapsulation.  Is what I'm doing good?  Is there a better way to solve this problem?

答:
From my perspective: your design is wrong.

Translated to natural language, you are saying the following:

Given we have animals, there are cats and fish.
animals have properties, which are common to cats and fish. But that's not enough: there are some properties, which differentiate cat from fish, therefore you need to subclass.

Now you have the problem, that you forgot to model movement.
Okay. That's relatively easy:

```<code>for(Animal a : animals){
   if (a instanceof Fish) swim();
   if (a instanceof Cat) walk();
}
</code>```

But that is a wrong design. The correct way would be:

```<code>for(Animal a : animals){
    animal.move()
}
</code>```

Where move would be shared behavior implemented differently by each animal.

Since these methods take different parameters and do entirely different things, they're completely incompatible, and I can't just use polymorphism to solve this problem.

This means: your design is broken.

My recommendation: refactor Base, Sub1 and Sub2.

Body:
From my perspective: your design is wrong.

Translated to natural language, you are saying the following:

Given we have animals, there are cats and fish.
animals have properties, which are common to cats and fish. But that's not enough: there are some properties, which differentiate cat from fish, therefore you need to subclass.

Now you have the problem, that you forgot to model movement.
Okay. That's relatively easy:

for(Animal a : animals){
   if (a instanceof Fish) swim();
   if (a instanceof Cat) walk();
}

But that is a wrong design. The correct way would be:

for(Animal a : animals){
    animal.move()
}

Where move would be shared behavior implemented differently by each animal.

Since these methods take different parameters and do entirely different things, they're completely incompatible, and I can't just use polymorphism to solve this problem.

This means: your design is broken.

My recommendation: refactor Base, Sub1 and Sub2.


问:
Contract / Freelance Programming, The initial communication process / sending documents to them (terms, etc)
I've been searching around for info on contract / freelance programming as far as steps to take in the initial communication with a client (someone who has contacted me regarding a project). I am wondering if anyone has links to good resources as far as what I should send them (should I send them a document outlining "my process", etc?).

Often the initial requirements that they send are vague and I want to immediately "take charge" of the process and starting asking them questions, talking about price, etc but I don't want to be too overbearing so I'm just curious if there is much out there written about this, my google searches aren't turning up much that is good about this sort of thing.

答:
Well done on having this on your radar

1) In my experience you need to approach clients with a clear idea about

```<code>a) You price

b) Want you will and will not do
</code>```

2) In addition you do need your own processes (it helps you stay sane)

After that it's a question of negotiation and talking. If you are dealing with customers remotely then it's a bit harder. I have written documents that outline change control, scope, expenses etc, but it was hard not having a conversation.

So I don't think you should put a document in front of customer as a first step, but something short and succinct may be useful in case the client really has not clue. A simple check list for yourself might be good as well (help you understand risks and stops you being distracted during the discussions)

If there is no clear requirements or scope (as you mention above) then I would attempt to make that an initiation phase (with a project initiation document at the end) that you can charge for. Depending on the project it may only be a days work, but does set the tone.

Body:
Well done on having this on your radar

1) In my experience you need to approach clients with a clear idea about

a) You price

b) Want you will and will not do

2) In addition you do need your own processes (it helps you stay sane)

After that it's a question of negotiation and talking. If you are dealing with customers remotely then it's a bit harder. I have written documents that outline change control, scope, expenses etc, but it was hard not having a conversation.

So I don't think you should put a document in front of customer as a first step, but something short and succinct may be useful in case the client really has not clue. A simple check list for yourself might be good as well (help you understand risks and stops you being distracted during the discussions)

If there is no clear requirements or scope (as you mention above) then I would attempt to make that an initiation phase (with a project initiation document at the end) that you can charge for. Depending on the project it may only be a days work, but does set the tone.