问:
Is there a concept of a variable with phases of initialization: uninitialized, initializing, immutable?
I was looking at this thread on Stack Overflow and thinking about the functional programming I've been learning, and how immutability is so key there, and it occured to me that maybe some language has gotten the idea to have variables start out "null", then go to a "building" state, and finally become the same as any other immutable when initialization is done.

Is this a valid concept and/or has it been tried or experimented with at the language level?

It might look something like this:

```<code>string s new String(); // empty strings start out mutable
for x = 1 to 10
  s = s + "z"
s.Freeze() // now it's immutable
</code>```

It's just a thought.. maybe it's not a good one, but it seems like a hybrid of two things that seem to be opposing one another.

答:
The pattern you describe looks a lot like a constructor in object-oriented programming; while fields are not necessarily immutable, it is common practice to build your objects to be immutable except for the constructors, e.g., in a hypothetical OOP language:

```<code>class NumberSequenceString {
    private string val;

    public function __construct(top) {
        val = "";
        for (i = 1; i <= top; i++)
            val = val + (string)i;
        val = val + "z";
    }

    public getVal() { return val; }
}

var myString = new NumberSequenceString(10);
</code>```

(I took the liberty to make your code sample a bit more interesting: instead of repeating "z" 10 times, it now spits out the string "12345678910z"; the code required to build this string is just complex enough to demonstrate nontrivial processing later).

However, most functional programming idioms take a different route; instead of distinguishing between the "uninitialized", "constructing" and "immutable" phases of a variable's life cycle, they just eliminate the first two: a variable's life cycle starts when it is defined, and the definition already provides the only value it will every have. This is possible because the functional programming idiom favors powerful expressions over statements, which means that the value you're assigning can itself be constructed in just one expression; instead of using iterative loops with a mutable counter variable, functional programmers think in terms of map and reduce. Your example in functional style would look something like this:

```<code>function makeSequenceString(top) {
    return range(1, top).map(toString).reduce(+) + "z";
}

const myString = makeSequenceString(10);
</code>```

Or, more idiomatically, in some sort of pseudo-Haskell/ML/F# kind of syntax:

```<code>makeSequenceString top = (reduce (+) (map toString [1..top])) + "z"
myString = makeSequenceString 10
</code>```

Note that the part that constructs the value is just one big expression, and the makeSequenceString function does absolutely nothing but evaluate the expression and return its value. And since we're assigning that value immediately as part of the definition of myString, there is no point in the program at which myString is uninitialized or "being constructed" - as soon as it exists, it has a value, and that's the only value it will ever have (at least as long as the programmer sticks with a purely functional style).

Body:
The pattern you describe looks a lot like a constructor in object-oriented programming; while fields are not necessarily immutable, it is common practice to build your objects to be immutable except for the constructors, e.g., in a hypothetical OOP language:

class NumberSequenceString {
    private string val;

    public function __construct(top) {
        val = "";
        for (i = 1; i <= top; i++)
            val = val + (string)i;
        val = val + "z";
    }

    public getVal() { return val; }
}

var myString = new NumberSequenceString(10);

(I took the liberty to make your code sample a bit more interesting: instead of repeating "z" 10 times, it now spits out the string "12345678910z"; the code required to build this string is just complex enough to demonstrate nontrivial processing later).

However, most functional programming idioms take a different route; instead of distinguishing between the "uninitialized", "constructing" and "immutable" phases of a variable's life cycle, they just eliminate the first two: a variable's life cycle starts when it is defined, and the definition already provides the only value it will every have. This is possible because the functional programming idiom favors powerful expressions over statements, which means that the value you're assigning can itself be constructed in just one expression; instead of using iterative loops with a mutable counter variable, functional programmers think in terms of map and reduce. Your example in functional style would look something like this:

function makeSequenceString(top) {
    return range(1, top).map(toString).reduce(+) + "z";
}

const myString = makeSequenceString(10);

Or, more idiomatically, in some sort of pseudo-Haskell/ML/F# kind of syntax:

makeSequenceString top = (reduce (+) (map toString [1..top])) + "z"
myString = makeSequenceString 10

Note that the part that constructs the value is just one big expression, and the makeSequenceString function does absolutely nothing but evaluate the expression and return its value. And since we're assigning that value immediately as part of the definition of myString, there is no point in the program at which myString is uninitialized or "being constructed" - as soon as it exists, it has a value, and that's the only value it will ever have (at least as long as the programmer sticks with a purely functional style).


问:
Should user input of a contact form be validated?
On software company websites I visit the first time, I often open the "Contact us" page and try to submit the contact form with all fields empty. I am just curios if they validate the user input.

If it is just submitted or only validated poorly (e.g. only Javascript validation), I often hear myself thinking

Oh, look how sloppy they are! Can't even validate user input. That calls itself a software company? No, I don't think I want to buy any software services of them.

A friend of mine has such a "sloppy" contact form. You can submit a completely empty form. I asked him why he does not validate user input, and he said:

Look, I want that customers can contact me. They should enter any information they want. If they only want to enter a message and leave the other fields empty, why should I care? They enter the relevant information anyway. I do not want to add any barriers when contacting me.

I did not ask him how many empty messages he gets, though.

However, what is the better option now? Both arguments (check how company handles user input vs. not adding any barriers in contacting) seem to make sense for me.

I want that the user can easily contact me, but still has the impression that I am precise when programming webpages.

答:
Validation is important for two reasons:

If you don't have any validation, you may end up with your
database/inbox full of useless messages (Messages that have no
content or messages whose sender info is missing or makes no sense).

SQL injection. Not having any validation may compromise your
database.

However:

No. 1 may not be an issue if, like your friend, you don't mind getting some fields empty.

No. 2 may not be an issue if you don't save the data from the form to a database (I've seen contact forms that use the data to send an email to the company's support department without ever storing them in a database, for example.)

So the answer here is (as it is so many times): It is good practice, but depends on the particulars of the project.

ContentLicense: CC BY-SA 3.0


问:
Getting started with AI (Artificial Intelligence)
I recently got interested in Artificial Intelligence. In my daily life I am a software engineer at a company that develops mobile apps. I am wondering what is the best way to read up on AI? What are 'must-read' books for information about AI?</p>

答:
Off the top of my head, the very classic, must-read, heavy book that will help you throughout your AI experience : Artificial Intelligence, A Modern Approach.
Don't be scared by the size, this book is trying to explore multiple kinds of AI, and the authors warn that the reading of the entire book will need nearly a 2-semester period.

If you want to focus on game development and skip the linguistics/robotics/philosophical part of AI, just buy Artificial Intelligence for Games, this book will give you a fine overview of the basic algorithms and game logic behind different types of games.

I read this one last month and am currently reading the 'Modern Approach' one because, let's be honest, when I read some pages of that big AI Bible I was discouraged so I tried the more game-oriented one and was happy with it.


问:
How ensure secure two cloud services can only talk to each other?
Question

Given two cloud services, Sender A & Receiver B, communicating over HTTPS, what options do I have to ensure that Receiver B only response to Sender A?  For the purposes of

Background

The receiver is generating activation keys for some hardware from a serial number.  Our support team is using Salesforce and we're making callouts from Salesforce to an Azure service to generate the key.  Since neither are behind a firewall we want to make sure that only request from our Salesforce instance can generate an activation key.

My thought was just to create a nice long key stored on both sides that could be used to validate the request, but I'm not a security expert and don't know if there is anything else I should be considering.

答:
I would recommend a SSH tunnel: http://www.ibm.com/developerworks/aix/library/au-tunnelingssh/
https://en.wikipedia.org/wiki/Tunneling_protocol</p>


问:
TDD Mock call verification - is it an anti-pattern?
I've been doing TDD for a while now, I feel pretty good about it, I love my test suites and all. However I've noticed that lately I've been doing a lot of mock call verification. For example I'd have a Service that will have a Repository injected - in my unit test I'd pass a mock of the Repository and verify that it was called within the method that I'm testing. I'd then check if the results returned are correct (in another test). This definitely "feels" wrong, since my unit tests are now tightly coupled to the implementation details. I've heard that you should test "behavior", however in a lot of the situations that's ... emm - not possible? If you have a void method for example, you usually test side-effects. I mean it's easy to go ahead and show some simple code-kata's where this can be demonstrated, but IMHO it doesn't reflect very well to the real world programs that we write. Is what I'm doing wrong? Is this type of testing sort of an anti-pattern? I'd appreciate your opinion on this.

答:
The purpose of a test is to restrict the possible productive implementations. Make sure that you only put restrictions on the implementation that you actually need. Typically this is what your program should do, and not how it does it.

So if for example your service adds something to the repository, you should test that the new entry is contained in the repository afterwards, and not that the add action is triggered.

For this to work, you need to be able to use the repository implementation (tested elsewhere) in the test of the service. I found that using the real implementation of a collaborator is generally a good approach – because it is really the best implementation around.

"So but what if using the real implementations in the test is expensive (e.g. because they require resources which are complicated to set up)? I need to use mocks in this case, right?"

In any case you'd probably want one integration test which tests that the real implementations work together. Make sure that this one integration test is all that is needed to test your service. Or in other words: If a service plugs together a lot of collaborators (and is hence potentially hard to test), make sure that it doesn't contain any logic. If it does, and you'd need multiple (integration) tests, you need to change the structure of your code, e.g. by isolating the logic and hence making it more testable.

Using mocks in this case eases the pain of testing a piece of badly isolated logic, and hence hides an architectual problem. So don't use mocks to test badly structured code, but fix the structure instead.

ContentLicense: CC BY-SA 4.0


问:
What would be the fastest way of storing or calculating legal move sets for chess pieces?
For example if a move is attempted I could just loop through a list of legal moves and compare the x,y but I have to write logic to calculate those at least every time the piece is moved.

Or, I can store in an array [,] and then check if x and y are not 0 then it is a legal move and then I save the data like this
[0][1][0][0] etc etc for each row where 1 is a legal move, but I still have to populate it.

I wonder what the fastest way to store and read a legal move on a piece object for calculation.

I could use matrix math as well I suppose but I don't know.

Basically I want to persist the rules for a given piece so I can assign a piece object a little template of all it's possible moves considering it is starting from it's current location, which should be just one table of data. But is it faster to loop or write LINQ queries or store arrays and matrices?

```<code>public class Move
{
    public int x;
    public int y;
}

public class ChessPiece : Move
{
    private List<Move> possibleMoves { get; set; }

    public bool LegalMove(int x, int y){
      foreach(var p in possibleMoves)
      {
         if(p.x == x && p.y == y)
         {  return true;  }
      }
    }
}
</code>```

Anyone know?

答: Look out how strong chess engines implement this. A good technique is to use bitboards. A lot of work can be saved using pre-calculation. Here is one article: http://www.frayn.net/beowulf/theory.html#bitboards</p>


问:
What is the most inspiring speech from a developer you ever watched?
Please put a direct link to it.

Required:

Still available online (please put a direct link to it)

Must be a speech from a current or former developer

Speaker's popularity doesn't matter

Target audience should be other developers

It is not required that the topic is programming (the task). I'm more looking for subject generally developing here within P.SE rather than SO.

Explain why it was inspiring

(please, native english speaker, edit my question)

答:
I like Balmer's speech Developer developer developers... and on and on..
Simply because it is entusiastic. How many people we know who love thier jobs so passionaltely.

http://www.youtube.com/watch?v=t6ZarKIKpSA&feature=related

ContentLicense: CC BY-SA 2.5


问:
Most "native"/integrated functional language for Mac OS X development?
If one views the CLR/.NET runtime and associated libraries as the future of windows, then the F# programming language could be seen in that light as the most native functional language.  Meaning that it has support from the OS creator, presumably integrates best with their libraries, etc.

Is there a similar logical choice of language on the Mac OS X platform?  While the most-native language itself is obviously Objective-C, is there a first-among-equals or most obvious functional paradigm language that stands out?

答:
I"m just going to to throw this out there from outside the functional programming community...

Objective-C++11

Or, more formally, Objective-C++ since clang finished implementing the full c++11 spec.

Programming primarily in C++11 gives you strong support for immutable data structures, template meta-programming and you can use Apple's blocks across all of C, C++ and Objective-C code. Blocks are easier to use than C++ lambdas, see Mike Ash's comparison.

At the same time, you can trivially flip between Objective-C and C++ classes in the same source file, each can contain pointers to the others objects, so calling native code is inherent.


问:
Should I be learning JavaScript before studying computer science?
So I've done a lot of research and found that Codecademy has been mentioned several times on other forums. I got stuck in and chose JavaScript through Codecademy most probably thinking it was 'Java' and I'm now slightly concerned that I have made a bad choice.. due to the fact that I see posts mentioning JavaScript teaches bad habits and so on...

Should I stop and learn other languages offered on 'Codecademy'?

Should I stop using codecademy altogether?

Or finally should I just wait until I start my degree and pose as a blank canvas?

All opinions wanted, thank you.

P.s I'm not entirely certain what jobs I will be applying for in the future but to give some indication I don't believe it will be website development and more so on the game or application designing side of things

答:
When you're getting started, any experience is good experience. You'll learn more about what you want to do once you've started your course. I would suggest you continue with the javascript whilst it's still teaching you new things.

Early on in learning programming, the concepts you're getting to grips with are basically consistent between different languages. All the languages you're likely to be using early on will have some way to do looping, assigning variables and encapsulation (creating functions or classes). You can certainly get used to those concepts just fine in JavaScript.

For what it's worth, I'm very fond of javascript as a language. I appreciate its versatility of style and the extent to which programming in it is fun. In my experience, it doesn't necessarily teach bad coding habits, though it is true that it is easier to code badly in it than in some other langauges.

I've done some of the courses on codeacademy to see how they were structured, and to me they seem like an extremely well thought out introduction to basic programming. I've pointed several other people at them and genuinely believe that they'll give you a good start in life as a programmer. I wouldn't give up on them just yet.


问:
Why is TDD not working here?
I want to write a class A that has a method calculate(<params>). That method should calculate a value using database data. So I wrote a class Test_A for unit testing (TDD). The database access is done using another class which I have mocked with a class, let's call it Accessor_Mockup.

Now, the TDD cycle requires me to add a test that fails and make the simplest changes to A so that the test passes. So I add data to Accessor_Mockup and call A.calculate with appropriate parameters.

But why should A use the accessor class at all? It would be simpler (!) if the class just "knows" the values it could retrieve from the database. For every test I write I could introduce such a new value (or an if-branch or whatever).

But wait ... TDD is more. There is the refactoring part. I could refactor class A using the DB accessor. But I could refactor it in any other way as well (e.g. introducing new classes that encapsulate the data). So, again: How do I write tests that force A to use the database (and nothing else)?

答:
But why should A use the accessor class at all? It would be simpler
  (!) if the class just "knows" the values it could retrieve from the
  database. For every test I write I could introduce such a new value
  (or an if-branch or whatever).

TDD won't work if your aim is to trick the tests when writing the productive code. An if cascade for all parameter combination used in the test is not a reasonable implementation – the tests only need to ensure that any simple, non-malicious implementation is correct.

So in your database example, just make sure that you pass in enough data via the accessor stub so that any (lazy) programmer will implement a solution that uses that data, instead of making up the answers.

Title: Why is TDD not working here?


答:
Personally, I wouldn't say you've made a bad choice - it just might not be all that relevant to what you end up doing.

Look up what you're going to be doing on your degree programme (this is what I did), if you are going to be doing Java download a Java IDE and get stuck in with some tutorials. If you are going to be doing C# or C++ download the express edition of Visual Studio, find some tutorials and have a go. I found it very useful to have some prior experience of what I was going to be doing - it took the pressure off for the first couple of weeks and I found I understood things a little better.

It's a bit vague, but I just "had a play" with C# and C++ before I went to uni and it really helped. Just read what you're going to be doing and have a go.

Title: Should I be learning JavaScript before studying computer science?

Body:
So I've done a lot of research and found that Codecademy has been mentioned several times on other forums. I got stuck in and chose JavaScript through Codecademy most probably thinking it was 'Java' and I'm now slightly concerned that I have made a bad choice.. due to the fact that I see posts mentioning JavaScript teaches bad habits and so on...

Should I stop and learn other languages offered on 'Codecademy'?

Should I stop using codecademy altogether?

Or finally should I just wait until I start my degree and pose as a blank canvas?

All opinions wanted, thank you.

P.s I'm not entirely certain what jobs I will be applying for in the future but to give some indication I don't believe it will be website development and more so on the game or application designing side of things


答:
JavaScript is a language with practical applicability, and will stay so in the foreseeable future. It famously has good and bad parts. If you learn JavaScript, it would be good to use a course that focuses on the good parts.

I do not believe in avoiding to learn something for fear of bad habits, nor in "blank canvas" being something a human should strive for.

However, if you know that your CS curriculum is mainly based on Java (or whatever), then it might be a better use of your time to learn that language in preparation. On the other hand, if you're ambitious, why not learn more than one language? It's generally considered essential for good computer scientists and developers to know serveral different languages, preferably very different ones.

JavaScript and Java are superficially similar but very different at a deeper level. This might make learning both a bit confusing.


答:
There seems to be a strong correlation between the first programming language a programmer learns and his or her capacity to learn other programming languages which are more or less "difficult."  Learning a difficult language at first is usually more beneficial for learning less difficult languages later.  I suppose it is a bit like learning how to do long division before being able to use a calculator in that you gain insight that otherwise would be dificult to acquire going in the opposite direction.

In my humble opinion, Javascript is an excellent first programming language in that it is a highly used language and that it is easy to write your first program.  I honestly don't know what that says about your ability to perform object-oriented programming, since you could easily use Javascript without ever having to use functions as objects.  Most best practices for programming in javascript involve knowing important concepts which you will use with other languages, but they are not strictly required to use javascript correctly.

I don't think you have to worry too much.  Focus on learn javascript well, since you will need it.  Don't just learn syntax.  Try to understand programming concepts, since these are the things that will help you most when learning other languages later.  It's difficult to explain now, but you will understand these concepts better when you begin to use other languages which have things Javascript doesn't (like scope) or don't have things Javascript does (like loose typing).

When you feel confident that you understand Javascript well, you can move on to a more object-oriented language like Java or C# that will also ground you on concepts related to memory management and compiler-based languages.


问:
What are good reasons to drop Windows XP support?
Recently the software team in my company decide to use VS2012 (upgrade from VS2008) but we found out that VS2012 does not provide a nice support for Windows XP (e.g. really hard to deploy .Net 3.5 managed C++ project).

So we want to convince our manager to drop Windows XP compatible development and and target Windows 7 only. This allows us to use some new technologies such as .Net 4.5 (we are using 3.5 ATM). But we have many existing customers are using Windows XP and they will not able to upgrade to new version of our software (we may still provide bug fixes for XP though).

So what are some good reasons to use VS2012 and drop XP compatibility?

What in my list currently:

Able to use .Net 4.5

Use VS2012 (without compile some project using VS2008 tool chain)

No need to test on XP machine

答: There is only one good reason you can give your manager: To support XP, you need to test on XP, which in turn means that you have to maintain at least one XP machine. And that's extra costly since it is a non-standard machine, without vendor support, so it has to be run in an extra secure environment (probably airgapped).</p>


问:
Is fewer lines of code always better?
Which of these programming styles is better?

```<code>var result = methodOne(methodTwo(a, methodThree(b)), c, d);
</code>```

or

```<code>var result3 = methodThree(b);
var result2 = methodTwo(a, result3);
var result = methodOne(result2, c, d);
</code>```

答:
No.

In fact, I'd go further and say fewer lines of code are rarely better.

Now, that's not to say don't encapsulate method calls etc but in your example above, when debugging - it's going be very hard to see the outcome of the methodThree and methodTwo when it's all inlined like that.

Lots of code in a method doing lots of things is bad. Lots of small methods that get called and assign to local variables enhance readability, enhance maintainability and have no real cost as the compiler will happily optimise away.

Title: Is fewer lines of code always better?


答:
In layman's words:

The important thing is not the numbers of lines but the readability of the code.

Any fool can write code that a computer can understand. Good
  programmers write code that humans can understand. (M. Fowler)

In the examples you gave, the second one is definitively easier to read.

Source code is for people to read.

Besides, intermediate values make the code easier to debug.

Code one-liners, on the other hand, are useful to show other people that you are "smart" and that you don't care.

Title: Is fewer lines of code always better?

Body:
Which of these programming styles is better?

```<code>var result = methodOne(methodTwo(a, methodThree(b)), c, d);
</code>```

or

```<code>var result3 = methodThree(b);
var result2 = methodTwo(a, result3);
var result = methodOne(result2, c, d);
</code>```


答:
You could also try BerkeleyX AI course that is available on edX.

More info here: CS188.1x Artificial Intelligence

I haven't taken this particular one, but the quality of presentation is generally very good.

If you go through the archived course that already ended, you can just study at your own pace. However, if you register for the upcoming one you may also get to submit your exercises and take exams, and even receive a certificate at the end. But it will probably start around Fall.

Also their forums are great for asking questions of fellow students and community assistants.

Title: Getting started with AI (Artificial Intelligence)

Body: I recently got interested in Artificial Intelligence. In my daily life I am a software engineer at a company that develops mobile apps. I am wondering what is the best way to read up on AI? What are 'must-read' books for information about AI?</p>


问:
Which is faster NSDictionaries or object properties?
If I abandon creating model objects which I only use to pass information and use NSDictionaries instead and have constant for keys in the same place where I am using the model, then does it have any impact on performance ?

For example: If I start passing NSDictionaries to custom cell's instead of creating Model classes for the cell, will it be fine if I am not providing any methods in the class of that model.

I have seen this a lot in iOS APIs like NSNotifications.
I have rarely seen this in Java where collections are being used as an integral part of an API.

答:
Object properties are generally at least an order of magnitude faster to access. Property
access speed is also predictable whereas hash table access can take up to linear time.

Accessing property can be done by just accessing some memory address directly.

Accessing hash table requires you to get the hash value for the string (compute or take cached hash - both already take many instructions), then go through all the
entries that match the bucket index and do expensive string comparisons until match is found or not found.

Still for many kinds of applications the hash table speed is not bad. In many language implementations
object properties are hash table accesses (Ruby, CPython, PHP) and while it makes these languages
extremely slow in an objective sense, they are still fast enough for many kinds of applications.

This is also assuming the implementation for NSDictionary is a hash table, any other implementation will be even slower.


答:
It depends, and your example is not useful in making the decision.

While fewer lines of code are not always better (at some point it leads to obfuscation), they usually are, simply because there's fewer things to keep track of when trying to understand the code.

In your specific example:

If the names of the intermediate values actually convey meaning that is not made obvious by the names of the methods and parameters used to compute those intermediate values, then they help in understanding the code.

However, if the names of the intermediate values do not add information, then they make the code harder to understand, since they're an additional state to keep track of. Even if they're immutable, they force you to consider whether they're used only once, or in different places.

Title: Is fewer lines of code always better?


答:
In the first version, it is hard to see which parameters are passed to which method. So the second version is clearly better. In other cases however may not be that obvious.

The main difference of the second version is that it allows you to name the intermediate values. There may be cases where this name is crucial for understanding the code.

If however the intermediate values are anyway just called something like varOne, you may also just omit them by in-lining them.

Title: Is fewer lines of code always better?


答:
Measuring programming progress by lines of code is like measuring aircraft building progress by weight. (Bill Gates)

Of course, fewer lines are not always better. But in my experience, fewer lines are often better than more lines in terms of readability and maintainability. There are exceptions, of course, and your example might be one such exception.

Weight is needed to build an aircraft. But it should be in the right places.

Title: Is fewer lines of code always better?


问:
Implicit or explicit database save actions
I'm writing a web app that requires the usage of drag and drop as well as other jQuery/HTML5 features.

There are two options for saving a user's changes to a database

Implicit: database save on the end of an event, such as drop, hover, ect.

Explicit: save changes to local array and submit on submit button click event

Currently, the only difference between the two is that implicit saves hooked to user events results in many more POST/GET data requests as compared to the explicit save.

Other than that, is there a major distinction between the two, and what are the reasons for choosing either option?

答:
Implicit save will behave as many people would expect drag and drop to behave.  Also users won't lose changes.

Explicit save will likely result in much more support effort as users are likely to forget to save their changes.  They may also lose work if they delete the source and then forget to save.

In either case consider the requirement for undo and how to implement it.  This may require storing either prior state or a change log.


答:
You are confusing concepts, in your code the string variable "s" is immutable all along and in no moment it ceases to be immutable.

```<code>String s new String(); // Strings are ummutable

    for x = 1 to 10
      s = s + "z"   // you are destroying an object, creating
                    // another one and assining it to the
                    // reference. You are not changing the
                    // internal state of the String.
      s.Freeze()    // It makes no sense. The only way to avoid
                    // assigning a new value to a variable is
                    // converting it into a constant. But then you can only
            // assign an initial value when you declare it.
</code>```

Immutability means not being able to alter the internal state of an object via properties, settters or methods.

In Java, the String class is immutable, meaning it has no setters or other method of changing its state.

The class StringBuffers is mutable, it has an Append() method and others that change its internal state.

The String class being immutable doesn't mean you cannot over-write the a String object, and assing other string to the reference.

That being clear, you can certainly program a class whose setters raise and IllegalStateException if you try to set a value after you have "frozen" it.

```<code>public class FreezableThing {
    private String name="";
    private int number=0;
    boolean frozen = false;

    public boolean isFrozen() { return frozen; }

    public void setFrozen(boolean frozen) { this.frozen = frozen; }

    public String getName() { return name; }

    public int getNumber() { return number; }

    public void setName(String name) {
        if (this.frozen){
            throw new IllegalStateException("Frozen object cannot be changed");
        }
        this.name = name;
    }

    public void setNumber(int number) {
        if (this.frozen){
            throw new IllegalStateException("Frozen object cannot be changed");
        }
        this.number = number;
    }

}
</code>```

...

Title: Is there a concept of a variable with phases of initialization: uninitialized, initializing, immutable?

Body:
I was looking at this thread on Stack Overflow and thinking about the functional programming I've been learning, and how immutability is so key there, and it occured to me that maybe some language has gotten the idea to have variables start out "null", then go to a "building" state, and finally become the same as any other immutable when initialization is done.

Is this a valid concept and/or has it been tried or experimented with at the language level?

It might look something like this:

```<code>string s new String(); // empty strings start out mutable
for x = 1 to 10
  s = s + "z"
s.Freeze() // now it's immutable
</code>```

It's just a thought.. maybe it's not a good one, but it seems like a hybrid of two things that seem to be opposing one another.

Body:
You are confusing concepts, in your code the string variable "s" is immutable all along and in no moment it ceases to be immutable.

String s new String(); // Strings are ummutable

    for x = 1 to 10
      s = s + "z"   // you are destroying an object, creating
                    // another one and assining it to the
                    // reference. You are not changing the
                    // internal state of the String.
      s.Freeze()    // It makes no sense. The only way to avoid
                    // assigning a new value to a variable is
                    // converting it into a constant. But then you can only
            // assign an initial value when you declare it.

Immutability means not being able to alter the internal state of an object via properties, settters or methods.

In Java, the String class is immutable, meaning it has no setters or other method of changing its state.

The class StringBuffers is mutable, it has an Append() method and others that change its internal state.

The String class being immutable doesn't mean you cannot over-write the a String object, and assing other string to the reference.

That being clear, you can certainly program a class whose setters raise and IllegalStateException if you try to set a value after you have "frozen" it.

public class FreezableThing {
    private String name="";
    private int number=0;
    boolean frozen = false;

    public boolean isFrozen() { return frozen; }

    public void setFrozen(boolean frozen) { this.frozen = frozen; }

    public String getName() { return name; }

    public int getNumber() { return number; }

    public void setName(String name) {
        if (this.frozen){
            throw new IllegalStateException("Frozen object cannot be changed");
        }
        this.name = name;
    }

    public void setNumber(int number) {
        if (this.frozen){
            throw new IllegalStateException("Frozen object cannot be changed");
        }
        this.number = number;
    }

}

...


答:
My rule of thumb is to put each operation on its own line. This is especially helpful when stepping through code with the debugger. I also like assigning the result of an operation to a variable before passing it along so that I can break and examine its contents. so instead of

```<code>var result = methodOne(methodTwo(a, methodThree(b)), c, d);
</code>```

I would go

```<code>var result3 = methodThree(b);
var result2 = methodTwo(a, result3);
var result = methodOne(result2, c, d);
</code>```

If I'm not mistaken, the java and .Net JIT compilers would compile the two examples the same way.

alternatively, I would write a very detailed comment before the line explaining what it is I'm doing.

Title: Is fewer lines of code always better?

Body:
My rule of thumb is to put each operation on its own line. This is especially helpful when stepping through code with the debugger. I also like assigning the result of an operation to a variable before passing it along so that I can break and examine its contents. so instead of

var result = methodOne(methodTwo(a, methodThree(b)), c, d);

I would go

var result3 = methodThree(b);
var result2 = methodTwo(a, result3);
var result = methodOne(result2, c, d);

If I'm not mistaken, the java and .Net JIT compilers would compile the two examples the same way.

alternatively, I would write a very detailed comment before the line explaining what it is I'm doing.


问:
Tabs versus spaces—what is the proper indentation character for everything, in every situation, ever?
The coding standards for the code hosted in drupal.org suggest to use two spaces to indent the code; other sites suggest to use tabs to indent the code.

What is the proper indentation character for everything, and in every situation? Please explain the answer you give.

答:
Tabs

allow mistakes to be more noticeable, it's annoying to micro manage to spaces.

are consistent, they are only used for indentation, unless you are commenting wrong.

are customizable, you can specify in the options of the editor how wide they are.

are more productive, why type 4 spaces when ye can hit 1 tab.

take less size than multiple spaces.

take more space than a space.

take less time to go through.

tend to work better in IDEs.

Spaces should be used where tabs are completely useless.

Even for aligning parameters and comments, tabs still work better.


答:
Doug Engelbart: The Demo

Doug Engelbart giving the "mother of all Demos" 1968

http://video.google.com/videoplay?docid=-8734787622017763097

Doug's 1968 Demo - web page with links to various versions and archived various at sites, from Douglas Engelbart's web site.

It's unbelievable what was invented back then!

Title: What is the most inspiring speech from a developer you ever watched?

Body:
Please put a direct link to it.

Required:

Still available online (please put a direct link to it)

Must be a speech from a current or former developer

Speaker's popularity doesn't matter

Target audience should be other developers

It is not required that the topic is programming (the task). I'm more looking for subject generally developing here within P.SE rather than SO.

Explain why it was inspiring

(please, native english speaker, edit my question)


问:
data maintenance/migrations in image based sytems
Web applications usually have a database.
The code and the database work hand in hand together.
Therefore Frameworks like Ruby on Rails and Django create migration files

Sure there are also servers written in Self or Smalltalk or other image-based systems that face the same problem: Code is not written on the server but in a separate image of the programmer.

How do these systems deal with a changing schema, changing classes/prototypes.
Which way do the migrations go?

Example: What is the process of a new attribute going from programmer's idea to the server code and all objects?

I found the Gemstone/S manual chapter 8 but it does not really talk about the process of shipping code to the server.

答:
I think the migration file based method has been an innovation.

Before that new schema's were mostly created by building "converters", in other words, creating an entirely new image then copying user data in in it's new shape.

Alternatively an image can contain schema version metadata per record so a reader could migrate (and store in new format) on the fly or in a (lower priority) background process. Similar techniques you may find build on top of document databases these days.

The focus on small text based migration in small delta's has been an improvement over previous practices though.


问:
How far to go with Domain Driven Design?
I've read a little about domain driven design and the usage of a rich domain model, as described by Martin Fowler, and I've decided to put it in practice in a personal project, instead of using transaction scripts.

Everything went fine until UI implementation started. The thing is some views will use rich components that are backed up by unusual models and, thus, I must transform the domain model into what is used by those components. And that transformation is specially "complex" in the view-to-domain portion, up to the point that some business logic is involved.

Wich brings me to the questioning: where should I do these adaptations? So far I've got the following conclusions:

Doing it in the presentation layer is good because, well, if that layer imposes restrictions in it's model, then it should be the one to handle them. But it's bad because there'll be some business leakage.

If I do it on the services objects (controllers, actions, whatever), then it'd be good because there won't be any change to the domain API just because of presentation layer, but it's bad because then I'd have transaction scripts, wich is not the intended design.

Finally, if I do it on the domain model, there'd be no leakage of business logic at all. But in the future I could expect an explosion of the API into a series of methods designed just to handle that view-model <-> domain-model adaptation.

I hope I could make myself clear on this.

答:
If the 'business logic' you mention is only relevant for a view then it may not be 'business logic' as you call it. It could simply be presentation logic, having an if statement somewhere doesn't immediately mean it's business logic.

Populating a view or edit model I usually do either in the controller, sometimes I let the view or edit model populate itself by passing in a domain object. If possible I prefer creating AutoMapper mappings to do most of the work.

If it really is business logic then maybe your domain model needs some improvement. This is not uncommon, if a view or edit model really differs a lot with the domain concepts maybe there is something fishy about the domain model.


答:
Javascript may not be that bad for learning a little

Any programming experience will help you in your Computer Science studies. From that point of view, learning Javascript is better than learning nothing. If you are going to learn just a little programming, Javascript is as good as any other language.

Javascript is not very good for learning on your own

However, if you want to learn as much programming as possible before you start, it is good to know that Javascript is a programming language that is full of traps and bad things for learners, especially self-learners, and there are other languages that are better for learning from scratch on your own (Python comes to mind). At this stage, you can probably switch to a different language.

Javascript: the good parts

If you want to continue with Javascript, watch the video on Javascript: The Good Parts (and maybe buy the book). And then learn to use JSLint and use it with your Javascript code: it will help you write better code, and it will help you learn better.


答:
Think from basics.
Why we write code, when we want to add some functionality and hand it over to another developer, can he understand your code or not, why it's important to structure, why should one follow basic standard guidelines?

The answers are as follows:

Why we put comments in our code.

For developers (who can take advantage of this small documentation to understand the code and routine functionality), computers or decoding/encoding systems just bypass comments, and only deal with the actual code. For example:development bundle and minifest version,

If we use second option it's easy to read and extend and not much guidance is needed by a new developer extending our code.
But if we use first option which is less documented only the person who wrote this code or can understand its purpose, and not the entire team. We are working on rapid development cycle where we need to work on different project and don't have much time to get co-ordinate with other departments, so in this case the second approach works well and another developer can easily extend functionality. It's all about dependency: we work on modularization of code where thousands of developers work on thousands of function and they know only what to return, what to pass to function and which variable is assigned to what, and for what.

For single user or small programs the first approach is ok when team are working together but when people are working remotely what to do, thats the point you likely to go with second option, optimization is another technique to shorten the code but only after we are happy with output.

computer is machine , only understand zero and one's language , but if we write code who itself guide other developer about programe like second approach , new people can also use this as guidance or to edit the program ,

computer understand 0 and 1 and human can understand comments

so i like second approach which help developer to understand whats going on inside loop or function

eg:**suppose if you are working on some project and you use 1st way and at some case you had another task and another developer is working on your code , does he understand this or not? its not question about simplicity or how to document , its all about **how to farward our code to our partner when he want to update the code with hassle free support.

second approach is well for partners and developers and 1st options work well when we are working on web platform , or writting script where size of the code matters

TL;DR:

Document your code. Write comments when you're writing it. It will save you valuable time three months down the line when you come back to it and can't understand what the code is doing. Also, your co-workers will sing praises of you when they can actually understand what you're doing, and are easily able to extend/refactor or otherwise modify code written by you.
Don't overdo it, however.

If fewer lines of code make sense, go ahead and do it in that many lines. But do not make it so that typing fewer lines would make you have to add comments to explain your code. It should be as self-explanatory as possible.

Title: Is fewer lines of code always better?


问:
Need help understanding Mocks and Stubs
I'm new to use mocking frameworks and I have a few questions on the things that I am not clear on. I'm using Rhinomocks to generate mock objects in my unit tests. I understand that mocks can be created to verify interactions between methods and they record the interactions etc and stubs allow you to setup data and entities required by the test but you do not verify expectations on stubs.

Looking at the recent unit tests I have created, I appear to be creating mocks literally for the purpose of stubbing and allowing for data to be setup. Is this a correct usage of mocks or is it incorrect if you're not actually calling verify on them?

For example:

```<code>user = MockRepository.GenerateMock<User>();
        user.Stub(x => x.Id = Guid.NewGuid());
        user.Stub(x => x.Name = "User1");
</code>```

In the above code I generate a new user mock object, but I use a mock so I can stub the properties of the user because in some cases if the properties do not have a setter and I need to set them it seems the only way is to stub the property values. Is this a correct usage of stubbing and mocking?

Also, I am not completely clear on what the difference between the following lines is:

```<code>user.Stub(x => x.Id).Return(new Guid());

user.Stub(x => x.Id = Guid.NewGuid());
</code>```

答:
I am taking the help from these mentioned links and will modify accordingly as per my understanding:

Good links:

Good explanation by Jim

Explanation by martin frowler

Informative Link, but a little advanced (talks about integration testing)

Ok before going forward there are two things when You are Unit Testing:

Sate Testing

Behaviour Testing

In state testing You are only checking whether the actual method or System Under Test(SUT) is returning the correct value

In behaviour testing You check whether the correct method was called, or in other words whether a correct sequence of methods were called.

Stubs  provide canned answers to calls made during the test, usually not responding at all to anything outside the test method.Here You generally do State testing.

Mocks are used to verify interaction between your SUT and its dependencies.You generally do behavior testing here

Title: Need help understanding Mocks and Stubs


问:
Subversion permissions and Visual Studio projects
I have a quite specific question regarding Subversion structure, different permission levels and Visual Studio projects and solutions: We develop a framework with external partners with functionality the partner is not allowed to see.

Consider following structure of a VS solution:

example.sln

|_ /unit1/unit1.csproj (incl. cs files)

|_ /unit2/unit2.csproj (incl. cs files)

|_ /unit3/unit3.csproj (incl. cs files)

unit1 and unit2 belongs to the framework, unit3 is specific (secret) functionality. Framework is functionally without unit3 (which will be shipped as dll).

My question now is: How can this project be structured if the two parties should have a functional development environment, example.sln references unit3, but our external partner won't have this part because of the SVN permission. We, of course, have full access to the repository.

I hope my request has become clear... Am I one a wrong track with my question?

EDIT: Thanks to this answer I see clearer. Last question: How to implement different solutions for different groups so that each group can only check out their solution:

two sln files in one directory with different permissions

two directory trees for each solution with links to the shared projects?

答:
You have to create a separate solution which will reference only the projects your partners have access to.

If public projects use secret projects, those secret projects won't be included in the solution, and will be simply referenced in their binary form (like you reference an assembly from .NET Framework or any library within a DLL that you download locally). NuGet can also be used, if appropriate.

Note that this also creates a few issues with the dependencies. For example, if the secret unit3 relies on the public unit1 and your partner modifies the interface of unit1, the change won't be reflected in unit3, which will in fine break the build. Make sure your partners understand that, and agree on some guidelines relative to the changes which affect public interfaces.


问:
Using Power of 2 numbers to represent types
Let's say that we have some values, represented by power of 2:

```<code>TYPE_1 = 1
TYPE_2 = 2
TYPE_3 = 4
TYPE_4 = 8
...
</code>```

I need to store some of these types in one value.

Example:
To represent TYPE_1 with TYPE_3, the value is 5.

What operation is used to identify that value 5 represent TYPE_1 with TYPE_3?

答:
If you use the bitwise or operator, you will get the value 5

```<code>print(TYPE_1 | TYPE_3) //5
</code>```

Body:
If you use the bitwise or operator, you will get the value 5

print(TYPE_1 | TYPE_3) //5


问:
design practice for business layer when supporting API versioning
Is there any design pattern or practice recommended for business layer when dealing with multiple API version.

For example, I have something like this.

http://site.com/blogs/v1/?count=10

   which calls business object method GetAllBlogs(int count) to get information

http://site.com/blogs/v2/?blog_count=20

which calls business object method GetAllBlogs_v2(int blogCounts)

Since parameter name is changed, I created another business method for version 2.  This is just one example but it could have other breaking changes for which it requires me to create another method to support both version.  Is there any design pattern or best practice for business/data access layer I should follow when supporting API Versioning?

答:
If you are going to mix v1 and v2 in one current code base you'd need to a have a reason for this. Typically this is because you are going to route old version method calls from your API service to new 'business object methods', this may involve some conversion and such.

If you are going to keep the v1 and v2 paths separate vertically (the code paths aren't sharing anything) you may as well let v1 be served by the old(er) version of your software.

Between v1 and v2 try to bundle API changes so you can offer your clients a document about migrating. API stability is typically appreciated.

Your example on it's own is -not- worth it, it's such a small cosmetic change try to not do those. Or if you do sneak them in while introducing other bigger changes.

While stacking up new interface for your v2 you could offer them early through some sort of extension mechanism, libraries like OpenGl do this.

Try to come up with a deprecation model for your older API surfaces. Supporting all old interfaces till the end of time is going to be hard and very costly.

If at all possible try maintain older version with old distributions of your software. If you can avoid to not mix API generations in one code base do so.

It's very hard to come up with a good interface on the first incarnation of your API surface. Clients may appreciate this, perhaps you can avoid the version management by allowing API instability and breaking changes through a alpha, beta cycle or 0.X releases.


问:
Is there a concept of a variable with phases of initialization: uninitialized, initializing, immutable?
I was looking at this thread on Stack Overflow and thinking about the functional programming I've been learning, and how immutability is so key there, and it occured to me that maybe some language has gotten the idea to have variables start out "null", then go to a "building" state, and finally become the same as any other immutable when initialization is done.

Is this a valid concept and/or has it been tried or experimented with at the language level?

It might look something like this:

```<code>string s new String(); // empty strings start out mutable
for x = 1 to 10
  s = s + "z"
s.Freeze() // now it's immutable
</code>```

It's just a thought.. maybe it's not a good one, but it seems like a hybrid of two things that seem to be opposing one another.

答:
The work on typestate introduced ways for a type system to keep track of what operations are permitted on a piece of data as the state of the data changes over time.  The original paper used typesafe to safely initialize and finalize variables.  Later work applied typestate to high-level properties, such as keeping track of whether a file is open or closed.  Plaid uses typestate.

In a language with typestate, objects have a type at each program point.  Functions can alter the types of the objects that they access.  The language's typing rules ensure that variables are always used in a way that's consistent with their type, so that attempts to use an uninitialized variable or read from a closed file are caught at compile time.


问:
Structuring Access Control In Hierarchical Object Graph
I have a Folder entity that can be Moderated by users.  Folders can contain other folders.  So I may have a structure like this:

```<code>Folder 1
    Folder 2
        Folder 3
    Folder 4
</code>```

I have to decide how to implement Moderation for this entity.  I've come up with two options:

Option 1

When the user is given moderation privileges to Folder 1, define a moderator relationship between Folder 1 and User 1.  No other relationships are added to the db.

To determine if the user can moderate Folder 3, I check and see if User 1 is the moderator of any parent folders.

This seems to alleviate some of the complexity of handling updates / moved entities / additions under Folder 1 after the relationship has been defined, and reverting the relationship means I only have to deal with one entity.

Option 2

When the user is given moderation privileges to Folder 1, define a new relationship between User 1 and Folder 1, and all child entities down to the grandest of grandchildren when the relationship is created, and if it's ever removed, iterate back down the graph to remove the relationship.  If I add something under Folder 2 after this relationship has been made, I just copy all Moderators into the new Entity.

But when I need to show only the top-level Folders that a user is Moderating, I need to query all folders that have a parent folder that the user does not moderate, as opposed to option 1, where I just query any items that the user is moderating.

Thoughts

I think it comes down to determining if users will be querying for all parent items more than they'll be querying child items... if so, then option 1 seems better.  But I'm not sure.

Is either approach better than the other?  Why?  Or is there another approach that's better than both?  I'm using Entity Framework in case it matters.

答:
For option 2 you may want to store whether or not privileges are inherited from the parent or not. Otherwise you may loose user intent when changing the parent.

The better approach is keeping it logical. Recurse on your ancestors to determine privileges. Depending on how deep your average hierarchy is you may get away with doing a couple of queries, measure it. You could recurse in a Stored Procedure on the database tier also if you are using SQL.

Only if this is not fast enough I would materialize the privileges. I'd try to do that in a query caching layer and not in the authoritative / normalized database.


答:
Both examples are actually bad.

What happens if methodOne fails?  What happens if methodTwo fails?  What happens if methodThree fails?  You obviously omitted the error checking for clarity here, but it is an important point - adding error checking will add more lines of code (which on it's own should answer your question) so extra lines of meaningful code that actually does something should never be viewed as a bad thing.

Aside from that, I would still favour the second example.  The reason why is because it's more maintainable; you can more easily insert a call to methodTwoPointFive between the calls to methodTwo and methodThree, for example, should future requirements need it.

Title: Is fewer lines of code always better?


问:
In MVC software, who should load the models?
I'm working in a REST JavaScript client, and I'm trying to follow the MVC pattern, but a very basic question came to my mind: who should make the http request and load the data into the model?

My intuition tells me that the controller should do it, but in lots of examples (the ember.js documentation, by example) it's done by the model, with a find() method. But other frameworks, like Django, do it in the controller.

What do you think it's the better way to do this?

答:
Both can work. I prefer neither. The model loading could be done by some repository or 'store' service.

ExtJs uses Stores which have the knowledge about obtaining model data, provide client side caching etc. I appreciate this design, good separation of concerns.


问:
Career advice: stay with PHP or start a new career in something else ( .Net?)
I'm planning on moving to NY in 6-12 months tops, so I'm forced to find a new job. When I'm planing to start my life in another city it's also probably a good time to think about career changes.

I've found a lot of different opinions about PHP vs .Net vs Java and this is not the topic here. I don't want to start a new fight about which language is better. Knowing a programming language is not the most important thing for being a software developer. To be a really good developer you need to know OOP, design patterns, testing... and a language is just a tool to make things happen.

So back to my question. I have mixed experience in IT - 1 year as an IT support guy (Windows administration and support), around 2 years of experience in embedded programming (VB.Net 2005) and for the last 2 years I'm working with PHP/MySQL. I have worked with Magento web shop, assisted in some projects in Symfony, modified few Drupal sites.

My main concerns are the following:

Do I continue to improve my skills in PHP e.g. to start learning some major PHP framework like Zend, Symfony maybe get some PHP certification.

Or do I start learning .NET or Java. I'm more familiar to .NET so I'll probably choose it if choice falls between .NET and Java ( or you could convince me to choose Java :).

Career-wise, I don't know what is the best choice. Learning a new framework and language is more time consuming then improving my existing skills in PHP. But with .NET you have a lot of possibilities (Windows 7 Phone development, Silverlight, WPF) and possibly bigger chances to find better jobs.

PHP jobs are less well payed then .NET, at least, according to my research (correct me if I'm wrong). But if I start now with .NET I'm just a beginner and my salary will be low. I need at least 2+ years of experience in some language to even try to find some job that is paying higher than $50-60k in NY. My main goal in the next 2-3 years is to try to find a job in the $60-80k category. Don't get me wrong, I'm not just chasing money, but money is an important factor when you're trying to start a family.

I'm 27 years old and I feel that there isn't a lot of room for wrong decisions regarding my career, so any advice will be very welcome.

Update

Thank you all for spending time to help me with my problem. All of the answers and comments have been very helpful. I have decided to stick with PHP but also to learn C# and Silverlight 4. We'll see where the life will take me.

答:
What on earth does the choice of programming language have anything to do with your career?

This question is like asking, "I have two choices for a place to work. Should I work at the one where the boss has a norwegian accent, or the one where the boss has a spanish accent?"

There are much more important career considerations.

Startup or established company?

Product company or company where IT is a support function?

Will you be learning new things or rehashing the old?

9 to 5 or "work any 80 hours you want?"

Nice co-workers or mean co-workers?

Smart co-workers or stupid co-workers?

Suit and tie or t-shirt?

This list could go on for hours. The choice of a programming language is just about as relevant to a programmer's career as the choice of whether to comb your hair to the left or to the right. It's all software development no matter what programming language dialect you happen to be speaking.


答:
I'm using C here, but similar operators exist in most languages.

Assume you have some variable to store the types:

```<code>unsigned char mytypes;

 #define TYPE_1  1
 #define TYPE_2  2
 #define TYPE_3  4
 #define TYPE_4  8
</code>```

To set one of the types, you would use either:

```<code>mytypes = mytypes | TYPE_1;
</code>```

or, as a shorthand in C,

```<code>mytypes |= TYPE_1;
</code>```

in either case, any existing bits (types) present in mytypes are preserved.

To check whether mytypes contains a specific type, you would write:

```<code>if ((mytypes & TYPE_1) == TYPE_1)
</code>```

Similarly, if you wanted to check for two types at once, you would write:

```<code>if (((mytypes & (TYPE_1 | TYPE_3)) == (TYPE_1 | TYPE_3))
</code>```

where TYPE_1 | TYPE_3 equals 5 as per your example.

Title: Using Power of 2 numbers to represent types

Body:
Let's say that we have some values, represented by power of 2:

```<code>TYPE_1 = 1
TYPE_2 = 2
TYPE_3 = 4
TYPE_4 = 8
...
</code>```

I need to store some of these types in one value.

Example:
To represent TYPE_1 with TYPE_3, the value is 5.

What operation is used to identify that value 5 represent TYPE_1 with TYPE_3?

Body:
I'm using C here, but similar operators exist in most languages.

Assume you have some variable to store the types:

unsigned char mytypes;

 #define TYPE_1  1
 #define TYPE_2  2
 #define TYPE_3  4
 #define TYPE_4  8

To set one of the types, you would use either:

mytypes = mytypes | TYPE_1;

or, as a shorthand in C,

mytypes |= TYPE_1;

in either case, any existing bits (types) present in mytypes are preserved.

To check whether mytypes contains a specific type, you would write:

if ((mytypes & TYPE_1) == TYPE_1)

Similarly, if you wanted to check for two types at once, you would write:

if (((mytypes & (TYPE_1 | TYPE_3)) == (TYPE_1 | TYPE_3))

where TYPE_1 | TYPE_3 equals 5 as per your example.


答:
It looks like you're using JavaScript, which changes the paramaters ever so slightly.

Unless you have a reason to store those var's, you'd be better off not initalizing them at all.  But, you should make the single-statement version as readable as possible, by adding whitespace and a comment.

```<code>//Do X, Y, Z....
var result = methodOne(
    methodTwo(
        a,
        methodThree(b)
    ),
    c,
    d
);
</code>```

Title: Is fewer lines of code always better?

Body:
It looks like you're using JavaScript, which changes the paramaters ever so slightly.

Unless you have a reason to store those var's, you'd be better off not initalizing them at all.  But, you should make the single-statement version as readable as possible, by adding whitespace and a comment.

//Do X, Y, Z....
var result = methodOne(
    methodTwo(
        a,
        methodThree(b)
    ),
    c,
    d
);


问:
Dev environment different from testing environment
I'm working on a .net web app project where we develop on our personal machines, but our testing and production environments are in a corporate intranet. The problem is I run into bugs that only present in the testing/production environment, but not in dev. I find this makes it really difficult to track down the cause of the problem.

Are there any tips/strategies to deal with this issue?

**Please note I have no control or options when it comes to setting up new servers or modifying the test environment. I can only make changes to my local machine. I also do not have access to a company image file to image my PC.

答:
Here are a few ideas:

If it is possible to get additional hardware or machines, here are a couple of ideas:

Get a development server that is a mirror of the test server.  This will provide a way to test functionality on a server rather than on developer's machines to ensure that functionality that may require configuration is picked up properly.  Using Continuous Integration here can also be a useful tool in verifying bug fixes and preventing regression if developers keep making appropriate tests.

Ensure developers have a separate machine, possibly virtually, so that tests can be done over a network rather than everything being done locally.  This is where it can be handy to have older PCs that may be similar to client machines that can be used to test in various browsers on a machine separate from the intended server.  This may not always be do able but it is something to suggest.

If not, here are a few other ideas to consider:

While you develop on your personal machines, are you using IIS or Visual Studio's built-in web server to run your code?  There can be differences here worth noting and is something to consider in going from one environment to another.  This is where it can be important to have standards for the developers and ensure everyone understands why things are this way.

Add additional debug information that may be useful in dev and testing environments that is turned off in production as it could well harm the performance.  This would be where you could log exceptions with additional information or add informational messages about the state of the server since it is possible that App_pool recycling or other IIS settings could be what is triggering bugs that wouldn't easily be caught by developers that often restart their own App_pool to reflect code changes.  In a sense, you want to have some performance counters in the code that log values at regular intervals that may help diagnose issues as there can be issues with heavy load that could harm an app that is different than what developers may initially test within their code.

Log the differences in environments.  Multiple servers?  Firewalls? Load balancing? Versions of software?  Ensuring patches are up to date on all the servers?  While this is a menial task on one level, maintaining a document that shows differences could be quite useful as if you develop on IIS 7.5 and deploy to IIS 5.0 then there may be some differences that could be an issue.

Consider what kinds of tests do you have on your environments.  Are there load tests?  Are there penetration tests?  This can be something to explore though depending on the issues being found it may or may not be easy to justify the costs for some of the higher-end tools.


答:
What operation is used to identify that value 5 represent TYPE_1 with
  TYPE_3?

I'm going to assume you mean that you've been handed a value (say, 5) and want to know how to tell that the first and third bits are set and therefore represent TYPE_1 and TYPE_3.

There are a couple of ways to handle this.  Both involve using a series of logical ANDs to shut off all of the bits in the value you've been handed except the one you're interested in to see if the remaining bit is 1 or 0:

```<code>    00000101   The value; 5 in this case
and 00000100   The mask, TYPE_3
    --------
    00000100   The ANDed result, which is nonzero.  TYPE_3's bit is set.
</code>```

Same thing, but with TYPE_2, which isn't present in the value:

```<code>    00000101   The value; 5 in this case
and 00000010   The mask, TYPE_2
    --------
    00000000   The ANDed result, which is zero.  TYPE_2's bit is not set.
</code>```

The first way to handle this is to do comparisons against each type:

```<code>if ( value & TYPE_1 ) handle_type_1();
if ( value & TYPE_2 ) handle_type_2();
 ...etc...
</code>```

This is the brute force method, but if you're dependent on the TYPE_* macros defined in some header file, this is the only way to do it safely.  You can't depend on the bits representing each type not changing.  (And shame on whoever wrote the header file for not providing some functions or macros to help you figure these things out.)

If you do have control over the arrangement of the bit field and can declare that bit n represents type n, it becomes easy to put together a few macros (or functions if you're not using C) to handle it:

```<code>#define NUMBER_OF_TYPES       4

/* These are bit numbers, not powers of two */
#define TYPE_1                1
#define TYPE_2                2
#define TYPE_3                3
#define TYPE_4                4

#define TYPE_MASK(t)          (1 << (t-1))
#define VALUE_HAS_TYPE(v,t)   ((v) & TYPE_MASK((t)))

/* Construct a value holding two types */
unsigned value = TYPE_MASK(TYPE_1) | TYPE_MASK(TYPE_3);

for (unsigned type_num=0 ; type_num < NUMBER_OF_TYPES ; ++type_num) {
    if ( VALUE_HAS_TYPE(value, type_num)
        do_something_with_type_number(type_num);
}
</code>```

This iterates over the number of types you have, checks to see if each one is present and then calls a function with its type number.  This gives you a huge amount of flexibility in do_something_with_type_number(), because you can use a switch statement on the type number or use it as an index into an array that might point at functions to handle each type.  You can't do either of those with bitwise comparisons.

Body:
What operation is used to identify that value 5 represent TYPE_1 with
  TYPE_3?

I'm going to assume you mean that you've been handed a value (say, 5) and want to know how to tell that the first and third bits are set and therefore represent TYPE_1 and TYPE_3.

There are a couple of ways to handle this.  Both involve using a series of logical ANDs to shut off all of the bits in the value you've been handed except the one you're interested in to see if the remaining bit is 1 or 0:

    00000101   The value; 5 in this case
and 00000100   The mask, TYPE_3
    --------
    00000100   The ANDed result, which is nonzero.  TYPE_3's bit is set.

Same thing, but with TYPE_2, which isn't present in the value:

    00000101   The value; 5 in this case
and 00000010   The mask, TYPE_2
    --------
    00000000   The ANDed result, which is zero.  TYPE_2's bit is not set.

The first way to handle this is to do comparisons against each type:

if ( value & TYPE_1 ) handle_type_1();
if ( value & TYPE_2 ) handle_type_2();
 ...etc...

This is the brute force method, but if you're dependent on the TYPE_* macros defined in some header file, this is the only way to do it safely.  You can't depend on the bits representing each type not changing.  (And shame on whoever wrote the header file for not providing some functions or macros to help you figure these things out.)

If you do have control over the arrangement of the bit field and can declare that bit n represents type n, it becomes easy to put together a few macros (or functions if you're not using C) to handle it:

#define NUMBER_OF_TYPES       4

/* These are bit numbers, not powers of two */
#define TYPE_1                1
#define TYPE_2                2
#define TYPE_3                3
#define TYPE_4                4

#define TYPE_MASK(t)          (1 << (t-1))
#define VALUE_HAS_TYPE(v,t)   ((v) & TYPE_MASK((t)))

/* Construct a value holding two types */
unsigned value = TYPE_MASK(TYPE_1) | TYPE_MASK(TYPE_3);

for (unsigned type_num=0 ; type_num < NUMBER_OF_TYPES ; ++type_num) {
    if ( VALUE_HAS_TYPE(value, type_num)
        do_something_with_type_number(type_num);
}

This iterates over the number of types you have, checks to see if each one is present and then calls a function with its type number.  This gives you a huge amount of flexibility in do_something_with_type_number(), because you can use a switch statement on the type number or use it as an index into an array that might point at functions to handle each type.  You can't do either of those with bitwise comparisons.


问:
How can programming ability be used to help people in poverty?
As a student studying Computer Science in college, I often hear from friends working on various humanitarian projects, and I want to do something myself. But it seems that programmers don't have as many obvious avenues to help out as, say, doctors or teachers. What are some ways in which programmers can put their talent to use for people in poverty?</p>

答:
Despite the many answers, I feel like I can contribute to this subject - a group has been considering (In a different context) what "Good" means and some of what they have written about is charity.

First, harsh words (That have been posted in other answers as well)

Efficient Charity, by Yvain

In the "Buy A Brushstroke" campaign, eleven thousand British donors gave a total of £550,000 to keep the famous painting "Blue Rigi" in a UK museum. If they had given that £550,000 to buy better sanitation systems in African villages instead, the latest statistics suggest it would have saved the lives of about one thousand two hundred people from disease. Each individual $50 donation could have given a year of normal life back to a Third Worlder afflicted with a disabling condition like blindness or limb deformity..

Most of those 11,000 donors genuinely wanted to help people by preserving access to the original canvas of a beautiful painting. And most of those 11,000 donors, if you asked, would say that a thousand people's lives are more important than a beautiful painting, original or no. But these people didn't have the proper mental habits to realize that was the choice before them, and so a beautiful painting remains in a British museum and somewhere in the Third World a thousand people are dead.

Second, words on what you can do AS A PROGRAMMER that doesn't feel as cold.

Money: the Unit of Caring, by Eliezer Yudkowsky

The bolding underneath is mine, to draw attention to the important point.

There is this very, very old puzzle/observation in economics about the lawyer who spends an hour volunteering at the soup kitchen, instead of working an extra hour and donating the money to hire someone to work for five hours at the soup kitchen.

There's this thing called "Ricardo's Law of Comparative Advantage".  There's this idea called "professional specialization".  There's this notion of "economies of scale".  There's this concept of "gains from trade".  The whole reason why we have money is to realize the tremendous gains possible from each of us doing what we do best.

This is what grownups do.  This is what you do when you want something to actually get done.  You use money to employ full-time specialists.

Yes, people are sometimes limited in their ability to trade time for money (underemployed), so that it is better for them if they can directly donate that which they would usually trade for money.  If the soup kitchen needed a lawyer, and the lawyer donated a large contiguous high-priority block of lawyering, then that sort of volunteering makes sense—that's the same specialized capability the lawyer ordinarily trades for money.  But "volunteering" just one hour of legal work, constantly delayed, spread across three weeks in casual minutes between other jobs?  This is not the way something gets done when anyone actually cares about it, or to state it near-equivalently, when money is involved.

Third, the thing I actually came here to post:

Purchase Fuzzies and Utilions Separately, by Eliezer Yudkowsky

If I had to give advice to some new-minted billionaire entering the realm of charity, my advice would go something like this:

To purchase warm fuzzies, find some hard-working but poverty-stricken woman who's about to drop out of state college after her husband's hours were cut back, and personally, but anonymously, give her a cashier's check for $10,000.  Repeat as desired.

To purchase status among your friends, donate $100,000 to the current sexiest X-Prize, or whatever other charity seems to offer the most stylishness for the least price.  Make a big deal out of it, show up for their press events, and brag about it for the next five years.

Then—with absolute cold-blooded calculation — without scope insensitivity or ambiguity aversion — without concern for status or warm fuzzies — figuring out some common scheme for converting outcomes to utilons, and trying to express uncertainty in percentage probabilitiess—find the charity that offers the greatest expected utilons per dollar.  Donate up to however much money you wanted to give to charity, until their marginal efficiency drops below that of the next charity on the list.

Obviously, you are not a billionaire (I guess. If you are, thank you for considering charity), but even so, that third quote is applicaple. You want to feel good about being a good person and you want to be a good person. You are allowed to do both - especially if you are more likely to help people if you feel good about helping. The important part, after all, is that people get help.

If you feel that helping people, personally, so you can feel that you are helping, is more likely to happen than you spending that same amount of time earning money to give away, then help personally. The important part is that people get help.

And if anybody, anywhere, ever accuses you of just doing it to feel good? Remember always that you have helped, and they have not.


答:
I would suggest looking for a PHP job because that is what you do best.

I would also suggest you start educating yourself in the new technologies you want to learn so you can eventually start looking for jobs using those, but don't do it on a deadline so short because you will find that these things are huge and employers expect you to know enough of these behemoths to be productive.  That requires time and practice.  Do not underestimate the amount of time and amount of practice you will have to do.

To give you an estimate of what "I can program in Java" potential employee should be capable of, you can have a look at the Sun Java Tutorial.  I would expect you to be familiar with at least half the concepts listed, where familiar means being able to use it in a program written by you, and use it correctly.  I would expect it to take longer than 6 months spare time studying to reach that level.

Title: Career advice: stay with PHP or start a new career in something else ( .Net?)

Body:
I'm planning on moving to NY in 6-12 months tops, so I'm forced to find a new job. When I'm planing to start my life in another city it's also probably a good time to think about career changes.

I've found a lot of different opinions about PHP vs .Net vs Java and this is not the topic here. I don't want to start a new fight about which language is better. Knowing a programming language is not the most important thing for being a software developer. To be a really good developer you need to know OOP, design patterns, testing... and a language is just a tool to make things happen.

So back to my question. I have mixed experience in IT - 1 year as an IT support guy (Windows administration and support), around 2 years of experience in embedded programming (VB.Net 2005) and for the last 2 years I'm working with PHP/MySQL. I have worked with Magento web shop, assisted in some projects in Symfony, modified few Drupal sites.

My main concerns are the following:

Do I continue to improve my skills in PHP e.g. to start learning some major PHP framework like Zend, Symfony maybe get some PHP certification.

Or do I start learning .NET or Java. I'm more familiar to .NET so I'll probably choose it if choice falls between .NET and Java ( or you could convince me to choose Java :).

Career-wise, I don't know what is the best choice. Learning a new framework and language is more time consuming then improving my existing skills in PHP. But with .NET you have a lot of possibilities (Windows 7 Phone development, Silverlight, WPF) and possibly bigger chances to find better jobs.

PHP jobs are less well payed then .NET, at least, according to my research (correct me if I'm wrong). But if I start now with .NET I'm just a beginner and my salary will be low. I need at least 2+ years of experience in some language to even try to find some job that is paying higher than $50-60k in NY. My main goal in the next 2-3 years is to try to find a job in the $60-80k category. Don't get me wrong, I'm not just chasing money, but money is an important factor when you're trying to start a family.

I'm 27 years old and I feel that there isn't a lot of room for wrong decisions regarding my career, so any advice will be very welcome.

Update

Thank you all for spending time to help me with my problem. All of the answers and comments have been very helpful. I have decided to stick with PHP but also to learn C# and Silverlight 4. We'll see where the life will take me.


答:
```<code>Code with as few lines as possible is definitely the best code and every semi-colon you see is basically the developer admitting they weren't clever enough to use advanced constructions like the comma operator or short-circuiting operators to keep the line going as long as possible like you can say `(x++ && false) || y += 2` instead of `x++; y += 2` and the first variant is just so much more concise and clearer as you can tell because it contains no semi-colons honestly I almost threw up writing the second one I mean who wants to use a character whose name contains a word related to your butt that's just dumb and anyways semi-colons introduce lots of vulnerabilities like what if you typed `while(true) ;` that would just keep running forever and so its clearly better to have no semi-colons to avoid problems like that overall I'd say programmer salaries should be inversely proportional to the number of newlines and semi-colons in their code because everyone knows as soon as you start using a metric like that it starts working even better than before you incentivized it
</code>```

Title: Is fewer lines of code always better?


答:
In this particular example I don't find the first version harder to read, it's just as reading a simple arithmetical expression such has (a + f(b)) * c * d. The second version doesn't add any information that helps to understand it (unless the variables have meaningful names that help to understand a complicated process).

What I feel a bit problematic with the second version is that it introduces additional complexity when analyzing the code. A programmer who reads the code needs to think about if resultThirdMethod or resultSecondMethod is used somewhere else then just to compute result. And if you write a method full of such statements there is no clear line of computation, you have to check constantly what is computed from what and where. So in this case, if you want the more verbose version, I'd suggest to either encapsulate it into a separate function:

```<code>function methodCombined(a, b, c, d)
    var resultThirdMethod = methodThree(b);
    var resultSecondMethod = methodTwo(a, resultThirdMethod);
    return methodOne(resultSecondMethod, c, d);
}
// ...
result = methodCombined(a, b, c, d);
</code>```

or at least enclose it into a code block so that the scope of variables is immediately visible:

```<code>var result;
{
    var resultThirdMethod = methodThree(b);
    var resultSecondMethod = methodTwo(a, resultThirdMethod);
    result = methodOne(resultSecondMethod, c, d);
}
</code>```

Title: Is fewer lines of code always better?

Body:
In this particular example I don't find the first version harder to read, it's just as reading a simple arithmetical expression such has (a + f(b)) * c * d. The second version doesn't add any information that helps to understand it (unless the variables have meaningful names that help to understand a complicated process).

What I feel a bit problematic with the second version is that it introduces additional complexity when analyzing the code. A programmer who reads the code needs to think about if resultThirdMethod or resultSecondMethod is used somewhere else then just to compute result. And if you write a method full of such statements there is no clear line of computation, you have to check constantly what is computed from what and where. So in this case, if you want the more verbose version, I'd suggest to either encapsulate it into a separate function:

function methodCombined(a, b, c, d)
    var resultThirdMethod = methodThree(b);
    var resultSecondMethod = methodTwo(a, resultThirdMethod);
    return methodOne(resultSecondMethod, c, d);
}
// ...
result = methodCombined(a, b, c, d);

or at least enclose it into a code block so that the scope of variables is immediately visible:

var result;
{
    var resultThirdMethod = methodThree(b);
    var resultSecondMethod = methodTwo(a, resultThirdMethod);
    result = methodOne(resultSecondMethod, c, d);
}


答:
I suspect what everyone wants to hear is "no".

The fact of the matter is that your example isn't clear enough to give a solid answer.

resultThirdMethod is a horrible name. I find the first version much clearer than the second.

However, if you could give your variables names -- names that give more information than merely where the data came from -- then it could be better. It all depends on the actual situation.

Title: Is fewer lines of code always better?


答:
Best style is the one which makes the code most readable (for a human, that is -- computers don't care). But "readable" depends a lot on who does the reading so that's context dependent. This is enough, though, to answer your exact question: "Is [whatever] always better" ? Then no, it depends on the context.

The first person who must read code is the developer himself. If you write code such that you will yourself be able to read and understand it four weeks from now, then you will have already done a good job -- a much better job than the majority of developers in the industry (alas).

One can add a few generalities, though. Reading code implies using the eye and brain. Human eyes tire faster when they have to move a lot, especially when they have to move vertically (lateral movement is less an issue). Using fewer lines of code, all other things being equal, will allow the reader to grasp the code with less vertical eye movement, so that's somewhat good.

On the other hand, the syntax analysis which goes in the brain will want to use as many "visual anchors" as possible, and will suffer from certain activities, in particular counting parentheses. Spreading the code over more lines, with indentation, helps the brain. It really is a trade-off between eye fatigue and brain fatigue, and, I insist, the right balance point is not the same for everybody.

Ultimately, it is a matter of "good taste". People who write ugly code are also people who are happy eating bad pizza.

Title: Is fewer lines of code always better?


问:
log4cxx: is it a stable option to include as part of distributed library?
We are porting our Java API library to C++. (Our target platforms are Linux and Windows.)  Since we have minimal C++ experience, the learning curve has been pretty steep, but overall we have been able to make a clean port so far.

In Java we use log4j, and are looking at to use log4cxx in the C++ version.  It took us a few hours to get log4cxx to build on Windows (due both to our inexperience, and also build documentation seems out of date). We haven't yet tried to build on Linux.

To my uninformed eye, log4cxx seems messy and somewhat outdated. Is there any consensus on whether this is a good logging framework to go forward with?  (Log4j also seems to have been superceded by SLF4J and Logback.)

I looked also at boost logging, but that does not appear to be part of the main distribution, so I wasn't sure if I was provided a more standard option with that or not.

One other piece of information to add into the evaluation - the first client we are providing this to is already using log4cxx.

答:
Boost.Log is a part of the official Boost distribution since 1.54.0.

Today applications grow rapidly, becoming complicated and difficult to test and debug...

This library aims to make logging significantly easier for the application developer. It provides a wide range of out-of-the-box tools along with public interfaces for extending the library. The main goals of the library are:

Simplicity. A small example code snippet should be enough to get the feel of the library and be ready to use its basic features.

Extensibility. A user should be able to extend functionality of the library for collecting and storing information into logs.

Performance. The library should have as little performance impact on the user's application as possible...


问:
Demonstration of garbage collection being faster than manual memory management
I've read in many places (heck, I've even written so myself) that garbage collection could (theoretically) be faster than manual memory management.

However, showing is a lot harder to come by than telling.

I have never actually seen any piece of code that demonstrates this effect in action.

Does anyone have (or know where I can find) code that demonstrates this performance advantage?

答:
It's easy to construct an artificial situation where GC is infinitely more efficient than manual methods - just arrange that there is only one "root" for the garbage collector, and that everything is garbage, so the GC step is instantly completed.

If you think about it, that is the model used when garbage collecting the memory allocated
to a processes.  The process dies, all it's memory is garbage, we're done.  Even in practical terms, a process that starts, runs, and dies leaving no trace might be more efficient than one that starts and runs forever.

For practical programs, written in languages with garbage collection, the advantage of garbage collection is not speed but correctness, and simplicity.


答:
See Link and follow all of the links to see Rico Mariani vs Raymond Chen (both very competent programmers at Microsoft) dueling it out.  Raymond would improve the unmanaged one, Rico would respond by optimizing the same thing in the managed ones.

With essentially zero optimization effort, the managed versions started off many times faster than the manual.  Eventually the manual beat the managed, but only by optimizing to a level that most programmers would not want to go to.  In all versions, the memory usage of the manual was significant better than the managed.

Title: Demonstration of garbage collection being faster than manual memory management

Body:
I've read in many places (heck, I've even written so myself) that garbage collection could (theoretically) be faster than manual memory management.

However, showing is a lot harder to come by than telling.

I have never actually seen any piece of code that demonstrates this effect in action.

Does anyone have (or know where I can find) code that demonstrates this performance advantage?


答:
A model shouldn't have to worry or even know about persistence. So a model loading itself is out for me.

In MVC: the controller should be the one in control of having the model loaded. Whether it does it itself, or delegates that to a store or repository or whatever other data-persistence service name you can think of is immaterial.

Title: In MVC software, who should load the models?

Body:
I'm working in a REST JavaScript client, and I'm trying to follow the MVC pattern, but a very basic question came to my mind: who should make the http request and load the data into the model?

My intuition tells me that the controller should do it, but in lots of examples (the ember.js documentation, by example) it's done by the model, with a find() method. But other frameworks, like Django, do it in the controller.

What do you think it's the better way to do this?


问:
Is knowing .NET only enough for a successful career in IT industry?

Possible Duplicate:

  Is it better to specialize in a single field I like, or expand into other fields to broaden my horizons?

Recently, I don’t know from where I got a thought in my mind that, “is knowing .NET development environment enough for a successful career in IT industry”. Should I be learning more languages too or will .NET suffice me for next 10-15 years.

By successful career I mean earning decent living and having good growth opportunities.

答:
No.

To stay on the edge in the constantly moving IT world you constantly have to learn new technologies. If you only focus on the .NET platform this will limit you.

OwnerDisplayName: Peter Moberg


问:
Configuring DI in a decoupled app
I'm reading through Mark Seeman's Dependency Injection in .NET (excellent read so far) and something is escaping me.

If the application's architecture is like [DAL] => [BLL] <= [UI], with the Business Logic Layer free of dependencies upon Data Access and UI layers (and both dependent upon the BLL), and if the composition root is located in the UI layer, then how on Earth are we supposed to be able to bind the interface of a type in the BLL with an implementation that's in the DAL?

Mark Seeman gives a nice, typical example: abstract class ProductRepository lives in the BLL and class SqlProductRepository in the DAL. This may sound like a silly question but how is the UI layer supposed to be able to bind ProductRepository to SqlProductRepository without a reference to the DAL?

I move all the Controllers and ViewModels from the User Interface Layer to the Presentation Model layer, leaving only the Views (the .aspx and .ascx files) and the COMPOSITION ROOT in the User Interface layer.

Thing is, I'm pretty sure this guy knows what he's talking about, so what part have I missed?

Also where would I have to put the composition root in the case of a class library project? At first I thought the BLL would be perfect (given [DAL] <= [BLL] => [UI]), but now that I've refactored my project to literally reverse the dependencies, I don't know anymore - I used to have a BLL that knew about both the DAL and the UI layer so binding the types of these layers was easy, now nobody knows about everyone anymore, it's like I don't have anywhere I could possibly put a composition root. Help me out here, I feel like I'm missing a fundamental cornerstone...

答:
Just create a Bootstrapper project in your UI layer. This is were the binding between your BLL interfaces and your concrete implementation will be defined.

Have a look at this SO answer where I explain all the steps to let it work.

It's an Onion architecture related question but things are almost the same here.

Last thing to mention is that if you have Internal services that your Bootstrapper project have to know about, edit the AssemblyInfo.cs file of your BLL project and allow Bootstrapper to see its Internal types as follows: [assembly: InternalsVisibleTo("Bootstrapper")]

Title: Configuring DI in a decoupled app